pi-webapp 0.1.56 → 0.1.57-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/dist/extension.js CHANGED
@@ -1,68 +1,71 @@
1
- var pS=Object.defineProperty;var w=(i,e,t)=>()=>{if(t)throw t[0];try{return i&&(e=i(i=0)),e}catch(r){throw t=[r],r}};var Du=(i,e)=>{for(var t in e)pS(i,t,{get:e[t],enumerable:!0})};var bg,hg=w(()=>{bg="server.address"});var Q,ze=w(()=>{Q=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var pe,xt=w(()=>{pe=globalThis});var yt,Ls=w(()=>{yt="11.11.0"});function Pe(){return ct(pe),pe}function ct(i){let e=i.__SENTRY__=i.__SENTRY__||{};return e.version=e.version||yt,e[yt]=e[yt]||{}}function ft(i,e,t=pe){let r=t.__SENTRY__=t.__SENTRY__||{},n=r[yt]=r[yt]||{};return n[i]||(n[i]=e())}var _t=w(()=>{Ls();xt()});function At(i){if(!("console"in pe))return i();let e=pe.console,t={},r=Object.keys(tl);r.forEach(n=>{let s=tl[n];t[n]=e[n],e[n]=s});try{return i()}finally{r.forEach(n=>{e[n]=t[n]})}}function yT(){rl().enabled=!0}function fT(){rl().enabled=!1}function yg(){return rl().enabled}function _T(...i){il("log",...i)}function vT(...i){il("warn",...i)}function kT(...i){il("error",...i)}function il(i,...e){Q&&yg()&&At(()=>{pe.console[i](`${hT}[${i}]:`,...e)})}function rl(){return Q?ft("loggerSettings",()=>({enabled:!1})):{enabled:!1}}var hT,tl,Y,Ve=w(()=>{_t();ze();xt();hT="Sentry Logger ",tl={};Y={enable:yT,disable:fT,isEnabled:yg,log:_T,warn:vT,error:kT}});function sl(...i){let e=i.sort((t,r)=>t[0]-r[0]).map(t=>t[1]);return(t,r=0,n=0)=>{let s=[],o=t.split(`
2
- `);for(let l=r;l<o.length;l++){let a=o[l];a.length>1024&&(a=a.slice(0,1024));let c=fg.test(a)?a.replace(fg,"$1"):a;if(!c.includes("Error: ")){for(let p of e){let d=p(c);if(d){s.push(d);break}}if(s.length>=50+n)break}}return vg(s.slice(n))}}function vg(i){if(!i.length)return[];let e=Array.from(i);return/sentryWrapped/.test(qs(e).function||"")&&e.pop(),e.reverse(),_g.test(qs(e).function||"")&&(e.pop(),_g.test(qs(e).function||"")&&e.pop()),e.slice(0,50).map(t=>({...t,filename:t.filename||qs(e).filename,function:t.function||"?"}))}function qs(i){return i[i.length-1]||{}}function al(i){try{return!i||typeof i!="function"?nl:i.name||nl}catch{return nl}}function kg(i){let e=i?.startsWith("file://")?i.slice(7):i;return e?.match(/\/[A-Z]:/)&&(e=e.slice(1)),e}var fg,_g,nl,Us=w(()=>{fg=/\(error: (.*)\)/,_g=/captureMessage|captureException/;nl="<anonymous>"});function Ot(i){switch(wg.call(i)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Ig(i,Error)}}function js(i,e){return wg.call(i)===`[object ${e}]`}function Sg(i){return js(i,"ErrorEvent")}function un(i){return js(i,"String")}function mn(i){return typeof i=="object"&&i!==null&&"__sentry_template_string__"in i&&"__sentry_template_values__"in i}function ii(i){return i===null||mn(i)||typeof i!="object"&&typeof i!="function"}function _r(i){return js(i,"Object")}function gn(i){return typeof i=="object"&&i!==null}function Eg(i){return typeof Event<"u"&&Ig(i,Event)}function Tg(i){return js(i,"RegExp")}function ri(i){return!!(i?.then&&typeof i.then=="function")}function Ig(i,e){try{return i instanceof e}catch{return!1}}var wg,rt=w(()=>{wg=Object.prototype.toString});function Bs(i,e,t){try{Object.defineProperty(i,e,{value:t,writable:!0,configurable:!0})}catch{Q&&Y.log(`Failed to add non-enumerable property "${String(e)}" to object`,i)}}function ol(i){if(Ot(i))return{message:i.message,name:i.name,stack:i.stack,...xg(i)};if(Eg(i)){let{type:e,target:t,currentTarget:r,detail:n}=i;return{type:e,target:t,currentTarget:r,...n?{detail:n}:{},...xg(i)}}return i}function xg(i){return gn(i)?Object.fromEntries(Object.entries(i)):{}}function Ag(i){let e=Object.keys(ol(i));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}var bn=w(()=>{ze();Ve();rt()});function bi(i){if(vr!==void 0)return vr?vr(i):i();let e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),t=pe;return e in t&&typeof t[e]=="function"?(vr=t[e],vr(i)):(vr=null,i())}function vt(){return bi(()=>Math.random())}function $e(){return bi(()=>Date.now())}var vr,Rt=w(()=>{xt()});function Og(i){return!!i[wT]}function Rg(i){let e=i[ST];return typeof e=="number"?e:void 0}var wT,ST,Ng=w(()=>{wT=Symbol.for("sentry.skipNormalization"),ST=Symbol.for("sentry.overrideNormalizationDepth")});function Nt(i,e=100,t=1/0){try{return ll("",i,e,t)}catch(r){return{ERROR:`**non-serializable** (${r})`}}}function cl(i,e=3,t=100*1024){let r=Nt(i,e);return xT(r)>t?cl(i,e-1,t):r}function ll(i,e,t=1/0,r=1/0,n=AT()){let[s,o]=n;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;let l=ET(i,e);if(!l.startsWith("[object "))return l;if(Og(e))return e;let a=Rg(e),c=a!==void 0?a:t;if(c===0)return l.replace("object ","");if(s(e))return"[Circular ~]";let p=e;if(p&&typeof p.toJSON=="function")try{let v=p.toJSON();return ll("",v,c-1,r,n)}catch{}let d=Array.isArray(e)?[]:{},g=0,b=ol(e);for(let v in b){if(!Object.prototype.hasOwnProperty.call(b,v))continue;if(g>=r){d[v]="[MaxProperties ~]";break}let y=b[v];d[v]=ll(v,y,c-1,r,n),g++}return o(e),d}function ET(i,e){try{if(Cg){let r=Cg(e);if(r)return r}return typeof global<"u"&&e===global?"[Global]":typeof e=="number"&&!Number.isFinite(e)?`[${e}]`:typeof e=="function"?`[Function: ${al(e)}]`:typeof e=="symbol"?`[${String(e)}]`:typeof e=="bigint"?`[BigInt: ${String(e)}]`:`[object ${TT(e)}]`}catch(t){return`**non-serializable** (${t})`}}function TT(i){let e=Object.getPrototypeOf(i);return e?.constructor?e.constructor.name:"null prototype"}function IT(i){return~-encodeURI(i).split(/%..|./).length}function xT(i){return IT(JSON.stringify(i))}function AT(){let i=new WeakSet;function e(r){return i.has(r)?!0:(i.add(r),!1)}function t(r){i.delete(r)}return[e,t]}var Cg,Fs=w(()=>{Ng();bn();Us()});function hn(i,e=0){return typeof i!="string"||e===0||i.length<=e?i:`${i.slice(0,e)}...`}function yn(i,e,t=!1){return un(i)?Tg(e)?e.test(i):un(e)?t?i===e:i.includes(e):typeof e=="function"?e(i):!1:!1}var Gs=w(()=>{rt()});function OT(){let i=pe;return i.crypto||i.msCrypto}function RT(){return vt()*16}function Me(i=OT()){try{if(i?.randomUUID)return bi(()=>i.randomUUID()).replace(/-/g,"")}catch{}return pl||(pl="10000000100040008000"+1e11),pl.replace(/[018]/g,e=>(e^(RT()&15)>>e/4).toString(16))}function NT(i){return i.exception?.values?.[0]}function ul(i,e,t){let r=i.exception=i.exception||{},n=r.values=r.values||[],s=n[0]=n[0]||{};s.value||(s.value=e||""),s.type||(s.type=t||"Error")}function Hs(i,e){let t=NT(i);t&&Dg(t,e)}function Pg(i,e){let t=i.exception?.values,r=t?.find(n=>n.mechanism?.exception_id===0)??t?.[0];r&&Dg(r,e)}function Dg(i,e){let t={type:"generic",handled:!0},r=i.mechanism;i.mechanism={...t,...r,...e},e&&"data"in e&&(i.mechanism.data={...r?.data,...e.data})}function dl(i){return parseInt(i||"",10)}function ml(i){let e=i.match(CT)||[],t=dl(e[1]),r=dl(e[2]),n=dl(e[3]);return{buildmetadata:e[5],major:isNaN(t)?void 0:t,minor:isNaN(r)?void 0:r,patch:isNaN(n)?void 0:n,prerelease:e[4]}}function Ws(i){if(Mg(i))return!0;try{Bs(i,"__sentry_captured__",!0)}catch{}return!1}function Mg(i){try{return i.__sentry_captured__}catch{}}var pl,CT,ni=w(()=>{bn();Rt();xt();CT=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/});function zi(){return $e()/qg}function MT(){let{performance:i}=pe;if(!i?.now||!i.timeOrigin)return i?.now&&(kr=[{from:0,origin:$e()-bi(()=>i.now())}]),zi;let e=i.timeOrigin;kr=[{from:0,origin:e}];let t=!0,r=0;return()=>bi(()=>{let n=i.now(),s=Date.now();return Math.abs(e+n-s)>PT&&(e=s-n,t?kr=[{from:0,origin:e}]:(kr.push({from:r,origin:e}),kr.length>DT&&kr.splice(1,1))),t=!1,r=n,(e+n)/qg})}function zs(){return(Lg??(Lg=MT()))()}var qg,PT,DT,kr,Lg,wr=w(()=>{Rt();xt();qg=1e3,PT=1e3,DT=100;kr=[]});function fn(i,e={}){if(e.user&&(!i.ipAddress&&e.user.ip_address&&(i.ipAddress=e.user.ip_address),!i.did&&!e.did&&(i.did=e.user.id||e.user.email||e.user.username)),i.timestamp=e.timestamp||zs(),e.abnormal_mechanism&&(i.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(i.ignoreDuration=e.ignoreDuration),e.sid&&(i.sid=e.sid.length===32?e.sid:Me()),e.init!==void 0&&(i.init=e.init),!i.did&&e.did&&(i.did=`${e.did}`),typeof e.started=="number"&&(i.started=e.started),i.ignoreDuration)i.duration=void 0;else if(typeof e.duration=="number")i.duration=e.duration;else{let t=i.timestamp-i.started;i.duration=t>=0?t:0}e.release&&(i.release=e.release),e.environment&&(i.environment=e.environment),!i.ipAddress&&e.ipAddress&&(i.ipAddress=e.ipAddress),!i.userAgent&&e.userAgent&&(i.userAgent=e.userAgent),typeof e.errors=="number"&&(i.errors=e.errors),e.status&&(i.status=e.status)}var gl=w(()=>{ni();wr()});function hi(i,e,t=2){if(!e||typeof e!="object"||t<=0)return e;if(i&&Object.keys(e).length===0)return i;let r={...i};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=hi(r[n],e[n],t-1));return r}var Vs=w(()=>{});function Vi(){return Me()}function _n(){return Me().substring(16)}var vn=w(()=>{ni()});var LT,Ze,Sr=w(()=>{ze();gl();Ve();rt();bn();Vs();ni();vn();Rt();Gs();wr();LT=100,Ze=class i{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},Bs(this,"refs",{}),this._propagationContext={traceId:Vi(),sampleRand:vt()}}clone(){let e=new i;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._attributes={...this._attributes},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,e._conversationId=this._conversationId,e.refs={...this.refs},e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&fn(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(e){return this._conversationId=e||void 0,this._notifyScopeListeners(),this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,t){return this.setTags({[e]:t})}setAttributes(e){return this._attributes={...this._attributes,...e},this._notifyScopeListeners(),this}setAttribute(e,t){return this.setAttributes({[e]:t})}removeAttribute(e){return e in this._attributes&&(delete this._attributes[e],this._notifyScopeListeners()),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,t){return this._extra={...this._extra,[e]:t},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,t){return t===null?delete this._contexts[e]:this._contexts[e]=t,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;let t=typeof e=="function"?e(this):e,r=t instanceof i?t.getScopeData():_r(t)?e:void 0,{tags:n,attributes:s,extra:o,user:l,contexts:a,level:c,fingerprint:p=[],propagationContext:d,conversationId:g}=r||{};return this._tags={...this._tags,...n},this._attributes={...this._attributes,...s},this._extra={...this._extra,...o},this._contexts={...this._contexts,...a},l&&Object.keys(l).length&&(this._user=l),c&&(this._level=c),p.length&&(this._fingerprint=p),d&&(this._propagationContext=d),g&&(this._conversationId=g),this}addBreadcrumb(e,t){let r=typeof t=="number"?t:LT;if(r<=0)return this;let n={timestamp:zi(),...e,message:e.message?hn(e.message,2048):e.message};return this._breadcrumbs.push(n),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r)),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,conversationId:this._conversationId}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=hi(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,t){let r=t?.event_id||Me();if(!this._client)return Q&&Y.warn("No client configured on scope - will not capture exception!"),r;let n=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:n,...t,event_id:r},this),r}captureMessage(e,t,r){let n=r?.event_id||Me();if(!this._client)return Q&&Y.warn("No client configured on scope - will not capture message!"),n;let s=r?.syntheticException??new Error(e);return this._client.captureMessage(e,t,{originalException:e,syntheticException:s,...r,event_id:n},this),n}captureEvent(e,t){let r=e.event_id||t?.event_id||Me();return this._client?(this._client.captureEvent(e,{...t,event_id:r},this),r):(Q&&Y.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}});function $i(){return ft("defaultCurrentScope",()=>new Ze)}function Yi(){return ft("defaultIsolationScope",()=>new Ze)}var bl=w(()=>{_t();Sr()});var hl,Ug=w(()=>{hl="__SENTRY_SUPPRESS_TRACING__"});var jg,Bg,Fg,qT,Gg=w(()=>{jg=i=>i instanceof Promise&&!i[Bg],Bg=Symbol("chained PromiseLike"),Fg=(i,e,t)=>{let r=i.then(n=>(e(n),n),n=>{throw t(n),n});return jg(r)&&jg(i)?r:qT(i,r)},qT=(i,e)=>{if(!e)return i;let t=!1;for(let r in i){if(r in e)continue;t=!0;let n=i[r];typeof n=="function"?Object.defineProperty(e,r,{value:(...s)=>n.apply(i,s),enumerable:!0,configurable:!0,writable:!0}):e[r]=n}return t&&Object.assign(e,{[Bg]:!0}),e}});function Er(){let i=Pe(),e=ct(i);return e.stack=e.stack||new yl($i(),Yi())}function Wg(i){return Er().withScope(i)}function UT(i,e){let t=Er();return t.withScope(()=>(t.getStackTop().scope=i,e(i)))}function Hg(i){return Er().withScope(()=>i(Er().getIsolationScope()))}function zg(){return{suppressTracing:jT,withIsolationScope:Hg,withScope:Wg,withSetScope:UT,withSetIsolationScope:(i,e)=>Hg(e),getCurrentScope:()=>Er().getScope(),getIsolationScope:()=>Er().getIsolationScope()}}function jT(i){return Wg(e=>{e.setSDKProcessingMetadata({[hl]:!0});let t=i();return e.setSDKProcessingMetadata({[hl]:void 0}),t})}var yl,Vg=w(()=>{bl();Sr();Ug();Gg();rt();_t();yl=class{constructor(e,t){let r;e?r=e:r=new Ze;let n;t?n=t:n=new Ze,this._stack=[{scope:r}],this._isolationScope=n}withScope(e){let t=this._pushScope(),r;try{r=e(t)}catch(n){throw this._popScope(),n}return ri(r)?Fg(r,()=>this._popScope(),()=>this._popScope()):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}});function kn(i){let e=Pe(),t=ct(e);t.acs=i}function Ct(i){let e=ct(i);return e.acs?e.acs:zg()}var $s=w(()=>{_t();Vg()});function BT(i){return typeof i=="object"&&i!=null&&!Array.isArray(i)&&Object.keys(i).includes("value")}function FT(i,e){let{value:t,unit:r}=BT(i)?i:{value:i,unit:void 0},n=GT(t),s=r&&typeof r=="string"?{unit:r}:{};if(n)return{...n,...s};if(!e||e==="skip-undefined"&&t===void 0)return;let o="";try{o=JSON.stringify(t)??""}catch{}return{value:o,type:"string",...s}}function fl(i,e=!1){let t={};for(let[r,n]of Object.entries(i??{})){let s=FT(n,e);s&&(t[r]=s)}return t}function _l(i){if(!i)return 0;let e=0;for(let[t,r]of Object.entries(i)){e+=t.length*2,e+=r.type.length*2,e+=(r.unit?.length??0)*2;let n=r.value;Array.isArray(n)?e+=$g(n[0])*n.length:ii(n)?e+=$g(n):e+=100}return e}function $g(i){return typeof i=="string"?i.length*2:typeof i=="boolean"?4:typeof i=="number"?8:0}function GT(i){if(Array.isArray(i))return{value:i,type:"array"};let e=typeof i=="string"?"string":typeof i=="boolean"?"boolean":typeof i=="number"&&!Number.isNaN(i)?Number.isInteger(i)?"integer":"double":null;if(e)return{value:i,type:e}}var vl=w(()=>{rt()});function Ys(){return ct(Pe()).externalPropagationContextProvider?.()}function si(){let i=Pe();return Ct(i).getCurrentScope()}function Ki(){let i=Pe();return Ct(i).getIsolationScope()}function kl(){return ft("globalScope",()=>new Ze)}function Ks(...i){let e=Pe(),t=Ct(e);if(i.length===2){let[r,n]=i;return r?t.withSetScope(r,n):t.withScope(n)}return t.withScope(i[0])}function Ft(){return si().getClient()}function Qi(i){let e=Ys();if(e)return{trace_id:e.traceId,span_id:e.spanId};let t=i.getPropagationContext(),{traceId:r,parentSpanId:n,propagationSpanId:s}=t,o={trace_id:r,span_id:s||_n()};return n&&(o.parent_span_id=n),o}var Pt=w(()=>{$s();_t();Sr();vn()});var Yg,Kg,Qg,Jg,Xg,Zg,eb,wl,tb,ib,rb,wn,nb,sb,ab,ob,lb,cb,Sl,pb,db,ub,mb,gb,bb,hb,yb,fb,yi=w(()=>{Yg="angular.version",Kg="culture.locale",Qg="culture.timezone",Jg="http.response.body.size",Xg="http.response.status_code",Zg="react.version",eb="sentry.environment",wl="sentry.exclusive_time",tb="sentry.op",ib="sentry.origin",rb="sentry.profiler_id",wn="sentry.profile_id",nb="sentry.release",sb="sentry.sdk.integrations",ab="sentry.sdk.name",ob="sentry.sdk.version",lb="sentry.segment.id",cb="sentry.segment.name",Sl="sentry.segment.name.source",pb="sentry.status.message",db="sentry.trace_lifecycle",ub="server.address",mb="state.type",gb="url.path",bb="user.email",hb="user.id",yb="user.ip_address",fb="user.name"});var _b,vb,kb,El=w(()=>{_b="sentry.sample_rate",vb="sentry.previous_trace_sample_rate",kb="sentry.custom_span_name"});var wb,Sb=w(()=>{wb=["ok","deadline_exceeded","unauthenticated","permission_denied","not_found","resource_exhausted","invalid_argument","unimplemented","unavailable","internal_error","unknown_error","cancelled","already_exists","failed_precondition","aborted","out_of_range","data_loss"]});function Eb(i){return i!=="ok"&&wb.includes(i)}var Tl,Il,Tb=w(()=>{Sb();Tl=0,Il=1});function Tr(i){try{let e=pe.WeakRef;if(typeof e=="function")return new e(i)}catch{}return i}function Ji(i){if(i){if(typeof i=="object"&&"deref"in i&&typeof i.deref=="function")try{return i.deref()}catch{return}return i}}var Qs=w(()=>{xt()});function fi(i){let e=i;return{scope:e[HT],isolationScope:Ji(e[WT])}}var HT,WT,Js=w(()=>{Qs();HT="_sentryScope",WT="_sentryIsolationScope"});function Sn(i){let e=xb(i);if(!e)return;let t=Object.entries(e).reduce((r,[n,s])=>{if(n.startsWith(xl)){let o=n.slice(xl.length);r[o]=s}return r},{});if(Object.keys(t).length>0)return t}function xb(i){if(!(!i||!un(i)&&!Array.isArray(i)))return Array.isArray(i)?i.reduce((e,t)=>{let r=Ib(t);return Object.entries(r).forEach(([n,s])=>{e[n]=s}),e},{}):Ib(i)}function Ib(i){return i.split(",").map(e=>{let t=e.indexOf("=");if(t===-1)return[];let r=e.slice(0,t),n=e.slice(t+1);return[r,n].map(s=>{try{return decodeURIComponent(s.trim())}catch{return}})}).reduce((e,[t,r])=>(t&&r&&(e[t]=r),e),{})}var xl,Al=w(()=>{rt();xl="sentry-"});function $T(i){return i==="http"||i==="https"}function Be(i,e=!1){let{host:t,path:r,pass:n,port:s,projectId:o,protocol:l,publicKey:a}=i;return`${l}://${a}${e&&n?`:${n}`:""}@${t}${s?`:${s}`:""}/${r&&`${r}/`}${o}`}function YT(i){let e=VT.exec(i);if(!e){At(()=>{console.error(`Invalid Sentry Dsn: ${i}`)});return}let[t,r,n="",s="",o="",l=""]=e.slice(1),a="",c=l,p=c.split("/");if(p.length>1&&(a=p.slice(0,-1).join("/"),c=p.pop()),c){let d=c.match(/^\d+/);d&&(c=d[0])}return Ab({host:s,pass:n,path:a,projectId:c,port:o,protocol:t,publicKey:r})}function Ab(i){return{protocol:i.protocol,publicKey:i.publicKey||"",pass:i.pass||"",host:i.host,port:i.port||"",path:i.path||"",projectId:i.projectId}}function KT(i){if(!Q)return!0;let{port:e,projectId:t,protocol:r}=i;return["protocol","publicKey","host","projectId"].find(o=>i[o]?!1:(Y.error(`Invalid Sentry Dsn: ${o} missing`),!0))?!1:t.match(/^\d+$/)?$T(r)?e&&isNaN(parseInt(e,10))?(Y.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(Y.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(Y.error(`Invalid Sentry Dsn: Invalid projectId ${t}`),!1)}function QT(i){return i.match(zT)?.[1]}function Ob(i){let e=i.getOptions(),{host:t}=i.getDsn()||{},r;return e.orgId?r=String(e.orgId):t&&(r=QT(t)),r}function En(i){let e=typeof i=="string"?YT(i):Ab(i);if(!(!e||!KT(e)))return e}var zT,VT,Gt=w(()=>{ze();Ve();zT=/^o(\d+)\./,VT=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/});function Rb(i){if(typeof i=="boolean")return Number(i);let e=typeof i=="string"?parseFloat(i):i;if(!(typeof e!="number"||isNaN(e)||e<0||e>1))return e}var Nb=w(()=>{});function Tn(i){return!!i.parentSpanId||!!i.dsc}var JT,Cb=w(()=>{JT=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$")});function Xs(i,e){e?i.refs[Ol]=Tr(e):delete i.refs[Ol]}function Pb(i){return Ji(i.refs[Ol])}var Ol,Rl=w(()=>{Qs();Ol="span"});function ea(i){let{spanId:e,traceId:t,isRemote:r}=i.spanContext(),n=r?e:Ir(i).parent_span_id,s=fi(i).scope,o=r?s?.getPropagationContext().propagationSpanId||_n():e;return{parent_span_id:n,span_id:o,trace_id:t}}function XT(i){if(i&&i.length>0)return i.map(({context:{spanId:e,traceId:t,traceFlags:r,...n},attributes:s})=>({span_id:e,trace_id:t,sampled:r===Nl,attributes:s,...n}))}function ZT(i){if(i?.length)return i.map(({context:{spanId:e,traceId:t,traceFlags:r},attributes:n})=>({span_id:e,trace_id:t,sampled:r===Nl,attributes:n}))}function Zs(i){return typeof i=="number"?Db(i):Array.isArray(i)?i[0]+i[1]/1e9:i instanceof Date?Db(i.getTime()):zs()}function Db(i){return i>9999999999?i/1e3:i}function Ir(i){if(Ub(i))return i.getStaticSpanJSON();let{spanId:e,traceId:t}=i.spanContext();if(qb(i)){let{attributes:r,startTime:n,name:s,endTime:o,status:l,links:a}=i;return{span_id:e,trace_id:t,data:r,description:s,parent_span_id:Lb(i),start_timestamp:Zs(n),timestamp:Zs(o)||void 0,status:eI(l),op:r[tb],origin:r[ib],links:XT(a)}}return{span_id:e,trace_id:t,start_timestamp:0,status:"ok",data:{}}}function Cl(i){if(Ub(i))return i.getSpanJSON();let{spanId:e,traceId:t}=i.spanContext();if(qb(i)){let{attributes:r,startTime:n,name:s,endTime:o,status:l,links:a}=i;return{name:s,span_id:e,trace_id:t,parent_span_id:Lb(i),start_timestamp:Zs(n),end_timestamp:Zs(o)||void 0,is_segment:Mb(i),status:jb(l),attributes:tI(r,l),links:ZT(a)}}return{span_id:e,trace_id:t,start_timestamp:0,name:"",status:"ok",is_segment:Mb(i),attributes:{}}}function Lb(i){return"parentSpanId"in i?i.parentSpanId:"parentSpanContext"in i?i.parentSpanContext?.spanId:void 0}function ta(i){return{...i,end_timestamp:i.end_timestamp??i.start_timestamp,attributes:fl(i.attributes),links:i.links?.map(e=>({...e,attributes:fl(e.attributes)}))}}function qb(i){let e=i;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function Ub(i){return typeof i.getSpanJSON=="function"}function ia(i){let{traceFlags:e}=i.spanContext();return e===Nl}function eI(i){return!i||i.code===Tl||i.code===Il?"ok":i.message&&Eb(i.message)?i.message:"internal_error"}function jb(i){return!i||i.code===Il||i.code===Tl||i.message==="cancelled"?"ok":"error"}function tI(i,e){let t=jb(e)==="error"?e?.message:void 0;return{...t&&{[pb]:t},...i}}function na(i){return i[iI]||i}function Mb(i){return i===na(i)}function In(i){let e=Pe(),t=Ct(e);return t.getActiveSpan?t.getActiveSpan(i):Pb(i||si())}var Nl,iI,ra,_i=w(()=>{$s();vl();_t();Pt();yi();Tb();Js();vn();wr();Rl();Nl=1;iI="_sentryRootSpan",ra=na});function Pl(i){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;let e=i||Ft()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}var Bb=w(()=>{Pt()});function Fb(i){Y.log(`Ignoring span ${i.op} - ${i.description} because it matches \`ignoreSpans\`.`)}function Dl(i,e){if(!e?.length)return!1;for(let t of e){if(nI(t)){if(i.description&&yn(i.description,t))return Q&&Fb(i),!0;continue}let r=!!t.attributes&&Object.keys(t.attributes).length>0;if(!t.name&&!t.op&&!r)continue;let n=t.name?i.description&&yn(i.description,t.name):!0,s=t.op?i.op&&yn(i.op,t.op):!0,o=t.attributes?Object.entries(t.attributes).every(([l,a])=>rI(i.attributes?.[l],a)):!0;if(n&&s&&o)return Q&&Fb(i),!0}return!1}function rI(i,e){return typeof i=="string"&&(typeof e=="string"||e instanceof RegExp)?yn(i,e):Array.isArray(i)&&Array.isArray(e)?i.length===e.length&&i.every((t,r)=>t===e[r]):i===e}function Gb(i,e){let t=e.parent_span_id,r=e.span_id;if(t)for(let n of i)n.parent_span_id===r&&(n.parent_span_id=t)}function nI(i){return typeof i=="string"||i instanceof RegExp}var Hb=w(()=>{ze();Ve();Gs()});function zb(i,e){let t={};return e.forEach(r=>{r?.beforeSetup&&r.beforeSetup(i)}),e.forEach(r=>{r&&Ll(i,r,t)}),t}function Ml(i,e){for(let t of e)t?.afterAllSetup&&t.afterAllSetup(i)}function Ll(i,e,t){if(t[e.name]){Q&&Y.log(`Integration skipped because it was already installed: ${e.name}`);return}if(t[e.name]=e,!Wb.includes(e.name)&&typeof e.setupOnce=="function"&&(e.setupOnce(),Wb.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(i),typeof e.preprocessEvent=="function"){let r=e.preprocessEvent.bind(e);i.on("preprocessEvent",(n,s)=>r(n,s,i))}if(typeof e.processEvent=="function"){let r=e.processEvent.bind(e),n=Object.assign((s,o)=>r(s,o,i),{id:e.name});i.addEventProcessor(n)}["processSpan","processSegmentSpan"].forEach(r=>{let n=e[r];typeof n=="function"&&i.on(r,s=>n.call(e,s,i))}),Q&&Y.log(`Integration installed: ${e.name}`)}var Wb,Vb=w(()=>{ze();Ve();Wb=[]});var vi,xn=w(()=>{vi="production"});function $b(i){return!!i&&i[sI]===!0}var sI,Yb=w(()=>{sI=Symbol.for("sentry.nonRecordingSpan")});function ql(i,e){let t=e.getOptions(),{publicKey:r}=e.getDsn()||{},n={environment:t.environment||vi,release:t.release,public_key:r,trace_id:i,org_id:Ob(e)};return e.emit("createDsc",n),n}function xr(i,e){if(Ys())return;let t=e.getPropagationContext();return t.dsc||ql(t.traceId,i)}function ai(i){let e=Ft();if(!e)return{};let t=ra(i),r=Ir(t),n=r.data,s=t.spanContext().traceState,o=s?.get("sentry.sample_rate")??n[_b]??n[vb];function l(S){return(typeof o=="number"||typeof o=="string")&&(S.sample_rate=`${o}`),S}let a=t[aI];if(a)return l(a);let c=$b(t),p=c&&t.dropReason==="ignored";if(c&&(!Pl(e.getOptions())||p)){let S=fi(t).scope,T=S&&xr(e,S);if(T){let I={...T};return p&&(I.sampled="false"),l(I)}}let d=s?.get("sentry.dsc"),g=d&&Sn(d);if(g)return l(g);let b=ql(i.spanContext().traceId,e),v=n[Sl],y=r.description;return v!=="url"&&y&&(b.transaction=y),Pl()&&(b.sampled=String(ia(t)),b.sample_rand=s?.get("sentry.sample_rand")??fi(t).scope?.getPropagationContext().sampleRand.toString()),l(b),e.emit("createDsc",b,t),b}var aI,Ar=w(()=>{xn();Pt();yi();El();Al();Gt();Bb();_i();Yb();Js();aI="_frozenDsc"});function Jb(i,e){let{fingerprint:t,breadcrumbs:r,sdkProcessingMetadata:n}=e;oI(i,e),pI(i,t),lI(i,r),cI(i,n)}function Qb(i,e){let{extra:t,tags:r,attributes:n,user:s,contexts:o,level:l,sdkProcessingMetadata:a,breadcrumbs:c,fingerprint:p,eventProcessors:d,attachments:g,propagationContext:b,transactionName:v}=e;An(i,"extra",t),An(i,"tags",r),An(i,"attributes",n),An(i,"user",s),An(i,"contexts",o),i.sdkProcessingMetadata=hi(i.sdkProcessingMetadata,a,2),l&&(i.level=l),v&&(i.transactionName=v),c.length&&(i.breadcrumbs=[...i.breadcrumbs,...c]),p.length&&(i.fingerprint=[...i.fingerprint,...p]),d.length&&(i.eventProcessors=[...i.eventProcessors,...d]),g.length&&(i.attachments=[...i.attachments,...g]),i.propagationContext={...i.propagationContext,...b}}function An(i,e,t){i[e]=hi(i[e],t,1)}function sa(i,e){let t=kl().getScopeData();return i&&Qb(t,i.getScopeData()),e&&Qb(t,e.getScopeData()),t}function oI(i,e){let{extra:t,tags:r,user:n,contexts:s,level:o,transactionName:l}=e;Object.keys(t).length&&(i.extra={...t,...i.extra}),Object.keys(r).length&&(i.tags={...r,...i.tags}),Object.keys(n).length&&(i.user={...n,...i.user}),Object.keys(s).length&&(i.contexts={...s,...i.contexts}),o&&(i.level=o),l&&i.type!=="transaction"&&(i.transaction=l)}function lI(i,e){let t=[...i.breadcrumbs||[],...e];i.breadcrumbs=t.length?t:void 0}function cI(i,e){i.sdkProcessingMetadata={...i.sdkProcessingMetadata,...e}}function Xb(i,e){i.contexts={trace:ea(e),...i.contexts},i.sdkProcessingMetadata={dynamicSamplingContext:ai(e),...i.sdkProcessingMetadata};let t=ra(e),r=Ir(t).description;r&&!i.transaction&&i.type==="transaction"&&(i.transaction=r)}function pI(i,e){i.fingerprint=i.fingerprint?Array.isArray(i.fingerprint)?i.fingerprint:[i.fingerprint]:[],e&&(i.fingerprint=i.fingerprint.concat(e)),i.fingerprint.length||delete i.fingerprint}var Ul=w(()=>{Pt();Ar();Vs();_i()});function Xi(i,e,t){let r;try{r=e()}catch(n){return Zb(i,n,t)}return ri(r)?r.then(void 0,n=>Zb(i,n,t)):r}function Zb(i,e,t){return Q&&Y.error(i,e),t(e)}var aa=w(()=>{ze();Ve();rt()});function On(i){return!!i&&typeof i=="function"&&"_static"in i&&!!i._static}function Rn(i,e){return Xi(Q?"The `beforeSendSpan` callback threw an error, sending the span unmodified:":"",()=>e(i),()=>i)||i}var jl=w(()=>{ze();aa()});function eh(i){let e={trace_id:i.trace_id,span_id:i.span_id,parent_span_id:i.parent_span_id,name:i.description||"",start_timestamp:i.start_timestamp,end_timestamp:i.timestamp,status:!i.status||i.status==="ok"||i.status==="cancelled"?"ok":"error",is_segment:!1,attributes:{...i.data},links:i.links};return ta(e)}var th=w(()=>{_i()});function ih(i){let e={},{response:t,profile:r,cloud_resource:n,culture:s,state:o}=i;if(t&&(t.status_code!=null&&(e[Xg]=t.status_code),t.body_size!=null&&(e[Jg]=t.body_size)),r&&(r.profile_id&&(e[wn]=r.profile_id),r.profiler_id&&(e[rb]=r.profiler_id)),n)for(let[c,p]of Object.entries(n))p!=null&&(e[c]=p);s&&(s.locale&&(e[Kg]=s.locale),s.timezone&&(e[Qg]=s.timezone)),o?.state&&typeof o.state.type=="string"&&(e[mb]=o.state.type);let l=i.angular;if(l){let c=l.version;(typeof c=="string"||typeof c=="number")&&(e[Yg]=c)}let a=i.react;if(a){let c=a.version;(typeof c=="string"||typeof c=="number")&&(e[Zg]=c)}return e}var rh=w(()=>{yi()});function nh(i,e){let t=Cl(i);t.attributes&&delete t.attributes[kb];let r=na(i),n=Cl(r),{isolationScope:s,scope:o}=fi(i),l=sa(s,o);gI(t,n,e,l),e.emit("preprocessSpan",t),t.is_segment&&(dI(t,l),uI(t,e),e.emit("processSegmentSpan",t)),e.emit("processSpan",t);let{beforeSendSpan:a,traceLifecycle:c}=e.getOptions(),p=c!=="static"&&a&&!On(a)?Rn(t,a):t;return{...ta(p),_segmentSpan:r}}function dI(i,e){let t=ih(e.contexts);Bl(i,t)}function Bl(i,e){let t=i.attributes??(i.attributes={});Object.entries(e).forEach(([r,n])=>{n!=null&&!(r in t)&&(t[r]=n)})}function uI(i,e){let t=e.getIntegrationNames();t.length&&Bl(i,{[sb]:t})}function mI(i,e,t,r=!0){let n=e.getSdkMetadata(),{release:s,environment:o}=e.getOptions();return{[db]:"stream",[cb]:i.name,[lb]:i.span_id,[ab]:n?.sdk?.name,[ob]:n?.sdk?.version,[nb]:s,[eb]:o||vi,[hb]:t.user?.id,[bb]:t.user?.email,[yb]:t.user?.ip_address,[fb]:t.user?.username,...r?t.attributes:void 0}}function gI(i,e,t,r){Bl(i,mI(e,t,r))}var sh=w(()=>{El();Ul();_i();Js();jl();rh();xn();yi()});function oa(i){return i.getOptions().traceLifecycle==="stream"}var Fl=w(()=>{});function ki(i){return typeof i=="object"&&typeof i.unref=="function"&&i.unref(),i}var Nn=w(()=>{});function et(i,e=[]){return[i,e]}function Hl(i,e){let[t,r]=i;return[t,[...r,e]]}function la(i,e){let t=i[1];for(let r of t){let n=r[0].type;if(e(r,n))return!0}return!1}function ah(i,e){return la(i,(t,r)=>e.includes(r))}function Gl(i){let e=ct(pe);return e.encodePolyfill?e.encodePolyfill(i):new TextEncoder().encode(i)}function oh(i){let[e,t]=i,r=JSON.stringify(e);function n(s){typeof r=="string"?r=typeof s=="string"?r+s:[Gl(r),s]:r.push(typeof s=="string"?Gl(s):s)}for(let s of t){let[o,l]=s;if(n(`
3
- ${JSON.stringify(o)}
4
- `),typeof l=="string"||l instanceof Uint8Array)n(l);else{let a;try{a=JSON.stringify(l)}catch{a=JSON.stringify(Nt(l))}n(a)}}return typeof r=="string"?r:bI(r)}function bI(i){let e=i.reduce((n,s)=>n+s.length,0),t=new Uint8Array(e),r=0;for(let n of i)t.set(n,r),r+=n.length;return t}function lh(i){let e=typeof i.data=="string"?Gl(i.data):i.data;return[{type:"attachment",length:e.length,filename:i.filename,content_type:i.contentType,attachment_type:i.attachmentType},e]}function hI(i){return i in ch}function Wl(i){return hI(i)?ch[i]:i}function Cn(i){if(!i?.sdk)return;let{name:e,version:t}=i.sdk;return{name:e,version:t}}function ph(i,e,t,r){let n=i.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:i.event_id,sent_at:new Date($e()).toISOString(),...e&&{sdk:e},...!!t&&r&&{dsn:Be(r)},...n&&{trace:n}}}function Pn(i){return i==="replay_event"?"replay":i||"error"}var ch,Ht=w(()=>{_t();Gt();Fs();Rt();xt();ch={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",metric:"trace_metric"}});function dh(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}var uh=w(()=>{});function mh(){return!dh()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}var gh=w(()=>{uh()});function Or(){return typeof window<"u"&&(!mh()||yI())}function yI(){return pe.process?.type==="renderer"}var ca=w(()=>{gh();xt()});function bh(i,e,t){let r=t.getOptions(),n=t.getDsn(),s=r.tunnel,o=Cn(r._metadata),l={sent_at:new Date($e()).toISOString(),...fI(e)&&{trace:e},...o&&{sdk:o},...!!s&&n&&{dsn:Be(n)}};return et(l,[zl(i,t)])}function zl(i,e){let t=e.getDataCollectionOptions().userInfo?"auto":"never";return[{type:"span",item_count:i.length,content_type:"application/vnd.sentry.items.span.v2+json"},{version:2,ingest_settings:Or()?{infer_ip:t,infer_user_agent:t}:void 0,items:i}]}function fI(i){return!!i.trace_id&&!!i.public_key}var Vl=w(()=>{Gt();Ht();ca();Rt()});function hh(i){let e=156;if(e+=i.name.length*2,e+=_l(i.attributes),i.links&&i.links.length>0){let r=i.links[0]?.attributes,n=100+(r?_l(r):0);e+=n*i.links.length}return e}var yh=w(()=>{vl()});var fh,_I,pa,_h=w(()=>{ze();Ve();Nn();Ar();Vl();yh();fh=1e3,_I=5e6,pa=class{constructor(e,t){this._traceBuckets=new Map,this._client=e;let{maxSpanLimit:r,flushInterval:n,maxTraceWeightInBytes:s}=t??{};this._maxSpanLimit=r&&r>0&&r<=fh?r:fh,this._flushInterval=n&&n>0?n:5e3,this._maxTraceWeight=s&&s>0?s:_I,this._client.on("flush",()=>{this.drain()}),this._client.on("close",()=>{this._traceBuckets.forEach(o=>{clearTimeout(o.timeout)}),this._traceBuckets.clear()})}add(e){let t=e.trace_id,r=this._traceBuckets.get(t);r||(r={spans:new Set,size:0,timeout:ki(setTimeout(()=>{this.flush(t)},this._flushInterval))},this._traceBuckets.set(t,r)),r.spans.add(e),r.size+=hh(e),(r.spans.size>=this._maxSpanLimit||r.size>=this._maxTraceWeight)&&this.flush(t)}drain(){this._traceBuckets.size&&(Q&&Y.log(`Flushing span tree map with ${this._traceBuckets.size} traces`),this._traceBuckets.forEach((e,t)=>{this.flush(t)}))}flush(e){let t=this._traceBuckets.get(e);if(!t)return;if(!t.spans.size){this._removeTrace(e);return}let r=Array.from(t.spans),n=r[0]?._segmentSpan;if(!n){Q&&Y.warn("No segment span reference found on span JSON, cannot compute DSC"),this._removeTrace(e);return}let s=ai(n),o=r.map(a=>{let{_segmentSpan:c,...p}=a;return p}),l=bh(o,s,this._client);Q&&Y.log(`Sending span envelope for trace ${e} with ${o.length} spans`),this._client.sendEnvelope(l).then(null,a=>{Q&&Y.error("Error while sending streamed span envelope:",a)}),this._removeTrace(e)}_removeTrace(e){let t=this._traceBuckets.get(e);t&&clearTimeout(t.timeout),this._traceBuckets.delete(e)}}});var da,vh,kh=w(()=>{ze();sh();Fl();_h();Ve();_i();Nn();da="SpanStreaming",vh=(i={})=>{let e=i.flushOnSegmentEnd??!0;return{name:da,setup(t){if(!oa(t)){Q&&Y.log(`[${da}] \`traceLifecycle\` is "static", skipping setup.`);return}let r=new pa(t);t.on("afterSpanEnd",n=>{ia(n)&&r.add(nh(n,t))}),t.on("flushTraceSpans",n=>{r.flush(n)}),e&&t.on("afterSegmentSpanEnd",n=>{let s=n.spanContext().traceId;ki(setTimeout(()=>{r.flush(s)},500))})}}}});function kI(i){return ii(i)?void 0:i}function wh(i,e,t){let r=kI(e.originalException),n=r&&vI.get(r);if(!n)return;let s=i.contexts?.trace;(s?.trace_id??(t&&Qi(t).trace_id))===n.trace_id&&(i.contexts={...i.contexts,trace:{...s,...n}})}var vI,Sh=w(()=>{Pt();rt();vI=new WeakMap});function Eh(i){ct(Pe()).segmentSpanCaptureStrategy=i}function Th(){return ct(Pe()).segmentSpanCaptureStrategy}var Ih=w(()=>{_t()});function xh(i,e,t){let r,n,s,o=t?.maxWait?Math.max(t.maxWait,e):0,l=t?.setTimeoutImpl||setTimeout;function a(){return c(),r=i(),r}function c(){n!==void 0&&clearTimeout(n),s!==void 0&&clearTimeout(s),n=s=void 0}function p(){return n!==void 0||s!==void 0?a():r}function d(){return n&&clearTimeout(n),n=l(a,e),o&&s===void 0&&(s=l(a,o)),r}return d.cancel=c,d.flush=p,d}var Ah=w(()=>{});function $l(i){if(Th()||Eh(wI),ma.has(i))return;let e=new Set,t=xh(()=>{let r=[...e];e.clear();for(let n of r)n()},1,{maxWait:100});i.on("flush",()=>{t.flush()}),ma.set(i,r=>{e.add(r),t()})}var ua,Oh,Rh,ma,wI,Nh=w(()=>{Ah();Ih();ua=new WeakSet,Oh=i=>ua.has(i),Rh=i=>{ua.add(i)},ma=new WeakMap;wI={onSegmentSpanEnded(i,e){let t=e.getClient(),r=t&&ma.get(t);if(!r){let n=i();n&&t?.captureEvent(n);return}r(()=>{let n=i({isSpanAlreadyCaptured:Oh,onSpanCaptured:Rh});n&&t.captureEvent(n)})},onChildSpanEnded(i,e,t,r){if(ua.has(i)||!ua.has(e))return;let n=r.getClient(),s=n&&ma.get(n),o=()=>{let l=t({isSpanAlreadyCaptured:Oh,onSpanCaptured:Rh});l?.contexts?.trace?.data&&(l.contexts.trace.data["sentry.parent_span_already_sent"]=!0),l&&n?.captureEvent(l)};s?s(o):o()}}});function SI(i,e){if(!e)return i;let t=i.sdk||{};return i.sdk={...t,name:t.name||e.name,version:t.version||e.version,integrations:[...i.sdk?.integrations||[],...e.integrations||[]],packages:[...i.sdk?.packages||[],...e.packages||[]],settings:i.sdk?.settings||e.settings?{...i.sdk?.settings,...e.settings}:void 0},i}function Ch(i,e,t,r){let n=Cn(t),s={sent_at:new Date($e()).toISOString(),...n&&{sdk:n},...!!r&&e&&{dsn:Be(e)}},o="aggregates"in i?[{type:"sessions"},i]:[{type:"session"},i.toJSON()];return et(s,[o])}function Ph(i,e,t,r){let n=Cn(t),s=i.type&&i.type!=="replay_event"?i.type:"event";SI(i,t?.sdk);let o=ph(i,n,r,e);return delete i.sdkProcessingMetadata,et(o,[[{type:s},i]])}var Dh=w(()=>{Gt();Ht();Rt()});function oi(i){return new ga(e=>{e(i)})}function Rr(i){return new ga((e,t)=>{t(i)})}var Yl,Mh,Lh,ga,Nr=w(()=>{rt();Yl=0,Mh=1,Lh=2;ga=class i{constructor(e){this._state=Yl,this._handlers=[],this._runExecutor(e)}then(e,t){return new i((r,n)=>{this._handlers.push([!1,s=>{if(!e)r(s);else try{r(e(s))}catch(o){n(o)}},s=>{if(!t)n(s);else try{r(t(s))}catch(o){n(o)}}]),this._executeHandlers()})}catch(e){return this.then(t=>t,e)}finally(e){return new i((t,r)=>{let n,s;return this.then(o=>{s=!1,n=o,e&&e()},o=>{s=!0,n=o,e&&e()}).then(()=>{if(s){r(n);return}t(n)})})}_executeHandlers(){if(this._state===Yl)return;let e=this._handlers.slice();this._handlers=[],e.forEach(t=>{t[0]||(this._state===Mh&&t[1](this._value),this._state===Lh&&t[2](this._value),t[0]=!0)})}_runExecutor(e){let t=(s,o)=>{if(this._state===Yl){if(ri(o)){o.then(r,n);return}this._state=s,this._value=o,this._executeHandlers()}},r=s=>{t(Mh,s)},n=s=>{t(Lh,s)};try{e(r,n)}catch(s){n(s)}}}});function qh(i,e,t,r=0,n){try{let s=Kl(e,t,i,r,n);return ri(s)?s:oi(s)}catch(s){return Rr(s)}}function Kl(i,e,t,r,n){let s=t[r];if(!i||!s)return i;let o=`Event processor "${s.id||"?"}"`,l=!1,a=Xi(Q?`${o} threw an error, dropping event:`:"",()=>s({...i},e),()=>(l=!0,null));return Q&&a===null&&Y.log(`${o} dropped event`),ri(a)?a.then(c=>c?Kl(c,e,t,r+1,n):(n?.(l?"callback_error":"event_processor"),null)):a?Kl(a,e,t,r+1,n):(n?.(l?"callback_error":"event_processor"),null)}var Uh=w(()=>{ze();Ve();rt();aa();Nr()});function Fh(i){let e=pe._sentryDebugIds,t=pe._debugIds;if(!e&&!t)return{};let r=e?Object.keys(e):[],n=t?Object.keys(t):[];if(wi&&r.length===jh&&n.length===Bh)return wi;jh=r.length,Bh=n.length,wi={},Zi||(Zi={});let s=(o,l)=>{for(let a of o){let c=l[a],p=Zi?.[a];if(p&&wi&&c)wi[p[0]]=c,Zi&&(Zi[a]=[p[0],c]);else if(c){let d=i(a);for(let g=d.length-1;g>=0;g--){let v=d[g]?.filename;if(v&&wi&&Zi){wi[v]=c,Zi[a]=[v,c];break}}}}};return e&&s(r,e),t&&s(n,t),wi}var Zi,jh,Bh,wi,Gh=w(()=>{xt()});function Dn(i){return i.data?.__sentry__===!0}function Hh(i){let e=[];i.message&&e.push(i.message);try{let t=i.exception.values[i.exception.values.length-1];t?.value&&(e.push(t.value),t.type&&e.push(`${t.type}: ${t.value}`))}catch{}return e}var Ql=w(()=>{});function Wh(i,e,t,r,n,s){let{normalizeDepth:o=3,normalizeMaxBreadth:l=1e3}=i,a={...e,event_id:e.event_id||t.event_id||Me(),timestamp:e.timestamp||zi()},c=t.integrations||i.integrations.map(x=>x.name);EI(a,i),xI(a,c),n&&n.emit("applyFrameMetadata",e),e.type===void 0&&TI(a,i.stackParser);let p=OI(r,t.captureContext);t.mechanism&&Pg(a,t.mechanism);let d=n?n.getEventProcessors():[],g=sa(s,p),b=[...t.attachments||[],...g.attachments];b.length&&(t.attachments=b),Jb(a,g);let v=In(p);v&&Xb(a,v),wh(a,t,p);let y=[...d,...g.eventProcessors],S=e.type==="transaction",T=e.spans?.length||0;return(Dn(t)?oi(a):qh(y,a,t,0,x=>{n&&(n.recordDroppedEvent(x,Pn(e.type)),S&&n.recordDroppedEvent(x,"span",1+T))})).then(x=>{if(!x)return null;if(S&&n){let P=T-(x.spans?.length||0);P>0&&n.recordDroppedEvent("event_processor","span",P)}return II(x),typeof o=="number"&&o>0?AI(x,o,l):x})}function EI(i,e){let{environment:t,release:r,dist:n,maxValueLength:s}=e;i.environment=i.environment||t||vi,!i.release&&r&&(i.release=r),!i.dist&&n&&(i.dist=n);let o=i.request;o?.url&&s&&(o.url=hn(o.url,s)),s&&i.exception?.values?.forEach(l=>{l.value&&(l.value=hn(l.value,s))})}function TI(i,e){let t=Fh(e);i.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.filename&&(n.debug_id=t[n.filename])})})}function II(i){let e={};if(i.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.debug_id&&(n.abs_path?e[n.abs_path]=n.debug_id:n.filename&&(e[n.filename]=n.debug_id),delete n.debug_id)})}),Object.keys(e).length===0)return;i.debug_meta=i.debug_meta||{},i.debug_meta.images=i.debug_meta.images||[];let t=i.debug_meta.images;Object.entries(e).forEach(([r,n])=>{t.push({type:"sourcemap",code_file:r,debug_id:n})})}function xI(i,e){e.length>0&&(i.sdk=i.sdk||{},i.sdk.integrations=[...i.sdk.integrations||[],...e])}function AI(i,e,t){if(!i)return null;let r={...i,...i.breadcrumbs&&{breadcrumbs:i.breadcrumbs.map(n=>({...n,...n.data&&{data:Nt(n.data,e,t)}}))},...i.user&&{user:Nt(i.user,e,t)},...i.contexts&&{contexts:Nt(i.contexts,e,t)},...i.extra&&{extra:Nt(i.extra,e,t)}};return i.contexts?.trace&&r.contexts&&(r.contexts.trace=i.contexts.trace,i.contexts.trace.data&&(r.contexts.trace.data=Nt(i.contexts.trace.data,e,t))),i.spans&&(r.spans=i.spans.map(n=>({...n,...n.data&&{data:Nt(n.data,e,t)}}))),i.contexts?.flags&&r.contexts&&(r.contexts.flags=Nt(i.contexts.flags,3,t)),r}function OI(i,e){if(!e)return i;let t=i?i.clone():new Ze;return t.update(e),t}var zh=w(()=>{xn();Uh();Sr();Gh();Ht();Sh();Ql();ni();Fs();Ul();_i();Gs();Nr();wr()});function NI(i){let e=i.protocol?`${i.protocol}:`:"",t=i.port?`:${i.port}`:"";return`${e}//${i.host}${t}${i.path?`/${i.path}`:""}/api/`}function CI(i){return`${NI(i)}${i.projectId}/envelope/`}function PI(i,e){let t={sentry_version:RI};return i.publicKey&&(t.sentry_key=i.publicKey),e&&(t.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(t).toString()}function Vh(i,e,t){return e||`${CI(i)}?${PI(i,t)}`}var RI,$h=w(()=>{RI="7"});function Yh(i,e){return e?Ks(e,()=>{let t=In(),r=t?ea(t):Qi(e);return[t?ai(t):xr(i,e),r]}):[void 0,void 0]}var Kh=w(()=>{Pt();Ar();_i()});function DI(i,e){let t=e?"auto":"never";return[{type:"log",item_count:i.length,content_type:"application/vnd.sentry.items.log+json"},{version:2,...Or()&&{ingest_settings:{infer_ip:t,infer_user_agent:t}},items:i}]}function Qh(i,e,t,r,n){let s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),t&&r&&(s.dsn=Be(r)),et(s,[DI(i,n)])}var Jh=w(()=>{Gt();Ht();ca()});function Xh(i,e){let t=e??MI(i)??[];if(t.length===0)return;let r=i.getOptions(),n=Qh(t,r._metadata,r.tunnel,i.getDsn(),i.getDataCollectionOptions().userInfo);Zh().set(i,[]),i.emit("flushLogs"),i.sendEnvelope(n)}function MI(i){return Zh().get(i)}function Zh(){return ft("clientToLogBufferMap",()=>new WeakMap)}var ey=w(()=>{_t();Jh()});function LI(i,e){let t=e?"auto":"never";return[{type:"trace_metric",item_count:i.length,content_type:"application/vnd.sentry.items.trace-metric+json"},{version:2,...Or()&&{ingest_settings:{infer_ip:t,infer_user_agent:t}},items:i}]}function ty(i,e,t,r,n){let s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),t&&r&&(s.dsn=Be(r)),et(s,[LI(i,n)])}var iy=w(()=>{Gt();Ht();ca()});function ry(i,e){let t=e??qI(i)??[];if(t.length===0)return;let r=i.getOptions(),n=ty(t,r._metadata,r.tunnel,i.getDsn(),i.getDataCollectionOptions().userInfo);ny().set(i,[]),i.emit("flushMetrics"),i.sendEnvelope(n)}function qI(i){return ny().get(i)}function ny(){return ft("clientToMetricBufferMap",()=>new WeakMap)}var sy=w(()=>{_t();iy()});function ay(i,e){if(i.type!=="transaction"||!i.spans?.length||!i.sdkProcessingMetadata?.hasGenAiSpans||oa(e))return;let t=[],r=[];for(let n of i.spans)n.op?.startsWith("gen_ai.")?t.push(eh(n)):r.push(n);if(t.length!==0)return i.spans=r,zl(t,e)}var oy=w(()=>{Vl();Fl();th()});function Cr(i=100){let e=new Set;function t(){return e.size<i}function r(o){e.delete(o)}function n(o){if(!t())return Rr(Mn);let l=o();return e.add(l),l.then(()=>r(l),()=>r(l)),l}function s(o){if(!e.size)return oi(!0);let l=Promise.allSettled(Array.from(e)).then(()=>!0);if(!o)return l;let a=[l,new Promise(c=>ki(setTimeout(()=>c(!1),o)))];return Promise.race(a)}return{get $(){return Array.from(e)},add:n,drain:s}}var Mn,ba=w(()=>{Nr();Nn();Mn=Symbol.for("SentryBufferFullError")});function jI(i,e=$e()){let t=parseInt(`${i}`,10);if(!isNaN(t))return t*1e3;let r=Date.parse(`${i}`);return isNaN(r)?UI:r-e}function BI(i,e){return i[e]||i.all||0}function ly(i,e,t=$e()){return BI(i,e)>t}function cy(i,{statusCode:e,headers:t},r=$e()){let n={...i},s=t?.["x-sentry-rate-limits"],o=t?.["retry-after"];if(s)for(let l of s.trim().split(",")){let[a,c,,,p]=l.split(":",5),d=parseInt(a,10),g=(isNaN(d)?60:d)*1e3;if(!c)n.all=r+g;else for(let b of c.split(";"))b==="metric_bucket"?(!p||p.split(";").includes("custom"))&&(n[b]=r+g):n[b]=r+g}else o?n.all=r+jI(o,r):e===429&&(n.all=r+60*1e3);return n}var UI,py=w(()=>{Rt();UI=60*1e3});function Jl(i,e,t=Cr(i.bufferSize||Ln)){let r={},n=l=>t.drain(l);function s(l,[a,c],p){let d=Wl(p);p==="transaction"&&i.recordDroppedEvent(l,"span",(c.spans?.length??0)+1),i.recordDroppedEvent(l,d,typeof a.item_count=="number"?a.item_count:1)}function o(l){let a=[];if(la(l,(g,b)=>{ly(r,Wl(b))?s("ratelimit_backoff",g,b):a.push(g)}),a.length===0)return Promise.resolve({});let c=et(l[0],a),p=g=>{if(ah(c,["client_report"])){Q&&Y.warn(`Dropping client report. Will not send outcomes (reason: ${g}).`);return}la(c,(b,v)=>{s(g,b,v)})},d=()=>e({body:oh(c)}).then(g=>g.statusCode===413?(Q&&Y.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),p("send_error"),g):(Q&&g.statusCode!==void 0&&(g.statusCode<200||g.statusCode>=300)&&Y.warn(`Sentry responded with status code ${g.statusCode} to sent event.`),r=cy(r,g),g),g=>{throw p("network_error"),Q&&Y.error("Encountered error running transport request:",g),g});return t.add(d).then(g=>g,g=>{if(g===Mn)return Q&&Y.error("Skipped sending event because buffer is full."),p("queue_overflow"),Promise.resolve({});throw g})}return{send:o,flush:n}}var Ln,ha=w(()=>{ze();Ve();Ht();ba();py();Ln=64});function dy(i,e,t){let r=[{type:"client_report"},{timestamp:t||zi(),discarded_events:i}];return et(e?{dsn:e}:{},[r])}var uy=w(()=>{Ht();wr()});function my(i){let{trace_id:e,parent_span_id:t,span_id:r,status:n,origin:s,data:o,op:l,links:a}=i.contexts?.trace??{};return{data:o??{},description:i.transaction,op:l,parent_span_id:t,span_id:r??"",start_timestamp:i.start_timestamp??0,status:n??"ok",timestamp:i.timestamp,trace_id:e??"",origin:s,links:a,profile_id:o?.[wn],exclusive_time:o?.[wl],measurements:i.measurements,is_segment:!0}}function gy(i){return{type:"transaction",timestamp:i.timestamp,start_timestamp:i.start_timestamp,transaction:i.description,contexts:{trace:{trace_id:i.trace_id,span_id:i.span_id,parent_span_id:i.parent_span_id,op:i.op,status:i.status,origin:i.origin,links:i.links,data:{...i.data,...i.profile_id&&{[wn]:i.profile_id},...i.exclusive_time&&{[wl]:i.exclusive_time}}}},measurements:i.measurements}}var by=w(()=>{yi()});function hy(i){i.traceLifecycle!=="stream"||!(i.beforeSendTransaction||i.ignoreTransactions?.length)||At(()=>{console.warn("[Sentry] `beforeSendTransaction` and `ignoreTransactions` are ignored with `traceLifecycle: 'stream'` (enabled by default). Use `beforeSendSpan` and `ignoreSpans` instead, or set `traceLifecycle: 'static'`.")})}var yy=w(()=>{Ve()});function FI(i){return typeof i=="boolean"||"allow"in i||"deny"in i}function GI(i){return i===void 0?{...Fe.httpHeaders}:FI(i)?{request:i,response:i}:{request:i.request??Fe.httpHeaders.request,response:i.response??Fe.httpHeaders.response}}function fy(i){let e=i.dataCollection??{};return{userInfo:e.userInfo??Fe.userInfo,cookies:e.cookies??Fe.cookies,httpHeaders:GI(e.httpHeaders),httpBodies:e.httpBodies??Fe.httpBodies,urlQueryParams:e.urlQueryParams??Fe.urlQueryParams,graphQL:{document:e.graphQL?.document??Fe.graphQL.document,variables:e.graphQL?.variables??Fe.graphQL.variables},genAI:{inputs:e.genAI?.inputs??Fe.genAI.inputs,outputs:e.genAI?.outputs??Fe.genAI.outputs},mcp:{inputs:e.mcp?.inputs??Fe.mcp.inputs,outputs:e.mcp?.outputs??Fe.mcp.outputs},databaseQueryData:e.databaseQueryData??Fe.databaseQueryData,queues:e.queues??Fe.queues,stackFrameVariables:e.stackFrameVariables??Fe.stackFrameVariables,frameContextLines:e.frameContextLines??Fe.frameContextLines}}var Fe,_y=w(()=>{Fe={userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},mcp:{inputs:!0,outputs:!0},databaseQueryData:!0,queues:!0,stackFrameVariables:!0,frameContextLines:5}});function wy(i){return{message:i,[Ay]:!0}}function Xl(i){return{message:i,[Oy]:!0}}function Sy(i){return Xl(`Discarding event because it's not included in the random sample (sampling rate = ${i})`)}function Ey(i){return gn(i)&&Ay in i}function Ty(i){return gn(i)&&Oy in i}function Iy(i,e,t,r,n){let s=0,o,l=!1;i.on(t,()=>{s=0,clearTimeout(o),l=!1}),i.on(e,a=>{if(s+=r(a),s>=8e5)n(i);else if(!l){let c=i.getOptions()._flushInterval??HI;c>0&&(l=!0,o=ki(setTimeout(()=>{n(i)},c)))}}),i.on("flush",()=>{n(i)})}function zI(i,e,t,r,n){let{beforeSend:s,ignoreSpans:o,beforeSendTransaction:l}=i,a=On(i.beforeSendSpan)&&i.beforeSendSpan,c=e;if(Zl(c)&&s){let p=c;return Xi(Q?"The `beforeSend` callback threw an error, dropping the event:":"",()=>s(p,t),()=>(r("callback_error"),null))}if(Ry(c)){if(a||o){let p=my(c);if(o?.length&&Dl({description:p.description,op:p.op,attributes:p.data},o))return r("ignored"),null;if(a){let d=Rn(p,a);c=hi(e,gy(d))}if(c.spans){let d=[],g=c.spans;for(let b of g){if(o?.length&&Dl({description:b.description,op:b.op,attributes:b.data},o)){Gb(g,b);continue}a?d.push(Rn(b,a)):d.push(b)}n(g.length-d.length),c.spans=d}}if(l)return Xi(Q?"The `beforeSendTransaction` callback threw an error, dropping the event:":"",()=>l(c,t),()=>(r("callback_error"),null))}return c}function Zl(i){return i.type===void 0}function Ry(i){return i.type==="transaction"}function VI(i){let e=0;return i.name&&(e+=i.name.length*2),e+=8,e+Ny(i.attributes)}function $I(i){let e=0;return i.message&&(e+=i.message.length*2),e+Ny(i.attributes)}function Ny(i){if(!i)return 0;let e=0;return Object.values(i).forEach(t=>{Array.isArray(t)?e+=t.length*xy(t[0]):ii(t)?e+=xy(t):e+=100}),e}function xy(i){return typeof i=="string"?i.length*2:typeof i=="number"?8:typeof i=="boolean"?4:0}var vy,ky,Ay,Oy,HI,WI,ya,Cy=w(()=>{$h();xn();Pt();ze();Dh();Vb();ey();sy();gl();Ar();jl();oy();ha();uy();Ve();Gt();Ht();Ql();rt();Vs();ni();Nb();zh();ba();Rt();aa();Hb();Nr();Nn();by();yy();_y();vy="Not capturing exception because it's already been captured.",ky="Discarded session because of missing or non-string release",Ay=Symbol.for("SentryInternalError"),Oy=Symbol.for("SentryDoNotSendEventError"),HI=5e3,WI=Symbol.for("SentryClosedClient");ya=class{constructor(e){this._options={attachStacktrace:!0,...e,traceLifecycle:e.traceLifecycle==="static"?"static":"stream"},this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=Cr(e.transportOptions?.bufferSize??Ln),this._dataCollection=fy(e),this._unhandledSessionStatus="crashed",this._attachStacktraceIsDefault=e.attachStacktrace===void 0,e.dsn?this._dsn=En(e.dsn):Q&&Y.warn("No DSN provided, client will not send events.");let{beforeSendSpan:t,traceLifecycle:r}=this._options;if(Q&&t&&On(t)!==(r==="static")&&At(()=>{console.warn(`Ignoring \`beforeSendSpan\`: ${r==="static"?"wrap it with":"remove"} \`Sentry.withStaticSpan\` to use it with \`traceLifecycle: "${r}"\`.`)}),this._dsn){let n=Vh(this._dsn,e.tunnel,e._metadata?e._metadata.sdk:void 0);this._transport=e.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:n})}Iy(this,"afterCaptureLog","flushLogs",$I,Xh),Iy(this,"afterCaptureMetric","flushMetrics",VI,ry)}captureException(e,t,r){let n=Me();if(Ws(e))return Q&&Y.log(vy),n;let s={event_id:n,...t};return this._process(()=>this.eventFromException(e,s).then(o=>this._captureEvent(o,s,r)).then(o=>o),"error"),s.event_id}captureMessage(e,t,r,n){let s={event_id:Me(),...r},o=mn(e)?e:String(e),l=ii(e),a=l?this.eventFromMessage(o,t,s).then(c=>(c.exception&&this._attachStacktraceIsDefault&&(c.sdkProcessingMetadata={...c.sdkProcessingMetadata,hasDefaultSyntheticStacktrace:!0}),c)):this.eventFromException(e,s);return this._process(()=>a.then(c=>this._captureEvent(c,s,n)),l?"unknown":"error"),s.event_id}captureEvent(e,t,r){let n=Me();if(t?.originalException&&Ws(t.originalException))return Q&&Y.log(vy),n;let s={event_id:n,...t},o=e.sdkProcessingMetadata||{},l=o.capturedSpanScope,a=o.capturedSpanIsolationScope,c=Pn(e.type);return this._process(()=>this._captureEvent(e,s,l||r,a),c),s.event_id}captureSession(e){this.sendSession(e),fn(e,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getDataCollectionOptions(){return this._dataCollection}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(e){let t=this._transport;if(this.emit("flush"),!t)return!0;let r=await this._isClientDoneProcessing(e),n=await t.flush(e);return r&&n}async close(e){Object.defineProperty(this,WI,{value:!0});let t=await this.flush(e);return this.getOptions().enabled=!1,this.emit("close"),t}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some(({name:e})=>e.startsWith("Spotlight")))&&(this._setupIntegrations(),hy(this._options))}getIntegrationByName(e){return this._integrations[e]}getIntegrationNames(){return Object.keys(this._integrations)}addIntegration(e){let t=this._integrations[e.name];!t&&e.beforeSetup&&e.beforeSetup(this),Ll(this,e,this._integrations),t||Ml(this,[e])}sendEvent(e,t={}){this.emit("beforeSendEvent",e,t);let r=ay(e,this),n=Ph(e,this._dsn,this._options._metadata,this._options.tunnel);if(!Dn(t))for(let s of t.attachments||[])n=Hl(n,lh(s));r&&(n=Hl(n,r)),this.sendEnvelope(n).then(s=>this.emit("afterSendEvent",e,s))}sendSession(e){let{release:t,environment:r=vi}=this._options;if("aggregates"in e){let s=e.attrs||{};if(!s.release&&!t){Q&&Y.warn(ky);return}s.release=s.release||t,s.environment=s.environment||r,e.attrs=s}else{if(!e.release&&!t){Q&&Y.warn(ky);return}e.release=e.release||t,e.environment=e.environment||r}this.emit("beforeSendSession",e);let n=Ch(e,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(n)}recordDroppedEvent(e,t,r=1){if(this._options.sendClientReports){let n=`${e}:${t}`;Q&&Y.log(`Recording outcome: "${n}"${r>1?` (${r} times)`:""}`),this._outcomes[n]=(this._outcomes[n]||0)+r}}on(e,t){let r=this._hooks[e]=this._hooks[e]||new Set,n=(...s)=>t(...s);return r.add(n),()=>{r.delete(n)}}emit(e,...t){let r=this._hooks[e];r&&r.forEach(n=>n(...t))}async sendEnvelope(e){if(this.emit("beforeEnvelope",e),this._isEnabled()&&this._transport)try{let t=await this._transport.send(e);return this.emit("afterEnvelope",e),t}catch(t){return Q&&Y.error("Error while sending envelope:",t),{}}return Q&&Y.error("Transport disabled"),{}}registerCleanup(e){}dispose(){}_setupIntegrations(){let{integrations:e}=this._options;this._integrations=zb(this,e),Ml(this,e)}_updateSessionFromEvent(e,t){let r=t.level==="fatal",n=!1,s=t.exception?.values;if(s){n=!0,r=!1;for(let a of s)if(a.mechanism?.handled===!1){r=!0;break}}let o=e.status==="ok";(o&&e.errors===0||o&&r)&&(fn(e,{...r&&{status:this._unhandledSessionStatus},errors:e.errors||Number(n||r)}),this.captureSession(e))}async _isClientDoneProcessing(e){let t=0;for(;!e||t<e;){if(await new Promise(r=>setTimeout(r,1)),!this._numProcessing)return!0;t++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(e,t,r,n){let s=this.getOptions(),o=this.getIntegrationNames();return!t.integrations&&o.length&&(t.integrations=o),this.emit("preprocessEvent",e,t),e.type||n.setLastEventId(e.event_id||t.event_id),Wh(s,e,t,r,this,n).then(l=>{if(l===null)return l;this.emit("postprocessEvent",l,t),l.contexts={trace:{...l.contexts?.trace,...Qi(r)},...l.contexts};let a=xr(this,r);return l.sdkProcessingMetadata={dynamicSamplingContext:a,...l.sdkProcessingMetadata},l})}_captureEvent(e,t={},r=si(),n=Ki()){return Q&&Zl(e)&&Y.log(`Captured error event \`${Hh(e)[0]||"<unknown>"}\``),this._processEvent(e,t,r,n).then(s=>s.event_id,s=>{Q&&(Ty(s)?Y.log(s.message):Ey(s)?Y.warn(s.message):Y.warn(s))})}_processEvent(e,t,r,n){let s=this.getOptions(),{sampleRate:o}=s,l=Ry(e),a=Zl(e),p=`before send for type \`${e.type||"error"}\``,d="before_send",g=0,b=typeof o>"u"?void 0:Rb(o),v=a&&typeof b=="number"&&vt()>b,y=Pn(e.type),S=0,T=r.getSession()||n.getSession();return v&&T?.status!=="ok"?(this.recordDroppedEvent("sample_rate","error"),Rr(Sy(o))):this._prepareEvent(e,t,r,n).then(I=>{if(I===null)throw Xl("An event processor returned `null`, will not send event.");return S=I.spans?.length||0,Dn(t)?I:zI(s,I,t,x=>{d=x},x=>{g=x})}).then(I=>{if(g&&this.recordDroppedEvent("ignored","span",g),!_r(I)||I===null){if(this.recordDroppedEvent(d,y),l&&this.recordDroppedEvent(d,"span",1+S-g),I!==null)throw wy(`${p} must return \`null\` or a valid event.`);let U=d==="ignored"?"Transaction matched `ignoreSpans`":`${p} ${d==="callback_error"?"threw an error":"returned `null`"}`;throw Xl(`${U}, will not send event.`)}if(a&&T&&this._updateSessionFromEvent(T,I),v)throw this.recordDroppedEvent("sample_rate","error"),Sy(o);if(l){let U=S-g-(I.spans?.length||0);U>0&&this.recordDroppedEvent("before_send","span",U)}let P=I.transaction_info;if(l&&P&&I.transaction!==e.transaction){let U="custom";I.transaction_info={...P,source:U}}return this.sendEvent(I,t),I}).then(null,I=>{throw Ty(I)||Ey(I)?I:(this.captureException(I,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:I}),wy(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
5
- Reason: ${I}`))})}_process(e,t){this._numProcessing++,this._promiseBuffer.add(e).then(r=>(this._numProcessing--,r),r=>(this._numProcessing--,r===Mn&&this.recordDroppedEvent("queue_overflow",t),r))}_clearOutcomes(){let e=this._outcomes;return this._outcomes={},Object.entries(e).map(([t,r])=>{let[n,s]=t.split(":");return{reason:n,category:s,quantity:r}})}_flushOutcomes(){Q&&Y.log("Flushing outcomes...");let e=this._clearOutcomes();if(e.length===0){Q&&Y.log("No outcomes to send");return}if(!this._dsn){Q&&Y.log("No dsn provided, will not send outcomes");return}Q&&Y.log("Sending outcomes:",e);let t=dy(e,this._options.tunnel&&Be(this._dsn));this.sendEnvelope(t)}}});function ec(){YI.clear(),Q&&Y.log("Cleared AI provider skip registrations")}var YI,Py=w(()=>{ze();Ve();YI=new Set});function Dy(i,e,t,r,n){let s={sent_at:new Date($e()).toISOString()};t?.sdk&&(s.sdk={name:t.sdk.name,version:t.sdk.version}),r&&n&&(s.dsn=Be(n)),e&&(s.trace=e);let o=KI(i);return et(s,[o])}function KI(i){return[{type:"check_in"},i]}var My=w(()=>{Gt();Ht();Rt()});function tc(i){return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var Ly=w(()=>{});function qy(i,e,t){let r=ex(e.allowedDsns,i.getDsn()),n={paths:ZI(e,r),basePath:e.basePath,allowedDsns:r,forward:t};return QI.set(i,n),n}function Uy(i){return i.getIntegrationByName?.(JI)?.forward}function XI(i){let e=i?En(i):Ft()?.getDsn();return e?`/${tx(Be(e)).toString(36)}`:void 0}function ZI(i,e){let t=i.path?.replace(/\/$/,"");if(t)return[t];let r=e.map(n=>XI(n));return[...new Set(r.filter(n=>!!n))]}function jy(i,e){if(!e.length)return[];let r=`${tc(ic(i.basePath))}(?:${e.map(tc).join("|")})/?`;return[{attributes:{[gb]:new RegExp(`^${r}$`)}},{attributes:{"http.url":new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${r}(?:[?#].*)?$`)}}]}function ic(i){let e=(i?.startsWith("./")?i.slice(1):i??"").replace(/\/$/,"");return!e||e.startsWith("/")?e:`/${e}`}function ex(i,e){let t=new Set;for(let r of[...(i??[]).map(n=>En(n)),e])r&&t.add(Be(r));return[...t]}function tx(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var QI,JI,By=w(()=>{Pt();yi();Ly();Gt();QI=new WeakMap,JI="ServeTunnel"});function rc(i,e,t=[e],r="npm"){let n=(i._metadata=i._metadata||{}).sdk=i._metadata.sdk||{};n.name||(n.name=`sentry.javascript.${e}`,n.packages=t.map(s=>({name:`${r}:@sentry/${s}`,version:yt})),n.version=yt)}var Fy=w(()=>{Ls()});function nc(i){return Array.from(new Set(i))}var Gy=w(()=>{});function Hy(i,e,t,r,n,s){if(!n.exception?.values||!s||!Ot(s.originalException))return;let o=n.exception.values.length>0?n.exception.values[n.exception.values.length-1]:void 0;o&&(n.exception.values=fa(i,e,r,s.originalException,t,n.exception.values,o,0))}function fa(i,e,t,r,n,s,o,l){if(s.length>=t+1)return s;let a=[...s];if(Ot(r[n])){sc(o,l,r);let c=i(e,r[n]),p=a.length;ac(c,n,p,l),a=fa(i,e,t,r[n],n,[c,...a],c,p)}return Wy(r)&&r.errors.forEach((c,p)=>{if(a.length<t+1&&Ot(c)){sc(o,l,r);let d=i(e,c),g=a.length;ac(d,`errors[${p}]`,g,l),a=fa(i,e,t,c,n,[d,...a],d,g)}}),ix(r)&&["error","suppressed"].forEach(c=>{let p=r[c];if(a.length<t+1&&Ot(p)){sc(o,l,r);let d=i(e,p),g=a.length;ac(d,c,g,l),a=fa(i,e,t,p,n,[d,...a],d,g)}}),a}function Wy(i){return Array.isArray(i.errors)}function ix(i){return"error"in i&&"suppressed"in i}function sc(i,e,t){i.mechanism={handled:!0,type:"auto.core.linked_errors",...Wy(t)&&{is_exception_group:!0},...i.mechanism,exception_id:e}}function ac(i,e,t,r){i.mechanism={handled:!0,...i.mechanism,type:"chained",source:e,exception_id:t,parent_id:r}}var zy=w(()=>{rt()});function Vy(i,e){return i(e.stack||"",1)}function rx(i){return Ot(i)&&"__sentry_fetch_url_host__"in i&&typeof i.__sentry_fetch_url_host__=="string"}function nx(i){return rx(i)?`${i.message} (${i.__sentry_fetch_url_host__})`:i.message}function oc(i,e){let t={type:e.name||e.constructor.name,value:nx(e)},r=Vy(i,e);return r.length&&(t.stacktrace={frames:r}),t}function sx(i){for(let e in i)if(Object.prototype.hasOwnProperty.call(i,e)){let t=i[e];if(Ot(t))return t}}function ax(i){if("name"in i&&typeof i.name=="string"){let r=`'${i.name}' captured as exception`;return"message"in i&&typeof i.message=="string"&&(r+=` with message '${i.message}'`),r}else if("message"in i&&typeof i.message=="string")return i.message;let e=Ag(i);if(Sg(i))return`Event \`ErrorEvent\` captured as exception with message \`${i.message}\``;let t=ox(i);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${e}`}function ox(i){try{let e=Object.getPrototypeOf(i);return e?e.constructor.name:void 0}catch{}}function lx(i,e,t,r){if(Ot(t))return[t,void 0];if(e.synthetic=!0,_r(t)){let s=i?.getOptions().normalizeDepth,o={__serialized__:cl(t,s)},l=sx(t);if(l)return[l,o];let a=ax(t),c=r?.syntheticException||new Error(a);return c.message=a,[c,o]}let n=r?.syntheticException||new Error(t);return n.message=`${t}`,[n,void 0]}function $y(i,e,t,r){let s=r?.data&&r.data.mechanism||{handled:!0,type:"generic"},[o,l]=lx(i,s,t,r),a={exception:{values:[oc(e,o)]}};return l&&(a.extra=l),ul(a,void 0,void 0),Hs(a,s),{...a,event_id:r?.event_id}}function Yy(i,e,t="info",r,n){let s={event_id:r?.event_id,level:t};if(n&&r?.syntheticException){let o=Vy(i,r.syntheticException);o.length&&(s.exception={values:[{value:e,stacktrace:{frames:o}}]},Hs(s,{synthetic:!0}))}if(mn(e)){let{__sentry_template_string__:o,__sentry_template_values__:l}=e;return s.logentry={message:o,params:l},s}return s.message=e,s}var lc=w(()=>{rt();ni();Fs();bn()});var cx,px,dx,ux,cc,Ky=w(()=>{zy();lc();cx="cause",px=5,dx="LinkedErrors",ux=((i={})=>{let e=i.limit||px,t=i.key||cx;return{name:dx,preprocessEvent(r,n,s){let o=s.getOptions();Hy(oc,o.stackParser,t,e,r,n)}}}),cc=ux});function gx(i){let e=i.length>1024?`<truncated>${i.slice(-1024)}`:i,t=mx.exec(e);return t?t.slice(1):[]}function pc(i){let e=gx(i),t=e[0]||"",r=e[1];return!t&&!r?".":(r&&(r=r.slice(0,r.length-1)),t+r)}var mx,Qy=w(()=>{mx=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/});var Wt=w(()=>{Nh();Ar();Pt();bl();$s();_t();Sr();ha();Py();Rl();Fy();Gy();Qs();Ky();xt();Ve();ni();Qy();Us();Cb();Al();vn();Ls();Rt()});function Xy(i){let e=i._metadata?.sdk,t=e?.name&&e?.version?`${e?.name}/${e?.version}`:void 0;i.transportOptions={...i.transportOptions,headers:{...t&&{"user-agent":t},...i.transportOptions?.headers}}}var Zy=w(()=>{});function tf(i){let e=i?.getOptions(),t=e?._managedTunnel??dc?.tunnel,r=i&&(yx.get(i)??Uy(i)??dc?.forward);if(!i||!e||!t||!r)return;let n=ic(dc?.basePath),s=t.basePath===void 0&&!t.path&&n?{...t,basePath:n}:t;e._managedTunnel=s;let{paths:o}=qy(i,s,r),l=ef.get(i)??[],a=jy(s,o);e.ignoreSpans=[...(e.ignoreSpans??[]).filter(c=>!l.includes(c)),...a],ef.set(i,a)}var dc,yx,ef,rf=w(()=>{By();yx=new WeakMap,ef=new WeakMap});function nf(i){let e=Ki().getScopeData().sdkProcessingMetadata.requestSession;if(e){let t=i?.mechanism?.handled??!0;t&&e.status!=="crashed"?e.status="errored":t||(e.status="crashed")}}var qn,sf=w(()=>{yi();My();Cy();Pt();ze();kh();ha();Zy();Ve();lc();ni();ba();Nr();Kh();rf();qn=class extends ya{constructor(e){Xy(e),(typeof __SENTRY_TRACING__>"u"||__SENTRY_TRACING__)&&e.traceLifecycle!=="static"&&!e.integrations.some(t=>t.name===da)&&e.integrations.push(vh()),super(e),this._disposeCallbacks=[],tf(this),this._setUpMetricsProcessing()}eventFromException(e,t){let r=$y(this,this._options.stackParser,e,t);return r.level="error",oi(r)}eventFromMessage(e,t="info",r){return oi(Yy(this._options.stackParser,e,t,r,this._options.attachStacktrace))}captureException(e,t,r){return nf(t),super.captureException(e,t,r)}captureEvent(e,t,r){return!e.type&&e.exception?.values&&e.exception.values.length>0&&nf(t),super.captureEvent(e,t,r)}captureCheckIn(e,t,r){let n="checkInId"in e&&e.checkInId?e.checkInId:Me();if(!this._isEnabled())return Q&&Y.warn("SDK not enabled, will not capture check-in."),n;let s=this.getOptions(),{release:o,environment:l,tunnel:a}=s,c={check_in_id:n,monitor_slug:e.monitorSlug,status:e.status,release:o,environment:l};"duration"in e&&(c.duration=e.duration),t&&(c.monitor_config={schedule:t.schedule,checkin_margin:t.checkinMargin,max_runtime:t.maxRuntime,timezone:t.timezone,failure_issue_threshold:t.failureIssueThreshold,recovery_threshold:t.recoveryThreshold});let[p,d]=Yh(this,r);d&&(c.contexts={trace:d});let g=Dy(c,p,this.getSdkMetadata(),a,this.getDsn());return Q&&Y.log("Sending checkin:",e.monitorSlug,e.status),this.sendEnvelope(g),n}registerCleanup(e){this._disposeCallbacks.push(e)}dispose(){Q&&Y.log("Disposing client...");for(let e of this._disposeCallbacks)try{e()}catch{}this._disposeCallbacks.length=0;for(let e of Object.keys(this._hooks))this._hooks[e]?.clear();this._hooks={},this._eventProcessors.length=0,this._integrations={},this._outcomes={},this._transport=void 0,this._promiseBuffer=Cr(Ln)}_prepareEvent(e,t,r,n){return this._options.platform&&(e.platform=e.platform||this._options.platform),this._options.runtime&&(e.contexts={...e.contexts,runtime:e.contexts?.runtime||this._options.runtime}),this._options.serverName&&(e.server_name=e.server_name||this._options.serverName),super._prepareEvent(e,t,r,n)}_setUpMetricsProcessing(){this.on("processMetric",e=>{this._options.serverName&&(e.attributes={[ub]:this._options.serverName,...e.attributes})})}}});function of(i,e=!1){return!(e||i&&!i.startsWith("/")&&!i.match(/^[A-Z]:/)&&!i.startsWith(".")&&!i.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&i!==void 0&&!i.includes("node_modules/")}function lf(i){let e=/^\s*[-]{4,}$/,t=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,r=/at (?:async )?(.+?) \(data:(.*?),/;return n=>{let s=n.match(r);if(s)return{filename:`<data:${s[2]}>`,function:s[1]};let o=n.match(t);if(o){let l,a,c,p,d;if(o[1]){c=o[1];let y=c.lastIndexOf(".");if(c[y-1]==="."&&y--,y>0){l=c.slice(0,y),a=c.slice(y+1);let S=l.indexOf(".Module");S>0&&(c=c.slice(S+1),l=l.slice(0,S))}p=void 0}a&&(p=l,d=a),a==="<anonymous>"&&(d=void 0,c=void 0),c===void 0&&(d=d||"?",c=p?`${p}.${d}`:d);let g=kg(o[2]),b=o[5]==="native";!g&&o[5]&&!b&&(g=o[5]);let v=g?fx(g):void 0;return{filename:v??g,module:v&&i?.(v),function:c,lineno:af(o[3]),colno:af(o[4]),in_app:of(g||"",b)}}if(n.match(e))return{filename:n}}}function uc(i){return[90,lf(i)]}function af(i){return parseInt(i||"",10)||void 0}function fx(i){try{return decodeURI(i)}catch{return}}var cf=w(()=>{Us()});var mc=w(()=>{sf();cf()});var Si,gc=w(()=>{Si="1.10.0"});function _x(i){let e=new Set([i]),t=new Set,r=i.match(pf);if(!r)return()=>!1;let n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null)return function(a){return a===i};function s(l){return t.add(l),!1}function o(l){return e.add(l),!0}return function(a){if(e.has(a))return!0;if(t.has(a))return!1;let c=a.match(pf);if(!c)return s(a);let p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||n.major!==p.major?s(a):n.major===0?n.minor===p.minor&&n.patch<=p.patch?o(a):s(a):n.minor<=p.minor?o(a):s(a)}}var pf,df,uf=w(()=>{gc();pf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;df=_x(Si)});function kx(){return Object.defineProperty({},"version",{value:Si,enumerable:!0,writable:!1,configurable:!1})}function Pr(i,e,t,r=!1){var n;let s=va[_a]=(n=va[_a])!==null&&n!==void 0?n:kx();if(!r&&s[i]){let o=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${i}`);return t.error(o.stack||o.message),!1}if(s.version!=="1.10.0"){let o=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${i} does not match previously registered API v${Si}`);return t.error(o.stack||o.message),!1}return s[i]=e,t.debug(`@opentelemetry/api: Registered a global for ${i} v${Si}.`),!0}function li(i){let e=va[_a];if(e!=null){if(e!==mf){if(!e.version||!df(e.version))return;mf=e}return e[i]}}function Dr(i,e){e.debug(`@opentelemetry/api: Unregistering a global for ${i} v${Si}.`);let t=va[_a];t&&delete t[i]}var vx,_a,va,mf,Un=w(()=>{gc();uf();vx=Si.split(".")[0],_a=Symbol.for(`opentelemetry.js.api.${vx}`),va=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function jn(i,e,t){let r=li("diag");if(r)return r[i](e,...t)}var gf,bf=w(()=>{Un();gf=class{constructor(i){this._namespace=i.namespace||"DiagComponentLogger"}debug(...i){return jn("debug",this._namespace,i)}error(...i){return jn("error",this._namespace,i)}info(...i){return jn("info",this._namespace,i)}warn(...i){return jn("warn",this._namespace,i)}verbose(...i){return jn("verbose",this._namespace,i)}}});function hf(i,e){i<0?i=0:i>9999&&(i=9999),e=e||{};function t(r,n){let s=e[r];return typeof s=="function"&&i>=n?s.bind(e):function(){}}return{error:t("error",30),warn:t("warn",50),info:t("info",60),debug:t("debug",70),verbose:t("verbose",80)}}var yf=w(()=>{});var wx,er,bc=w(()=>{Un();bf();yf();wx="diag",er=class ff{static instance(){return this._instance||(this._instance=new ff),this._instance}constructor(){function e(n){return function(...s){let o=li("diag");if(o)return o[n](...s)}}let t=this,r=(n,s={logLevel:60})=>{var o;if(n===t){var l;let d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((l=d.stack)!==null&&l!==void 0?l:d.message),!1}typeof s=="number"&&(s={logLevel:s});let a=li("diag"),c=hf((o=s.logLevel)!==null&&o!==void 0?o:60,n);if(a&&!s.suppressOverrideMessage){var p;let d=(p=new Error().stack)!==null&&p!==void 0?p:"<failed to generate stacktrace>";a.warn(`Current logger will be overwritten from ${d}`),c.warn(`Current logger will overwrite one already registered from ${d}`)}return Pr("diag",c,t,!0)};t.setLogger=r,t.disable=()=>{Dr(wx,t)},t.createComponentLogger=n=>new gf(n),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}});function ci(i){return Symbol.for(i)}var Bn,ka=w(()=>{Bn=new class hc{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=r=>t._currentContext.get(r),t.setValue=(r,n)=>{let s=new hc(t._currentContext);return s._currentContext.set(r,n),s},t.deleteValue=r=>{let n=new hc(t._currentContext);return n._currentContext.delete(r),n}}}});var yc,_f=w(()=>{yc=(function(i){return i[i.NONE=0]="NONE",i[i.SAMPLED=1]="SAMPLED",i})({})});var Sx,Ex,vf,kf=w(()=>{Sx="0000000000000000",Ex="00000000000000000000000000000000",vf={traceId:Ex,spanId:Sx,traceFlags:0}});var Ei,wa=w(()=>{kf();Ei=class{constructor(i=vf){this._spanContext=i}spanContext(){return this._spanContext}setAttribute(i,e){return this}setAttributes(i){return this}addEvent(i,e){return this}addLink(i){return this}addLinks(i){return this}setStatus(i){return this}updateName(i){return this}end(i){}isRecording(){return!1}recordException(i,e){}}});function wf(i,e){if(typeof i!="string"||i.length!==e)return!1;let t=0;for(let r=0;r<i.length;r+=4)t+=(Sa[i.charCodeAt(r)]|0)+(Sa[i.charCodeAt(r+1)]|0)+(Sa[i.charCodeAt(r+2)]|0)+(Sa[i.charCodeAt(r+3)]|0);return t===e}function Sf(i){return wf(i,32)&&i!=="00000000000000000000000000000000"}function Ef(i){return wf(i,16)&&i!=="0000000000000000"}function tr(i){return Sf(i.traceId)&&Ef(i.spanId)}function Tf(i){return new Ei(i)}var Sa,Ea=w(()=>{wa();Sa=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});var If,xf=w(()=>{ka();If=class{active(){return Bn}with(i,e,t,...r){return e.call(t,...r)}bind(i,e){return e}enable(){return this}disable(){return this}attach(i){return{dispose(){}}}}});var fc,Tx,Ix,Mr,Ta=w(()=>{Un();bc();xf();fc="context",Tx=new If,Ix=Object.freeze({dispose:()=>{}}),Mr=class Af{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new Af),this._instance}setGlobalContextManager(e){return Pr(fc,e,er.instance())}active(){return this._getContextManager().active()}with(e,t,r,...n){return this._getContextManager().with(e,t,r,...n)}bind(e,t){return this._getContextManager().bind(e,t)}attach(e){let t=this._getContextManager();return t.attach?t.attach(e):(this._attachUnsupportedWarned||(this._attachUnsupportedWarned=!0,er.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.")),Ix)}_getContextManager(){return li(fc)||Tx}disable(){this._getContextManager().disable(),Dr(fc,er.instance())}}});function Ia(i){return i.getValue(_c)||void 0}function Of(){return Ia(Mr.getInstance().active())}function Fn(i,e){return i.setValue(_c,e)}function Rf(i){return i.deleteValue(_c)}function Nf(i,e){return Fn(i,new Ei(e))}function xa(i){var e;return(e=Ia(i))===null||e===void 0?void 0:e.spanContext()}var _c,vc=w(()=>{ka();Ta();wa();_c=ci("OpenTelemetry Context Key SPAN")});function xx(i){return i!==null&&typeof i=="object"&&"spanId"in i&&typeof i.spanId=="string"&&"traceId"in i&&typeof i.traceId=="string"&&"traceFlags"in i&&typeof i.traceFlags=="number"}var kc,Aa,wc=w(()=>{Ta();wa();vc();Ea();kc=Mr.getInstance(),Aa=class{startSpan(i,e,t=kc.active()){if(e?.root)return new Ei;let r=t&&xa(t);return xx(r)&&tr(r)?new Ei(r):new Ei}startActiveSpan(i,e,t,r){var n;let s,o,l;if(arguments.length<2)return;arguments.length===2?l=e:arguments.length===3?(s=e,l=t):(s=e,o=t,l=r);let a=(n=o)!==null&&n!==void 0?n:kc.active(),c=this.startSpan(i,s,a),p=Fn(a,c);return kc.with(p,l,void 0,c)}}});var Ax,Cf,Pf=w(()=>{wc();Ax=new Aa,Cf=class{constructor(i,e,t,r){this._provider=i,this.name=e,this.version=t,this.options=r}startSpan(i,e,t){return this._getTracer().startSpan(i,e,t)}startActiveSpan(i,e,t,r){let n=this._getTracer();return Reflect.apply(n.startActiveSpan,n,arguments)}_getTracer(){if(this._delegate)return this._delegate;let i=this._provider.getDelegateTracer(this.name,this.version,this.options);return i?(this._delegate=i,this._delegate):Ax}}});var Df,Mf=w(()=>{wc();Df=class{getTracer(i,e,t){return new Aa}}});var Ox,Sc,Lf=w(()=>{Pf();Mf();Ox=new Df,Sc=class{getTracer(i,e,t){var r;return(r=this.getDelegateTracer(i,e,t))!==null&&r!==void 0?r:new Cf(this,i,e,t)}getDelegate(){var i;return(i=this._delegate)!==null&&i!==void 0?i:Ox}setDelegate(i){this._delegate=i}getDelegateTracer(i,e,t){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(i,e,t)}}});var Ye,qf=w(()=>{Ta();Ye=Mr.getInstance()});var Ec,Uf,Bf=w(()=>{Un();bc();vc();Ea();Lf();Ec="trace",Uf=class jf{constructor(){this._proxyTracerProvider=new Sc,this.wrapSpanContext=Tf,this.isSpanContextValid=tr,this.deleteSpan=Rf,this.getSpan=Ia,this.getActiveSpan=Of,this.getSpanContext=xa,this.setSpan=Fn,this.setSpanContext=Nf}static getInstance(){return this._instance||(this._instance=new jf),this._instance}setGlobalTracerProvider(e){let t=Pr(Ec,this._proxyTracerProvider,er.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return li(Ec)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){Dr(Ec,er.instance()),this._proxyTracerProvider=new Sc}}});var Ti,Ff=w(()=>{Bf();Ti=Uf.getInstance()});var Oa=w(()=>{ka();_f();Ea();qf();Ff()});import{AsyncLocalStorage as Nx}from"node:async_hooks";function Tc(){let e=Ct(Pe()).getTracingChannelBinding?.()?.asyncLocalStorage??new Nx;function t(){let l=e.getStore();return l||{scope:$i(),isolationScope:Yi()}}function r(l){let a=t().scope.clone(),c=t().isolationScope;return e.run({scope:a,isolationScope:c},()=>l(a))}function n(l,a){let c=t().isolationScope;return e.run({scope:l,isolationScope:c},()=>a(l))}function s(l){let a=t().scope.clone(),c=t().isolationScope.clone();return Tn(a.getPropagationContext())||a.setPropagationContext({traceId:Vi(),sampleRand:vt()}),e.run({scope:a,isolationScope:c},()=>l(c))}function o(l,a){let c=t().scope.clone();return e.run({scope:c,isolationScope:l},()=>a(l))}return kn({withScope:r,withSetScope:n,withIsolationScope:s,withSetIsolationScope:o,getCurrentScope:()=>t().scope,getIsolationScope:()=>t().isolationScope,getTracingChannelBinding:()=>({asyncLocalStorage:e})}),e}var Gf=w(()=>{Wt()});function z(i){return[...new Set(i.map(e=>e.module.name))]}var le=w(()=>{});var Ic,R6,Hf=w(()=>{le();Ic=[{channelName:"send",module:{name:"@smithy/core",versionRange:">=3.24.0 <4",filePath:"dist-cjs/submodules/client/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@smithy/smithy-client",versionRange:">=1.0.3 <5",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@aws-sdk/smithy-client",versionRange:"^3.1.0",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}}],R6=z(Ic)});var Dt,xc,P6,Wf=w(()=>{le();Dt={name:"amqplib",versionRange:">=0.5.5 <3"},xc=[...["lib/channel_model.js","lib/callback_model.js"].flatMap(i=>[{channelName:"publish",module:{...Dt,filePath:i},functionQuery:{className:"Channel",methodName:"publish",kind:"Sync"}},{channelName:"confirmPublish",module:{...Dt,filePath:i},functionQuery:{className:"ConfirmChannel",methodName:"publish",kind:"Callback"}},{channelName:"consume",module:{...Dt,filePath:i},functionQuery:{className:"Channel",methodName:"consume",kind:"Sync"}},{channelName:"ack",module:{...Dt,filePath:i},functionQuery:{className:"Channel",methodName:"ack",kind:"Sync"}},{channelName:"nack",module:{...Dt,filePath:i},functionQuery:{className:"Channel",methodName:"nack",kind:"Sync"}},{channelName:"reject",module:{...Dt,filePath:i},functionQuery:{className:"Channel",methodName:"reject",kind:"Sync"}},{channelName:"ackAll",module:{...Dt,filePath:i},functionQuery:{className:"Channel",methodName:"ackAll",kind:"Sync"}},{channelName:"nackAll",module:{...Dt,filePath:i},functionQuery:{className:"Channel",methodName:"nackAll",kind:"Sync"}}]),{channelName:"registerConsumer",module:{...Dt,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"registerConsumer",kind:"Sync"}},{channelName:"dispatch",module:{...Dt,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"dispatchMessage",kind:"Sync"}},{channelName:"connect",module:{...Dt,filePath:"lib/connect.js"},functionQuery:{functionName:"connect",kind:"Callback"}}],P6=z(xc)});var Ac,L6,zf=w(()=>{le();Ac=[...["resources/messages/messages.js","resources/messages/messages.mjs"].map(i=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:i},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/completions.js","resources/completions.mjs"].map(i=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <1",filePath:i},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(i=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:i},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/messages/messages.js","resources/messages/messages.mjs"].map(i=>({channelName:"messages-stream",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:i},functionQuery:{className:"Messages",methodName:"stream",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(i=>({channelName:"tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.63.0 <2",filePath:i},functionQuery:{className:"Messages",methodName:"toolRunner",kind:"Sync"}})),...["lib/tools/SessionToolRunner.js","lib/tools/SessionToolRunner.mjs"].map(i=>({channelName:"session-tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.97.0 <2",filePath:i},functionQuery:{className:"SessionToolRunner"}}))],L6=z(Ac)});var Oc,j6,Vf=w(()=>{le();Oc=[{channelName:"cronJobConstructor",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob"}},{channelName:"cronJobSetTime",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob",methodName:"setTime",kind:"Sync"}}],j6=z(Oc)});var Lr,$f,Yf=w(()=>{Lr={name:"dataloader",versionRange:">=2.0.0 <3",filePath:"index.js"},$f=[{channelName:"construct",module:Lr,functionQuery:{functionName:"DataLoader",kind:"Sync"}},{channelName:"load",module:Lr,functionQuery:{expressionName:"load",kind:"Async"}},{channelName:"loadMany",module:Lr,functionQuery:{expressionName:"loadMany",kind:"Async"}},{channelName:"prime",module:Lr,functionQuery:{expressionName:"prime",kind:"Sync"}},{channelName:"clear",module:Lr,functionQuery:{expressionName:"clear",kind:"Sync"}},{channelName:"clearAll",module:Lr,functionQuery:{expressionName:"clearAll",kind:"Sync"}}]});var Rc,H6,Kf=w(()=>{le();Rc=[{channelName:"handle",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/layer.js"},functionQuery:{expressionName:"handle_request",kind:"Callback"}},{channelName:"handle",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"lib/layer.js"},functionQuery:{expressionName:"handleRequest",kind:"Callback"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"use",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"use",kind:"Sync"}}],H6=z(Rc)});var Cx,Px,Dx,Mx,Lx,Nc,V6,Qf=w(()=>{le();Cx=">=3.0.0 <5",Px=/dist\/lite\/(index|common-[^/]+)\.node\.(cjs\.js|mjs)$/,Dx=[{functionName:"addDoc",channelName:"add-doc"},{functionName:"getDocs",channelName:"get-docs"},{functionName:"setDoc",channelName:"set-doc"},{functionName:"deleteDoc",channelName:"delete-doc"}],Mx=">=6.0.0 <7",Lx=[{file:"lib/v2/providers/https.js",functionName:"onRequest",channelName:"http-request"},{file:"lib/v2/providers/https.js",functionName:"onCall",channelName:"http-call"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreated",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreatedWithAuthContext",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdated",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdatedWithAuthContext",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeleted",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeletedWithAuthContext",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWritten",channelName:"firestore-written"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWrittenWithAuthContext",channelName:"firestore-written"},{file:"lib/v2/providers/scheduler.js",functionName:"onSchedule",channelName:"scheduler"},{file:"lib/v2/providers/storage.js",functionName:"onObjectFinalized",channelName:"storage-finalized"},{file:"lib/v2/providers/storage.js",functionName:"onObjectArchived",channelName:"storage-archived"},{file:"lib/v2/providers/storage.js",functionName:"onObjectDeleted",channelName:"storage-deleted"},{file:"lib/v2/providers/storage.js",functionName:"onObjectMetadataUpdated",channelName:"storage-metadata-updated"}],Nc=[...Dx.map(({functionName:i,channelName:e})=>({channelName:e,module:{name:"@firebase/firestore",versionRange:Cx,filePath:Px},functionQuery:{functionName:i,kind:"Auto"}})),...Lx.map(({file:i,functionName:e,channelName:t})=>({channelName:t,module:{name:"firebase-functions",versionRange:Mx,filePath:i},functionQuery:{functionName:e,kind:"Sync"}}))],V6=z(Nc)});var Cc,K6,Jf=w(()=>{le();Cc=[{channelName:"acquire",module:{name:"generic-pool",versionRange:">=3.0.0 <4",filePath:"lib/Pool.js"},functionQuery:{className:"Pool",methodName:"acquire",kind:"Auto"}},{channelName:"acquire",module:{name:"generic-pool",versionRange:">=2.4.0 <3",filePath:"lib/generic-pool.js"},functionQuery:{expressionName:"acquire",kind:"Callback"}}],K6=z(Cc)});var Pc,Dc,X6,Xf=w(()=>{le();Pc=["dist/node/index.js","dist/node/index.mjs","dist/node/index.cjs"],Dc=[...Pc.flatMap(i=>["generateContent","generateContentStream"].map(e=>({channelName:"generate-content",module:{name:"@google/genai",versionRange:">=0.10.0 <3",filePath:i},functionQuery:{expressionName:e,kind:"Auto"}}))),...Pc.map(i=>({channelName:"embed-content",module:{name:"@google/genai",versionRange:">=0.10.0 <3",filePath:i},functionQuery:{className:"Models",methodName:"embedContent",kind:"Auto"}})),...Pc.flatMap(i=>["sendMessage","sendMessageStream"].map(e=>({channelName:"chat",module:{name:"@google/genai",versionRange:">=0.10.0 <3",filePath:i},functionQuery:{className:"Chat",methodName:e,kind:"Auto"}})))],X6=z(Dc)});var Mc,tB,Zf=w(()=>{le();Mc=[...["language/parser.js","language/parser.mjs"].map(i=>({channelName:"parse",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:i},functionQuery:{functionName:"parse",kind:"Sync"}})),...["validation/validate.js","validation/validate.mjs"].map(i=>({channelName:"validate",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:i},functionQuery:{functionName:"validate",kind:"Sync"}})),...["execution/execute.js","execution/execute.mjs"].map(i=>({channelName:"execute",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:i},functionQuery:{functionName:"execute",kind:"Auto"}}))],tB=z(Mc)});function Gn(i,e={chat:"Completions",embeddings:"Embeddings"}){return[...["resources/chat/completions.js","resources/chat/completions.mjs"].map(t=>({channelName:"chat",module:{...i,filePath:t},functionQuery:{className:e.chat,methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(t=>({channelName:"embeddings",module:{...i,filePath:t},functionQuery:{className:e.embeddings,methodName:"create",kind:"Sync"}}))]}var Lc=w(()=>{});var qc,aB,e_=w(()=>{le();Lc();qc=Gn({name:"groq-sdk",versionRange:">=0.3.0 <2"}),aB=z(qc)});var Uc,cB,t_=w(()=>{le();Uc=[{channelName:"route",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"route",kind:"Sync"}},{channelName:"ext",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"ext",kind:"Sync"}},{channelName:"start",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"start",kind:"Sync"}},{channelName:"initialize",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"initialize",kind:"Sync"}}],cB=z(Uc)});var qx,jc,uB,i_=w(()=>{le();qx=[{channelName:"context",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?context\.js$/},functionQuery:{className:"Context"}},{channelName:"request",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?hono-base\.js$/},astQuery:"PropertyDefinition[key.name='request'] > ArrowFunctionExpression",functionQuery:{kind:"Auto"}}],jc=qx,uB=z(jc)});function Ke(i){return{channelName:"module-registration",module:i,astQuery:"Program",transform:Ux}}var Ux,pi=w(()=>{Ux="sentryModuleRegistration"});var Bc,yB,r_=w(()=>{le();pi();Bc=[Ke({name:"ioredis",versionRange:">=5.11.0",filePath:"built/Redis.js"}),...["lib/redis.js","built/redis.js","built/redis/index.js"].flatMap(i=>[{channelName:"command",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:i},functionQuery:{expressionName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:i},functionQuery:{expressionName:"connect",kind:"Async"}}]),{channelName:"command",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"connect",kind:"Async"}}],yB=z(Bc)});var Fc,vB,n_=w(()=>{le();Fc=[{channelName:"send_batch",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/producer/messageProducer.js"},functionQuery:{expressionName:"sendBatch",kind:"Async"}},{channelName:"consumer_run",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/consumer/index.js"},functionQuery:{expressionName:"run",kind:"Async"}}],vB=z(Fc)});function Gx(i,e){return{channelName:"query",module:{name:s_,versionRange:e,filePath:i},functionQuery:{className:"Runner",methodName:"query",kind:"Async"}}}function Hx(i,e,t){return{channelName:i,module:{name:s_,versionRange:t,filePath:e},functionQuery:{className:"Client",methodName:i,kind:"Sync"}}}var s_,jx,Bx,Fx,a_,o_=w(()=>{s_="knex",jx=[{filePath:"lib/execution/runner.js",versionRange:">=0.22.0 <4"},{filePath:"lib/runner.js",versionRange:">=0.10.0 <0.22.0"},{filePath:"src/runner.js",versionRange:">=0.18.0 <0.19.0"}],Bx=[{filePath:"lib/client.js",versionRange:">=0.10.0 <4"},{filePath:"src/client.js",versionRange:">=0.18.0 <0.19.0"}],Fx=["queryBuilder","schemaBuilder","raw"];a_=[...jx.map(({filePath:i,versionRange:e})=>Gx(i,e)),...Bx.flatMap(({filePath:i,versionRange:e})=>Fx.map(t=>Hx(t,i,e)))]});var Gc,EB,l_=w(()=>{le();Gc=[{channelName:"use",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"use",kind:"Sync"}},{channelName:"callback",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"callback",kind:"Sync"}}],EB=z(Gc)});var Wx,Hc,Ra,c_,zx,Vx,Wc,xB,AB,p_=w(()=>{le();Wx=["dist/language_models/chat_models.cjs","dist/language_models/chat_models.js"].flatMap(i=>{let e={name:"@langchain/core",versionRange:">=0.1.0 <2.0.0",filePath:i};return[{channelName:"chatModelInvoke",module:e,functionQuery:{className:"BaseChatModel",methodName:"invoke",kind:"Async"}},{channelName:"chatModelStream",module:e,functionQuery:{className:"BaseChatModel",methodName:"_streamIterator",kind:"Async"}}]}),Hc="embedQuery",Ra="embedDocuments",c_=[{name:"@langchain/openai",versionRange:">=0.1.0 <2.0.0",methods:[Hc,Ra]},{name:"@langchain/google-genai",versionRange:">=0.1.0 <3.0.0",methods:[Hc,Ra]},{name:"@langchain/mistralai",versionRange:">=0.1.0 <2.0.0",methods:[Hc,Ra]},{name:"@langchain/google-common",versionRange:">=0.1.0 <3.0.0",methods:[Ra]}],zx=c_.flatMap(({name:i,versionRange:e,methods:t})=>["dist/embeddings.cjs","dist/embeddings.js"].flatMap(r=>t.map(n=>({channelName:n,module:{name:i,versionRange:e,filePath:r},functionQuery:{methodName:n,kind:"Async"}})))),Vx=["dist/classifier.cjs","dist/classifier.js"].map(i=>({channelName:"typesafeClassifierInvoke",module:{name:"@langchain/typesafe",versionRange:">=0.0.1 <1.0.0",filePath:i},functionQuery:{className:"TypeSafeClassifier",methodName:"invoke",kind:"Async"}})),Wc=[...Wx,...zx,...Vx],xB=c_.flatMap(({name:i,methods:e})=>e.map(t=>`orchestrion:${i}:${t}`)),AB=z(Wc)});var d_,$x,Yx,zc,NB,u_=w(()=>{le();d_=i=>({name:"@langchain/langgraph",versionRange:">=0.0.0 <2.0.0",filePath:i}),$x=["dist/graph/state.cjs","dist/graph/state.js"].map(i=>({channelName:"stateGraphCompile",module:d_(i),functionQuery:{className:"StateGraph",methodName:"compile",kind:"Sync"}})),Yx=["dist/prebuilt/react_agent_executor.cjs","dist/prebuilt/react_agent_executor.js"].map(i=>({channelName:"createReactAgent",module:d_(i),functionQuery:{functionName:"createReactAgent",kind:"Sync"}})),zc=[...$x,...Yx],NB=z(zc)});var Vc,DB,m_=w(()=>{le();Vc=[{channelName:"load",module:{name:"lru-memoizer",versionRange:">=2.1.0 <4",filePath:"lib/async.js"},functionQuery:{functionName:"memoizedFunction",kind:"Callback"}}],DB=z(Vc)});var g_,b_=w(()=>{pi();g_=[Ke({name:"@flue/runtime",versionRange:">=2.0.0 <3.0.0",filePath:"dist/index.mjs"})]});var Kx,Qx,Jx,$c,jB,h_=w(()=>{le();Kx=[{channelName:"mastraConstructor",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/(?:[\w.-]+\/)?mastra[\w.-]*\.(?:cjs|mjs|js)$/},functionQuery:{className:"Mastra"}}],Qx=["executeWithContext","executeWithContextSync"].map(i=>({channelName:"mastraExecuteWithContext",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/observability\/context-storage\.(?:cjs|mjs|js)$/},functionQuery:{functionName:i,kind:"Auto"}})),Jx=[{channelName:"mastraClassifierEvaluate",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/classifier\/index\.(?:cjs|mjs|js)$/},functionQuery:{className:"Classifier",methodName:"evaluate",kind:"Async"}}],$c=[...Kx,...Qx,...Jx],jB=z($c)});var y_,Yc,GB,f_=w(()=>{le();y_={name:"@earendil-works/pi-durable",versionRange:">=1.0.0 <2.0.0"},Yc=[{channelName:"harnessOpen",module:{...y_,filePath:"dist/harness/harness.js"},functionQuery:{methodName:"open",kind:"Async"}},...[["bash","createBashTool"],["read","createReadTool"],["edit","createEditTool"],["write","createWriteTool"]].map(([i,e])=>({channelName:"codingTool",module:{...y_,filePath:`dist/tools/${i}.js`},functionQuery:{functionName:e,kind:"Sync"}}))],GB=z(Yc)});var Xx,Zx,Kc,zB,__=w(()=>{le();Xx=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/server",versionRange:">=2.0.0 <3",filePath:/^dist\/mcp-[\w-]+\.(?:cjs|mjs)$/},functionQuery:{className:"McpServer"}}],Zx=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/sdk",versionRange:">=1.9.0 <2",filePath:/(?:^|\/)server\/mcp\.js$/},functionQuery:{className:"McpServer"}}],Kc=[...Xx,...Zx],zB=z(Kc)});var Qc,Na,v_,Jc,YB,k_=w(()=>{le();Qc={name:"@mistralai/mistralai",versionRange:">=2.0.0 <4"},Na={...Qc,filePath:"esm/sdk/chat.js"},v_={...Qc,filePath:"esm/sdk/agents.js"},Jc=[{channelName:"chat",module:Na,functionQuery:{className:"Chat",methodName:"complete",kind:"Auto"}},{channelName:"chat",module:Na,functionQuery:{className:"Chat",methodName:"parse",kind:"Auto"}},{channelName:"chat-stream",module:Na,functionQuery:{className:"Chat",methodName:"stream",kind:"Auto"}},{channelName:"chat-stream",module:Na,functionQuery:{className:"Chat",methodName:"parseStream",kind:"Auto"}},{channelName:"embeddings",module:{...Qc,filePath:"esm/sdk/embeddings.js"},functionQuery:{className:"Embeddings",methodName:"create",kind:"Auto"}},{channelName:"agents",module:v_,functionQuery:{className:"Agents",methodName:"complete",kind:"Auto"}},{channelName:"agents-stream",module:v_,functionQuery:{className:"Agents",methodName:"stream",kind:"Auto"}}],YB=z(Jc)});var ir,Xc,JB,w_=w(()=>{le();ir={name:"mongodb"},Xc=[{channelName:"command",module:{...ir,versionRange:">=6.4.0 <8",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Async"}},{channelName:"command",module:{...ir,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Callback"}},{channelName:"checkout",module:{...ir,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection_pool.js"},functionQuery:{methodName:"checkOut",kind:"Callback"}},...["insert","update","remove"].map(i=>({channelName:`v3_${i}`,module:{...ir,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/index.js"},functionQuery:{expressionName:i,kind:"Callback"}})),{channelName:"v3_command",module:{...ir,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/command.js"},functionQuery:{functionName:"command",kind:"Callback"}},{channelName:"v3_query",module:{...ir,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/query.js"},functionQuery:{functionName:"query",kind:"Callback"}},{channelName:"v3_get_more",module:{...ir,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/get_more.js"},functionQuery:{functionName:"getMore",kind:"Callback"}}],JB=z(Xc)});var Ii,S_,Zc,tF,iF,E_=w(()=>{le();pi();Ii={name:"mongoose",versionRange:">=5.9.7 <9.7.0"},S_=["find","findOne","deleteOne","deleteMany","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace","remove","count","findOneAndRemove"],Zc=[Ke({name:"mongoose",versionRange:">=9.7.0",filePath:"lib/query.js"}),{channelName:"query_exec",module:{...Ii,filePath:"lib/query.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"aggregate_exec",module:{...Ii,filePath:"lib/aggregate.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"model_save",module:{...Ii,filePath:"lib/model.js"},functionQuery:{expressionName:"save",kind:"Auto"}},{channelName:"model_insert_many",module:{...Ii,filePath:"lib/model.js"},functionQuery:{expressionName:"insertMany",kind:"Auto"}},{channelName:"model_bulk_write",module:{...Ii,filePath:"lib/model.js"},functionQuery:{expressionName:"bulkWrite",kind:"Auto"}},{channelName:"model_remove",module:{...Ii,filePath:"lib/model.js"},functionQuery:{expressionName:"remove",kind:"Auto"}},{channelName:"model_aggregate",module:{...Ii,filePath:"lib/model.js"},functionQuery:{expressionName:"aggregate",kind:"Sync"}},...S_.map(i=>({channelName:`ctx_${i}`,module:{...Ii,filePath:"lib/query.js"},functionQuery:{expressionName:i,kind:"Sync"}}))],tF=z(Zc),iF=S_.map(i=>`orchestrion:mongoose:ctx_${i}`)});var ep,aF,T_=w(()=>{le();pi();ep=[Ke({name:"mysql2",versionRange:">=3.20.0",filePath:"lib/base/connection.js"}),{channelName:"query",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"execute",kind:"Callback"}},{channelName:"query",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"execute",kind:"Callback"}}],aF=z(ep)});var tp,cF,I_=w(()=>{le();tp=[{channelName:"query",module:{name:"mysql",versionRange:">=2.0.0 <3",filePath:"lib/Connection.js"},functionQuery:{expressionName:"query",kind:"Auto"}}],cF=z(tp)});var ip,rp,uF,x_=w(()=>{le();ip={name:"@neondatabase/serverless",versionRange:">=1.0.0 <2",filePath:/^index\.m?js$/},rp=[{channelName:"query",module:ip,astQuery:'ClassBody:has(MethodDefinition[key.name="_pulseQueryQueue"]) > MethodDefinition[key.name="query"] > FunctionExpression',functionQuery:{methodName:"query",kind:"Auto"}},{channelName:"http-query",module:ip,astQuery:'FunctionDeclaration[async=true]:has(Literal[value="Neon-Connection-String"])',functionQuery:{kind:"Async"}},{channelName:"resolve-connection",module:ip,astQuery:'FunctionDeclaration[async=true]:has(ReturnStatement > ObjectExpression > Property[key.name="resolvedURL"])',functionQuery:{kind:"Async"}}],uF=z(rp)});var A_,O_=w(()=>{A_=[{channelName:"nestFactoryCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"nest-factory.js"},functionQuery:{className:"NestFactoryStatic",methodName:"create",kind:"Async"}},{channelName:"routerExecutionContextCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"router/router-execution-context.js"},functionQuery:{className:"RouterExecutionContext",methodName:"create",kind:"Sync"}},{channelName:"injectableDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/injectable.decorator.js"},astQuery:'FunctionDeclaration[id.name="Injectable"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"catchDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/catch.decorator.js"},astQuery:'FunctionDeclaration[id.name="Catch"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"cronDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/cron.decorator.js"},functionQuery:{functionName:"Cron",kind:"Sync"}},{channelName:"intervalDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/interval.decorator.js"},functionQuery:{functionName:"Interval",kind:"Sync"}},{channelName:"timeoutDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/timeout.decorator.js"},functionQuery:{functionName:"Timeout",kind:"Sync"}},{channelName:"scheduleExplorerWrap",module:{name:"@nestjs/schedule",versionRange:">=6.0.0",filePath:"dist/schedule.explorer.js"},functionQuery:{className:"ScheduleExplorer",methodName:"wrapFunctionInTryCatchBlocks",kind:"Sync"}},{channelName:"onEventDecorator",module:{name:"@nestjs/event-emitter",versionRange:">=2.0.0",filePath:"dist/decorators/on-event.decorator.js"},functionQuery:{expressionName:"OnEvent",kind:"Sync"}},{channelName:"processorDecorator",module:{name:"@nestjs/bullmq",versionRange:">=10.0.0",filePath:"dist/decorators/processor.decorator.js"},functionQuery:{functionName:"Processor",kind:"Sync"}}]});var R_,N_=w(()=>{pi();R_=[Ke({name:"h3",versionRange:">=2.0.0-0",filePath:"dist/h3.mjs"})]});var rr,np,fF,C_=w(()=>{le();rr={functionName:"createTask",kind:"Sync"},np=[{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.cjs"},functionQuery:rr},{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.js"},functionQuery:rr},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.3.0 <4.6.0",filePath:"dist/node-cron.cjs"},functionQuery:rr},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.6.0",filePath:"dist/node-cron.js"},functionQuery:rr},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/cjs/node-cron.js"},functionQuery:rr},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/esm/node-cron.js"},functionQuery:rr},{channelName:"v3_createTask",module:{name:"node-cron",versionRange:">=3.0.0 <4",filePath:"src/node-cron.js"},functionQuery:rr}],fF=z(np)});var P_,sp,kF,D_=w(()=>{le();P_={channelName:"schedule",astQuery:"AssignmentExpression[left.object.property.name='prototype'][left.property.name='schedule'] > FunctionExpression",functionQuery:{methodName:"schedule",kind:"Sync"}},sp=[{...P_,module:{name:"node-schedule",versionRange:">=1.3.0 <2",filePath:"lib/schedule.js"}},{...P_,module:{name:"node-schedule",versionRange:">=2.0.0 <3",filePath:"lib/Job.js"}}],kF=z(sp)});var ap,EF,M_=w(()=>{le();ap=[...["resources/chat/completions/completions.js","resources/chat/completions/completions.mjs"].map(i=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:i},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/responses/responses.js","resources/responses/responses.mjs"].map(i=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:i},functionQuery:{className:"Responses",methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(i=>({channelName:"embeddings",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:i},functionQuery:{className:"Embeddings",methodName:"create",kind:"Sync"}})),...["resources/conversations/conversations.js","resources/conversations/conversations.mjs"].map(i=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:i},functionQuery:{className:"Conversations",methodName:"create",kind:"Sync"}})),...["resources/decisions.js","resources/decisions.mjs"].map(i=>({channelName:"decide",module:{name:"openai",versionRange:">=7.30.0 <8",filePath:i},functionQuery:{className:"Decisions",methodName:"create",kind:"Sync"}}))],EF=z(ap)});var op,xF,L_=w(()=>{le();op=[{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"connect",kind:"Auto"}},{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"connect",kind:"Auto"}},{channelName:"connect",module:{name:"pg-pool",versionRange:">=2.0.0 <4",filePath:"index.js"},functionQuery:{className:"Pool",methodName:"connect",kind:"Auto"}}],xF=z(op)});var eA,lp,NF,q_=w(()=>{le();pi();eA=i=>[{channelName:"handle",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${i}/query.js`},functionQuery:{className:"Query",methodName:"handle",kind:"Async"}},{channelName:"connection",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${i}/connection.js`},functionQuery:{functionName:"Connection",kind:"Sync"}},{channelName:"execute",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${i}/connection.js`},functionQuery:{functionName:"execute",kind:"Sync"}},{channelName:"connect",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${i}/connection.js`},functionQuery:{methodName:"connect",kind:"Sync"}}],lp=[Ke({name:"postgres",versionRange:">=4.0.0",filePath:"src/query.js"}),...["src","cjs/src"].flatMap(eA)],NF=z(lp)});function U_(i,e){return{channelName:i,module:{name:tA,versionRange:rA,filePath:iA},functionQuery:{className:"CollectionBase",methodName:i,kind:e}}}var tA,iA,rA,nA,sA,cp,DF,j_=w(()=>{le();tA="@prisma/orm-family-sql",iA="dist/orm-client.mjs",rA=">=8.0.0-rc.15 <9",nA=["aggregate","first","create","createAndCount","upsert","update","updateAndCount","delete","deleteAndCount"],sA=["all","createAll","updateAll","deleteAll"];cp=[...nA.map(i=>U_(i,"Async")),...sA.map(i=>U_(i,"Sync"))],DF=z(cp)});var pp,UF,B_=w(()=>{le();pi();pp=[Ke({name:"@redis/client",versionRange:">=5.12.0",filePath:"dist/lib/client/index.js"}),{channelName:"command",module:{name:"redis",versionRange:">=2.6.0 <4",filePath:"index.js"},functionQuery:{expressionName:"internal_send_command",kind:"Sync"}},{channelName:"executor",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"commandsExecutor",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"multi",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executeMulti",kind:"Async"}},{channelName:"pipeline",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executePipeline",kind:"Async"}},{channelName:"batch",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"multiExecutor",kind:"Async"}}],UF=z(pp)});var aA,F_,G_=w(()=>{aA=i=>[{channelName:"requestHandler",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${i}/server.js`},astQuery:'FunctionExpression[id.name="requestHandler"]',functionQuery:{kind:"Async"}},{channelName:"matchServerRoutes",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${i}/routeMatching.js`},functionQuery:{functionName:"matchServerRoutes",kind:"Sync"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${i}/data.js`},functionQuery:{functionName:"callRouteLoader",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${i}/data.js`},functionQuery:{functionName:"callRouteAction",kind:"Async"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${i}/data.js`},functionQuery:{functionName:"callRouteLoaderRR",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${i}/data.js`},functionQuery:{functionName:"callRouteActionRR",kind:"Async"}}],F_=["dist","dist/esm"].flatMap(aA)});var H_,W_=w(()=>{H_=[{channelName:"createRouter",module:{name:"@remix-run/fetch-router",versionRange:">=0.21.0 <2",filePath:"dist/lib/router.js"},functionQuery:{functionName:"createRouter",kind:"Sync"}},{channelName:"createAssetServer",module:{name:"@remix-run/assets",versionRange:">=0.6.0 <2",filePath:"dist/lib/asset-server.js"},functionQuery:{functionName:"createAssetServer",kind:"Sync"}},{channelName:"createRequestListener",module:{name:"@remix-run/node-fetch-server",versionRange:">=0.14.0 <2",filePath:"dist/lib/request-listener.js"},functionQuery:{functionName:"createRequestListener",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/ui",versionRange:">=0.8.0 <1",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/component",versionRange:">=1.0.0 <2",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}}]});var oA,lA,cA,pA,dp,HF,z_=w(()=>{le();oA="tedious",lA="lib/connection.js",cA=">=1.11.0 <21",pA=["connect","execSql","execSqlBatch","callProcedure","execBulkLoad","prepare","execute"],dp=pA.map(i=>({channelName:i,module:{name:oA,versionRange:cA,filePath:lA},functionQuery:{className:"Connection",methodName:i,kind:"Sync"}})),HF=z(dp)});var up,$F,V_=w(()=>{le();Lc();up=[...Gn({name:"together-ai",versionRange:">=0.6.0 <1"}),...Gn({name:"together-ai",versionRange:">=1.0.0 <2"},{chat:"BaseCompletions",embeddings:"BaseEmbeddings"})],$F=z(up)});var mp,QF,$_=w(()=>{le();mp=["dist/index.mjs","dist/index.cjs"].map(i=>({channelName:"system-one",module:{name:"@typesafe-ai/sdk",versionRange:">=0.5.0 <1",filePath:i},functionQuery:{className:"TypeSafeClient",methodName:"systemOne",kind:"Sync"}})),QF=z(mp)});function nr(i,e,t,r){return["dist/index.js","dist/index.mjs"].map(n=>({channelName:e,module:{name:"ai",versionRange:i,filePath:n},functionQuery:{functionName:t,kind:r}}))}var gp,e7,Y_=w(()=>{le();pi();gp=[...["dist/index.js","dist/index.mjs"].map(i=>Ke({name:"ai",versionRange:">=7.0.0",filePath:i})),...nr(">=4.0.0 <7.0.0","generateText","generateText","Async"),...nr(">=4.0.0 <7.0.0","streamText","streamText","Sync"),...nr(">=4.0.0 <7.0.0","generateObject","generateObject","Async"),...nr(">=4.0.0 <7.0.0","embed","embed","Async"),...nr(">=4.0.0 <7.0.0","embedMany","embedMany","Async"),...nr(">=5.0.0 <7.0.0","resolveLanguageModel","resolveLanguageModel","Sync"),...nr(">=6.0.0 <7.0.0","executeToolCall","executeToolCall","Async")];e7=z(gp)});function dA(i=[]){return[...nc([...K_,...i].map(e=>e.module.name)),"@remix-run/node"]}var K_,Hn,Y7,Q_=w(()=>{Wt();Hf();Wf();zf();Vf();Yf();Kf();Qf();Jf();Xf();Zf();e_();t_();i_();r_();n_();o_();l_();p_();u_();m_();b_();h_();f_();__();k_();w_();E_();T_();I_();x_();O_();N_();C_();D_();M_();L_();q_();j_();B_();G_();W_();z_();V_();$_();Y_();K_=[...xc,...Ac,...Ic,...Oc,...$f,...Rc,...Nc,...Cc,...Dc,...Mc,...qc,...Uc,...jc,...Bc,...Fc,...a_,...Gc,...Wc,...zc,...Vc,...g_,...$c,...Kc,...Jc,...Xc,...Zc,...ep,...tp,...rp,...A_,...R_,...np,...sp,...ap,...op,...Yc,...lp,...cp,...pp,...F_,...H_,...dp,...up,...mp,...gp],Hn=K_.filter(i=>!i.transform);Y7=dA()});var J_=w(()=>{Gf()});var X_,Z_=w(()=>{X_=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});import{posix as uA,sep as mA}from"node:path";function ev(i){return i.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function tv(i=process.argv[1]?pc(process.argv[1]):process.cwd(),e=mA==="\\"){let t=e?ev(i):i;return r=>{if(!r)return;let n=e?ev(r):r,{dir:s,base:o,ext:l}=uA.parse(n);(l===".js"||l===".mjs"||l===".cjs")&&(o=o.slice(0,l.length*-1));let a=decodeURIComponent(o);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${a}`;if(s.startsWith(t)){let p=s.slice(t.length+1).replace(/\//g,".");return p?`${p}:${a}`:a}return a}}var iv=w(()=>{Wt()});var bp,rv=w(()=>{Wt();mc();iv();bp=sl(uc(tv()))});import{AsyncLocalStorage as gA}from"node:async_hooks";function av(i){return i.getValue(wp)}function hA(i,e){return i.setValue(wp,e)}function yA(i,e){i.refs[sv]=Tr(e)}function ov(i){return Ji(i.refs[sv])}function fA(i,e){let t=i?Ti.setSpan(Ye.active(),i):Ti.deleteSpan(Ye.active());return Ye.with(t,()=>{let r=si();return Xs(r,i??void 0),e(r)})}function _A(i){let e=i?vA(i):Ti.getActiveSpan();return e&&tr(e.spanContext())?e:void 0}function vA(i){let e=ov(i);return e?Ti.getSpan(e):void 0}function kA(i){let e=av(i),t=e?.scope||si(),r=e?.isolationScope||Ki(),n=i.getValue(fp)===!0,s=i.getValue(_p),o=i.getValue(vp),l=s||t.clone(),a=o||(n?r.clone():r),d=hA(i,{scope:l,isolationScope:a}).deleteValue(fp).deleteValue(_p).deleteValue(vp);return yA(l,d),d}function SA(i){if(typeof i!="object"||!i)return!1;let e=i;return typeof e.on=="function"&&typeof e.emit=="function"}function hp(i,e){let t=i[e];return typeof t=="function"?t:void 0}function yp(i,e,t){try{i[e]=t}catch{}}function lv(){let e=Ct(Pe()).getTracingChannelBinding?.()?.asyncLocalStorage??new gA;function t(){let d=Ye.active(),g=av(d);return g||{scope:$i(),isolationScope:Yi()}}function r(d){let g=Ye.active();return Ye.with(g,()=>d(l()))}function n(d,g){let b=ov(d)||Ye.active();return Ye.with(b.setValue(_p,d),()=>g(d))}function s(d){let g=Ye.active();return Ye.with(g.setValue(fp,!0),()=>{let b=l();return Tn(b.getPropagationContext())||b.setPropagationContext({traceId:Vi(),sampleRand:vt()}),d(a())})}function o(d,g){let b=Ye.active();return Ye.with(b.setValue(vp,d),()=>g(a()))}function l(){return t().scope}function a(){return t().isolationScope}function c(){return{asyncLocalStorage:e}}kn({withScope:r,withSetScope:n,withSetIsolationScope:o,withIsolationScope:s,getCurrentScope:l,getIsolationScope:a,getActiveSpan:_A,withActiveSpan:fA,getTracingChannelBinding:c});let p=new kp(e);return Ye.setGlobalContextManager(p),p.getAsyncLocalStorageLookup()}function EA(i){let{traceFlags:e,traceState:t}=i,r=t?t.get(bA)==="1":!1;if(e===yc.SAMPLED)return!0;if(r)return!1;let n=t?t.get(nv):void 0,s=n?Sn(n):void 0;if(s?.sampled==="true")return!0;if(s?.sampled==="false")return!1}function cv(i){i.on("prepareSpanScope",e=>{let{scope:t,parentSpan:r}=e;if(!r?.spanContext().isRemote)return;let{spanId:n,traceId:s,traceState:o}=r.spanContext(),l=ai(r),a=typeof l.sample_rand=="string"?Number(l.sample_rand):void 0,c=!!o?.get(nv),p=t.clone();p.setPropagationContext({traceId:s,parentSpanId:n,sampled:EA(r.spanContext()),dsc:c?l:void 0,sampleRand:typeof a=="number"&&!Number.isNaN(a)?a:vt()}),Xs(p,void 0),e.scope=p,e.parentSpan=void 0})}var nv,bA,wp,fp,_p,vp,sv,kG,wA,kp,pv=w(()=>{Wt();Oa();Oa();nv="sentry.dsc",bA="sentry.sampled_not_recording",wp=ci("sentry_scopes"),fp=ci("sentry_fork_isolation_scope"),_p=ci("sentry_fork_set_scope"),vp=ci("sentry_fork_set_isolation_scope"),sv="context";kG=ci("OpenTelemetry SDK Context Key SUPPRESS_TRACING");wA=["addListener","on","once","prependListener","prependOnceListener"],kp=class{constructor(e){this._kOtListeners=Symbol("OtListeners"),this._wrapped=!1,this._asyncLocalStorage=e}active(){return this._asyncLocalStorage.getStore()??Bn}with(e,t,r,...n){let s=kA(e),o=r==null?t:t.bind(r);return this._asyncLocalStorage.run(s,o,...n)}enable(){return this}disable(){try{this._asyncLocalStorage.disable()}catch{}return this}bind(e,t){return SA(t)?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:wp}}_bindFunction(e,t){let r=this.with.bind(this),n=function(...s){return r(e,()=>t.apply(this,s))};return Object.defineProperty(n,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),n}_bindEventEmitter(e,t){if(this._getPatchMap(t)!==void 0||this._createPatchMap(t)===void 0)return t;for(let n of wA){let s=hp(t,n);s&&yp(t,n,this._patchAddListener(t,s,e))}for(let n of["removeListener","off"]){let s=hp(t,n);s&&yp(t,n,this._patchRemoveListener(t,s))}let r=hp(t,"removeAllListeners");return r&&yp(t,"removeAllListeners",this._patchRemoveAllListeners(t,r)),t}_patchRemoveListener(e,t){let r=this;return function(n,s){let o=r._getPatchMap(e)?.[n];if(o===void 0)return t.call(this,n,s);let l=o.get(s);return t.call(this,n,l||s)}}_patchRemoveAllListeners(e,t){let r=this;return function(n){let s=r._getPatchMap(e);return s!==void 0&&(arguments.length===0?r._createPatchMap(e):n!==void 0&&s[n]!==void 0&&delete s[n]),t.apply(this,arguments)}}_patchAddListener(e,t,r){let n=this;return function(s,o){if(n._wrapped)return t.call(this,s,o);let l=n._getPatchMap(e)??n._createPatchMap(e);if(l===void 0)return t.call(this,s,o);let a=l[s];a===void 0&&(a=new WeakMap,l[s]=a);let c=n.bind(r,o);a.set(o,c),n._wrapped=!0;try{return t.call(this,s,c)}finally{n._wrapped=!1}}}_createPatchMap(e){let t=Object.create(null);try{e[this._kOtListeners]=t}catch{return}return this._getPatchMap(e)===t?t:void 0}_getPatchMap(e){return e[this._kOtListeners]}}});function qr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function dv(i){return i&&Object.prototype.hasOwnProperty.call(i,"default")&&Object.keys(i).length===1?i.default:i}var Wn=w(()=>{});function TA(i,e){let[t]=gv(i,"");for(let r of xA(e))if(IA(r,t))return!0;return!1}function IA(i,e){for(let[t,r]of i)if(!RA(e,r,t))return!1;return!0}function uv(i){return i==="latest"&&(i=">=0"),i.match(/^([^\d+]*)(\d.*)$/)||[null,"","*.*.*"]}function xA(i){let e=[],t=[],r=i.trim().split(/\s+/);for(let n=0;n<r.length;n++){let s=r[n];if(s==="-")continue;if(s==="||"){e.push(t),t=[];continue}if(/^[<>=~v^]+$/.test(s)&&n+1<r.length){r[n+1]=s+r[n+1];continue}let o=uv(s),l=o[1]||"=";l.endsWith("v")&&(l=l.slice(0,-1));let[a,c]=gv(o[2],l);if(n+2<r.length&&r[n+1]==="-"){let p=uv(r[n+2]);r[n+2]="<="+(p[2].indexOf("-")===-1?p[2]+".*.*":p[2]),c=">="}if(c[0]==="~"){let p=o[2].split("-")[0].split(".").length;t.push([">=",a]),t.push(["<",p===1?Ur(a,0):Ur(a,1)])}else if(c[0]==="^"){let p=a[0]!==0?0:a[1]!==0?1:2;t.push([">=",a]),t.push(["<",p===0?Ur(a,0):p===1?Ur(a,1):Ur(a,2)])}else t.push([c.replace("~","").replace("^",""),a])}return t.length&&e.push(t),e}function Ur(i,e){let t=i.slice(0);if(i[e]===-1)return t;for(t[e++]++;e<3;e++)t[e]=0;return t}function AA(i){return i==="x"||i==="X"||i==="*"||i==="latest"?-1:Number(i)}function OA(i){return/^\d+$/.test(i)?Number(i):i}function xi(i,e,t){return t===-1?i!=="<":i==="="?e===t:i===">"?e>t:i===">="?e>=t:i==="<"?e<t:i==="<="?e<=t:!1}function gv(i,e){i=i.split("+")[0];let[t,r]=i.split("-"),n=t.split(".").map(AA).slice(0,3),s=Math.max(n.length-1,0);return e===">"?(e=">=",n.push(0,0,0),n[s]++):e===""?n.push(0,0,0):n.push(-1,-1,-1),r?[n.slice(0,3).concat(r.split(".").map(OA)),e]:[n.slice(0,3),e]}function RA(i,e,t){if(!xi("=",i[0],e[0]))return xi(t,i[0],e[0]);if(!xi("=",i[1],e[1]))return xi(t,i[1],e[1]);if(!xi("=",i[2],e[2])||i.length===3&&e.length===3)return xi(t,i[2],e[2]);if(t[0]==="<"&&(e.length===3||i.length===3))return!1;if(t[0]===">"){if(i.length===3)return!0;if(e.length===3)return!1}for(let r=3;r<Math.max(i.length,e.length);r++)if(xi(t,i[r]||"",e[r]||""))return!0;return!1}var mv,bv=w(()=>{mv=TA});function Ep(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,r=Array(e);t<e;t++)r[t]=i[t];return r}function Ip(i,e){return(function(t){if(Array.isArray(t))return t})(i)||(function(t,r){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var s,o,l,a,c=[],p=!0,d=!1;try{if(l=(n=n.call(t)).next,r!==0)for(;!(p=(s=l.call(n)).done)&&(c.push(s.value),c.length!==r);p=!0);}catch(g){d=!0,o=g}finally{try{if(!p&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(d)throw o}}return c}})(i,e)||vv(i,e)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function NA(i){return(function(e){if(Array.isArray(e))return Ep(e)})(i)||(function(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)})(i)||vv(i)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
7
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function zn(i){return(zn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(i)}function vv(i,e){if(i){if(typeof i=="string")return Ep(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Ep(i,e):void 0}}function kv(i,e){return i(e={exports:{}},e.exports),e.exports}function Mt(i,e){for(var t=0;t<e.length;++t){if(i==null)return i;i=i[e[t]]}return i}function Ge(i){if(i==null)return function(){return!0};if(Sp!=null){var e=Sp.get(i);return e!=null||(e=hv(i),Sp.set(i,e)),e}return hv(i)}function hv(i){switch(i.type){case"wildcard":return function(){return!0};case"identifier":var e=i.value.toLowerCase();return function(N,k,h){var M=h&&h.nodeTypeKey||"type";return e===N[M].toLowerCase()};case"exactNode":return function(N,k){return k.length===0};case"field":var t=i.name.split(".");return function(N,k){return(function h(M,Z,re,ae){for(var C=Z,Se=ae;Se<re.length;++Se){if(C==null)return!1;var me=C[re[Se]];if(Array.isArray(me)){for(var fe=0;fe<me.length;++fe)if(h(M,me[fe],re,Se+1))return!0;return!1}C=me}return M===C})(N,k[t.length-1],t,0)};case"matches":var r=i.selectors.map(Ge);return function(N,k,h){for(var M=0;M<r.length;++M)if(r[M](N,k,h))return!0;return!1};case"compound":var n=i.selectors.map(Ge);return function(N,k,h){for(var M=0;M<n.length;++M)if(!n[M](N,k,h))return!1;return!0};case"not":var s=i.selectors.map(Ge);return function(N,k,h){for(var M=0;M<s.length;++M)if(s[M](N,k,h))return!1;return!0};case"has":var o=i.selectors.map(Ge);return function(N,k,h){var M=!1,Z=[];return Ca.traverse(N,{enter:function(re,ae){ae!=null&&Z.unshift(ae);for(var C=0;C<o.length;++C)if(o[C](re,Z,h))return M=!0,void this.break()},leave:function(){Z.shift()},keys:h&&h.visitorKeys,fallback:h&&h.fallback||"iteration"}),M};case"child":var l=Ge(i.left),a=Ge(i.right);return function(N,k,h){return!!(k.length>0&&a(N,k,h))&&l(k[0],k.slice(1),h)};case"descendant":var c=Ge(i.left),p=Ge(i.right);return function(N,k,h){if(p(N,k,h)){for(var M=0,Z=k.length;M<Z;++M)if(c(k[M],k.slice(M+1),h))return!0}return!1};case"attribute":var d=i.name.split(".");switch(i.operator){case void 0:return function(N){return Mt(N,d)!=null};case"=":switch(i.value.type){case"regexp":return function(N){var k=Mt(N,d);return typeof k=="string"&&i.value.value.test(k)};case"literal":var g="".concat(i.value.value);return function(N){return g==="".concat(Mt(N,d))};case"type":return function(N){return i.value.value===zn(Mt(N,d))}}throw new Error("Unknown selector value type: ".concat(i.value.type));case"!=":switch(i.value.type){case"regexp":return function(N){return!i.value.value.test(Mt(N,d))};case"literal":var b="".concat(i.value.value);return function(N){return b!=="".concat(Mt(N,d))};case"type":return function(N){return i.value.value!==zn(Mt(N,d))}}throw new Error("Unknown selector value type: ".concat(i.value.type));case"<=":return function(N){return Mt(N,d)<=i.value.value};case"<":return function(N){return Mt(N,d)<i.value.value};case">":return function(N){return Mt(N,d)>i.value.value};case">=":return function(N){return Mt(N,d)>=i.value.value}}throw new Error("Unknown operator: ".concat(i.operator));case"sibling":var v=Ge(i.left),y=Ge(i.right);return function(N,k,h){return y(N,k,h)&&yv(N,v,k,"LEFT_SIDE",h)||i.left.subject&&v(N,k,h)&&yv(N,y,k,"RIGHT_SIDE",h)};case"adjacent":var S=Ge(i.left),T=Ge(i.right);return function(N,k,h){return T(N,k,h)&&fv(N,S,k,"LEFT_SIDE",h)||i.right.subject&&S(N,k,h)&&fv(N,T,k,"RIGHT_SIDE",h)};case"nth-child":var I=i.index.value,x=Ge(i.right);return function(N,k,h){return x(N,k,h)&&_v(N,k,I,h)};case"nth-last-child":var P=-i.index.value,U=Ge(i.right);return function(N,k,h){return U(N,k,h)&&_v(N,k,P,h)};case"class":var B=i.name.toLowerCase();return function(N,k,h){if(h&&h.matchClass)return h.matchClass(i.name,N,k);if(h&&h.nodeTypeKey)return!1;switch(B){case"statement":if(N.type.slice(-9)==="Statement")return!0;case"declaration":return N.type.slice(-11)==="Declaration";case"pattern":if(N.type.slice(-7)==="Pattern")return!0;case"expression":return N.type.slice(-10)==="Expression"||N.type.slice(-7)==="Literal"||N.type==="Identifier"&&(k.length===0||k[0].type!=="MetaProperty")||N.type==="MetaProperty";case"function":return N.type==="FunctionDeclaration"||N.type==="FunctionExpression"||N.type==="ArrowFunctionExpression"}throw new Error("Unknown class name: ".concat(i.name))}}throw new Error("Unknown selector type: ".concat(i.type))}function xp(i,e){var t=e&&e.nodeTypeKey||"type",r=i[t];return e&&e.visitorKeys&&e.visitorKeys[r]?e.visitorKeys[r]:Ca.VisitorKeys[r]?Ca.VisitorKeys[r]:e&&typeof e.fallback=="function"?e.fallback(i):Object.keys(i).filter((function(n){return n!==t}))}function Tp(i,e){var t=e&&e.nodeTypeKey||"type";return i!==null&&zn(i)==="object"&&typeof i[t]=="string"}function yv(i,e,t,r,n){var s=Ip(t,1)[0];if(!s)return!1;for(var o=xp(s,n),l=0;l<o.length;++l){var a=s[o[l]];if(Array.isArray(a)){var c=a.indexOf(i);if(c<0)continue;var p=void 0,d=void 0;r==="LEFT_SIDE"?(p=0,d=c):(p=c+1,d=a.length);for(var g=p;g<d;++g)if(Tp(a[g],n)&&e(a[g],t,n))return!0}}return!1}function fv(i,e,t,r,n){var s=Ip(t,1)[0];if(!s)return!1;for(var o=xp(s,n),l=0;l<o.length;++l){var a=s[o[l]];if(Array.isArray(a)){var c=a.indexOf(i);if(c<0)continue;if(r==="LEFT_SIDE"&&c>0&&Tp(a[c-1],n)&&e(a[c-1],t,n)||r==="RIGHT_SIDE"&&c<a.length-1&&Tp(a[c+1],n)&&e(a[c+1],t,n))return!0}}return!1}function _v(i,e,t,r){if(t===0)return!1;var n=Ip(e,1)[0];if(!n)return!1;for(var s=xp(n,r),o=0;o<s.length;++o){var l=n[s[o]];if(Array.isArray(l)){var a=t<0?l.length+t:t-1;if(a>=0&&a<l.length&&l[a]===i)return!0}}return!1}function wv(i,e,t,r){if(e){var n=[],s=Ge(e),o=(function l(a,c){if(a==null||zn(a)!="object")return[];c==null&&(c=a);for(var p=a.subject?[c]:[],d=Object.keys(a),g=0;g<d.length;++g){var b=d[g],v=a[b];p.push.apply(p,NA(l(v,b==="left"?v:c)))}return p})(e).map(Ge);Ca.traverse(i,{enter:function(l,a){if(a!=null&&n.unshift(a),s(l,n,r))if(o.length)for(var c=0,p=o.length;c<p;++c){o[c](l,n,r)&&t(l,a,n);for(var d=0,g=n.length;d<g;++d){var b=n.slice(d+1);o[c](n[d],b,r)&&t(n[d],a,b)}}else t(l,a,n)},leave:function(){n.shift()},keys:r&&r.visitorKeys,fallback:r&&r.fallback||"iteration"})}}function Sv(i,e,t){var r=[];return wv(i,e,(function(n){r.push(n)}),t),r}function Ev(i){return CA.parse(i)}function zt(i,e,t){return Sv(i,Ev(e),t)}var Ca,CA,Sp,Ap=w(()=>{Ca=kv((function(i,e){(function t(r){var n,s,o,l,a,c;function p(x){var P,U,B={};for(P in x)x.hasOwnProperty(P)&&(U=x[P],B[P]=typeof U=="object"&&U!==null?p(U):U);return B}function d(x,P){this.parent=x,this.key=P}function g(x,P,U,B){this.node=x,this.path=P,this.wrap=U,this.ref=B}function b(){}function v(x){return x!=null&&typeof x=="object"&&typeof x.type=="string"}function y(x,P){return(x===n.ObjectExpression||x===n.ObjectPattern)&&P==="properties"}function S(x,P){for(var U=x.length-1;U>=0;--U)if(x[U].node===P)return!0;return!1}function T(x,P){return new b().traverse(x,P)}function I(x,P){var U;return U=(function(B,N){var k,h,M,Z;for(h=B.length,M=0;h;)N(B[Z=M+(k=h>>>1)])?h=k:(M=Z+1,h-=k+1);return M})(P,(function(B){return B.range[0]>x.range[0]})),x.extendedRange=[x.range[0],x.range[1]],U!==P.length&&(x.extendedRange[1]=P[U].range[0]),(U-=1)>=0&&(x.extendedRange[0]=P[U].range[1]),x}return n={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},o={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},s={Break:l={},Skip:a={},Remove:c={}},d.prototype.replace=function(x){this.parent[this.key]=x},d.prototype.remove=function(){return Array.isArray(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},b.prototype.path=function(){var x,P,U,B,N;function k(h,M){if(Array.isArray(M))for(U=0,B=M.length;U<B;++U)h.push(M[U]);else h.push(M)}if(!this.__current.path)return null;for(N=[],x=2,P=this.__leavelist.length;x<P;++x)k(N,this.__leavelist[x].path);return k(N,this.__current.path),N},b.prototype.type=function(){return this.current().type||this.__current.wrap},b.prototype.parents=function(){var x,P,U;for(U=[],x=1,P=this.__leavelist.length;x<P;++x)U.push(this.__leavelist[x].node);return U},b.prototype.current=function(){return this.__current.node},b.prototype.__execute=function(x,P){var U,B;return B=void 0,U=this.__current,this.__current=P,this.__state=null,x&&(B=x.call(this,P.node,this.__leavelist[this.__leavelist.length-1].node)),this.__current=U,B},b.prototype.notify=function(x){this.__state=x},b.prototype.skip=function(){this.notify(a)},b.prototype.break=function(){this.notify(l)},b.prototype.remove=function(){this.notify(c)},b.prototype.__initialize=function(x,P){this.visitor=P,this.root=x,this.__worklist=[],this.__leavelist=[],this.__current=null,this.__state=null,this.__fallback=null,P.fallback==="iteration"?this.__fallback=Object.keys:typeof P.fallback=="function"&&(this.__fallback=P.fallback),this.__keys=o,P.keys&&(this.__keys=Object.assign(Object.create(this.__keys),P.keys))},b.prototype.traverse=function(x,P){var U,B,N,k,h,M,Z,re,ae,C,Se,me;for(this.__initialize(x,P),me={},U=this.__worklist,B=this.__leavelist,U.push(new g(x,null,null,null)),B.push(new g(null,null,null,null));U.length;)if((N=U.pop())!==me){if(N.node){if(M=this.__execute(P.enter,N),this.__state===l||M===l)return;if(U.push(me),B.push(N),this.__state===a||M===a)continue;if(h=(k=N.node).type||N.wrap,!(C=this.__keys[h])){if(!this.__fallback)throw new Error("Unknown node type "+h+".");C=this.__fallback(k)}for(re=C.length;(re-=1)>=0;)if(Se=k[Z=C[re]]){if(Array.isArray(Se)){for(ae=Se.length;(ae-=1)>=0;)if(Se[ae]&&!S(B,Se[ae])){if(y(h,C[re]))N=new g(Se[ae],[Z,ae],"Property",null);else{if(!v(Se[ae]))continue;N=new g(Se[ae],[Z,ae],null,null)}U.push(N)}}else if(v(Se)){if(S(B,Se))continue;U.push(new g(Se,Z,null,null))}}}}else if(N=B.pop(),M=this.__execute(P.leave,N),this.__state===l||M===l)return},b.prototype.replace=function(x,P){var U,B,N,k,h,M,Z,re,ae,C,Se,me,fe;function _(D){var V,ie,ue,je;if(D.ref.remove()){for(ie=D.ref.key,je=D.ref.parent,V=U.length;V--;)if((ue=U[V]).ref&&ue.ref.parent===je){if(ue.ref.key<ie)break;--ue.ref.key}}}for(this.__initialize(x,P),Se={},U=this.__worklist,B=this.__leavelist,M=new g(x,null,null,new d(me={root:x},"root")),U.push(M),B.push(M);U.length;)if((M=U.pop())!==Se){if((h=this.__execute(P.enter,M))!==void 0&&h!==l&&h!==a&&h!==c&&(M.ref.replace(h),M.node=h),this.__state!==c&&h!==c||(_(M),M.node=null),this.__state===l||h===l)return me.root;if((N=M.node)&&(U.push(Se),B.push(M),this.__state!==a&&h!==a)){if(k=N.type||M.wrap,!(ae=this.__keys[k])){if(!this.__fallback)throw new Error("Unknown node type "+k+".");ae=this.__fallback(N)}for(Z=ae.length;(Z-=1)>=0;)if(C=N[fe=ae[Z]])if(Array.isArray(C)){for(re=C.length;(re-=1)>=0;)if(C[re]){if(y(k,ae[Z]))M=new g(C[re],[fe,re],"Property",new d(C,re));else{if(!v(C[re]))continue;M=new g(C[re],[fe,re],null,new d(C,re))}U.push(M)}}else v(C)&&U.push(new g(C,fe,null,new d(N,fe)))}}else if(M=B.pop(),(h=this.__execute(P.leave,M))!==void 0&&h!==l&&h!==a&&h!==c&&M.ref.replace(h),this.__state!==c&&h!==c||_(M),this.__state===l||h===l)return me.root;return me.root},r.Syntax=n,r.traverse=T,r.replace=function(x,P){return new b().replace(x,P)},r.attachComments=function(x,P,U){var B,N,k,h,M=[];if(!x.range)throw new Error("attachComments needs range information");if(!U.length){if(P.length){for(k=0,N=P.length;k<N;k+=1)(B=p(P[k])).extendedRange=[0,x.range[0]],M.push(B);x.leadingComments=M}return x}for(k=0,N=P.length;k<N;k+=1)M.push(I(p(P[k]),U));return h=0,T(x,{enter:function(Z){for(var re;h<M.length&&!((re=M[h]).extendedRange[1]>Z.range[0]);)re.extendedRange[1]===Z.range[0]?(Z.leadingComments||(Z.leadingComments=[]),Z.leadingComments.push(re),M.splice(h,1)):h+=1;return h===M.length?s.Break:M[h].extendedRange[0]>Z.range[1]?s.Skip:void 0}}),h=0,T(x,{leave:function(Z){for(var re;h<M.length&&(re=M[h],!(Z.range[1]<re.extendedRange[0]));)Z.range[1]===re.extendedRange[0]?(Z.trailingComments||(Z.trailingComments=[]),Z.trailingComments.push(re),M.splice(h,1)):h+=1;return h===M.length?s.Break:M[h].extendedRange[0]>Z.range[1]?s.Skip:void 0}}),x},r.VisitorKeys=o,r.VisitorOption=s,r.Controller=b,r.cloneEnvironment=function(){return t({})},r})(e)})),CA=kv((function(i){i.exports&&(i.exports=(function(){function e(t,r,n,s){this.message=t,this.expected=r,this.found=n,this.location=s,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,e)}return(function(t,r){function n(){this.constructor=t}n.prototype=r.prototype,t.prototype=new n})(e,Error),e.buildMessage=function(t,r){var n={literal:function(a){return'"'+o(a.text)+'"'},class:function(a){var c,p="";for(c=0;c<a.parts.length;c++)p+=a.parts[c]instanceof Array?l(a.parts[c][0])+"-"+l(a.parts[c][1]):l(a.parts[c]);return"["+(a.inverted?"^":"")+p+"]"},any:function(a){return"any character"},end:function(a){return"end of input"},other:function(a){return a.description}};function s(a){return a.charCodeAt(0).toString(16).toUpperCase()}function o(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(function(c){return"\\x0"+s(c)})).replace(/[\x10-\x1F\x7F-\x9F]/g,(function(c){return"\\x"+s(c)}))}function l(a){return a.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,(function(c){return"\\x0"+s(c)})).replace(/[\x10-\x1F\x7F-\x9F]/g,(function(c){return"\\x"+s(c)}))}return"Expected "+(function(a){var c,p,d,g=new Array(a.length);for(c=0;c<a.length;c++)g[c]=(d=a[c],n[d.type](d));if(g.sort(),g.length>0){for(c=1,p=1;c<g.length;c++)g[c-1]!==g[c]&&(g[p]=g[c],p++);g.length=p}switch(g.length){case 1:return g[0];case 2:return g[0]+" or "+g[1];default:return g.slice(0,-1).join(", ")+", or "+g[g.length-1]}})(t)+" but "+(function(a){return a?'"'+o(a)+'"':"end of input"})(r)+" found."},{SyntaxError:e,parse:function(t,r){r=r!==void 0?r:{};var n,s,o,l,a={},c={start:xu},p=xu,d=_e(" ",!1),g=/^[^ [\],():#!=><~+.]/,b=jt([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),v=_e(">",!1),y=_e("~",!1),S=_e("+",!1),T=_e(",",!1),I=function(A,L){return[A].concat(L.map((function(j){return j[3]})))},x=_e("!",!1),P=_e("*",!1),U=_e("#",!1),B=_e("[",!1),N=_e("]",!1),k=/^[><!]/,h=jt([">","<","!"],!1,!1),M=_e("=",!1),Z=function(A){return(A||"")+"="},re=/^[><]/,ae=jt([">","<"],!1,!1),C=_e(".",!1),Se=function(A,L,j){return{type:"attribute",name:A,operator:L,value:j}},me=_e('"',!1),fe=/^[^\\"]/,_=jt(["\\",'"'],!0,!1),D=_e("\\",!1),V={type:"any"},ie=function(A,L){return A+L},ue=function(A){return{type:"literal",value:(L=A.join(""),L.replace(/\\(.)/g,(function(j,E){switch(E){case"b":return"\b";case"f":return"\f";case"n":return`
8
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";default:return E}})))};var L},je=_e("'",!1),qt=/^[^\\']/,gi=jt(["\\","'"],!0,!1),ge=/^[0-9]/,St=jt([["0","9"]],!1,!1),ys=_e("type(",!1),sn=/^[^ )]/,hu=jt([" ",")"],!0,!1),Fi=_e(")",!1),yu=/^[imsu]/,fu=jt(["i","m","s","u"],!1,!1),_u=_e("/",!1),vu=/^[^\]\\]/,ku=jt(["]","\\"],!0,!1),wu=/^[^\/\\[]/,Su=jt(["/","\\","["],!0,!1),tS=_e(":not(",!1),iS=_e(":matches(",!1),Eu=function(A){return{type:"matches",selectors:A}},rS=_e(":is(",!1),nS=_e(":has(",!1),sS=_e(":first-child",!1),aS=_e(":last-child",!1),oS=_e(":nth-child(",!1),lS=_e(":nth-last-child(",!1),cS=_e(":",!1),u=0,fs=[{line:1,column:1}],Ut=0,Mo=[],$={};if("startRule"in r){if(!(r.startRule in c))throw new Error(`Can't start parsing from rule "`+r.startRule+'".');p=c[r.startRule]}function _e(A,L){return{type:"literal",text:A,ignoreCase:L}}function jt(A,L,j){return{type:"class",parts:A,inverted:L,ignoreCase:j}}function Tu(A){var L,j=fs[A];if(j)return j;for(L=A-1;!fs[L];)L--;for(j={line:(j=fs[L]).line,column:j.column};L<A;)t.charCodeAt(L)===10?(j.line++,j.column=1):j.column++,L++;return fs[A]=j,j}function Iu(A,L){var j=Tu(A),E=Tu(L);return{start:{offset:A,line:j.line,column:j.column},end:{offset:L,line:E.line,column:E.column}}}function F(A){u<Ut||(u>Ut&&(Ut=u,Mo=[]),Mo.push(A))}function xu(){var A,L,j,E,R=36*u+0,W=$[R];return W?(u=W.nextPos,W.result):(A=u,(L=ce())!==a&&(j=_s())!==a&&ce()!==a?A=L=(E=j).length===1?E[0]:{type:"matches",selectors:E}:(u=A,A=a),A===a&&(A=u,(L=ce())!==a&&(L=void 0),A=L),$[R]={nextPos:u,result:A},A)}function ce(){var A,L,j=36*u+1,E=$[j];if(E)return u=E.nextPos,E.result;for(A=[],t.charCodeAt(u)===32?(L=" ",u++):(L=a,F(d));L!==a;)A.push(L),t.charCodeAt(u)===32?(L=" ",u++):(L=a,F(d));return $[j]={nextPos:u,result:A},A}function Jt(){var A,L,j,E=36*u+2,R=$[E];if(R)return u=R.nextPos,R.result;if(L=[],g.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,F(b)),j!==a)for(;j!==a;)L.push(j),g.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,F(b));else L=a;return L!==a&&(L=L.join("")),A=L,$[E]={nextPos:u,result:A},A}function Lo(){var A,L,j,E=36*u+3,R=$[E];return R?(u=R.nextPos,R.result):(A=u,(L=ce())!==a?(t.charCodeAt(u)===62?(j=">",u++):(j=a,F(v)),j!==a&&ce()!==a?A=L="child":(u=A,A=a)):(u=A,A=a),A===a&&(A=u,(L=ce())!==a?(t.charCodeAt(u)===126?(j="~",u++):(j=a,F(y)),j!==a&&ce()!==a?A=L="sibling":(u=A,A=a)):(u=A,A=a),A===a&&(A=u,(L=ce())!==a?(t.charCodeAt(u)===43?(j="+",u++):(j=a,F(S)),j!==a&&ce()!==a?A=L="adjacent":(u=A,A=a)):(u=A,A=a),A===a&&(A=u,t.charCodeAt(u)===32?(L=" ",u++):(L=a,F(d)),L!==a&&(j=ce())!==a?A=L="descendant":(u=A,A=a)))),$[E]={nextPos:u,result:A},A)}function _s(){var A,L,j,E,R,W,H,J,ee=36*u+5,te=$[ee];if(te)return u=te.nextPos,te.result;if(A=u,(L=vs())!==a){for(j=[],E=u,(R=ce())!==a?(t.charCodeAt(u)===44?(W=",",u++):(W=a,F(T)),W!==a&&(H=ce())!==a&&(J=vs())!==a?E=R=[R,W,H,J]:(u=E,E=a)):(u=E,E=a);E!==a;)j.push(E),E=u,(R=ce())!==a?(t.charCodeAt(u)===44?(W=",",u++):(W=a,F(T)),W!==a&&(H=ce())!==a&&(J=vs())!==a?E=R=[R,W,H,J]:(u=E,E=a)):(u=E,E=a);j!==a?A=L=I(L,j):(u=A,A=a)}else u=A,A=a;return $[ee]={nextPos:u,result:A},A}function qo(){var A,L,j,E,R,W=36*u+6,H=$[W];return H?(u=H.nextPos,H.result):(A=u,(L=Lo())===a&&(L=null),L!==a&&(j=vs())!==a?(R=j,A=L=(E=L)?{type:E,left:{type:"exactNode"},right:R}:R):(u=A,A=a),$[W]={nextPos:u,result:A},A)}function vs(){var A,L,j,E,R,W,H,J=36*u+7,ee=$[J];if(ee)return u=ee.nextPos,ee.result;if(A=u,(L=Uo())!==a){for(j=[],E=u,(R=Lo())!==a&&(W=Uo())!==a?E=R=[R,W]:(u=E,E=a);E!==a;)j.push(E),E=u,(R=Lo())!==a&&(W=Uo())!==a?E=R=[R,W]:(u=E,E=a);j!==a?(H=L,A=L=j.reduce((function(te,Ae){return{type:Ae[0],left:te,right:Ae[1]}}),H)):(u=A,A=a)}else u=A,A=a;return $[J]={nextPos:u,result:A},A}function Uo(){var A,L,j,E,R,W,H,J=36*u+8,ee=$[J];if(ee)return u=ee.nextPos,ee.result;if(A=u,t.charCodeAt(u)===33?(L="!",u++):(L=a,F(x)),L===a&&(L=null),L!==a){if(j=[],(E=Au())!==a)for(;E!==a;)j.push(E),E=Au();else j=a;j!==a?(R=L,H=(W=j).length===1?W[0]:{type:"compound",selectors:W},R&&(H.subject=!0),A=L=H):(u=A,A=a)}else u=A,A=a;return $[J]={nextPos:u,result:A},A}function Au(){var A,L=36*u+9,j=$[L];return j?(u=j.nextPos,j.result):((A=(function(){var E,R,W=36*u+10,H=$[W];return H?(u=H.nextPos,H.result):(t.charCodeAt(u)===42?(R="*",u++):(R=a,F(P)),R!==a&&(R={type:"wildcard",value:R}),E=R,$[W]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W,H=36*u+11,J=$[H];return J?(u=J.nextPos,J.result):(E=u,t.charCodeAt(u)===35?(R="#",u++):(R=a,F(U)),R===a&&(R=null),R!==a&&(W=Jt())!==a?E=R={type:"identifier",value:W}:(u=E,E=a),$[H]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W,H,J=36*u+12,ee=$[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.charCodeAt(u)===91?(R="[",u++):(R=a,F(B)),R!==a&&ce()!==a&&(W=(function(){var te,Ae,gt,he,Et=36*u+16,Xe=$[Et];return Xe?(u=Xe.nextPos,Xe.result):(te=u,(Ae=jo())!==a&&ce()!==a&&(gt=(function(){var G,K,ne,q=36*u+14,se=$[q];return se?(u=se.nextPos,se.result):(G=u,t.charCodeAt(u)===33?(K="!",u++):(K=a,F(x)),K===a&&(K=null),K!==a?(t.charCodeAt(u)===61?(ne="=",u++):(ne=a,F(M)),ne!==a?(K=Z(K),G=K):(u=G,G=a)):(u=G,G=a),$[q]={nextPos:u,result:G},G)})())!==a&&ce()!==a?((he=(function(){var G,K,ne,q,se,ke=36*u+20,bt=$[ke];if(bt)return u=bt.nextPos,bt.result;if(G=u,t.substr(u,5)==="type("?(K="type(",u+=5):(K=a,F(ys)),K!==a)if(ce()!==a){if(ne=[],sn.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(hu)),q!==a)for(;q!==a;)ne.push(q),sn.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(hu));else ne=a;ne!==a&&(q=ce())!==a?(t.charCodeAt(u)===41?(se=")",u++):(se=a,F(Fi)),se!==a?(K={type:"type",value:ne.join("")},G=K):(u=G,G=a)):(u=G,G=a)}else u=G,G=a;else u=G,G=a;return $[ke]={nextPos:u,result:G},G})())===a&&(he=(function(){var G,K,ne,q,se,ke,bt=36*u+22,Bt=$[bt];if(Bt)return u=Bt.nextPos,Bt.result;if(G=u,t.charCodeAt(u)===47?(K="/",u++):(K=a,F(_u)),K!==a){if(ne=[],(q=Ou())===a&&(q=ks())===a&&(q=Ru()),q!==a)for(;q!==a;)ne.push(q),(q=Ou())===a&&(q=ks())===a&&(q=Ru());else ne=a;ne!==a?(t.charCodeAt(u)===47?(q="/",u++):(q=a,F(_u)),q!==a?((se=(function(){var Xt,Gi,Pu=36*u+21,Bo=$[Pu];if(Bo)return u=Bo.nextPos,Bo.result;if(Xt=[],yu.test(t.charAt(u))?(Gi=t.charAt(u),u++):(Gi=a,F(fu)),Gi!==a)for(;Gi!==a;)Xt.push(Gi),yu.test(t.charAt(u))?(Gi=t.charAt(u),u++):(Gi=a,F(fu));else Xt=a;return $[Pu]={nextPos:u,result:Xt},Xt})())===a&&(se=null),se!==a?(ke=se,K={type:"regexp",value:new RegExp(ne.join(""),ke?ke.join(""):"")},G=K):(u=G,G=a)):(u=G,G=a)):(u=G,G=a)}else u=G,G=a;return $[bt]={nextPos:u,result:G},G})()),he!==a?(Ae=Se(Ae,gt,he),te=Ae):(u=te,te=a)):(u=te,te=a),te===a&&(te=u,(Ae=jo())!==a&&ce()!==a&&(gt=(function(){var G,K,ne,q=36*u+13,se=$[q];return se?(u=se.nextPos,se.result):(G=u,k.test(t.charAt(u))?(K=t.charAt(u),u++):(K=a,F(h)),K===a&&(K=null),K!==a?(t.charCodeAt(u)===61?(ne="=",u++):(ne=a,F(M)),ne!==a?(K=Z(K),G=K):(u=G,G=a)):(u=G,G=a),G===a&&(re.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,F(ae))),$[q]={nextPos:u,result:G},G)})())!==a&&ce()!==a?((he=(function(){var G,K,ne,q,se,ke,bt=36*u+17,Bt=$[bt];if(Bt)return u=Bt.nextPos,Bt.result;if(G=u,t.charCodeAt(u)===34?(K='"',u++):(K=a,F(me)),K!==a){for(ne=[],fe.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(_)),q===a&&(q=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(ke=t.charAt(u),u++):(ke=a,F(V)),ke!==a?(se=ie(se,ke),q=se):(u=q,q=a)):(u=q,q=a));q!==a;)ne.push(q),fe.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(_)),q===a&&(q=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(ke=t.charAt(u),u++):(ke=a,F(V)),ke!==a?(se=ie(se,ke),q=se):(u=q,q=a)):(u=q,q=a));ne!==a?(t.charCodeAt(u)===34?(q='"',u++):(q=a,F(me)),q!==a?(K=ue(ne),G=K):(u=G,G=a)):(u=G,G=a)}else u=G,G=a;if(G===a)if(G=u,t.charCodeAt(u)===39?(K="'",u++):(K=a,F(je)),K!==a){for(ne=[],qt.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(gi)),q===a&&(q=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(ke=t.charAt(u),u++):(ke=a,F(V)),ke!==a?(se=ie(se,ke),q=se):(u=q,q=a)):(u=q,q=a));q!==a;)ne.push(q),qt.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(gi)),q===a&&(q=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(ke=t.charAt(u),u++):(ke=a,F(V)),ke!==a?(se=ie(se,ke),q=se):(u=q,q=a)):(u=q,q=a));ne!==a?(t.charCodeAt(u)===39?(q="'",u++):(q=a,F(je)),q!==a?(K=ue(ne),G=K):(u=G,G=a)):(u=G,G=a)}else u=G,G=a;return $[bt]={nextPos:u,result:G},G})())===a&&(he=(function(){var G,K,ne,q,se,ke,bt,Bt=36*u+18,Xt=$[Bt];if(Xt)return u=Xt.nextPos,Xt.result;for(G=u,K=u,ne=[],ge.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(St));q!==a;)ne.push(q),ge.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(St));if(ne!==a?(t.charCodeAt(u)===46?(q=".",u++):(q=a,F(C)),q!==a?K=ne=[ne,q]:(u=K,K=a)):(u=K,K=a),K===a&&(K=null),K!==a){if(ne=[],ge.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(St)),q!==a)for(;q!==a;)ne.push(q),ge.test(t.charAt(u))?(q=t.charAt(u),u++):(q=a,F(St));else ne=a;ne!==a?(ke=ne,bt=(se=K)?[].concat.apply([],se).join(""):"",K={type:"literal",value:parseFloat(bt+ke.join(""))},G=K):(u=G,G=a)}else u=G,G=a;return $[Bt]={nextPos:u,result:G},G})())===a&&(he=(function(){var G,K,ne=36*u+19,q=$[ne];return q?(u=q.nextPos,q.result):((K=Jt())!==a&&(K={type:"literal",value:K}),G=K,$[ne]={nextPos:u,result:G},G)})()),he!==a?(Ae=Se(Ae,gt,he),te=Ae):(u=te,te=a)):(u=te,te=a),te===a&&(te=u,(Ae=jo())!==a&&(Ae={type:"attribute",name:Ae}),te=Ae)),$[Et]={nextPos:u,result:te},te)})())!==a&&ce()!==a?(t.charCodeAt(u)===93?(H="]",u++):(H=a,F(N)),H!==a?E=R=W:(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W,H,J,ee,te,Ae,gt=36*u+26,he=$[gt];if(he)return u=he.nextPos,he.result;if(E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,F(C)),R!==a)if((W=Jt())!==a){for(H=[],J=u,t.charCodeAt(u)===46?(ee=".",u++):(ee=a,F(C)),ee!==a&&(te=Jt())!==a?J=ee=[ee,te]:(u=J,J=a);J!==a;)H.push(J),J=u,t.charCodeAt(u)===46?(ee=".",u++):(ee=a,F(C)),ee!==a&&(te=Jt())!==a?J=ee=[ee,te]:(u=J,J=a);H!==a?(Ae=W,R={type:"field",name:H.reduce((function(Et,Xe){return Et+Xe[0]+Xe[1]}),Ae)},E=R):(u=E,E=a)}else u=E,E=a;else u=E,E=a;return $[gt]={nextPos:u,result:E},E})())===a&&(A=(function(){var E,R,W,H,J=36*u+27,ee=$[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,5)===":not("?(R=":not(",u+=5):(R=a,F(tS)),R!==a&&ce()!==a&&(W=_s())!==a&&ce()!==a?(t.charCodeAt(u)===41?(H=")",u++):(H=a,F(Fi)),H!==a?E=R={type:"not",selectors:W}:(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W,H,J=36*u+28,ee=$[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,9)===":matches("?(R=":matches(",u+=9):(R=a,F(iS)),R!==a&&ce()!==a&&(W=_s())!==a&&ce()!==a?(t.charCodeAt(u)===41?(H=")",u++):(H=a,F(Fi)),H!==a?(R=Eu(W),E=R):(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W,H,J=36*u+29,ee=$[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,4)===":is("?(R=":is(",u+=4):(R=a,F(rS)),R!==a&&ce()!==a&&(W=_s())!==a&&ce()!==a?(t.charCodeAt(u)===41?(H=")",u++):(H=a,F(Fi)),H!==a?(R=Eu(W),E=R):(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W,H,J=36*u+30,ee=$[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,5)===":has("?(R=":has(",u+=5):(R=a,F(nS)),R!==a&&ce()!==a&&(W=(function(){var te,Ae,gt,he,Et,Xe,G,K,ne=36*u+4,q=$[ne];if(q)return u=q.nextPos,q.result;if(te=u,(Ae=qo())!==a){for(gt=[],he=u,(Et=ce())!==a?(t.charCodeAt(u)===44?(Xe=",",u++):(Xe=a,F(T)),Xe!==a&&(G=ce())!==a&&(K=qo())!==a?he=Et=[Et,Xe,G,K]:(u=he,he=a)):(u=he,he=a);he!==a;)gt.push(he),he=u,(Et=ce())!==a?(t.charCodeAt(u)===44?(Xe=",",u++):(Xe=a,F(T)),Xe!==a&&(G=ce())!==a&&(K=qo())!==a?he=Et=[Et,Xe,G,K]:(u=he,he=a)):(u=he,he=a);gt!==a?te=Ae=I(Ae,gt):(u=te,te=a)}else u=te,te=a;return $[ne]={nextPos:u,result:te},te})())!==a&&ce()!==a?(t.charCodeAt(u)===41?(H=")",u++):(H=a,F(Fi)),H!==a?E=R={type:"has",selectors:W}:(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W=36*u+31,H=$[W];return H?(u=H.nextPos,H.result):(t.substr(u,12)===":first-child"?(R=":first-child",u+=12):(R=a,F(sS)),R!==a&&(R=Nu(1)),E=R,$[W]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W=36*u+32,H=$[W];return H?(u=H.nextPos,H.result):(t.substr(u,11)===":last-child"?(R=":last-child",u+=11):(R=a,F(aS)),R!==a&&(R=Cu(1)),E=R,$[W]={nextPos:u,result:E},E)})())===a&&(A=(function(){var E,R,W,H,J,ee=36*u+33,te=$[ee];if(te)return u=te.nextPos,te.result;if(E=u,t.substr(u,11)===":nth-child("?(R=":nth-child(",u+=11):(R=a,F(oS)),R!==a)if(ce()!==a){if(W=[],ge.test(t.charAt(u))?(H=t.charAt(u),u++):(H=a,F(St)),H!==a)for(;H!==a;)W.push(H),ge.test(t.charAt(u))?(H=t.charAt(u),u++):(H=a,F(St));else W=a;W!==a&&(H=ce())!==a?(t.charCodeAt(u)===41?(J=")",u++):(J=a,F(Fi)),J!==a?(R=Nu(parseInt(W.join(""),10)),E=R):(u=E,E=a)):(u=E,E=a)}else u=E,E=a;else u=E,E=a;return $[ee]={nextPos:u,result:E},E})())===a&&(A=(function(){var E,R,W,H,J,ee=36*u+34,te=$[ee];if(te)return u=te.nextPos,te.result;if(E=u,t.substr(u,16)===":nth-last-child("?(R=":nth-last-child(",u+=16):(R=a,F(lS)),R!==a)if(ce()!==a){if(W=[],ge.test(t.charAt(u))?(H=t.charAt(u),u++):(H=a,F(St)),H!==a)for(;H!==a;)W.push(H),ge.test(t.charAt(u))?(H=t.charAt(u),u++):(H=a,F(St));else W=a;W!==a&&(H=ce())!==a?(t.charCodeAt(u)===41?(J=")",u++):(J=a,F(Fi)),J!==a?(R=Cu(parseInt(W.join(""),10)),E=R):(u=E,E=a)):(u=E,E=a)}else u=E,E=a;else u=E,E=a;return $[ee]={nextPos:u,result:E},E})())===a&&(A=(function(){var E,R,W,H=36*u+35,J=$[H];return J?(u=J.nextPos,J.result):(E=u,t.charCodeAt(u)===58?(R=":",u++):(R=a,F(cS)),R!==a&&(W=Jt())!==a?E=R={type:"class",name:W}:(u=E,E=a),$[H]={nextPos:u,result:E},E)})()),$[L]={nextPos:u,result:A},A)}function jo(){var A,L,j,E,R,W,H,J,ee=36*u+15,te=$[ee];if(te)return u=te.nextPos,te.result;if(A=u,(L=Jt())!==a){for(j=[],E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,F(C)),R!==a&&(W=Jt())!==a?E=R=[R,W]:(u=E,E=a);E!==a;)j.push(E),E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,F(C)),R!==a&&(W=Jt())!==a?E=R=[R,W]:(u=E,E=a);j!==a?(H=L,J=j,A=L=[].concat.apply([H],J).join("")):(u=A,A=a)}else u=A,A=a;return $[ee]={nextPos:u,result:A},A}function Ou(){var A,L,j,E,R=36*u+23,W=$[R];if(W)return u=W.nextPos,W.result;if(A=u,t.charCodeAt(u)===91?(L="[",u++):(L=a,F(B)),L!==a){if(j=[],vu.test(t.charAt(u))?(E=t.charAt(u),u++):(E=a,F(ku)),E===a&&(E=ks()),E!==a)for(;E!==a;)j.push(E),vu.test(t.charAt(u))?(E=t.charAt(u),u++):(E=a,F(ku)),E===a&&(E=ks());else j=a;j!==a?(t.charCodeAt(u)===93?(E="]",u++):(E=a,F(N)),E!==a?A=L="["+j.join("")+"]":(u=A,A=a)):(u=A,A=a)}else u=A,A=a;return $[R]={nextPos:u,result:A},A}function ks(){var A,L,j,E=36*u+24,R=$[E];return R?(u=R.nextPos,R.result):(A=u,t.charCodeAt(u)===92?(L="\\",u++):(L=a,F(D)),L!==a?(t.length>u?(j=t.charAt(u),u++):(j=a,F(V)),j!==a?A=L="\\"+j:(u=A,A=a)):(u=A,A=a),$[E]={nextPos:u,result:A},A)}function Ru(){var A,L,j,E=36*u+25,R=$[E];if(R)return u=R.nextPos,R.result;if(L=[],wu.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,F(Su)),j!==a)for(;j!==a;)L.push(j),wu.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,F(Su));else L=a;return L!==a&&(L=L.join("")),A=L,$[E]={nextPos:u,result:A},A}function Nu(A){return{type:"nth-child",index:{type:"literal",value:A}}}function Cu(A){return{type:"nth-last-child",index:{type:"literal",value:A}}}if((n=p())!==a&&u===t.length)return n;throw n!==a&&u<t.length&&F({type:"end"}),s=Mo,o=Ut<t.length?t.charAt(Ut):null,l=Ut<t.length?Iu(Ut,Ut+1):Iu(Ut,Ut),new e(e.buildMessage(s,o),s,o,l)}}})())}));Sp=typeof WeakMap=="function"?new WeakMap:null;zt.parse=Ev,zt.match=Sv,zt.traverse=wv,zt.matches=function(i,e,t,r){return!e||!!i&&(t||(t=[]),Ge(e)(i,t,r))},zt.query=zt});var Pa,Op=w(()=>{Pa={}});var Tv,Iv=w(()=>{Tv={}});function DA(i){return[...(i||[]).filter(r=>r.type!=="RestElement"&&r.type!=="AssignmentPattern").map((r,n)=>({type:"Identifier",name:`__apm$arg${n}`})),{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}]}function Da(i,e,t,r){let n=r[r.length-1];e.type==="ClassDeclaration"||e.type==="ClassExpression"?BA(i,e,n):jA(i,e,n)}function MA(i,e){if(i.type!=="ReturnStatement")return!1;let t=i.argument?.type==="CallExpression"?i.argument.callee:null;return t?.type==="MemberExpression"&&t.property?.name==="runStores"&&t.object?.type==="MemberExpression"&&t.object.property?.name==="start"&&t.object.object?.type==="Identifier"&&t.object.object.name===e}function LA(i){let e=(s,o)=>s?.find(a=>a.type==="VariableDeclaration"&&a.declarations.some(c=>c.id?.name===o))?.declarations.find(a=>a.id?.name===o)?.init??null,t=e(i,"__apm$traced"),r=e(t?.body?.body,"__apm$wrapped"),n=r?.type;return n==="FunctionExpression"||n==="ArrowFunctionExpression"||n==="FunctionDeclaration"?r:null}function qA(i,e){let t=new Set,r=i;for(;r&&!t.has(r);){t.add(r);let n=r.body?.body;if(!Array.isArray(n))return!1;if(n.some(s=>MA(s,e)))return!0;r=LA(n)}return!1}function UA(i,e){let t=i?.value?.body?.body;return Array.isArray(t)?t.some(r=>r.type==="VariableDeclaration"&&r.declarations.some(n=>n.id?.name===e)):!1}function jA(i,e,t){if(qA(e,Vt(i.channelName)))return;i.transforms.tracingChannelDeclaration(i,t);let{functionQuery:{methodName:r,privateMethodName:n,functionName:s,expressionName:o,propertyName:l}}=i,a=r==="constructor"||!r&&!n&&!s&&!o&&!l,c=a?"ArrowFunctionExpression":e.type,p=e.params,d=`${Vt(i.channelName)}$self`;i.selfBinding=a&&FA(e,d)?d:null,e.body=Ov(i,{type:c,params:p,body:e.body,async:e.async,expression:!1,generator:e.generator},t),e.params=DA(p),e.generator=!1,e.async=!1,c!=="ArrowFunctionExpression"&&Rv(i,e)}function BA(i,e,t){let{functionQuery:r,operator:n,channelName:s}=i,{methodName:o}=r;if(!o)return;let l=e.body;if(l.body.some(({key:g})=>g?.name===o))return;let a=l.body.find(({kind:g})=>g==="constructor"),c=`${Vt(s)}$${o}`;if(a&&UA(a,c))return;i.transforms.tracingChannelDeclaration(i,t),a||(a=Qe(e.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],l.body.unshift(a));let p=Qe(`
9
- const ${c} = this["${o}"]
10
- this["${o}"] = function () {}
11
- if (typeof ${c} === 'function') {
12
- Object.defineProperty(this["${o}"], 'length', {
13
- value: ${c}.length,
1
+ var Hw=Object.defineProperty;var w=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}};var Gw=(t,e)=>{for(var i in e)Hw(t,i,{get:e[i],enumerable:!0})};var ju,Bu=w(()=>{ju=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var B,Ie=w(()=>{B=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var Q,rt=w(()=>{Q=globalThis});var At,zn=w(()=>{At="11.15.0"});function ye(){return He(Q),Q}function He(t){let e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||"11.15.0",e[At]=e["11.15.0"]||{}}function ht(t,e,i=Q){let r=i.__SENTRY__=i.__SENTRY__||{},n=r[At]=r["11.15.0"]||{};return n[t]||(n[t]=e())}var nt=w(()=>{zn();rt()});function st(t){if(!("console"in Q))return t();let e=Q.console,i={},r=Object.keys(Qa);r.forEach(n=>{let s=Qa[n];i[n]=e[n],e[n]=s});try{return t()}finally{r.forEach(n=>{e[n]=i[n]})}}function QS(){Xa().enabled=!0}function JS(){Xa().enabled=!1}function Fu(){return Xa().enabled}function XS(...t){Ja("log",...t)}function ZS(...t){Ja("warn",...t)}function ek(...t){Ja("error",...t)}function Ja(t,...e){B&&Fu()&&st(()=>{Q.console[t](`${YS}[${t}]:`,...e)})}function Xa(){return B?ht("loggerSettings",()=>({enabled:!1})):{enabled:!1}}var YS,Qa,U,Ae=w(()=>{nt();Ie();rt();YS="Sentry Logger ",Qa={};U={enable:QS,disable:JS,isEnabled:Fu,log:XS,warn:ZS,error:ek}});function eo(...t){let e=t.sort((i,r)=>i[0]-r[0]).map(i=>i[1]);return(i,r=0,n=0)=>{let s=[],a=i.split(`
2
+ `);for(let o=r;o<a.length;o++){let l=a[o];l.length>1024&&(l=l.slice(0,1024));let c=Hu.test(l)?l.replace(Hu,"$1"):l;if(!c.includes("Error: ")){for(let p of e){let u=p(c);if(u){s.push(u);break}}if(s.length>=50+n)break}}return Wu(s.slice(n))}}function Wu(t){if(!t.length)return[];let e=Array.from(t);return/sentryWrapped/.test(Kn(e).function||"")&&e.pop(),e.reverse(),Gu.test(Kn(e).function||"")&&(e.pop(),Gu.test(Kn(e).function||"")&&e.pop()),e.slice(0,50).map(i=>({...i,filename:i.filename||Kn(e).filename,function:i.function||"?"}))}function Kn(t){return t[t.length-1]||{}}function to(t){try{return!t||typeof t!="function"?Za:t.name||Za}catch{return Za}}function $u(t){let e=t?.startsWith("file://")?t.slice(7):t;return e?.match(/\/[A-Z]:/)&&(e=e.slice(1)),e}var Hu,Gu,Za,Yn=w(()=>{Hu=/\(error: (.*)\)/,Gu=/captureMessage|captureException/;Za="<anonymous>"});function at(t){switch(Vu.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Qu(t,Error)}}function Qn(t,e){return Vu.call(t)===`[object ${e}]`}function zu(t){return Qn(t,"ErrorEvent")}function Ir(t){return Qn(t,"String")}function Ar(t){return typeof t=="object"&&t!==null&&"__sentry_template_string__"in t&&"__sentry_template_values__"in t}function yt(t){return t===null||Ar(t)||typeof t!="object"&&typeof t!="function"}function di(t){return Qn(t,"Object")}function xr(t){return typeof t=="object"&&t!==null}function Ku(t){return typeof Event<"u"&&Qu(t,Event)}function Yu(t){return Qn(t,"RegExp")}function xt(t){return!!(t?.then&&typeof t.then=="function")}function Qu(t,e){try{return t instanceof e}catch{return!1}}var Vu,De=w(()=>{Vu=Object.prototype.toString});function Jn(t,e,i){try{Object.defineProperty(t,e,{value:i,writable:!0,configurable:!0})}catch{B&&U.log(`Failed to add non-enumerable property "${String(e)}" to object`,t)}}function io(t){if(at(t))return{message:t.message,name:t.name,stack:t.stack,...Ju(t)};if(Ku(t)){let{type:e,target:i,currentTarget:r,detail:n}=t;return{type:e,target:i,currentTarget:r,...n?{detail:n}:{},...Ju(t)}}return t}function Ju(t){return xr(t)?Object.fromEntries(Object.entries(t)):{}}function Xu(t){let e=Object.keys(io(t));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}var Or=w(()=>{Ie();Ae();De()});function jt(t){if(qi!==void 0)return qi?qi(t):t();let e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),i=Q;return e in i&&typeof i[e]=="function"?(qi=i[e],qi(t)):(qi=null,t())}function Qe(){return jt(()=>Math.random())}function xe(){return jt(()=>Date.now())}var qi,ot=w(()=>{rt()});function Zu(t){return!!t[tk]}function em(t){let e=t[ik];return typeof e=="number"?e:void 0}var tk,ik,tm=w(()=>{tk=Symbol.for("sentry.skipNormalization"),ik=Symbol.for("sentry.overrideNormalizationDepth")});function lt(t,e=100,i=1/0){try{return ro("",t,e,i)}catch(r){return{ERROR:`**non-serializable** (${rm(r)})`}}}function rm(t){try{return String(t)}catch{return"unknown error"}}function no(t,e=3,i=102400){let r=lt(t,e);return sk(r)>i?no(t,e-1,i):r}function ro(t,e,i=1/0,r=1/0,n=ak()){let[s,a]=n;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;let o=so(t,e);if(!o.startsWith("[object "))return o;if(Zu(e))return e;let l=em(e),c=l!==void 0?l:i;if(c===0)return o.replace("object ","");if(s(e))return"[Circular ~]";let p=e;if(p&&typeof p.toJSON=="function")try{return ro("",p.toJSON(),c-1,r,n)}catch{}let u=Array.isArray(e)?[]:{},m=0,g=io(e);for(let h in g){if(!Object.prototype.hasOwnProperty.call(g,h))continue;if(m>=r){u[h]="[MaxProperties ~]";break}let f=g[h];u[h]=ro(h,f,c-1,r,n),m++}return a(e),u}function so(t,e){try{if(im){let i=im(e);if(i)return i}return typeof global<"u"&&e===global?"[Global]":typeof e=="number"&&!Number.isFinite(e)?`[${e}]`:typeof e=="function"?`[Function: ${to(e)}]`:typeof e=="symbol"?`[${String(e)}]`:typeof e=="bigint"?`[BigInt: ${String(e)}]`:`[object ${rk(e)}]`}catch(i){return`**non-serializable** (${rm(i)})`}}function rk(t){let e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}function nk(t){return~-encodeURI(t).split(/%..|./).length}function sk(t){return nk(JSON.stringify(t))}function ak(){let t=new WeakSet;function e(r){return t.has(r)?!0:(t.add(r),!1)}function i(r){t.delete(r)}return[e,i]}var im,Xn=w(()=>{tm();Or();Yn()});function ao(t){return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var nm=w(()=>{});function sm(t,e="[unserializable]"){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return typeof e=="function"?e(t):e}}function Rr(t,e=0){return typeof t!="string"||e===0||t.length<=e?t:`${t.slice(0,e)}...`}function Nr(t,e,i=!1){return Ir(t)?Yu(e)?e.test(t):Ir(e)?i?t===e:t.includes(e):typeof e=="function"?e(t):!1:!1}var Pr=w(()=>{De()});function ok(){let t=Q;return t.crypto||t.msCrypto}function lk(){return Qe()*16}function _e(t=ok()){try{if(t?.randomUUID)return jt(()=>t.randomUUID()).replace(/-/g,"")}catch{}return oo||(oo="10000000100040008000100000000000"),oo.replace(/[018]/g,e=>(e^(lk()&15)>>e/4).toString(16))}function ck(t){return t.exception?.values?.[0]}function co(t,e,i){let r=t.exception=t.exception||{},n=r.values=r.values||[],s=n[0]=n[0]||{};s.value||(s.value=e||""),s.type||(s.type=i||"Error")}function Zn(t,e){let i=ck(t);i&&om(i,e)}function am(t,e){let i=t.exception?.values,r=i?.find(n=>n.mechanism?.exception_id===0)??i?.[0];r&&om(r,e)}function om(t,e){let i={type:"generic",handled:!0},r=t.mechanism;t.mechanism={...i,...r,...e},e&&"data"in e&&(t.mechanism.data={...r?.data,...e.data})}function lo(t){return parseInt(t||"",10)}function po(t){let e=t.match(pk)||[],i=lo(e[1]),r=lo(e[2]),n=lo(e[3]);return{buildmetadata:e[5],major:isNaN(i)?void 0:i,minor:isNaN(r)?void 0:r,patch:isNaN(n)?void 0:n,prerelease:e[4]}}function es(t){if(lm(t))return!0;try{Jn(t,"__sentry_captured__",!0)}catch{}return!1}function lm(t){try{return t.__sentry_captured__}catch{}}var oo,pk,Ot=w(()=>{Or();ot();rt();pk=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/});function ui(){return xe()/pm}function mk(){let{performance:t}=Q;if(!t?.now||!t.timeOrigin)return t?.now&&(ji=[{from:0,origin:xe()-jt(()=>t.now())}]),ui;let e=t.timeOrigin;ji=[{from:0,origin:e}];let i=!0,r=0;return()=>jt(()=>{let n=t.now(),s=Date.now();return Math.abs(e+n-s)>dk&&(e=s-n,i?ji=[{from:0,origin:e}]:(ji.push({from:r,origin:e}),ji.length>uk&&ji.splice(1,1))),i=!1,r=n,(e+n)/pm})}function ts(){return(cm??(cm=mk()))()}var pm,dk,uk,ji,cm,Bi=w(()=>{ot();rt();pm=1e3,dk=1e3,uk=100;ji=[]});function Cr(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),!t.did&&!e.did&&(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||ts(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=e.sid.length===32?e.sid:_e()),e.init!==void 0&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),typeof e.started=="number"&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if(typeof e.duration=="number")t.duration=e.duration;else{let i=t.timestamp-t.started;t.duration=i>=0?i:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),typeof e.errors=="number"&&(t.errors=e.errors),e.status&&(t.status=e.status)}var uo=w(()=>{Ot();Bi()});function Bt(t,e,i=2){if(!e||typeof e!="object"||i<=0)return e;if(t&&Object.keys(e).length===0)return t;let r={...t};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Bt(r[n],e[n],i-1));return r}var is=w(()=>{});function mi(){return _e()}function Mr(){return _e().substring(16)}var Dr=w(()=>{Ot()});var gk,Ge,Fi=w(()=>{Ie();uo();Ae();De();Or();is();Ot();Dr();ot();Pr();Bi();gk=100,Ge=class mo{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},Jn(this,"refs",{}),this._propagationContext={traceId:mi(),sampleRand:Qe()}}clone(){let e=new mo;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._attributes={...this._attributes},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,e._conversationId=this._conversationId,e.refs={...this.refs},e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Cr(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(e){return this._conversationId=e||void 0,this._notifyScopeListeners(),this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,i){return this.setTags({[e]:i})}setAttributes(e){return this._attributes={...this._attributes,...e},this._notifyScopeListeners(),this}setAttribute(e,i){return this.setAttributes({[e]:i})}removeAttribute(e){return e in this._attributes&&(delete this._attributes[e],this._notifyScopeListeners()),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,i){return this._extra={...this._extra,[e]:i},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,i){return i===null?delete this._contexts[e]:this._contexts[e]=i,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;let i=typeof e=="function"?e(this):e,{tags:r,attributes:n,extra:s,user:a,contexts:o,level:l,fingerprint:c=[],propagationContext:p,conversationId:u}=(i instanceof mo?i.getScopeData():di(i)?e:void 0)||{};return this._tags={...this._tags,...r},this._attributes={...this._attributes,...n},this._extra={...this._extra,...s},this._contexts={...this._contexts,...o},a&&Object.keys(a).length&&(this._user=a),l&&(this._level=l),c.length&&(this._fingerprint=c),p&&(this._propagationContext=p),u&&(this._conversationId=u),this}addBreadcrumb(e,i){let r=typeof i=="number"?i:gk;if(r<=0)return this;let n={timestamp:ui(),...e,message:e.message?Rr(e.message,2048):e.message};return this._breadcrumbs.push(n),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r)),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,conversationId:this._conversationId}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=Bt(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext=e,this}getPropagationContext(){return this._propagationContext}captureException(e,i){let r=i?.event_id||_e();if(!this._client)return B&&U.warn("No client configured on scope - will not capture exception!"),r;let n=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:n,...i,event_id:r},this),r}captureMessage(e,i,r){let n=r?.event_id||_e();if(!this._client)return B&&U.warn("No client configured on scope - will not capture message!"),n;let s=r?.syntheticException??new Error(e);return this._client.captureMessage(e,i,{originalException:e,syntheticException:s,...r,event_id:n},this),n}captureEvent(e,i){let r=e.event_id||i?.event_id||_e();return this._client?(this._client.captureEvent(e,{...i,event_id:r},this),r):(B&&U.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}});function gi(){return ht("defaultCurrentScope",()=>new Ge)}function fi(){return ht("defaultIsolationScope",()=>new Ge)}var go=w(()=>{nt();Fi()});var fo,dm=w(()=>{fo="__SENTRY_SUPPRESS_TRACING__"});var um,mm,gm,fk,fm=w(()=>{um=t=>t instanceof Promise&&!t[mm],mm=Symbol("chained PromiseLike"),gm=(t,e,i)=>{let r=t.then(n=>(e(n),n),n=>{throw i(n),n});return um(r)&&um(t)?r:fk(t,r)},fk=(t,e)=>{if(!e)return t;let i=!1;for(let r in t){if(r in e)continue;i=!0;let n=t[r];typeof n=="function"?Object.defineProperty(e,r,{value:(...s)=>n.apply(t,s),enumerable:!0,configurable:!0,writable:!0}):e[r]=n}return i&&Object.assign(e,{[mm]:!0}),e}});function Hi(){let t=ye(),e=He(t);return e.stack=e.stack||new hk(gi(),fi())}function ym(t){return Hi().withScope(t)}function yk(t,e){let i=Hi();return i.withScope(()=>(i.getStackTop().scope=t,e(t)))}function hm(t){return Hi().withScope(()=>t(Hi().getIsolationScope()))}function bm(){return{suppressTracing:bk,withIsolationScope:hm,withScope:ym,withSetScope:yk,withSetIsolationScope:(t,e)=>hm(e),getCurrentScope:()=>Hi().getScope(),getIsolationScope:()=>Hi().getIsolationScope()}}function bk(t){return ym(e=>{e.setSDKProcessingMetadata({[fo]:!0});let i=t();return e.setSDKProcessingMetadata({[fo]:void 0}),i})}var hk,_m=w(()=>{go();Fi();dm();fm();De();nt();hk=class{constructor(t,e){let i;t?i=t:i=new Ge;let r;e?r=e:r=new Ge,this._stack=[{scope:i}],this._isolationScope=r}withScope(t){let e=this._pushScope(),i;try{i=t(e)}catch(r){throw this._popScope(),r}return xt(i)?gm(i,()=>this._popScope(),()=>this._popScope()):(this._popScope(),i)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let t=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:t}),t}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}});function Lr(t){let e=ye(),i=He(e);i.acs=t}function ct(t){let e=He(t);return e.acs?e.acs:bm()}var rs=w(()=>{nt();_m()});function _k(t){return typeof t=="object"&&t!=null&&!Array.isArray(t)&&Object.keys(t).includes("value")}function vk(t,e){let{value:i,unit:r}=_k(t)?t:{value:t,unit:void 0},n=wk(i),s=r&&typeof r=="string"?{unit:r}:{};if(n)return{...n,...s};if(!e||e==="skip-undefined"&&i===void 0)return;let a="";try{a=JSON.stringify(i)??""}catch{}return{value:a,type:"string",...s}}function ho(t,e=!1){let i={};for(let[r,n]of Object.entries(t??{})){let s=vk(n,e);s&&(i[r]=s)}return i}function yo(t){if(!t)return 0;let e=0;for(let[i,r]of Object.entries(t)){e+=i.length*2,e+=r.type.length*2,e+=(r.unit?.length??0)*2;let n=r.value;Array.isArray(n)?e+=vm(n[0])*n.length:yt(n)?e+=vm(n):e+=100}return e}function vm(t){return typeof t=="string"?t.length*2:typeof t=="boolean"?4:typeof t=="number"?8:0}function wk(t){if(Array.isArray(t))return{value:t,type:"array"};let e=typeof t=="string"?"string":typeof t=="boolean"?"boolean":typeof t=="number"&&!Number.isNaN(t)?Number.isInteger(t)?"integer":"double":null;if(e)return{value:t,type:e}}var bo=w(()=>{De()});function ns(){return He(ye()).externalPropagationContextProvider?.()}function Rt(){let t=ye();return ct(t).getCurrentScope()}function hi(){let t=ye();return ct(t).getIsolationScope()}function _o(){return ht("globalScope",()=>new Ge)}function ss(...t){let e=ye(),i=ct(e);if(t.length===2){let[r,n]=t;return r?i.withSetScope(r,n):i.withScope(n)}return i.withScope(t[0])}function bt(){return Rt().getClient()}function yi(t){let e=ns();if(e)return{trace_id:e.traceId,span_id:e.spanId};let{traceId:i,parentSpanId:r,propagationSpanId:n}=t.getPropagationContext(),s={trace_id:i,span_id:n||Mr()};return r&&(s.parent_span_id=r),s}var pt=w(()=>{rs();nt();Fi();Dr()});var wm,Sm=w(()=>{wm="sentry.custom_span_name"});var km,Em=w(()=>{km=["ok","deadline_exceeded","unauthenticated","permission_denied","not_found","resource_exhausted","invalid_argument","unimplemented","unavailable","internal_error","unknown_error","cancelled","already_exists","failed_precondition","aborted","out_of_range","data_loss"]});var Tm,Im,Am,xm,Om,Rm,Nm,vo,Pm,Cm,Mm,Ur,Dm,Lm,Um,qm,jm,qr,wo,Bm,Fm,as,Hm,Gm,Wm,$m,Vm,zm,_t=w(()=>{Tm="angular.version",Im="culture.locale",Am="culture.timezone",xm="http.response.body.size",Om="http.response.status_code",Rm="react.version",Nm="sentry.environment",vo="sentry.exclusive_time",Pm="sentry.op",Cm="sentry.origin",Mm="sentry.profiler_id",Ur="sentry.profile_id",Dm="sentry.release",Lm="sentry.sdk.integrations",Um="sentry.sdk.name",qm="sentry.sdk.version",jm="sentry.segment.id",qr="sentry.segment.name",wo="sentry.segment.name.source",Bm="sentry.status.message",Fm="sentry.trace_lifecycle",as="server.address",Hm="state.type",Gm="url.path",Wm="user.email",$m="user.id",Vm="user.ip_address",zm="user.name"});function Km(t){return t!=="ok"&&km.includes(t)}var Ym=w(()=>{Em()});function Gi(t){try{let e=Q.WeakRef;if(typeof e=="function")return new e(t)}catch{}return t}function bi(t){if(t){if(typeof t=="object"&&"deref"in t&&typeof t.deref=="function")try{return t.deref()}catch{return}return t}}var os=w(()=>{rt()});function Ft(t){let e=t;return{scope:e[Sk],isolationScope:bi(e[kk])}}var Sk,kk,ls=w(()=>{os();Sk="_sentryScope",kk="_sentryIsolationScope"});function jr(t){let e=Jm(t);if(!e)return;let i=Object.entries(e).reduce((r,[n,s])=>{if(n.startsWith("sentry-")){let a=n.slice(7);r[a]=s}return r},{});if(Object.keys(i).length>0)return i}function Jm(t){if(!(!t||!Ir(t)&&!Array.isArray(t)))return Array.isArray(t)?t.reduce((e,i)=>{let r=Qm(i);return Object.entries(r).forEach(([n,s])=>{e[n]=s}),e},{}):Qm(t)}function Qm(t){return t.split(",").map(e=>{let i=e.indexOf("=");return i===-1?[]:[e.slice(0,i),e.slice(i+1)].map(r=>{try{return decodeURIComponent(r.trim())}catch{return}})}).reduce((e,[i,r])=>(i&&r&&(e[i]=r),e),{})}var So=w(()=>{De()});function Ik(t){return t==="http"||t==="https"}function We(t,e=!1){let{host:i,path:r,pass:n,port:s,projectId:a,protocol:o,publicKey:l}=t;return`${o}://${l}${e&&n?`:${n}`:""}@${i}${s?`:${s}`:""}/${r&&`${r}/`}${a}`}function Ak(t){let e=Tk.exec(t);if(!e){st(()=>{console.error(`Invalid Sentry Dsn: ${t}`)});return}let[i,r,n="",s="",a="",o=""]=e.slice(1),l="",c=o,p=c.split("/");if(p.length>1&&(l=p.slice(0,-1).join("/"),c=p.pop()),c){let u=c.match(/^\d+/);u&&(c=u[0])}return Xm({host:s,pass:n,path:l,projectId:c,port:a,protocol:i,publicKey:r})}function Xm(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function xk(t){if(!B)return!0;let{port:e,projectId:i,protocol:r}=t;return["protocol","publicKey","host","projectId"].find(n=>t[n]?!1:(U.error(`Invalid Sentry Dsn: ${n} missing`),!0))?!1:i.match(/^\d+$/)?Ik(r)?e&&isNaN(parseInt(e,10))?(U.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(U.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(U.error(`Invalid Sentry Dsn: Invalid projectId ${i}`),!1)}function Ok(t){return t.match(Ek)?.[1]}function Zm(t){let e=t.getOptions(),{host:i}=t.getDsn()||{},r;return e.orgId?r=String(e.orgId):i&&(r=Ok(i)),r}function Br(t){let e=typeof t=="string"?Ak(t):Xm(t);if(!(!e||!xk(e)))return e}var Ek,Tk,Ht=w(()=>{Ie();Ae();Ek=/^o(\d+)\./,Tk=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/});function eg(t){if(typeof t=="boolean")return Number(t);let e=typeof t=="string"?parseFloat(t):t;if(!(typeof e!="number"||isNaN(e)||e<0||e>1))return e}var tg=w(()=>{});function Fr(t){return!!t.parentSpanId||!!t.dsc}var ig=w(()=>{});function cs(t,e){e?t.refs[ko]=Gi(e):delete t.refs[ko]}function rg(t){return bi(t.refs[ko])}var ko,Eo=w(()=>{os();ko="span"});function ds(t){let{spanId:e,traceId:i,isRemote:r}=t.spanContext(),n=r?e:Wi(t).parent_span_id,s=Ft(t).scope;return{parent_span_id:n,span_id:r?s?.getPropagationContext().propagationSpanId||Mr():e,trace_id:i}}function Rk(t){if(t&&t.length>0)return t.map(({context:{spanId:e,traceId:i,traceFlags:r,...n},attributes:s})=>({span_id:e,trace_id:i,sampled:r===1,attributes:s,...n}))}function Nk(t){if(t?.length)return t.map(({context:{spanId:e,traceId:i,traceFlags:r},attributes:n})=>({span_id:e,trace_id:i,sampled:r===1,attributes:n}))}function ps(t){return typeof t=="number"?ng(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?ng(t.getTime()):ts()}function ng(t){return t>9999999999?t/1e3:t}function Wi(t){if(lg(t))return t.getStaticSpanJSON();let{spanId:e,traceId:i}=t.spanContext();if(og(t)){let{attributes:r,startTime:n,name:s,endTime:a,status:o,links:l}=t;return{span_id:e,trace_id:i,data:r,description:s,parent_span_id:ag(t),start_timestamp:ps(n),timestamp:ps(a)||void 0,status:Pk(o),op:r[Pm],origin:r[Cm],links:Rk(l)}}return{span_id:e,trace_id:i,start_timestamp:0,status:"ok",data:{}}}function Hr(t){if(lg(t))return t.getSpanJSON();let{spanId:e,traceId:i}=t.spanContext();if(og(t)){let{attributes:r,startTime:n,name:s,endTime:a,status:o,links:l}=t;return{name:s,span_id:e,trace_id:i,parent_span_id:ag(t),start_timestamp:ps(n),end_timestamp:ps(a)||void 0,is_segment:sg(t),status:cg(o),attributes:Ck(r,o),links:Nk(l)}}return{span_id:e,trace_id:i,start_timestamp:0,name:"",status:"ok",is_segment:sg(t),attributes:{}}}function ag(t){return"parentSpanId"in t?t.parentSpanId:"parentSpanContext"in t?t.parentSpanContext?.spanId:void 0}function us(t){return{...t,end_timestamp:t.end_timestamp??t.start_timestamp,attributes:ho(t.attributes),links:t.links?.map(e=>({...e,attributes:ho(e.attributes)}))}}function og(t){let e=t;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function lg(t){return typeof t.getSpanJSON=="function"}function ms(t){let{traceFlags:e}=t.spanContext();return e===1}function Pk(t){return!t||t.code===0||t.code===1?"ok":t.message&&Km(t.message)?t.message:"internal_error"}function cg(t){return!t||t.code===1||t.code===0||t.message==="cancelled"?"ok":"error"}function Ck(t,e){let i=cg(e)==="error"?e?.message:void 0;return{...i&&{[Bm]:i},...t}}function fs(t){return t[Mk]||t}function sg(t){return t===fs(t)}function Gr(t){let e=ye(),i=ct(e);return i.getActiveSpan?i.getActiveSpan(t):rg(t||Rt())}var Mk,gs,Nt=w(()=>{rs();bo();nt();pt();Ym();ls();Dr();Bi();Eo();_t();Mk="_sentryRootSpan",gs=fs});function To(t){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;let e=t||bt()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}var pg=w(()=>{pt()});function dg(t){U.log(`Ignoring span ${t.op} - ${t.description} because it matches \`ignoreSpans\`.`)}function Io(t,e){if(!e?.length)return!1;for(let i of e){if(Lk(i)){if(t.description&&Nr(t.description,i))return B&&dg(t),!0;continue}let r=!!i.attributes&&Object.keys(i.attributes).length>0;if(!i.name&&!i.op&&!r)continue;let n=i.name?t.description&&Nr(t.description,i.name):!0,s=i.op?t.op&&Nr(t.op,i.op):!0,a=i.attributes?Object.entries(i.attributes).every(([o,l])=>Dk(t.attributes?.[o],l)):!0;if(n&&s&&a)return B&&dg(t),!0}return!1}function Dk(t,e){return typeof t=="string"&&(typeof e=="string"||e instanceof RegExp)?Nr(t,e):Array.isArray(t)&&Array.isArray(e)?t.length===e.length&&t.every((i,r)=>i===e[r]):t===e}function ug(t,e){let i=e.parent_span_id,r=e.span_id;if(i)for(let n of t)n.parent_span_id===r&&(n.parent_span_id=i)}function Lk(t){return typeof t=="string"||t instanceof RegExp}var mg=w(()=>{Ie();Ae();Pr()});function fg(t,e){let i={};return e.forEach(r=>{r?.beforeSetup&&r.beforeSetup(t)}),e.forEach(r=>{r&&xo(t,r,i)}),i}function Ao(t,e){for(let i of e)i?.afterAllSetup&&i.afterAllSetup(t)}function xo(t,e,i){if(i[e.name]){B&&U.log(`Integration skipped because it was already installed: ${e.name}`);return}if(i[e.name]=e,!gg.includes(e.name)&&typeof e.setupOnce=="function"&&(e.setupOnce(),gg.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(t),typeof e.preprocessEvent=="function"){let r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(n,s)=>r(n,s,t))}if(typeof e.processEvent=="function"){let r=e.processEvent.bind(e),n=Object.assign((s,a)=>r(s,a,t),{id:e.name});t.addEventProcessor(n)}["processSpan","processSegmentSpan"].forEach(r=>{let n=e[r];typeof n=="function"&&t.on(r,s=>n.call(e,s,t))}),B&&U.log(`Integration installed: ${e.name}`)}var gg,hg=w(()=>{Ie();Ae();gg=[]});var yg,bg=w(()=>{yg="production"});function _g(t){return!!t&&t[Uk]===!0}var Uk,vg=w(()=>{Uk=Symbol.for("sentry.nonRecordingSpan")});function Oo(t,e){let i=e.getOptions(),{publicKey:r}=e.getDsn()||{},n={environment:i.environment||"production",release:i.release,public_key:r,trace_id:t,org_id:Zm(e)};return e.emit("createDsc",n),n}function $i(t,e){if(ns())return;let i=e.getPropagationContext();return i.dsc||Oo(i.traceId,t)}function Pt(t){let e=bt();if(!e)return{};let i=gs(t),r=Wi(i),n=r.data,s=i.spanContext().traceState,a=s?.get("sentry.sample_rate")??n["sentry.sample_rate"]??n["sentry.previous_trace_sample_rate"];function o(v){return(typeof a=="number"||typeof a=="string")&&(v.sample_rate=`${a}`),v}let l=i[qk];if(l)return o(l);let c=_g(i),p=c&&i.dropReason==="ignored";if(c&&(!To(e.getOptions())||p)){let v=Ft(i).scope,S=v&&$i(e,v);if(S){let E={...S};return p&&(E.sampled="false"),o(E)}}let u=s?.get("sentry.dsc"),m=u&&jr(u);if(m)return o(m);let g=Oo(t.spanContext().traceId,e),h=n[wo],f=r.description;return h!=="url"&&f&&(g.transaction=f),To()&&(g.sampled=String(ms(i)),g.sample_rand=s?.get("sentry.sample_rand")??Ft(i).scope?.getPropagationContext().sampleRand.toString()),o(g),e.emit("createDsc",g,i),g}var qk,Vi=w(()=>{pt();So();Ht();pg();Nt();vg();ls();_t();qk="_frozenDsc"});function kg(t,e){let{fingerprint:i,breadcrumbs:r,sdkProcessingMetadata:n}=e;jk(t,e),Hk(t,i),Bk(t,r),Fk(t,n)}function Sg(t,e){let{extra:i,tags:r,attributes:n,user:s,contexts:a,level:o,sdkProcessingMetadata:l,breadcrumbs:c,fingerprint:p,eventProcessors:u,attachments:m,propagationContext:g,transactionName:h}=e;Wr(t,"extra",i),Wr(t,"tags",r),Wr(t,"attributes",n),Wr(t,"user",s),Wr(t,"contexts",a),t.sdkProcessingMetadata=Bt(t.sdkProcessingMetadata,l,2),o&&(t.level=o),h&&(t.transactionName=h),c.length&&(t.breadcrumbs=[...t.breadcrumbs,...c]),p.length&&(t.fingerprint=[...t.fingerprint,...p]),u.length&&(t.eventProcessors=[...t.eventProcessors,...u]),m.length&&(t.attachments=[...t.attachments,...m]),t.propagationContext={...t.propagationContext,...g}}function Wr(t,e,i){t[e]=Bt(t[e],i,1)}function hs(t,e){let i=_o().getScopeData();return t&&Sg(i,t.getScopeData()),e&&Sg(i,e.getScopeData()),i}function jk(t,e){let{extra:i,tags:r,user:n,contexts:s,level:a,transactionName:o}=e;Object.keys(i).length&&(t.extra={...i,...t.extra}),Object.keys(r).length&&(t.tags={...r,...t.tags}),Object.keys(n).length&&(t.user={...n,...t.user}),Object.keys(s).length&&(t.contexts={...s,...t.contexts}),a&&(t.level=a),o&&t.type!=="transaction"&&(t.transaction=o)}function Bk(t,e){let i=[...t.breadcrumbs||[],...e];t.breadcrumbs=i.length?i:void 0}function Fk(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}function Eg(t,e){t.contexts={trace:ds(e),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:Pt(e),...t.sdkProcessingMetadata};let i=gs(e),r=Wi(i).description;r&&!t.transaction&&t.type==="transaction"&&(t.transaction=r)}function Hk(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint.length||delete t.fingerprint}var Ro=w(()=>{pt();Vi();is();Nt()});function _i(t,e,i){let r;try{r=e()}catch(n){return Tg(t,n,i)}return xt(r)?r.then(void 0,n=>Tg(t,n,i)):r}function Tg(t,e,i){return B&&U.error(t,e),i(e)}var ys=w(()=>{Ie();Ae();De()});function $r(t){return!!t&&typeof t=="function"&&"_static"in t&&!!t._static}function Vr(t,e){return _i(B?"The `beforeSendSpan` callback threw an error, sending the span unmodified:":"",()=>e(t),()=>t)||t}var No=w(()=>{Ie();ys()});function Ig(t){let e={trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,name:t.description||"",start_timestamp:t.start_timestamp,end_timestamp:t.timestamp,status:!t.status||t.status==="ok"||t.status==="cancelled"?"ok":"error",is_segment:!1,attributes:{...t.data},links:t.links};return us(e)}var Ag=w(()=>{Nt()});function xg(t){let e={},{response:i,profile:r,cloud_resource:n,culture:s,state:a}=t;if(i&&(i.status_code!=null&&(e[Om]=i.status_code),i.body_size!=null&&(e[xm]=i.body_size)),r&&(r.profile_id&&(e[Ur]=r.profile_id),r.profiler_id&&(e[Mm]=r.profiler_id)),n)for(let[c,p]of Object.entries(n))p!=null&&(e[c]=p);s&&(s.locale&&(e[Im]=s.locale),s.timezone&&(e[Am]=s.timezone)),a?.state&&typeof a.state.type=="string"&&(e[Hm]=a.state.type);let o=t.angular;if(o){let c=o.version;(typeof c=="string"||typeof c=="number")&&(e[Tm]=c)}let l=t.react;if(l){let c=l.version;(typeof c=="string"||typeof c=="number")&&(e[Rm]=c)}return e}var Og=w(()=>{_t()});function Rg(t,e){let i=Hr(t);i.attributes&&delete i.attributes[wm];let r=fs(t),n=Hr(r),{isolationScope:s,scope:a}=Ft(t),o=hs(s,a);Vk(i,n,e,o),e.emit("preprocessSpan",i),i.is_segment&&(Gk(i,o),Wk(i,e),e.emit("processSegmentSpan",i)),e.emit("processSpan",i);let{beforeSendSpan:l,traceLifecycle:c}=e.getOptions(),p=c!=="static"&&l&&!$r(l)?Vr(i,l):i;return{...us(p),_segmentSpan:r,_segmentNameAtCapture:n.name}}function Gk(t,e){Po(t,xg(e.contexts))}function Po(t,e){let i=t.attributes??(t.attributes={});Object.entries(e).forEach(([r,n])=>{n!=null&&!(r in i)&&(i[r]=n)})}function Wk(t,e){let i=e.getIntegrationNames();i.length&&Po(t,{[Lm]:i})}function $k(t,e,i,r=!0){let n=e.getSdkMetadata(),{release:s,environment:a}=e.getOptions();return{[Fm]:"stream",[qr]:t.name,[jm]:t.span_id,[Um]:n?.sdk?.name,[qm]:n?.sdk?.version,[Dm]:s,[Nm]:a||"production",[$m]:i.user?.id,[Wm]:i.user?.email,[Vm]:i.user?.ip_address,[zm]:i.user?.username,...r?i.attributes:void 0}}function Vk(t,e,i,r){Po(t,$k(e,i,r))}var Ng=w(()=>{Sm();Ro();Nt();ls();No();Og();_t()});function bs(t){return t.getOptions().traceLifecycle==="stream"}var Co=w(()=>{});function zi(t){return typeof t=="object"&&typeof t.unref=="function"&&t.unref(),t}var _s=w(()=>{});function dt(t,e=[]){return[t,e]}function Do(t,e){let[i,r]=t;return[i,[...r,e]]}function vs(t,e){let i=t[1];for(let r of i){let n=r[0].type;if(e(r,n))return!0}return!1}function Pg(t,e){return vs(t,(i,r)=>e.includes(r))}function Mo(t){let e=He(Q);return e.encodePolyfill?e.encodePolyfill(t):new TextEncoder().encode(t)}function Cg(t){let[e,i]=t,r=JSON.stringify(e);function n(s){typeof r=="string"?r=typeof s=="string"?r+s:[Mo(r),s]:r.push(typeof s=="string"?Mo(s):s)}for(let s of i){let[a,o]=s;if(n(`
3
+ ${JSON.stringify(a)}
4
+ `),typeof o=="string"||o instanceof Uint8Array)n(o);else{let l;try{l=JSON.stringify(o)}catch{l=JSON.stringify(lt(o))}n(l)}}return typeof r=="string"?r:zk(r)}function zk(t){let e=t.reduce((n,s)=>n+s.length,0),i=new Uint8Array(e),r=0;for(let n of t)i.set(n,r),r+=n.length;return i}function Mg(t){let e=typeof t.data=="string"?Mo(t.data):t.data;return[{type:"attachment",length:e.length,filename:t.filename,content_type:t.contentType,attachment_type:t.attachmentType},e]}function Kk(t){return t in Dg}function Lo(t){return Kk(t)?Dg[t]:t}function zr(t){if(!t?.sdk)return;let{name:e,version:i}=t.sdk;return{name:e,version:i}}function Lg(t,e,i,r){let n=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date(xe()).toISOString(),...e&&{sdk:e},...!!i&&r&&{dsn:We(r)},...n&&{trace:n}}}function Kr(t){return t==="replay_event"?"replay":t||"error"}var Dg,Gt=w(()=>{nt();Ht();Xn();ot();rt();Dg={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",metric:"trace_metric"}});function Ug(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}var qg=w(()=>{});function jg(){return!Ug()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}var Bg=w(()=>{qg()});function Fg(){return typeof window<"u"&&(!jg()||Yk())}function Yk(){return Q.process?.type==="renderer"}var Hg=w(()=>{Bg();rt()});function Gg(t,e,i){let r=i.getOptions(),n=i.getDsn(),s=r.tunnel,a=zr(r._metadata),o={sent_at:new Date(xe()).toISOString(),...Qk(e)&&{trace:e},...a&&{sdk:a},...!!s&&n&&{dsn:We(n)}};return dt(o,[Uo(t,i)])}function Uo(t,e){let i=e.getDataCollectionOptions().userInfo?"auto":"never";return[{type:"span",item_count:t.length,content_type:"application/vnd.sentry.items.span.v2+json"},{version:2,ingest_settings:Fg()?{infer_ip:i,infer_user_agent:i}:void 0,items:t}]}function Qk(t){return!!t.trace_id&&!!t.public_key}var qo=w(()=>{Ht();Gt();Hg();ot()});function Wg(t){let e=156;if(e+=t.name.length*2,e+=yo(t.attributes),t.links&&t.links.length>0){let i=t.links[0]?.attributes,r=100+(i?yo(i):0);e+=r*t.links.length}return e}var $g=w(()=>{bo()});function Xk(t,e,i){let r=t.attributes[qr];if(e===void 0||r?.value!==e)return;let n=i();n!==e&&(t.attributes[qr]={...r,value:n})}var Vg,Jk,zg,Kg=w(()=>{Ie();Ae();Nt();_s();Vi();qo();$g();_t();Vg=1e3,Jk=5e6,zg=class{constructor(t,e){this._traceBuckets=new Map,this._client=t;let{maxSpanLimit:i,flushInterval:r,maxTraceWeightInBytes:n}=e??{};this._maxSpanLimit=i&&i>0&&i<=Vg?i:Vg,this._flushInterval=r&&r>0?r:5e3,this._maxTraceWeight=n&&n>0?n:Jk,this._client.on("flush",()=>{this.drain()}),this._client.on("close",()=>{this._traceBuckets.forEach(s=>{clearTimeout(s.timeout)}),this._traceBuckets.clear()})}add(t){let e=t.trace_id,i=this._traceBuckets.get(e);i||(i={spans:new Set,size:0,timeout:zi(setTimeout(()=>{this.flush(e)},this._flushInterval))},this._traceBuckets.set(e,i)),i.spans.add(t),i.size+=Wg(t),(i.spans.size>=this._maxSpanLimit||i.size>=this._maxTraceWeight)&&this.flush(e)}drain(){this._traceBuckets.size&&(B&&U.log(`Flushing span tree map with ${this._traceBuckets.size} traces`),this._traceBuckets.forEach((t,e)=>{this.flush(e)}))}flush(t){let e=this._traceBuckets.get(t);if(!e)return;if(!e.spans.size){this._removeTrace(t);return}let i=Array.from(e.spans),r=i[0]?._segmentSpan;if(!r){B&&U.warn("No segment span reference found on span JSON, cannot compute DSC"),this._removeTrace(t);return}let n=Pt(r),s=new Map,a=c=>{let p=s.get(c);return p===void 0&&(p=Hr(c).name,s.set(c,p)),p},o=i.map(c=>{let{_segmentSpan:p,_segmentNameAtCapture:u,...m}=c;return Xk(m,u,()=>a(p)),m}),l=Gg(o,n,this._client);B&&U.log(`Sending span envelope for trace ${t} with ${o.length} spans`),this._client.sendEnvelope(l).then(null,c=>{B&&U.error("Error while sending streamed span envelope:",c)}),this._removeTrace(t)}_removeTrace(t){let e=this._traceBuckets.get(t);e&&clearTimeout(e.timeout),this._traceBuckets.delete(t)}}});var Zk,Yg,Qg=w(()=>{Ie();Ng();Co();Kg();Ae();Nt();_s();Zk="SpanStreaming",Yg=(t={})=>{let e=t.flushOnSegmentEnd??!0;return{name:Zk,setup(i){if(!bs(i)){B&&U.log('[SpanStreaming] `traceLifecycle` is "static", skipping setup.');return}let r=new zg(i);i.on("afterSpanEnd",n=>{ms(n)&&r.add(Rg(n,i))}),i.on("flushTraceSpans",n=>{r.flush(n)}),e&&i.on("afterSegmentSpanEnd",n=>{let s=n.spanContext().traceId;zi(setTimeout(()=>{r.flush(s)},500))})}}}});function tE(t){return yt(t)?void 0:t}function Jg(t,e,i){let r=tE(e.originalException),n=r&&eE.get(r);if(!n)return;let s=t.contexts?.trace;(s?.trace_id??(i&&yi(i).trace_id))===n.trace_id&&(t.contexts={...t.contexts,trace:{...s,...n}})}var eE,Xg=w(()=>{pt();De();eE=new WeakMap});function Zg(t){He(ye()).segmentSpanCaptureStrategy=t}function ef(){return He(ye()).segmentSpanCaptureStrategy}var tf=w(()=>{nt()});function rf(t,e,i){let r,n,s,a=i?.maxWait?Math.max(i.maxWait,e):0,o=i?.setTimeoutImpl||setTimeout;function l(){return c(),r=t(),r}function c(){n!==void 0&&clearTimeout(n),s!==void 0&&clearTimeout(s),n=s=void 0}function p(){return n!==void 0||s!==void 0?l():r}function u(){return n&&clearTimeout(n),n=o(l,e),a&&s===void 0&&(s=o(l,a)),r}return u.cancel=c,u.flush=p,u}var nf=w(()=>{});function jo(t){if(ef()||Zg(iE),Ss.has(t))return;let e=new Set,i=rf(()=>{let r=[...e];e.clear();for(let n of r)n()},1,{maxWait:100});t.on("flush",()=>{i.flush()}),Ss.set(t,r=>{e.add(r),i()})}var ws,sf,af,Ss,iE,of=w(()=>{nf();tf();ws=new WeakSet,sf=t=>ws.has(t),af=t=>{ws.add(t)},Ss=new WeakMap;iE={onSegmentSpanEnded(t,e){let i=e.getClient(),r=i&&Ss.get(i);if(!r){let n=t();n&&i?.captureEvent(n);return}r(()=>{let n=t({isSpanAlreadyCaptured:sf,onSpanCaptured:af});n&&i.captureEvent(n)})},onChildSpanEnded(t,e,i,r){if(ws.has(t)||!ws.has(e))return;let n=r.getClient(),s=n&&Ss.get(n),a=()=>{let o=i({isSpanAlreadyCaptured:sf,onSpanCaptured:af});o?.contexts?.trace?.data&&(o.contexts.trace.data["sentry.parent_span_already_sent"]=!0),o&&n?.captureEvent(o)};s?s(a):a()}}});function rE(t,e){if(!e)return t;let i=t.sdk||{};return t.sdk={...i,name:i.name||e.name,version:i.version||e.version,integrations:[...t.sdk?.integrations||[],...e.integrations||[]],packages:[...t.sdk?.packages||[],...e.packages||[]],settings:t.sdk?.settings||e.settings?{...t.sdk?.settings,...e.settings}:void 0},t}function lf(t,e,i,r){let n=zr(i),s={sent_at:new Date(xe()).toISOString(),...n&&{sdk:n},...!!r&&e&&{dsn:We(e)}},a="aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()];return dt(s,[a])}function cf(t,e,i,r){let n=zr(i),s=t.type&&t.type!=="replay_event"?t.type:"event";rE(t,i?.sdk);let a=Lg(t,n,r,e);return delete t.sdkProcessingMetadata,dt(a,[[{type:s},t]])}var pf=w(()=>{Ht();Gt();ot()});function Ct(t){return new mf(e=>{e(t)})}function Ki(t){return new mf((e,i)=>{i(t)})}var Bo,df,uf,mf,Yi=w(()=>{De();Bo=0,df=1,uf=2;mf=class Fo{constructor(e){this._state=Bo,this._handlers=[],this._runExecutor(e)}then(e,i){return new Fo((r,n)=>{this._handlers.push([!1,s=>{if(!e)r(s);else try{r(e(s))}catch(a){n(a)}},s=>{if(!i)n(s);else try{r(i(s))}catch(a){n(a)}}]),this._executeHandlers()})}catch(e){return this.then(i=>i,e)}finally(e){return new Fo((i,r)=>{let n,s;return this.then(a=>{s=!1,n=a,e&&e()},a=>{s=!0,n=a,e&&e()}).then(()=>{if(s){r(n);return}i(n)})})}_executeHandlers(){if(this._state===Bo)return;let e=this._handlers.slice();this._handlers=[],e.forEach(i=>{i[0]||(this._state===df&&i[1](this._value),this._state===uf&&i[2](this._value),i[0]=!0)})}_runExecutor(e){let i=(s,a)=>{if(this._state===Bo){if(xt(a)){a.then(r,n);return}this._state=s,this._value=a,this._executeHandlers()}},r=s=>{i(df,s)},n=s=>{i(uf,s)};try{e(r,n)}catch(s){n(s)}}}});function gf(t,e,i,r=0,n){try{let s=Ho(e,i,t,r,n);return xt(s)?s:Ct(s)}catch(s){return Ki(s)}}function Ho(t,e,i,r,n){let s=i[r];if(!t||!s)return t;let a=`Event processor "${s.id||"?"}"`,o=!1,l=_i(B?`${a} threw an error, dropping event:`:"",()=>s({...t},e),()=>(o=!0,null));return B&&l===null&&U.log(`${a} dropped event`),xt(l)?l.then(c=>c?Ho(c,e,i,r+1,n):(n?.(o?"callback_error":"event_processor"),null)):l?Ho(l,e,i,r+1,n):(n?.(o?"callback_error":"event_processor"),null)}var ff=w(()=>{Ie();Ae();De();ys();Yi()});function bf(t){let e=Q._sentryDebugIds,i=Q._debugIds;if(!e&&!i)return{};let r=e?Object.keys(e):[],n=i?Object.keys(i):[];if(Wt&&r.length===hf&&n.length===yf)return Wt;hf=r.length,yf=n.length,Wt={},vi||(vi={});let s=(a,o)=>{for(let l of a){let c=o[l],p=vi?.[l];if(p&&Wt&&c)Wt[p[0]]=c,vi&&(vi[l]=[p[0],c]);else if(c){let u=t(l);for(let m=u.length-1;m>=0;m--){let g=u[m]?.filename;if(g&&Wt&&vi){Wt[g]=c,vi[l]=[g,c];break}}}}};return e&&s(r,e),i&&s(n,i),Wt}var vi,hf,yf,Wt,_f=w(()=>{rt()});function Yr(t){return t.data?.__sentry__===!0}function vf(t){let e=[];t.message&&e.push(t.message);try{let i=t.exception.values[t.exception.values.length-1];i?.value&&(e.push(i.value),i.type&&e.push(`${i.type}: ${i.value}`))}catch{}return e}var Go=w(()=>{});function wf(t,e,i,r,n,s){let{normalizeDepth:a=3,normalizeMaxBreadth:o=1e3}=t,l={...e,event_id:e.event_id||i.event_id||_e(),timestamp:e.timestamp||ui()},c=i.integrations||t.integrations.map(E=>E.name);nE(l,t),oE(l,c),n&&n.emit("applyFrameMetadata",e),e.type===void 0&&sE(l,t.stackParser);let p=cE(r,i.captureContext);i.mechanism&&am(l,i.mechanism);let u=n?n.getEventProcessors():[],m=hs(s,p),g=[...i.attachments||[],...m.attachments];g.length&&(i.attachments=g),kg(l,m);let h=Gr(p);h&&Eg(l,h),Jg(l,i,p);let f=[...u,...m.eventProcessors],v=e.type==="transaction",S=e.spans?.length||0;return(Yr(i)?Ct(l):gf(f,l,i,0,E=>{n&&(n.recordDroppedEvent(E,Kr(e.type)),v&&n.recordDroppedEvent(E,"span",1+S))})).then(E=>{if(!E)return null;if(v&&n){let O=S-(E.spans?.length||0);O>0&&n.recordDroppedEvent("event_processor","span",O)}return aE(E),typeof a=="number"&&a>0?lE(E,a,o):E})}function nE(t,e){let{environment:i,release:r,dist:n,maxValueLength:s}=e;t.environment=t.environment||i||"production",!t.release&&r&&(t.release=r),!t.dist&&n&&(t.dist=n);let a=t.request;a?.url&&s&&(a.url=Rr(a.url,s)),s&&t.exception?.values?.forEach(o=>{o.value&&(o.value=Rr(o.value,s))})}function sE(t,e){let i=bf(e);t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.filename&&(n.debug_id=i[n.filename])})})}function aE(t){let e={};if(t.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.debug_id&&(n.abs_path?e[n.abs_path]=n.debug_id:n.filename&&(e[n.filename]=n.debug_id),delete n.debug_id)})}),Object.keys(e).length===0)return;t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];let i=t.debug_meta.images;Object.entries(e).forEach(([r,n])=>{i.push({type:"sourcemap",code_file:r,debug_id:n})})}function oE(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[...t.sdk.integrations||[],...e])}function lE(t,e,i){if(!t)return null;let r={...t,...t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map(n=>({...n,...n.data&&{data:lt(n.data,e,i)}}))},...t.user&&{user:lt(t.user,e,i)},...t.contexts&&{contexts:lt(t.contexts,e,i)},...t.extra&&{extra:lt(t.extra,e,i)}};return t.contexts?.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=lt(t.contexts.trace.data,e,i))),t.spans&&(r.spans=t.spans.map(n=>({...n,...n.data&&{data:lt(n.data,e,i)}}))),t.contexts?.flags&&r.contexts&&(r.contexts.flags=lt(t.contexts.flags,3,i)),r}function cE(t,e){if(!e)return t;let i=t?t.clone():new Ge;return i.update(e),i}var Sf=w(()=>{ff();Fi();_f();Gt();Xg();Go();Ot();Xn();Ro();Nt();Pr();Yi();Bi()});function pE(t){let e=t.protocol?`${t.protocol}:`:"",i=t.port?`:${t.port}`:"";return`${e}//${t.host}${i}${t.path?`/${t.path}`:""}/api/`}function dE(t){return`${pE(t)}${t.projectId}/envelope/`}function uE(t,e){let i={sentry_version:"7"};return t.publicKey&&(i.sentry_key=t.publicKey),e&&(i.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(i).toString()}function kf(t,e,i){return e||`${dE(t)}?${uE(t,i)}`}var Ef=w(()=>{});function Tf(t,e){if(t.type!=="transaction"||!t.spans?.length||!t.sdkProcessingMetadata?.hasGenAiSpans||bs(e))return;let i=[],r=[];for(let n of t.spans)n.op?.startsWith("gen_ai.")?i.push(Ig(n)):r.push(n);if(i.length!==0)return t.spans=r,Uo(i,e)}var If=w(()=>{qo();Co();Ag()});function Qi(t=100){let e=new Set;function i(){return e.size<t}function r(a){e.delete(a)}function n(a){if(!i())return Ki(Qr);let o=a();return e.add(o),o.then(()=>r(o),()=>r(o)),o}function s(a){if(!e.size)return Ct(!0);let o=Promise.allSettled(Array.from(e)).then(()=>!0);if(!a)return o;let l=[o,new Promise(c=>zi(setTimeout(()=>c(!1),a)))];return Promise.race(l)}return{get $(){return Array.from(e)},add:n,drain:s}}var Qr,ks=w(()=>{Yi();_s();Qr=Symbol.for("SentryBufferFullError")});function gE(t,e=xe()){let i=parseInt(`${t}`,10);if(!isNaN(i))return i*1e3;let r=Date.parse(`${t}`);return isNaN(r)?mE:r-e}function fE(t,e){return t[e]||t.all||0}function Af(t,e,i=xe()){return fE(t,e)>i}function xf(t,e,i=xe()){let r={...t};return hE(e,i,(n,s)=>{r[n]=Math.max(r[n]||0,s)}),r}function hE({statusCode:t,headers:e},i,r){let n=e?.["x-sentry-rate-limits"],s=e?.["retry-after"];if(n)for(let a of n.trim().split(",")){let[o,l,,,c]=a.split(":",5),p=parseInt(o,10),u=(isNaN(p)?60:p)*1e3;if(!l)r("all",i+u);else for(let m of l.split(";"))m==="metric_bucket"?(!c||c.split(";").includes("custom"))&&r(m,i+u):r(m,i+u)}else s?r("all",i+gE(s,i)):t===429&&r("all",i+6e4)}var mE,Of=w(()=>{ot();mE=6e4});function Wo(t,e,i=Qi(t.bufferSize||64)){let r={},n=o=>i.drain(o);function s(o,[l,c],p){let u=Lo(p);p==="transaction"&&t.recordDroppedEvent(o,"span",(c.spans?.length??0)+1),t.recordDroppedEvent(o,u,typeof l.item_count=="number"?l.item_count:1)}function a(o){let l=[];if(vs(o,(m,g)=>{Af(r,Lo(g))?s("ratelimit_backoff",m,g):l.push(m)}),l.length===0)return Promise.resolve({});let c=dt(o[0],l),p=m=>{if(Pg(c,["client_report"])){B&&U.warn(`Dropping client report. Will not send outcomes (reason: ${m}).`);return}vs(c,(g,h)=>{s(m,g,h)})},u=()=>e({body:Cg(c)}).then(m=>m.statusCode===413?(B&&U.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),p("send_error"),m):(B&&m.statusCode!==void 0&&(m.statusCode<200||m.statusCode>=300)&&U.warn(`Sentry responded with status code ${m.statusCode} to sent event.`),r=xf(r,m),m),m=>{throw p("network_error"),B&&U.error("Encountered error running transport request:",m),m});return i.add(u).then(m=>m,m=>{if(m===Qr)return B&&U.error("Skipped sending event because buffer is full."),p("queue_overflow"),Promise.resolve({});throw m})}return{send:a,flush:n}}var Rf=w(()=>{Ie();Ae();Gt();ks();Of()});function Nf(t,e,i){let r=[{type:"client_report"},{timestamp:i||ui(),discarded_events:t}];return dt(e?{dsn:e}:{},[r])}var Pf=w(()=>{Gt();Bi()});function Cf(t){let{trace_id:e,parent_span_id:i,span_id:r,status:n,origin:s,data:a,op:o,links:l}=t.contexts?.trace??{};return{data:a??{},description:t.transaction,op:o,parent_span_id:i,span_id:r??"",start_timestamp:t.start_timestamp??0,status:n??"ok",timestamp:t.timestamp,trace_id:e??"",origin:s,links:l,profile_id:a?.[Ur],exclusive_time:a?.[vo],measurements:t.measurements,is_segment:!0}}function Mf(t){return{type:"transaction",timestamp:t.timestamp,start_timestamp:t.start_timestamp,transaction:t.description,contexts:{trace:{trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,op:t.op,status:t.status,origin:t.origin,links:t.links,data:{...t.data,...t.profile_id&&{[Ur]:t.profile_id},...t.exclusive_time&&{[vo]:t.exclusive_time}}}},measurements:t.measurements}}var Df=w(()=>{_t()});function Lf(t){t.traceLifecycle!=="stream"||!(t.beforeSendTransaction||t.ignoreTransactions?.length)||st(()=>{console.warn("[Sentry] `beforeSendTransaction` and `ignoreTransactions` are ignored with `traceLifecycle: 'stream'` (enabled by default). Use `beforeSendSpan` and `ignoreSpans` instead, or set `traceLifecycle: 'static'`.")})}var Uf=w(()=>{Ae()});function yE(t){return typeof t=="boolean"||"allow"in t||"deny"in t}function bE(t){return t===void 0?{...ke.httpHeaders}:yE(t)?{request:t,response:t}:{request:t.request??ke.httpHeaders.request,response:t.response??ke.httpHeaders.response}}function qf(t){let e=t.dataCollection??{};return{userInfo:e.userInfo??ke.userInfo,cookies:e.cookies??ke.cookies,httpHeaders:bE(e.httpHeaders),httpBodies:e.httpBodies??ke.httpBodies,urlQueryParams:e.urlQueryParams??ke.urlQueryParams,graphQL:{document:e.graphQL?.document??ke.graphQL.document,variables:e.graphQL?.variables??ke.graphQL.variables},genAI:{inputs:e.genAI?.inputs??ke.genAI.inputs,outputs:e.genAI?.outputs??ke.genAI.outputs},mcp:{inputs:e.mcp?.inputs??ke.mcp.inputs,outputs:e.mcp?.outputs??ke.mcp.outputs},databaseQueryData:e.databaseQueryData??ke.databaseQueryData,queues:e.queues??ke.queues,stackFrameVariables:e.stackFrameVariables??ke.stackFrameVariables,frameContextLines:e.frameContextLines??ke.frameContextLines}}var ke,jf=w(()=>{ke={userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},mcp:{inputs:!0,outputs:!0},databaseQueryData:!0,queues:!0,stackFrameVariables:!0,frameContextLines:5}});function Hf(t){return{message:t,[Vf]:!0}}function $o(t){return{message:t,[zf]:!0}}function Gf(t){return $o(`Discarding event because it's not included in the random sample (sampling rate = ${t})`)}function Wf(t){return xr(t)&&Vf in t}function $f(t){return xr(t)&&zf in t}function vE(t,e,i,r,n){let{beforeSend:s,ignoreSpans:a,beforeSendTransaction:o}=t,l=$r(t.beforeSendSpan)&&t.beforeSendSpan,c=e;if(Vo(c)&&s){let p=c;return _i(B?"The `beforeSend` callback threw an error, dropping the event:":"",()=>s(p,i),()=>(r("callback_error"),null))}if(Yf(c)){if(l||a){let p=Cf(c);if(a?.length&&Io({description:p.description,op:p.op,attributes:p.data},a))return r("ignored"),null;if(l){let u=Vr(p,l);c=Bt(e,Mf(u))}if(c.spans){let u=[],m=c.spans;for(let g of m){if(a?.length&&Io({description:g.description,op:g.op,attributes:g.data},a)){ug(m,g);continue}l?u.push(Vr(g,l)):u.push(g)}n(m.length-u.length),c.spans=u}}if(o)return _i(B?"The `beforeSendTransaction` callback threw an error, dropping the event:":"",()=>o(c,i),()=>(r("callback_error"),null))}return c}function Vo(t){return t.type===void 0}function Yf(t){return t.type==="transaction"}var Bf,Ff,Vf,zf,_E,Kf,Qf=w(()=>{Ef();bg();pt();Ie();pf();hg();uo();Vi();No();If();Pf();Ae();Ht();Gt();Go();De();is();Ot();tg();Sf();ks();ot();ys();mg();Yi();Df();Uf();jf();Bf="Not capturing exception because it's already been captured.",Ff="Discarded session because of missing or non-string release",Vf=Symbol.for("SentryInternalError"),zf=Symbol.for("SentryDoNotSendEventError"),_E=Symbol.for("SentryClosedClient");Kf=class{constructor(t){this._options={attachStacktrace:!0,...t,traceLifecycle:t.traceLifecycle==="static"?"static":"stream"},this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=Qi(t.transportOptions?.bufferSize??64),this._dataCollection=qf(t),this._unhandledSessionStatus="crashed",this._attachStacktraceIsDefault=t.attachStacktrace===void 0,t.dsn?this._dsn=Br(t.dsn):B&&U.warn("No DSN provided, client will not send events.");let{beforeSendSpan:e,traceLifecycle:i}=this._options;if(B&&e&&$r(e)!==(i==="static")&&st(()=>{console.warn(`Ignoring \`beforeSendSpan\`: ${i==="static"?"wrap it with":"remove"} \`Sentry.withStaticSpan\` to use it with \`traceLifecycle: "${i}"\`.`)}),this._dsn){let r=kf(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:r})}}captureException(t,e,i){let r=_e();if(es(t))return B&&U.log(Bf),r;let n={event_id:r,...e};return this._process(()=>this.eventFromException(t,n).then(s=>this._captureEvent(s,n,i)).then(s=>s),"error"),n.event_id}captureMessage(t,e,i,r){let n={event_id:_e(),...i},s=Ar(t)?t:String(t),a=yt(t),o=a?this.eventFromMessage(s,e,n).then(l=>(l.exception&&this._attachStacktraceIsDefault&&(l.sdkProcessingMetadata={...l.sdkProcessingMetadata,hasDefaultSyntheticStacktrace:!0}),l)):this.eventFromException(t,n);return this._process(()=>o.then(l=>this._captureEvent(l,n,r)),a?"unknown":"error"),n.event_id}captureEvent(t,e,i){let r=_e();if(e?.originalException&&es(e.originalException))return B&&U.log(Bf),r;let n={event_id:r,...e},s=t.sdkProcessingMetadata||{},a=s.capturedSpanScope,o=s.capturedSpanIsolationScope,l=Kr(t.type);return this._process(()=>this._captureEvent(t,n,a||i,o),l),n.event_id}captureSession(t){this.sendSession(t),Cr(t,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getDataCollectionOptions(){return this._dataCollection}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(t){let e=this._transport;if(this.emit("flush"),!e)return!0;let i=await this._isClientDoneProcessing(t),r=await e.flush(t);return i&&r}async close(t){Object.defineProperty(this,_E,{value:!0});let e=await this.flush(t);return this.getOptions().enabled=!1,this.emit("close"),e}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}init(){(this._isEnabled()||this._options.integrations.some(({name:t})=>t.startsWith("Spotlight")))&&(this._setupIntegrations(),Lf(this._options))}getIntegrationByName(t){return this._integrations[t]}getIntegrationNames(){return Object.keys(this._integrations)}addIntegration(t){let e=this._integrations[t.name];!e&&t.beforeSetup&&t.beforeSetup(this),xo(this,t,this._integrations),e||Ao(this,[t])}sendEvent(t,e={}){this.emit("beforeSendEvent",t,e);let i=Tf(t,this),r=cf(t,this._dsn,this._options._metadata,this._options.tunnel);if(!Yr(e))for(let n of e.attachments||[])r=Do(r,Mg(n));i&&(r=Do(r,i)),this.sendEnvelope(r).then(n=>this.emit("afterSendEvent",t,n))}sendSession(t){let{release:e,environment:i=yg}=this._options;if("aggregates"in t){let n=t.attrs||{};if(!n.release&&!e){B&&U.warn(Ff);return}n.release=n.release||e,n.environment=n.environment||i,t.attrs=n}else{if(!t.release&&!e){B&&U.warn(Ff);return}t.release=t.release||e,t.environment=t.environment||i}this.emit("beforeSendSession",t);let r=lf(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(r)}recordDroppedEvent(t,e,i=1){if(this._options.sendClientReports){let r=`${t}:${e}`;B&&U.log(`Recording outcome: "${r}"${i>1?` (${i} times)`:""}`),this._outcomes[r]=(this._outcomes[r]||0)+i}}on(t,e){let i=this._hooks[t]=this._hooks[t]||new Set,r=(...n)=>e(...n);return i.add(r),()=>{i.delete(r)}}emit(t,...e){let i=this._hooks[t];i&&i.forEach(r=>r(...e))}async sendEnvelope(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)try{let e=await this._transport.send(t);return this.emit("afterEnvelope",t),e}catch(e){return B&&U.error("Error while sending envelope:",e),{}}return B&&U.error("Transport disabled"),{}}registerCleanup(t){}dispose(){}_setupIntegrations(){let{integrations:t}=this._options;this._integrations=fg(this,t),Ao(this,t)}_updateSessionFromEvent(t,e){let i=e.level==="fatal",r=!1,n=e.exception?.values;if(n){r=!0,i=!1;for(let a of n)if(a.mechanism?.handled===!1){i=!0;break}}let s=t.status==="ok";(s&&t.errors===0||s&&i)&&(Cr(t,{...i&&{status:this._unhandledSessionStatus},errors:t.errors||Number(r||i)}),this.captureSession(t))}async _isClientDoneProcessing(t){let e=0;for(;!t||e<t;){if(await new Promise(i=>setTimeout(i,1)),!this._numProcessing)return!0;e++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(t,e,i,r){let n=this.getOptions(),s=this.getIntegrationNames();return!e.integrations&&s.length&&(e.integrations=s),this.emit("preprocessEvent",t,e),t.type||r.setLastEventId(t.event_id||e.event_id),wf(n,t,e,i,this,r).then(a=>(a===null||(this.emit("postprocessEvent",a,e),a.contexts={trace:{...a.contexts?.trace,...yi(i)},...a.contexts},a.sdkProcessingMetadata={dynamicSamplingContext:$i(this,i),...a.sdkProcessingMetadata}),a))}_captureEvent(t,e={},i=Rt(),r=hi()){return B&&Vo(t)&&U.log(`Captured error event \`${vf(t)[0]||"<unknown>"}\``),this._processEvent(t,e,i,r).then(n=>n.event_id,n=>{B&&($f(n)?U.log(n.message):Wf(n)?U.warn(n.message):U.warn(n))})}_processEvent(t,e,i,r){let n=this.getOptions(),{sampleRate:s}=n,a=Yf(t),o=Vo(t),l=`before send for type \`${t.type||"error"}\``,c="before_send",p=0,u=typeof s>"u"?void 0:eg(s),m=o&&typeof u=="number"&&Qe()>u,g=Kr(t.type),h=0,f=i.getSession()||r.getSession();return m&&f?.status!=="ok"?(this.recordDroppedEvent("sample_rate","error"),Ki(Gf(s))):this._prepareEvent(t,e,i,r).then(v=>{if(v===null)throw $o("An event processor returned `null`, will not send event.");return h=v.spans?.length||0,Yr(e)?v:vE(n,v,e,S=>{c=S},S=>{p=S})}).then(v=>{if(p&&this.recordDroppedEvent("ignored","span",p),!di(v)||v===null)throw this.recordDroppedEvent(c,g),a&&this.recordDroppedEvent(c,"span",1+h-p),v!==null?Hf(`${l} must return \`null\` or a valid event.`):$o(`${c==="ignored"?"Transaction matched `ignoreSpans`":`${l} ${c==="callback_error"?"threw an error":"returned `null`"}`}, will not send event.`);if(o&&f&&this._updateSessionFromEvent(f,v),m)throw this.recordDroppedEvent("sample_rate","error"),Gf(s);if(a){let E=h-p-(v.spans?.length||0);E>0&&this.recordDroppedEvent("before_send","span",E)}let S=v.transaction_info;if(a&&S&&v.transaction!==t.transaction){let E="custom";v.transaction_info={...S,source:E}}return this.sendEvent(v,e),v}).then(null,v=>{throw $f(v)||Wf(v)?v:(this.captureException(v,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:v}),Hf(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
5
+ Reason: ${v}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t).then(i=>(this._numProcessing--,i),i=>(this._numProcessing--,i===Qr&&this.recordDroppedEvent("queue_overflow",e),i))}_clearOutcomes(){let t=this._outcomes;return this._outcomes={},Object.entries(t).map(([e,i])=>{let[r,n]=e.split(":");return{reason:r,category:n,quantity:i}})}_flushOutcomes(){B&&U.log("Flushing outcomes...");let t=this._clearOutcomes();if(t.length===0){B&&U.log("No outcomes to send");return}if(!this._dsn){B&&U.log("No dsn provided, will not send outcomes");return}B&&U.log("Sending outcomes:",t);let e=Nf(t,this._options.tunnel&&We(this._dsn));this.sendEnvelope(e)}}});function zo(){wE.clear(),B&&U.log("Cleared AI provider skip registrations")}var wE,Jf=w(()=>{Ie();Ae();wE=new Set});function Xf(t,e,i,r,n){let s={sent_at:new Date(xe()).toISOString()};i?.sdk&&(s.sdk={name:i.sdk.name,version:i.sdk.version}),r&&n&&(s.dsn=We(n)),e&&(s.trace=e);let a=SE(t);return dt(s,[a])}function SE(t){return[{type:"check_in"},t]}var Zf=w(()=>{Ht();Gt();ot()});function eh(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return(e>>>0).toString(36)}var th=w(()=>{});function Ko(){return ht("tunnelStore",()=>({clients:new WeakMap}))}function Es(t){return Ko().clients.get(t)}function Ts(t,e){let{clients:i}=Ko();i.set(t,{...i.get(t),...e})}function ih(){return Ko().defaults}var Yo=w(()=>{nt()});function rh(t,e,i){let r=TE(e.allowedDsns,t.getDsn()),n={paths:EE(e,r),basePath:e.basePath,allowedDsns:r,forward:i,intercept:e.intercept!==!1};return Ts(t,{served:n}),n}function kE(t){let e=t?Br(t):bt()?.getDsn();return e?`/${eh(We(e))}`:void 0}function EE(t,e){let i=t.path?.replace(/\/$/,"");if(i)return[i];let r=e.map(n=>kE(n));return[...new Set(r.filter(n=>!!n))]}function nh(t,e){if(!e.length)return[];let i=`${ao(Qo(t.basePath))}(?:${e.map(ao).join("|")})/?`;return[{attributes:{[Gm]:new RegExp(`^${i}$`)}},{attributes:{"http.url":new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${i}(?:[?#].*)?$`)}}]}function Qo(t){let e=(t?.startsWith("./")?t.slice(1):t??"").replace(/\/$/,"");return!e||e.startsWith("/")?e:`/${e}`}function TE(t,e){let i=new Set;for(let r of[...(t??[]).map(n=>Br(n)),e])r&&i.add(We(r));return[...i]}var sh=w(()=>{pt();nm();Ht();th();Yo();_t()});function Jo(t,e,i=[e],r="npm"){let n=(t._metadata=t._metadata||{}).sdk=t._metadata.sdk||{};n.name||(n.name=`sentry.javascript.${e}`,n.packages=i.map(s=>({name:`${r}:@sentry/${s}`,version:At})),n.version=At)}var ah=w(()=>{zn()});function Xo(t){return Array.from(new Set(t))}var oh=w(()=>{});function lh(t,e,i,r,n,s){if(!n.exception?.values||!s||!at(s.originalException))return;let a=n.exception.values.length>0?n.exception.values[n.exception.values.length-1]:void 0;a&&(n.exception.values=Is(t,e,r,s.originalException,i,n.exception.values,a,0))}function Is(t,e,i,r,n,s,a,o){if(s.length>=i+1)return s;let l=[...s];if(at(r[n])){Zo(a,o,r);let c=t(e,r[n]),p=l.length;el(c,n,p,o),l=Is(t,e,i,r[n],n,[c,...l],c,p)}return ch(r)&&r.errors.forEach((c,p)=>{if(l.length<i+1&&at(c)){Zo(a,o,r);let u=t(e,c),m=l.length;el(u,`errors[${p}]`,m,o),l=Is(t,e,i,c,n,[u,...l],u,m)}}),IE(r)&&["error","suppressed"].forEach(c=>{let p=r[c];if(l.length<i+1&&at(p)){Zo(a,o,r);let u=t(e,p),m=l.length;el(u,c,m,o),l=Is(t,e,i,p,n,[u,...l],u,m)}}),l}function ch(t){return Array.isArray(t.errors)}function IE(t){return"error"in t&&"suppressed"in t}function Zo(t,e,i){t.mechanism={handled:!0,type:"auto.core.linked_errors",...ch(i)&&{is_exception_group:!0},...t.mechanism,exception_id:e}}function el(t,e,i,r){t.mechanism={handled:!0,...t.mechanism,type:"chained",source:e,exception_id:i,parent_id:r}}var ph=w(()=>{De()});function dh(t,e){return t(e.stack||"",1)}function AE(t){return at(t)&&"__sentry_fetch_url_host__"in t&&typeof t.__sentry_fetch_url_host__=="string"}function xE(t){let e=OE(t.message);return AE(t)?`${e} (${t.__sentry_fetch_url_host__})`:e}function OE(t){if(typeof t=="string")return t;if(t==null)return"";if(yt(t))return String(t);if(di(t)||Array.isArray(t)){let e=sm(t,"");if(e)return e}return so(void 0,t)}function tl(t,e){let i={type:e.name||e.constructor.name,value:xE(e)},r=dh(t,e);return r.length&&(i.stacktrace={frames:r}),i}function RE(t){for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let i=t[e];if(at(i))return i}}function NE(t){if("name"in t&&typeof t.name=="string"){let r=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(r+=` with message '${t.message}'`),r}else if("message"in t&&typeof t.message=="string")return t.message;let e=Xu(t);if(zu(t))return`Event \`ErrorEvent\` captured as exception with message \`${t.message}\``;let i=PE(t);return`${i&&i!=="Object"?`'${i}'`:"Object"} captured as exception with keys: ${e}`}function PE(t){try{let e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch{}}function CE(t,e,i,r){if(at(i))return[i,void 0];if(e.synthetic=!0,di(i)){let s=t?.getOptions().normalizeDepth,a={__serialized__:no(i,s)},o=RE(i);if(o)return[o,a];let l=NE(i),c=r?.syntheticException||new Error(l);return c.message=l,[c,a]}let n=r?.syntheticException||new Error(i);return n.message=`${i}`,[n,void 0]}function uh(t,e,i,r){let n=r?.data&&r.data.mechanism||{handled:!0,type:"generic"},[s,a]=CE(t,n,i,r),o={exception:{values:[tl(e,s)]}};return a&&(o.extra=a),co(o,void 0,void 0),Zn(o,n),{...o,event_id:r?.event_id}}function mh(t,e,i="info",r,n){let s={event_id:r?.event_id,level:i};if(n&&r?.syntheticException){let a=dh(t,r.syntheticException);a.length&&(s.exception={values:[{value:e,stacktrace:{frames:a}}]},Zn(s,{synthetic:!0}))}if(Ar(e)){let{__sentry_template_string__:a,__sentry_template_values__:o}=e;return s.logentry={message:a,params:o},s}return s.message=e,s}var il=w(()=>{De();Ot();Xn();Or();Pr()});var ME,DE,LE,UE,rl,gh=w(()=>{ph();il();ME="cause",DE=5,LE="LinkedErrors",UE=((t={})=>{let e=t.limit||DE,i=t.key||ME;return{name:LE,preprocessEvent(r,n,s){let a=s.getOptions();lh(tl,a.stackParser,i,e,r,n)}}}),rl=UE});function fh(t,e){return e?ss(e,()=>{let i=Gr(),r=i?ds(i):yi(e);return[i?Pt(i):$i(t,e),r]}):[void 0,void 0]}var hh=w(()=>{pt();Vi();Nt()});function jE(t){let e=t.length>1024?`<truncated>${t.slice(-1024)}`:t,i=qE.exec(e);return i?i.slice(1):[]}function nl(t){let e=jE(t),i=e[0]||"",r=e[1];return!i&&!r?".":(r&&(r=r.slice(0,r.length-1)),i+r)}var qE,yh=w(()=>{qE=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/});var vt=w(()=>{pt();go();rs();nt();Fi();Rf();Jf();Vi();Eo();ah();of();oh();os();gh();rt();Ae();Ot();yh();Yn();ig();So();Dr();zn();ot()});function bh(t){let e=t._metadata?.sdk,i=e?.name&&e?.version?`${e?.name}/${e?.version}`:void 0;t.transportOptions={...t.transportOptions,headers:{...i&&{"user-agent":i},...t.transportOptions?.headers}}}var _h=w(()=>{});function vh(t){let e=ih(),i=t?.getOptions(),r=i?._managedTunnel??e?.tunnel,n=t&&(Es(t)?.forward??e?.forward);if(!t||!i||!r||!n)return;let s=Qo(e?.basePath),a=r.basePath===void 0&&!r.path&&s?{...r,basePath:s}:r;i._managedTunnel=a;let{paths:o}=rh(t,a,n),l=Es(t)?.spanFilters??[],c=nh(a,o);i.ignoreSpans=[...(i.ignoreSpans??[]).filter(p=>!l.includes(p)),...c],Ts(t,{spanFilters:c})}var wh=w(()=>{Yo();sh()});function Sh(t){let e=hi().getScopeData().sdkProcessingMetadata.requestSession;if(e){let i=t?.mechanism?.handled??!0;i&&e.status!=="crashed"?e.status="errored":i||(e.status="crashed")}}var sl,kh=w(()=>{Zf();Qf();pt();Ie();Qg();_h();Ae();il();Ot();ks();Yi();hh();wh();_t();sl=class extends Kf{constructor(t){bh(t),(typeof __SENTRY_TRACING__>"u"||__SENTRY_TRACING__)&&t.traceLifecycle!=="static"&&!t.integrations.some(e=>e.name==="SpanStreaming")&&t.integrations.push(Yg()),super(t),this._disposeCallbacks=[],vh(this),this._setUpMetricsProcessing()}eventFromException(t,e){let i=uh(this,this._options.stackParser,t,e);return i.level="error",Ct(i)}eventFromMessage(t,e="info",i){return Ct(mh(this._options.stackParser,t,e,i,this._options.attachStacktrace))}captureException(t,e,i){return Sh(e),super.captureException(t,e,i)}captureEvent(t,e,i){return!t.type&&t.exception?.values&&t.exception.values.length>0&&Sh(e),super.captureEvent(t,e,i)}captureCheckIn(t,e,i){let r="checkInId"in t&&t.checkInId?t.checkInId:_e();if(!this._isEnabled())return B&&U.warn("SDK not enabled, will not capture check-in."),r;let{release:n,environment:s,tunnel:a}=this.getOptions(),o={check_in_id:r,monitor_slug:t.monitorSlug,status:t.status,release:n,environment:s};"duration"in t&&(o.duration=t.duration),e&&(o.monitor_config={schedule:e.schedule,checkin_margin:e.checkinMargin,max_runtime:e.maxRuntime,timezone:e.timezone,failure_issue_threshold:e.failureIssueThreshold,recovery_threshold:e.recoveryThreshold});let[l,c]=fh(this,i);c&&(o.contexts={trace:c});let p=Xf(o,l,this.getSdkMetadata(),a,this.getDsn());return B&&U.log("Sending checkin:",t.monitorSlug,t.status),this.sendEnvelope(p),r}registerCleanup(t){this._disposeCallbacks.push(t)}dispose(){B&&U.log("Disposing client...");for(let t of this._disposeCallbacks)try{t()}catch{}this._disposeCallbacks.length=0;for(let t of Object.keys(this._hooks))this._hooks[t]?.clear();this._hooks={},this._eventProcessors.length=0,this._integrations={},this._outcomes={},this._transport=void 0,this._promiseBuffer=Qi(64)}_prepareEvent(t,e,i,r){return this._options.platform&&(t.platform=t.platform||this._options.platform),this._options.runtime&&(t.contexts={...t.contexts,runtime:t.contexts?.runtime||this._options.runtime}),this._options.serverName&&(t.server_name=t.server_name||this._options.serverName),super._prepareEvent(t,e,i,r)}_setUpMetricsProcessing(){this.on("processMetric",t=>{this._options.serverName&&(t.attributes={[as]:this._options.serverName,...t.attributes})})}}});function Th(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&t!==void 0&&!t.includes("node_modules/")}function Ih(t){let e=/^\s*[-]{4,}$/,i=/at (?:async )?(?:(?=.*\)\s*$)(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,r=/at (?:async )?(.+?) \(data:(.*?),/;return n=>{let s=n.match(r);if(s)return{filename:`<data:${s[2]}>`,function:s[1]};let a=n.match(i);if(a){let o,l,c,p,u;if(a[1]){c=a[1];let f=c.lastIndexOf(".");if(c[f-1]==="."&&f--,f>0){o=c.slice(0,f),l=c.slice(f+1);let v=o.indexOf(".Module");v>0&&(c=c.slice(v+1),o=o.slice(0,v))}p=void 0}l&&(p=o,u=l),l==="<anonymous>"&&(u=void 0,c=void 0),c===void 0&&(u=u||"?",c=p?`${p}.${u}`:u);let m=$u(a[2]),g=a[5]==="native";!m&&a[5]&&!g&&(m=a[5]);let h=m?HE(m):void 0;return{filename:h??m,module:h&&t?.(h),function:c,lineno:Eh(a[3]),colno:Eh(a[4]),in_app:Th(m||"",g)}}if(n.match(e))return{filename:n}}}function al(t){return[90,Ih(t)]}function Eh(t){return parseInt(t||"",10)||void 0}function HE(t){try{return decodeURI(t)}catch{return}}var Ah=w(()=>{Yn()});var ol=w(()=>{kh();Ah()});var $t,ll=w(()=>{$t="1.10.0"});function GE(t){let e=new Set([t]),i=new Set,r=t.match(xh);if(!r)return()=>!1;let n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null)return function(l){return l===t};function s(o){return i.add(o),!1}function a(o){return e.add(o),!0}return function(l){if(e.has(l))return!0;if(i.has(l))return!1;let c=l.match(xh);if(!c)return s(l);let p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||n.major!==p.major?s(l):n.major===0?n.minor===p.minor&&n.patch<=p.patch?a(l):s(l):n.minor<=p.minor?a(l):s(l)}}var xh,Oh,Rh=w(()=>{ll();xh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Oh=GE($t)});function $E(){return Object.defineProperty({},"version",{value:$t,enumerable:!0,writable:!1,configurable:!1})}function Ji(t,e,i,r=!1){var n;let s=xs[As]=(n=xs[As])!==null&&n!==void 0?n:$E();if(!r&&s[t]){let a=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return i.error(a.stack||a.message),!1}if(s.version!=="1.10.0"){let a=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${t} does not match previously registered API v${$t}`);return i.error(a.stack||a.message),!1}return s[t]=e,i.debug(`@opentelemetry/api: Registered a global for ${t} v${$t}.`),!0}function Mt(t){let e=xs[As];if(e!=null){if(e!==Nh){if(!e.version||!Oh(e.version))return;Nh=e}return e[t]}}function Xi(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${$t}.`);let i=xs[As];i&&delete i[t]}var WE,As,xs,Nh,Jr=w(()=>{ll();Rh();WE=$t.split(".")[0],As=Symbol.for(`opentelemetry.js.api.${WE}`),xs=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function Xr(t,e,i){let r=Mt("diag");if(r)return r[t](e,...i)}var Ph,Ch=w(()=>{Jr();Ph=class{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return Xr("debug",this._namespace,t)}error(...t){return Xr("error",this._namespace,t)}info(...t){return Xr("info",this._namespace,t)}warn(...t){return Xr("warn",this._namespace,t)}verbose(...t){return Xr("verbose",this._namespace,t)}}});function Mh(t,e){t<0?t=0:t>9999&&(t=9999),e=e||{};function i(r,n){let s=e[r];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:i("error",30),warn:i("warn",50),info:i("info",60),debug:i("debug",70),verbose:i("verbose",80)}}var Dh=w(()=>{});var VE,wi,cl=w(()=>{Jr();Ch();Dh();VE="diag",wi=class Lh{static instance(){return this._instance||(this._instance=new Lh),this._instance}constructor(){function e(n){return function(...s){let a=Mt("diag");if(a)return a[n](...s)}}let i=this,r=(n,s={logLevel:60})=>{var a;if(n===i){var o;let u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return i.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof s=="number"&&(s={logLevel:s});let l=Mt("diag"),c=Mh((a=s.logLevel)!==null&&a!==void 0?a:60,n);if(l&&!s.suppressOverrideMessage){var p;let u=(p=new Error().stack)!==null&&p!==void 0?p:"<failed to generate stacktrace>";l.warn(`Current logger will be overwritten from ${u}`),c.warn(`Current logger will overwrite one already registered from ${u}`)}return Ji("diag",c,i,!0)};i.setLogger=r,i.disable=()=>{Xi(VE,i)},i.createComponentLogger=n=>new Ph(n),i.verbose=e("verbose"),i.debug=e("debug"),i.info=e("info"),i.warn=e("warn"),i.error=e("error")}}});function Dt(t){return Symbol.for(t)}var Zr,Os=w(()=>{Zr=new class pl{constructor(e){let i=this;i._currentContext=e?new Map(e):new Map,i.getValue=r=>i._currentContext.get(r),i.setValue=(r,n)=>{let s=new pl(i._currentContext);return s._currentContext.set(r,n),s},i.deleteValue=r=>{let n=new pl(i._currentContext);return n._currentContext.delete(r),n}}}});var dl,Uh=w(()=>{dl=(function(t){return t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED",t})({})});var zE,KE,qh,jh=w(()=>{zE="0000000000000000",KE="00000000000000000000000000000000",qh={traceId:KE,spanId:zE,traceFlags:0}});var Vt,Rs=w(()=>{jh();Vt=class{constructor(t=qh){this._spanContext=t}spanContext(){return this._spanContext}setAttribute(t,e){return this}setAttributes(t){return this}addEvent(t,e){return this}addLink(t){return this}addLinks(t){return this}setStatus(t){return this}updateName(t){return this}end(t){}isRecording(){return!1}recordException(t,e){}}});function Bh(t,e){if(typeof t!="string"||t.length!==e)return!1;let i=0;for(let r=0;r<t.length;r+=4)i+=(Ns[t.charCodeAt(r)]|0)+(Ns[t.charCodeAt(r+1)]|0)+(Ns[t.charCodeAt(r+2)]|0)+(Ns[t.charCodeAt(r+3)]|0);return i===e}function Fh(t){return Bh(t,32)&&t!=="00000000000000000000000000000000"}function Hh(t){return Bh(t,16)&&t!=="0000000000000000"}function Si(t){return Fh(t.traceId)&&Hh(t.spanId)}function Gh(t){return new Vt(t)}var Ns,Ps=w(()=>{Rs();Ns=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});var Wh,$h=w(()=>{Os();Wh=class{active(){return Zr}with(t,e,i,...r){return e.call(i,...r)}bind(t,e){return e}enable(){return this}disable(){return this}attach(t){return{dispose(){}}}}});var ul,YE,QE,Zi,Cs=w(()=>{Jr();cl();$h();ul="context",YE=new Wh,QE=Object.freeze({dispose:()=>{}}),Zi=class Vh{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new Vh),this._instance}setGlobalContextManager(e){return Ji(ul,e,wi.instance())}active(){return this._getContextManager().active()}with(e,i,r,...n){return this._getContextManager().with(e,i,r,...n)}bind(e,i){return this._getContextManager().bind(e,i)}attach(e){let i=this._getContextManager();return i.attach?i.attach(e):(this._attachUnsupportedWarned||(this._attachUnsupportedWarned=!0,wi.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.")),QE)}_getContextManager(){return Mt(ul)||YE}disable(){this._getContextManager().disable(),Xi(ul,wi.instance())}}});function Ms(t){return t.getValue(ml)||void 0}function zh(){return Ms(Zi.getInstance().active())}function en(t,e){return t.setValue(ml,e)}function Kh(t){return t.deleteValue(ml)}function Yh(t,e){return en(t,new Vt(e))}function Ds(t){var e;return(e=Ms(t))===null||e===void 0?void 0:e.spanContext()}var ml,gl=w(()=>{Os();Cs();Rs();ml=Dt("OpenTelemetry Context Key SPAN")});function JE(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var fl,Ls,hl=w(()=>{Cs();Rs();gl();Ps();fl=Zi.getInstance(),Ls=class{startSpan(t,e,i=fl.active()){if(e?.root)return new Vt;let r=i&&Ds(i);return JE(r)&&Si(r)?new Vt(r):new Vt}startActiveSpan(t,e,i,r){var n;let s,a,o;if(arguments.length<2)return;arguments.length===2?o=e:arguments.length===3?(s=e,o=i):(s=e,a=i,o=r);let l=(n=a)!==null&&n!==void 0?n:fl.active(),c=this.startSpan(t,s,l),p=en(l,c);return fl.with(p,o,void 0,c)}}});var XE,Qh,Jh=w(()=>{hl();XE=new Ls,Qh=class{constructor(t,e,i,r){this._provider=t,this.name=e,this.version=i,this.options=r}startSpan(t,e,i){return this._getTracer().startSpan(t,e,i)}startActiveSpan(t,e,i,r){let n=this._getTracer();return Reflect.apply(n.startActiveSpan,n,arguments)}_getTracer(){if(this._delegate)return this._delegate;let t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):XE}}});var Xh,Zh=w(()=>{hl();Xh=class{getTracer(t,e,i){return new Ls}}});var ZE,yl,ey=w(()=>{Jh();Zh();ZE=new Xh,yl=class{getTracer(t,e,i){var r;return(r=this.getDelegateTracer(t,e,i))!==null&&r!==void 0?r:new Qh(this,t,e,i)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:ZE}setDelegate(t){this._delegate=t}getDelegateTracer(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(t,e,i)}}});var Oe,ty=w(()=>{Cs();Oe=Zi.getInstance()});var bl,iy,ny=w(()=>{Jr();cl();gl();Ps();ey();bl="trace",iy=class ry{constructor(){this._proxyTracerProvider=new yl,this.wrapSpanContext=Gh,this.isSpanContextValid=Si,this.deleteSpan=Kh,this.getSpan=Ms,this.getActiveSpan=zh,this.getSpanContext=Ds,this.setSpan=en,this.setSpanContext=Yh}static getInstance(){return this._instance||(this._instance=new ry),this._instance}setGlobalTracerProvider(e){let i=Ji(bl,this._proxyTracerProvider,wi.instance());return i&&this._proxyTracerProvider.setDelegate(e),i}getTracerProvider(){return Mt(bl)||this._proxyTracerProvider}getTracer(e,i){return this.getTracerProvider().getTracer(e,i)}disable(){Xi(bl,wi.instance()),this._proxyTracerProvider=new yl}}});var zt,sy=w(()=>{ny();zt=iy.getInstance()});var Us=w(()=>{Os();Uh();Ps();ty();sy()});import{AsyncLocalStorage as tT}from"node:async_hooks";function _l(){let t=ct(ye()).getTracingChannelBinding?.()?.asyncLocalStorage??new tT;function e(){let a=t.getStore();return a||{scope:gi(),isolationScope:fi()}}function i(a){let o=e().scope.clone(),l=e().isolationScope;return t.run({scope:o,isolationScope:l},()=>a(o))}function r(a,o){let l=e().isolationScope;return t.run({scope:a,isolationScope:l},()=>o(a))}function n(a){let o=e().scope.clone(),l=e().isolationScope.clone();return Fr(o.getPropagationContext())||o.setPropagationContext({traceId:mi(),sampleRand:Qe()}),t.run({scope:o,isolationScope:l},()=>a(l))}function s(a,o){let l=e().scope.clone();return t.run({scope:l,isolationScope:a},()=>o(a))}return Lr({withScope:i,withSetScope:r,withIsolationScope:n,withSetIsolationScope:s,getCurrentScope:()=>e().scope,getIsolationScope:()=>e().isolationScope,getTracingChannelBinding:()=>({asyncLocalStorage:t})}),t}var ay=w(()=>{vt()});function M(t){return[...new Set(t.map(e=>e.module.name))]}var V=w(()=>{});var oy,er,qs,vl,Aj,ly=w(()=>{V();oy={name:"@earendil-works/pi-ai",versionRange:">=0.80.0 <2.0.0"},er=(t,e,i)=>({channelName:e,module:{...oy,filePath:"dist/models.js"},functionQuery:{className:"ModelsImpl",methodName:t,kind:i}}),qs=(t,e,i)=>({channelName:e,module:{...oy,filePath:"dist/compat.js"},functionQuery:{functionName:t,kind:i}}),vl=[er("stream","stream","Sync"),er("streamSimple","stream","Sync"),qs("stream","stream","Sync"),qs("streamSimple","stream","Sync"),er("complete","complete","Async"),er("completeSimple","complete","Async"),qs("complete","complete","Async"),qs("completeSimple","complete","Async"),er("streamDeferred","stream","Sync"),er("fetchDeferred","complete","Async")],Aj=M(vl)});var wl,Rj,cy=w(()=>{V();wl=[{channelName:"send",module:{name:"@smithy/core",versionRange:">=3.24.0 <4",filePath:"dist-cjs/submodules/client/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@smithy/smithy-client",versionRange:">=1.0.3 <5",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}},{channelName:"send",module:{name:"@aws-sdk/smithy-client",versionRange:"^3.1.0",filePath:"dist-cjs/index.js"},functionQuery:{className:"Client",methodName:"send",kind:"Async"}}],Rj=M(wl)});var ut,Sl,Cj,py=w(()=>{V();ut={name:"amqplib",versionRange:">=0.5.5 <3"},Sl=[...["lib/channel_model.js","lib/callback_model.js"].flatMap(t=>[{channelName:"publish",module:{...ut,filePath:t},functionQuery:{className:"Channel",methodName:"publish",kind:"Sync"}},{channelName:"confirmPublish",module:{...ut,filePath:t},functionQuery:{className:"ConfirmChannel",methodName:"publish",kind:"Callback"}},{channelName:"consume",module:{...ut,filePath:t},functionQuery:{className:"Channel",methodName:"consume",kind:"Sync"}},{channelName:"ack",module:{...ut,filePath:t},functionQuery:{className:"Channel",methodName:"ack",kind:"Sync"}},{channelName:"nack",module:{...ut,filePath:t},functionQuery:{className:"Channel",methodName:"nack",kind:"Sync"}},{channelName:"reject",module:{...ut,filePath:t},functionQuery:{className:"Channel",methodName:"reject",kind:"Sync"}},{channelName:"ackAll",module:{...ut,filePath:t},functionQuery:{className:"Channel",methodName:"ackAll",kind:"Sync"}},{channelName:"nackAll",module:{...ut,filePath:t},functionQuery:{className:"Channel",methodName:"nackAll",kind:"Sync"}}]),{channelName:"registerConsumer",module:{...ut,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"registerConsumer",kind:"Sync"}},{channelName:"dispatch",module:{...ut,filePath:"lib/channel.js"},functionQuery:{className:"BaseChannel",methodName:"dispatchMessage",kind:"Sync"}},{channelName:"connect",module:{...ut,filePath:"lib/connect.js"},functionQuery:{functionName:"connect",kind:"Callback"}}],Cj=M(Sl)});var kl,Lj,dy=w(()=>{V();kl=[...["resources/messages/messages.js","resources/messages/messages.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/completions.js","resources/completions.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <1",filePath:t},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(t=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"create",kind:"Sync"}})),...["resources/messages/messages.js","resources/messages/messages.mjs"].map(t=>({channelName:"messages-stream",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <2",filePath:t},functionQuery:{className:"Messages",methodName:"stream",kind:"Sync"}})),...["resources/beta/messages/messages.js","resources/beta/messages/messages.mjs"].map(t=>({channelName:"tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.63.0 <2",filePath:t},functionQuery:{className:"Messages",methodName:"toolRunner",kind:"Sync"}})),...["lib/tools/SessionToolRunner.js","lib/tools/SessionToolRunner.mjs"].map(t=>({channelName:"session-tool-runner",module:{name:"@anthropic-ai/sdk",versionRange:">=0.97.0 <2",filePath:t},functionQuery:{className:"SessionToolRunner"}})),...["lib/BetaMessageStream.js","lib/BetaMessageStream.mjs"].map(t=>({channelName:"thread-stream",module:{name:"@anthropic-ai/sdk",versionRange:">=1.2.0 <2",filePath:t},functionQuery:{className:"BetaMessageStream",methodName:"_start",kind:"Sync"}}))],Lj=M(kl)});var El,jj,uy=w(()=>{V();El=[{channelName:"cronJobConstructor",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob"}},{channelName:"cronJobSetTime",module:{name:"cron",versionRange:">=4.3.0 <5",filePath:"dist/job.js"},functionQuery:{className:"CronJob",methodName:"setTime",kind:"Sync"}}],jj=M(El)});var tr,my,gy=w(()=>{tr={name:"dataloader",versionRange:">=2.0.0 <3",filePath:"index.js"},my=[{channelName:"construct",module:tr,functionQuery:{functionName:"DataLoader",kind:"Sync"}},{channelName:"load",module:tr,functionQuery:{expressionName:"load",kind:"Async"}},{channelName:"loadMany",module:tr,functionQuery:{expressionName:"loadMany",kind:"Async"}},{channelName:"prime",module:tr,functionQuery:{expressionName:"prime",kind:"Sync"}},{channelName:"clear",module:tr,functionQuery:{expressionName:"clear",kind:"Sync"}},{channelName:"clearAll",module:tr,functionQuery:{expressionName:"clearAll",kind:"Sync"}}]});var Tl,Gj,fy=w(()=>{V();Tl=[{channelName:"handle",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/layer.js"},functionQuery:{expressionName:"handle_request",kind:"Callback"}},{channelName:"handle",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"lib/layer.js"},functionQuery:{expressionName:"handleRequest",kind:"Callback"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"express",versionRange:">=4.0.0 <5",filePath:"lib/router/index.js"},functionQuery:{expressionName:"use",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"route",kind:"Sync"}},{channelName:"register",module:{name:"router",versionRange:">=2.0.0 <3",filePath:"index.js"},functionQuery:{expressionName:"use",kind:"Sync"}}],Gj=M(Tl)});var iT,rT,nT,sT,aT,Il,Vj,hy=w(()=>{V();iT=">=3.0.0 <5",rT=/dist\/lite\/(index|common-[^/]+)\.node\.(cjs\.js|mjs)$/,nT=[{functionName:"addDoc",channelName:"add-doc"},{functionName:"getDocs",channelName:"get-docs"},{functionName:"setDoc",channelName:"set-doc"},{functionName:"deleteDoc",channelName:"delete-doc"}],sT=">=6.0.0 <7",aT=[{file:"lib/v2/providers/https.js",functionName:"onRequest",channelName:"http-request"},{file:"lib/v2/providers/https.js",functionName:"onCall",channelName:"http-call"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreated",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentCreatedWithAuthContext",channelName:"firestore-created"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdated",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentUpdatedWithAuthContext",channelName:"firestore-updated"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeleted",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentDeletedWithAuthContext",channelName:"firestore-deleted"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWritten",channelName:"firestore-written"},{file:"lib/v2/providers/firestore.js",functionName:"onDocumentWrittenWithAuthContext",channelName:"firestore-written"},{file:"lib/v2/providers/scheduler.js",functionName:"onSchedule",channelName:"scheduler"},{file:"lib/v2/providers/storage.js",functionName:"onObjectFinalized",channelName:"storage-finalized"},{file:"lib/v2/providers/storage.js",functionName:"onObjectArchived",channelName:"storage-archived"},{file:"lib/v2/providers/storage.js",functionName:"onObjectDeleted",channelName:"storage-deleted"},{file:"lib/v2/providers/storage.js",functionName:"onObjectMetadataUpdated",channelName:"storage-metadata-updated"}],Il=[...nT.map(({functionName:t,channelName:e})=>({channelName:e,module:{name:"@firebase/firestore",versionRange:iT,filePath:rT},functionQuery:{functionName:t,kind:"Auto"}})),...aT.map(({file:t,functionName:e,channelName:i})=>({channelName:i,module:{name:"firebase-functions",versionRange:sT,filePath:t},functionQuery:{functionName:e,kind:"Sync"}}))],Vj=M(Il)});var Al,Yj,yy=w(()=>{V();Al=[{channelName:"acquire",module:{name:"generic-pool",versionRange:">=3.0.0 <4",filePath:"lib/Pool.js"},functionQuery:{className:"Pool",methodName:"acquire",kind:"Auto"}},{channelName:"acquire",module:{name:"generic-pool",versionRange:">=2.4.0 <3",filePath:"lib/generic-pool.js"},functionQuery:{expressionName:"acquire",kind:"Callback"}}],Yj=M(Al)});var js,xl,Xj,by=w(()=>{V();js=["dist/node/index.js","dist/node/index.mjs","dist/node/index.cjs"],xl=[...js.flatMap(t=>["generateContent","generateContentStream"].map(e=>({channelName:"generate-content",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{expressionName:e,kind:"Auto"}}))),...js.map(t=>({channelName:"embed-content",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{className:"Models",methodName:"embedContent",kind:"Auto"}})),...js.flatMap(t=>["sendMessage","sendMessageStream"].map(e=>({channelName:"chat",module:{name:"@google/genai",versionRange:">=0.10.0 <4",filePath:t},functionQuery:{className:"Chat",methodName:e,kind:"Auto"}}))),...js.map(t=>({channelName:"decide",module:{name:"@google/genai",versionRange:">=3.2.0 <4",filePath:t},functionQuery:{className:"GeminiNextGenDecisions",methodName:"create",kind:"Async"}}))],Xj=M(xl)});var Ol,tB,_y=w(()=>{V();Ol=[...["language/parser.js","language/parser.mjs"].map(t=>({channelName:"parse",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"parse",kind:"Sync"}})),...["validation/validate.js","validation/validate.mjs"].map(t=>({channelName:"validate",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"validate",kind:"Sync"}})),...["execution/execute.js","execution/execute.mjs"].map(t=>({channelName:"execute",module:{name:"graphql",versionRange:">=14.0.0 <17",filePath:t},functionQuery:{functionName:"execute",kind:"Auto"}}))],tB=M(Ol)});function tn(t,e={chat:"Completions",embeddings:"Embeddings"}){return[...["resources/chat/completions.js","resources/chat/completions.mjs"].map(i=>({channelName:"chat",module:{...t,filePath:i},functionQuery:{className:e.chat,methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(i=>({channelName:"embeddings",module:{...t,filePath:i},functionQuery:{className:e.embeddings,methodName:"create",kind:"Sync"}}))]}var Rl=w(()=>{});var Nl,aB,vy=w(()=>{V();Rl();Nl=tn({name:"groq-sdk",versionRange:">=0.3.0 <2"}),aB=M(Nl)});var Pl,cB,wy=w(()=>{V();Pl=[{channelName:"route",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"route",kind:"Sync"}},{channelName:"ext",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"ext",kind:"Sync"}},{channelName:"start",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"start",kind:"Sync"}},{channelName:"initialize",module:{name:"@hapi/hapi",versionRange:">=17.0.0 <22.0.0",filePath:"lib/server.js"},functionQuery:{methodName:"initialize",kind:"Sync"}}],cB=M(Pl)});var Cl,uB,Sy=w(()=>{V();Cl=[{channelName:"context",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?context\.js$/},functionQuery:{className:"Context"}},{channelName:"request",module:{name:"hono",versionRange:">=4.0.0 <5",filePath:/^dist\/(?:cjs\/)?hono-base\.js$/},astQuery:"PropertyDefinition[key.name='request'] > ArrowFunctionExpression",functionQuery:{kind:"Auto"}}],uB=M(Cl)});function Re(t){return{channelName:"module-registration",module:t,astQuery:"Program",transform:oT}}var oT,Lt=w(()=>{oT="sentryModuleRegistration"});var Ml,yB,ky=w(()=>{V();Lt();Ml=[Re({name:"ioredis",versionRange:">=5.11.0",filePath:"built/Redis.js"}),...["lib/redis.js","built/redis.js","built/redis/index.js"].flatMap(t=>[{channelName:"command",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:t},functionQuery:{expressionName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=2.0.0 <5.0.0",filePath:t},functionQuery:{expressionName:"connect",kind:"Async"}}]),{channelName:"command",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"ioredis",versionRange:">=5.0.0 <5.11.0",filePath:"built/Redis.js"},functionQuery:{className:"Redis",methodName:"connect",kind:"Async"}}],yB=M(Ml)});var Dl,vB,Ey=w(()=>{V();Dl=[{channelName:"send_batch",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/producer/messageProducer.js"},functionQuery:{expressionName:"sendBatch",kind:"Async"}},{channelName:"consumer_run",module:{name:"kafkajs",versionRange:">=2.0.0 <3",filePath:"src/consumer/index.js"},functionQuery:{expressionName:"run",kind:"Async"}}],vB=M(Dl)});function dT(t,e){return{channelName:"query",module:{name:Ty,versionRange:e,filePath:t},functionQuery:{className:"Runner",methodName:"query",kind:"Async"}}}function uT(t,e,i){return{channelName:t,module:{name:Ty,versionRange:i,filePath:e},functionQuery:{className:"Client",methodName:t,kind:"Sync"}}}var Ty,lT,cT,pT,Iy,Ay=w(()=>{Ty="knex",lT=[{filePath:"lib/execution/runner.js",versionRange:">=0.22.0 <4"},{filePath:"lib/runner.js",versionRange:">=0.10.0 <0.22.0"},{filePath:"src/runner.js",versionRange:">=0.18.0 <0.19.0"}],cT=[{filePath:"lib/client.js",versionRange:">=0.10.0 <4"},{filePath:"src/client.js",versionRange:">=0.18.0 <0.19.0"}],pT=["queryBuilder","schemaBuilder","raw"];Iy=[...lT.map(({filePath:t,versionRange:e})=>dT(t,e)),...cT.flatMap(({filePath:t,versionRange:e})=>pT.map(i=>uT(i,t,e)))]});var Ll,EB,xy=w(()=>{V();Ll=[{channelName:"use",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"use",kind:"Sync"}},{channelName:"callback",module:{name:"koa",versionRange:">=2.0.0 <4",filePath:"lib/application.js"},functionQuery:{className:"Application",methodName:"callback",kind:"Sync"}}],EB=M(Ll)});var mT,Ul,Bs,Oy,gT,fT,ql,AB,xB,Ry=w(()=>{V();mT=["dist/language_models/chat_models.cjs","dist/language_models/chat_models.js"].flatMap(t=>{let e={name:"@langchain/core",versionRange:">=0.1.0 <2.0.0",filePath:t};return[{channelName:"chatModelInvoke",module:e,functionQuery:{className:"BaseChatModel",methodName:"invoke",kind:"Async"}},{channelName:"chatModelStream",module:e,functionQuery:{className:"BaseChatModel",methodName:"_streamIterator",kind:"Async"}}]}),Ul="embedQuery",Bs="embedDocuments",Oy=[{name:"@langchain/openai",versionRange:">=0.1.0 <2.0.0",methods:[Ul,Bs]},{name:"@langchain/google-genai",versionRange:">=0.1.0 <3.0.0",methods:[Ul,Bs]},{name:"@langchain/mistralai",versionRange:">=0.1.0 <2.0.0",methods:[Ul,Bs]},{name:"@langchain/google-common",versionRange:">=0.1.0 <3.0.0",methods:[Bs]}],gT=Oy.flatMap(({name:t,versionRange:e,methods:i})=>["dist/embeddings.cjs","dist/embeddings.js"].flatMap(r=>i.map(n=>({channelName:n,module:{name:t,versionRange:e,filePath:r},functionQuery:{methodName:n,kind:"Async"}})))),fT=["dist/classifier.cjs","dist/classifier.js"].map(t=>({channelName:"typesafeClassifierInvoke",module:{name:"@langchain/typesafe",versionRange:">=0.0.1 <1.0.0",filePath:t},functionQuery:{className:"TypeSafeClassifier",methodName:"invoke",kind:"Async"}})),ql=[...mT,...gT,...fT],AB=Oy.flatMap(({name:t,methods:e})=>e.map(i=>`orchestrion:${t}:${i}`)),xB=M(ql)});var Ny,hT,yT,jl,NB,Py=w(()=>{V();Ny=t=>({name:"@langchain/langgraph",versionRange:">=0.0.0 <2.0.0",filePath:t}),hT=["dist/graph/state.cjs","dist/graph/state.js"].map(t=>({channelName:"stateGraphCompile",module:Ny(t),functionQuery:{className:"StateGraph",methodName:"compile",kind:"Sync"}})),yT=["dist/prebuilt/react_agent_executor.cjs","dist/prebuilt/react_agent_executor.js"].map(t=>({channelName:"createReactAgent",module:Ny(t),functionQuery:{functionName:"createReactAgent",kind:"Sync"}})),jl=[...hT,...yT],NB=M(jl)});var Bl,MB,Cy=w(()=>{V();Bl=[{channelName:"load",module:{name:"lru-memoizer",versionRange:">=2.1.0 <4",filePath:"lib/async.js"},functionQuery:{functionName:"memoizedFunction",kind:"Callback"}}],MB=M(Bl)});var My,Dy=w(()=>{Lt();My=[Re({name:"@flue/runtime",versionRange:">=2.0.0 <3.0.0",filePath:"dist/index.mjs"})]});var bT,_T,vT,Fl,jB,Ly=w(()=>{V();bT=[{channelName:"mastraConstructor",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/(?:[\w.-]+\/)?mastra[\w.-]*\.(?:cjs|mjs|js)$/},functionQuery:{className:"Mastra"}}],_T=["executeWithContext","executeWithContextSync"].map(t=>({channelName:"mastraExecuteWithContext",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/observability\/context-storage\.(?:cjs|mjs|js)$/},functionQuery:{functionName:t,kind:"Auto"}})),vT=[{channelName:"mastraClassifierEvaluate",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/classifier\/index\.(?:cjs|mjs|js)$/},functionQuery:{className:"Classifier",methodName:"evaluate",kind:"Async"}}],Fl=[...bT,..._T,...vT],jB=M(Fl)});var Uy,Hl,HB,qy=w(()=>{V();Uy={name:"@earendil-works/pi-durable",versionRange:">=1.0.0 <2.0.0"},Hl=[{channelName:"harnessOpen",module:{...Uy,filePath:"dist/harness/harness.js"},functionQuery:{methodName:"open",kind:"Async"}},...[["bash","createBashTool"],["read","createReadTool"],["edit","createEditTool"],["write","createWriteTool"]].map(([t,e])=>({channelName:"codingTool",module:{...Uy,filePath:`dist/tools/${t}.js`},functionQuery:{functionName:e,kind:"Sync"}}))],HB=M(Hl)});var wT,ST,Gl,$B,jy=w(()=>{V();wT=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/server",versionRange:">=2.0.0 <3",filePath:/^dist\/mcp-[\w-]+\.(?:cjs|mjs)$/},functionQuery:{className:"McpServer"}}],ST=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/sdk",versionRange:">=1.9.0 <2",filePath:/(?:^|\/)server\/mcp\.js$/},functionQuery:{className:"McpServer"}}],Gl=[...wT,...ST],$B=M(Gl)});var Wl,Fs,By,$l,KB,Fy=w(()=>{V();Wl={name:"@mistralai/mistralai",versionRange:">=2.0.0 <4"},Fs={...Wl,filePath:"esm/sdk/chat.js"},By={...Wl,filePath:"esm/sdk/agents.js"},$l=[{channelName:"chat",module:Fs,functionQuery:{className:"Chat",methodName:"complete",kind:"Auto"}},{channelName:"chat",module:Fs,functionQuery:{className:"Chat",methodName:"parse",kind:"Auto"}},{channelName:"chat-stream",module:Fs,functionQuery:{className:"Chat",methodName:"stream",kind:"Auto"}},{channelName:"chat-stream",module:Fs,functionQuery:{className:"Chat",methodName:"parseStream",kind:"Auto"}},{channelName:"embeddings",module:{...Wl,filePath:"esm/sdk/embeddings.js"},functionQuery:{className:"Embeddings",methodName:"create",kind:"Auto"}},{channelName:"agents",module:By,functionQuery:{className:"Agents",methodName:"complete",kind:"Auto"}},{channelName:"agents-stream",module:By,functionQuery:{className:"Agents",methodName:"stream",kind:"Auto"}}],KB=M($l)});var ki,Vl,JB,Hy=w(()=>{V();ki={name:"mongodb"},Vl=[{channelName:"command",module:{...ki,versionRange:">=6.4.0 <8",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Async"}},{channelName:"command",module:{...ki,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Callback"}},{channelName:"checkout",module:{...ki,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection_pool.js"},functionQuery:{methodName:"checkOut",kind:"Callback"}},...["insert","update","remove"].map(t=>({channelName:`v3_${t}`,module:{...ki,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/index.js"},functionQuery:{expressionName:t,kind:"Callback"}})),{channelName:"v3_command",module:{...ki,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/command.js"},functionQuery:{functionName:"command",kind:"Callback"}},{channelName:"v3_query",module:{...ki,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/query.js"},functionQuery:{functionName:"query",kind:"Callback"}},{channelName:"v3_get_more",module:{...ki,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/get_more.js"},functionQuery:{functionName:"getMore",kind:"Callback"}}],JB=M(Vl)});var Kt,Gy,zl,tF,iF,Wy=w(()=>{V();Lt();Kt={name:"mongoose",versionRange:">=5.9.7 <9.7.0"},Gy=["find","findOne","deleteOne","deleteMany","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace","remove","count","findOneAndRemove"],zl=[Re({name:"mongoose",versionRange:">=9.7.0",filePath:"lib/query.js"}),{channelName:"query_exec",module:{...Kt,filePath:"lib/query.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"aggregate_exec",module:{...Kt,filePath:"lib/aggregate.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"model_save",module:{...Kt,filePath:"lib/model.js"},functionQuery:{expressionName:"save",kind:"Auto"}},{channelName:"model_insert_many",module:{...Kt,filePath:"lib/model.js"},functionQuery:{expressionName:"insertMany",kind:"Auto"}},{channelName:"model_bulk_write",module:{...Kt,filePath:"lib/model.js"},functionQuery:{expressionName:"bulkWrite",kind:"Auto"}},{channelName:"model_remove",module:{...Kt,filePath:"lib/model.js"},functionQuery:{expressionName:"remove",kind:"Auto"}},{channelName:"model_aggregate",module:{...Kt,filePath:"lib/model.js"},functionQuery:{expressionName:"aggregate",kind:"Sync"}},...Gy.map(t=>({channelName:`ctx_${t}`,module:{...Kt,filePath:"lib/query.js"},functionQuery:{expressionName:t,kind:"Sync"}}))],tF=M(zl),iF=Gy.map(t=>`orchestrion:mongoose:ctx_${t}`)});var Kl,aF,$y=w(()=>{V();Lt();Kl=[Re({name:"mysql2",versionRange:">=3.20.0",filePath:"lib/base/connection.js"}),{channelName:"query",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=1.4.2 <3.11.5",filePath:"lib/connection.js"},functionQuery:{className:"Connection",methodName:"execute",kind:"Callback"}},{channelName:"query",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"query",kind:"Callback"}},{channelName:"execute",module:{name:"mysql2",versionRange:">=3.11.5 <3.20.0",filePath:"lib/base/connection.js"},functionQuery:{className:"BaseConnection",methodName:"execute",kind:"Callback"}}],aF=M(Kl)});var Yl,cF,Vy=w(()=>{V();Yl=[{channelName:"query",module:{name:"mysql",versionRange:">=2.0.0 <3",filePath:"lib/Connection.js"},functionQuery:{expressionName:"query",kind:"Auto"}}],cF=M(Yl)});var Ql,Jl,uF,zy=w(()=>{V();Ql={name:"@neondatabase/serverless",versionRange:">=1.0.0 <2",filePath:/^index\.m?js$/},Jl=[{channelName:"query",module:Ql,astQuery:'ClassBody:has(MethodDefinition[key.name="_pulseQueryQueue"]) > MethodDefinition[key.name="query"] > FunctionExpression',functionQuery:{methodName:"query",kind:"Auto"}},{channelName:"http-query",module:Ql,astQuery:'FunctionDeclaration[async=true]:has(Literal[value="Neon-Connection-String"])',functionQuery:{kind:"Async"}},{channelName:"resolve-connection",module:Ql,astQuery:'FunctionDeclaration[async=true]:has(ReturnStatement > ObjectExpression > Property[key.name="resolvedURL"])',functionQuery:{kind:"Async"}}],uF=M(Jl)});var Ky,Yy=w(()=>{Ky=[{channelName:"nestFactoryCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"nest-factory.js"},functionQuery:{className:"NestFactoryStatic",methodName:"create",kind:"Async"}},{channelName:"routerExecutionContextCreate",module:{name:"@nestjs/core",versionRange:">=8.0.0 <13",filePath:"router/router-execution-context.js"},functionQuery:{className:"RouterExecutionContext",methodName:"create",kind:"Sync"}},{channelName:"injectableDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/injectable.decorator.js"},astQuery:'FunctionDeclaration[id.name="Injectable"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"catchDecorator",module:{name:"@nestjs/common",versionRange:">=8.0.0 <13",filePath:"decorators/core/catch.decorator.js"},astQuery:'FunctionDeclaration[id.name="Catch"] ReturnStatement > ArrowFunctionExpression',functionQuery:{kind:"Sync"}},{channelName:"cronDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/cron.decorator.js"},functionQuery:{functionName:"Cron",kind:"Sync"}},{channelName:"intervalDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/interval.decorator.js"},functionQuery:{functionName:"Interval",kind:"Sync"}},{channelName:"timeoutDecorator",module:{name:"@nestjs/schedule",versionRange:">=2.0.0",filePath:"dist/decorators/timeout.decorator.js"},functionQuery:{functionName:"Timeout",kind:"Sync"}},{channelName:"scheduleExplorerWrap",module:{name:"@nestjs/schedule",versionRange:">=6.0.0",filePath:"dist/schedule.explorer.js"},functionQuery:{className:"ScheduleExplorer",methodName:"wrapFunctionInTryCatchBlocks",kind:"Sync"}},{channelName:"onEventDecorator",module:{name:"@nestjs/event-emitter",versionRange:">=2.0.0",filePath:"dist/decorators/on-event.decorator.js"},functionQuery:{expressionName:"OnEvent",kind:"Sync"}},{channelName:"processorDecorator",module:{name:"@nestjs/bullmq",versionRange:">=10.0.0",filePath:"dist/decorators/processor.decorator.js"},functionQuery:{functionName:"Processor",kind:"Sync"}}]});var Qy,Jy=w(()=>{Lt();Qy=[Re({name:"h3",versionRange:">=2.0.0-0",filePath:"dist/h3.mjs"})]});var Ei,Xl,bF,Xy=w(()=>{V();Ei={functionName:"createTask",kind:"Sync"},Xl=[{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.cjs"},functionQuery:Ei},{channelName:"createTask",module:{name:"node-cron",versionRange:">=4.6.0 <5",filePath:"dist/node-cron.js"},functionQuery:Ei},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.3.0 <4.6.0",filePath:"dist/node-cron.cjs"},functionQuery:Ei},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.6.0",filePath:"dist/node-cron.js"},functionQuery:Ei},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/cjs/node-cron.js"},functionQuery:Ei},{channelName:"v4_createTask",module:{name:"node-cron",versionRange:">=4.0.0 <4.3.0",filePath:"dist/esm/node-cron.js"},functionQuery:Ei},{channelName:"v3_createTask",module:{name:"node-cron",versionRange:">=3.0.0 <4",filePath:"src/node-cron.js"},functionQuery:Ei}],bF=M(Xl)});var Zy,Zl,wF,eb=w(()=>{V();Zy={channelName:"schedule",astQuery:"AssignmentExpression[left.object.property.name='prototype'][left.property.name='schedule'] > FunctionExpression",functionQuery:{methodName:"schedule",kind:"Sync"}},Zl=[{...Zy,module:{name:"node-schedule",versionRange:">=1.3.0 <2",filePath:"lib/schedule.js"}},{...Zy,module:{name:"node-schedule",versionRange:">=2.0.0 <3",filePath:"lib/Job.js"}}],wF=M(Zl)});var ec,EF,tb=w(()=>{V();ec=[...["resources/chat/completions/completions.js","resources/chat/completions/completions.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Completions",methodName:"create",kind:"Sync"}})),...["resources/responses/responses.js","resources/responses/responses.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Responses",methodName:"create",kind:"Sync"}})),...["resources/embeddings.js","resources/embeddings.mjs"].map(t=>({channelName:"embeddings",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Embeddings",methodName:"create",kind:"Sync"}})),...["resources/conversations/conversations.js","resources/conversations/conversations.mjs"].map(t=>({channelName:"chat",module:{name:"openai",versionRange:">=4.0.0 <8",filePath:t},functionQuery:{className:"Conversations",methodName:"create",kind:"Sync"}})),...["resources/decisions.js","resources/decisions.mjs"].map(t=>({channelName:"decide",module:{name:"openai",versionRange:">=7.30.0 <8",filePath:t},functionQuery:{className:"Decisions",methodName:"create",kind:"Sync"}}))],EF=M(ec)});var tc,AF,ib=w(()=>{V();tc=[{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/client.js"},functionQuery:{className:"Client",methodName:"connect",kind:"Auto"}},{channelName:"query",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"query",kind:"Auto"}},{channelName:"connect",module:{name:"pg",versionRange:">=8.0.3 <9",filePath:"lib/native/client.js"},functionQuery:{expressionName:"connect",kind:"Auto"}},{channelName:"connect",module:{name:"pg-pool",versionRange:">=2.0.0 <4",filePath:"index.js"},functionQuery:{className:"Pool",methodName:"connect",kind:"Auto"}}],AF=M(tc)});var kT,ic,NF,rb=w(()=>{V();Lt();kT=t=>[{channelName:"handle",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/query.js`},functionQuery:{className:"Query",methodName:"handle",kind:"Async"}},{channelName:"connection",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{functionName:"Connection",kind:"Sync"}},{channelName:"execute",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{functionName:"execute",kind:"Sync"}},{channelName:"connect",module:{name:"postgres",versionRange:">=3.0.0 <4",filePath:`${t}/connection.js`},functionQuery:{methodName:"connect",kind:"Sync"}}],ic=[Re({name:"postgres",versionRange:">=4.0.0",filePath:"src/query.js"}),...["src","cjs/src"].flatMap(kT)],NF=M(ic)});function nb(t,e){return{channelName:t,module:{name:ET,versionRange:IT,filePath:TT},functionQuery:{className:"CollectionBase",methodName:t,kind:e}}}var ET,TT,IT,AT,xT,rc,MF,sb=w(()=>{V();ET="@prisma/orm-family-sql",TT="dist/orm-client.mjs",IT=">=8.0.0-rc.15 <9",AT=["aggregate","first","create","createAndCount","upsert","update","updateAndCount","delete","deleteAndCount"],xT=["all","createAll","updateAll","deleteAll"];rc=[...AT.map(t=>nb(t,"Async")),...xT.map(t=>nb(t,"Sync"))],MF=M(rc)});var nc,qF,ab=w(()=>{V();Lt();nc=[Re({name:"@redis/client",versionRange:">=5.12.0",filePath:"dist/lib/client/index.js"}),{channelName:"command",module:{name:"redis",versionRange:">=2.6.0 <4",filePath:"index.js"},functionQuery:{expressionName:"internal_send_command",kind:"Sync"}},{channelName:"executor",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"commandsExecutor",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"command",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"sendCommand",kind:"Async"}},{channelName:"connect",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"connect",kind:"Async"}},{channelName:"multi",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executeMulti",kind:"Async"}},{channelName:"pipeline",module:{name:"@redis/client",versionRange:">=5.0.0 <5.12.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"_executePipeline",kind:"Async"}},{channelName:"batch",module:{name:"@redis/client",versionRange:"^1.0.0",filePath:"dist/lib/client/index.js"},functionQuery:{className:"RedisClient",methodName:"multiExecutor",kind:"Async"}}],qF=M(nc)});var OT,ob,lb=w(()=>{OT=t=>[{channelName:"requestHandler",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${t}/server.js`},astQuery:'FunctionExpression[id.name="requestHandler"]',functionQuery:{kind:"Async"}},{channelName:"matchServerRoutes",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <3",filePath:`${t}/routeMatching.js`},functionQuery:{functionName:"matchServerRoutes",kind:"Sync"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteLoader",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.9.0 <3",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteAction",kind:"Async"}},{channelName:"callRouteLoader",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteLoaderRR",kind:"Async"}},{channelName:"callRouteAction",module:{name:"@remix-run/server-runtime",versionRange:">=2.0.0 <2.9.0",filePath:`${t}/data.js`},functionQuery:{functionName:"callRouteActionRR",kind:"Async"}}],ob=["dist","dist/esm"].flatMap(OT)});var cb,pb=w(()=>{cb=[{channelName:"createRouter",module:{name:"@remix-run/fetch-router",versionRange:">=0.21.0 <2",filePath:"dist/lib/router.js"},functionQuery:{functionName:"createRouter",kind:"Sync"}},{channelName:"createAssetServer",module:{name:"@remix-run/assets",versionRange:">=0.6.0 <2",filePath:"dist/lib/asset-server.js"},functionQuery:{functionName:"createAssetServer",kind:"Sync"}},{channelName:"createRequestListener",module:{name:"@remix-run/node-fetch-server",versionRange:">=0.14.0 <2",filePath:"dist/lib/request-listener.js"},functionQuery:{functionName:"createRequestListener",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/ui",versionRange:">=0.8.0 <1",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}},{channelName:"run",module:{name:"@remix-run/component",versionRange:">=1.0.0 <2",filePath:"dist/runtime/run.js"},functionQuery:{functionName:"run",kind:"Sync"}}]});var RT,NT,PT,sc,GF,db=w(()=>{V();RT="tedious",NT="lib/connection.js",PT=">=1.11.0 <21",sc=["connect","execSql","execSqlBatch","callProcedure","execBulkLoad","prepare","execute"].map(t=>({channelName:t,module:{name:RT,versionRange:PT,filePath:NT},functionQuery:{className:"Connection",methodName:t,kind:"Sync"}})),GF=M(sc)});var ac,zF,ub=w(()=>{V();Rl();ac=[...tn({name:"together-ai",versionRange:">=0.6.0 <1"}),...tn({name:"together-ai",versionRange:">=1.0.0 <2"},{chat:"BaseCompletions",embeddings:"BaseEmbeddings"})],zF=M(ac)});var oc,QF,mb=w(()=>{V();oc=["dist/index.mjs","dist/index.cjs"].map(t=>({channelName:"system-one",module:{name:"@typesafe-ai/sdk",versionRange:">=0.5.0 <1",filePath:t},functionQuery:{className:"TypeSafeClient",methodName:"systemOne",kind:"Sync"}})),QF=M(oc)});function Yt(t,e,i,r){return["dist/index.js","dist/index.mjs"].map(n=>({channelName:e,module:{name:"ai",versionRange:t,filePath:n},functionQuery:{functionName:i,kind:r}}))}var lc,eH,gb=w(()=>{V();Lt();lc=[...["dist/index.js","dist/index.mjs"].map(t=>Re({name:"ai",versionRange:">=7.0.0",filePath:t})),...Yt(">=4.0.0 <7.0.0","generateText","generateText","Async"),...Yt(">=4.0.0 <7.0.0","streamText","streamText","Sync"),...Yt(">=4.0.0 <7.0.0","streamObject","streamObject","Sync"),...Yt(">=4.0.0 <7.0.0","generateObject","generateObject","Async"),...Yt(">=4.0.0 <7.0.0","embed","embed","Async"),...Yt(">=4.0.0 <7.0.0","embedMany","embedMany","Async"),...Yt(">=5.0.0 <7.0.0","resolveLanguageModel","resolveLanguageModel","Sync"),...Yt(">=6.0.0 <7.0.0","executeToolCall","executeToolCall","Async")];eH=M(lc)});function CT(t=[]){return[...Xo([...fb,...t].map(e=>e.module.name)),"@remix-run/node"]}var fb,rn,XH,hb=w(()=>{cy();py();dy();uy();gy();fy();hy();yy();by();_y();vy();wy();Sy();ky();Ey();Ay();xy();Ry();Py();Cy();Dy();Ly();ly();qy();jy();Fy();Hy();Wy();$y();Vy();zy();Yy();Jy();Xy();eb();tb();ib();rb();sb();ab();lb();pb();db();ub();mb();gb();vt();fb=[...Sl,...kl,...wl,...El,...my,...Tl,...Il,...Al,...xl,...Ol,...Nl,...Pl,...Cl,...Ml,...Dl,...Iy,...Ll,...ql,...jl,...Bl,...My,...Fl,...Gl,...$l,...Vl,...zl,...Kl,...Yl,...Jl,...Ky,...Qy,...Xl,...Zl,...ec,...tc,...vl,...Hl,...ic,...rc,...nc,...ob,...cb,...sc,...ac,...oc,...lc],rn=fb.filter(t=>!t.transform);XH=CT()});var yb=w(()=>{ay()});import{posix as MT,sep as DT}from"node:path";function bb(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function _b(t=process.argv[1]?nl(process.argv[1]):process.cwd(),e=DT==="\\"){let i=e?bb(t):t;return r=>{if(!r)return;let n=e?bb(r):r,{dir:s,base:a,ext:o}=MT.parse(n);(o===".js"||o===".mjs"||o===".cjs")&&(a=a.slice(0,o.length*-1));let l=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${l}`;if(s.startsWith(i)){let p=s.slice(i.length+1).replace(/\//g,".");return p?`${p}:${l}`:l}return l}}var vb=w(()=>{vt()});var cc,wb=w(()=>{vb();vt();ol();cc=eo(al(_b()))});import{AsyncLocalStorage as LT}from"node:async_hooks";function Eb(t){return t.getValue(fc)}function qT(t,e){return t.setValue(fc,e)}function jT(t,e){t.refs[kb]=Gi(e)}function hc(t){return bi(t.refs[kb])}function BT(t,e){let i=t?zt.setSpan(Oe.active(),t):zt.deleteSpan(Oe.active());return Oe.with(i,()=>{let r=Rt();return cs(r,t??void 0),e(r)})}function FT(t){let e=t?HT(t):zt.getActiveSpan();return e&&Si(e.spanContext())?e:void 0}function HT(t){let e=hc(t);return e?zt.getSpan(e):void 0}function GT(t){let e=Eb(t),i=e?.scope||Rt(),r=e?.isolationScope||hi(),n=t.getValue(uc)===!0,s=t.getValue(mc),a=t.getValue(gc),o=s||i.clone(),l=qT(t,{scope:o,isolationScope:a||(n?r.clone():r)}).deleteValue(uc).deleteValue(mc).deleteValue(gc);return(!s||!hc(s))&&jT(o,l),l}function VT(t){if(typeof t!="object"||!t)return!1;let e=t;return typeof e.on=="function"&&typeof e.emit=="function"}function pc(t,e){let i=t[e];return typeof i=="function"?i:void 0}function dc(t,e,i){try{t[e]=i}catch{}}function Tb(){let t=ct(ye()).getTracingChannelBinding?.()?.asyncLocalStorage??new LT;function e(){let p=Eb(Oe.active());return p||{scope:gi(),isolationScope:fi()}}function i(p){let u=Oe.active();return Oe.with(u,()=>p(a()))}function r(p,u){let m=hc(p)||Oe.active();return Oe.with(m.setValue(mc,p),()=>u(p))}function n(p){let u=Oe.active();return Oe.with(u.setValue(uc,!0),()=>{let m=a();return Fr(m.getPropagationContext())||m.setPropagationContext({traceId:mi(),sampleRand:Qe()}),p(o())})}function s(p,u){let m=Oe.active();return Oe.with(m.setValue(gc,p),()=>u(o()))}function a(){return e().scope}function o(){return e().isolationScope}function l(){return{asyncLocalStorage:t}}Lr({withScope:i,withSetScope:r,withSetIsolationScope:s,withIsolationScope:n,getCurrentScope:a,getIsolationScope:o,getActiveSpan:FT,withActiveSpan:BT,getTracingChannelBinding:l});let c=new $T(t);return Oe.setGlobalContextManager(c),c.getAsyncLocalStorageLookup()}function zT(t){let{traceFlags:e,traceState:i}=t,r=i?i.get(UT)==="1":!1;if(e===dl.SAMPLED)return!0;if(r)return!1;let n=i?i.get(Sb):void 0,s=n?jr(n):void 0;if(s?.sampled==="true")return!0;if(s?.sampled==="false")return!1}function Ib(t){t.on("prepareSpanScope",e=>{let{scope:i,parentSpan:r}=e;if(!r?.spanContext().isRemote)return;let{spanId:n,traceId:s,traceState:a}=r.spanContext(),o=Pt(r),l=typeof o.sample_rand=="string"?Number(o.sample_rand):void 0,c=!!a?.get(Sb),p=i.clone();p.setPropagationContext({traceId:s,parentSpanId:n,sampled:zT(r.spanContext()),dsc:c?o:void 0,sampleRand:typeof l=="number"&&!Number.isNaN(l)?l:Qe()}),cs(p,void 0),e.scope=p,e.parentSpan=void 0})}var Sb,UT,fc,uc,mc,gc,kb,E3,WT,$T,Ab=w(()=>{vt();Us();Us();Sb="sentry.dsc",UT="sentry.sampled_not_recording",fc=Dt("sentry_scopes"),uc=Dt("sentry_fork_isolation_scope"),mc=Dt("sentry_fork_set_scope"),gc=Dt("sentry_fork_set_isolation_scope"),kb="context";E3=Dt("OpenTelemetry SDK Context Key SUPPRESS_TRACING");WT=["addListener","on","once","prependListener","prependOnceListener"],$T=class{constructor(t){this._kOtListeners=Symbol("OtListeners"),this._wrapped=!1,this._asyncLocalStorage=t}active(){return this._asyncLocalStorage.getStore()??Zr}with(t,e,i,...r){let n=GT(t),s=i==null?e:e.bind(i);return this._asyncLocalStorage.run(n,s,...r)}enable(){return this}disable(){try{this._asyncLocalStorage.disable()}catch{}return this}bind(t,e){return VT(e)?this._bindEventEmitter(t,e):typeof e=="function"?this._bindFunction(t,e):e}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:fc}}_bindFunction(t,e){let i=this.with.bind(this),r=function(...n){return i(t,()=>e.apply(this,n))};return Object.defineProperty(r,"length",{enumerable:!1,configurable:!0,writable:!1,value:e.length}),r}_bindEventEmitter(t,e){if(this._getPatchMap(e)!==void 0||this._createPatchMap(e)===void 0)return e;for(let r of WT){let n=pc(e,r);n&&dc(e,r,this._patchAddListener(e,n,t))}for(let r of["removeListener","off"]){let n=pc(e,r);n&&dc(e,r,this._patchRemoveListener(e,n))}let i=pc(e,"removeAllListeners");return i&&dc(e,"removeAllListeners",this._patchRemoveAllListeners(e,i)),e}_patchRemoveListener(t,e){let i=this;return function(r,n){let s=i._getPatchMap(t)?.[r];if(s===void 0)return e.call(this,r,n);let a=s.get(n);return e.call(this,r,a||n)}}_patchRemoveAllListeners(t,e){let i=this;return function(r){let n=i._getPatchMap(t);return n!==void 0&&(arguments.length===0?i._createPatchMap(t):r!==void 0&&n[r]!==void 0&&delete n[r]),e.apply(this,arguments)}}_patchAddListener(t,e,i){let r=this;return function(n,s){if(r._wrapped)return e.call(this,n,s);let a=r._getPatchMap(t)??r._createPatchMap(t);if(a===void 0)return e.call(this,n,s);let o=a[n];o===void 0&&(o=new WeakMap,a[n]=o);let l=r.bind(i,s);o.set(s,l),r._wrapped=!0;try{return e.call(this,n,l)}finally{r._wrapped=!1}}}_createPatchMap(t){let e=Object.create(null);try{t[this._kOtListeners]=e}catch{return}return this._getPatchMap(t)===e?e:void 0}_getPatchMap(t){return t[this._kOtListeners]}}});var KT,nn,YT,QT,JT,yc,Le,ce,xb,Ob,ir,Rb,ue=w(()=>{KT=Object.create,nn=Object.defineProperty,YT=Object.getOwnPropertyDescriptor,QT=Object.getOwnPropertyNames,JT=Object.getPrototypeOf,yc=Object.prototype.hasOwnProperty,Le=(t,e,i)=>()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(r){throw i=[r],r}},ce=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e,e.exports),t=null),e.exports),xb=(t,e)=>{let i=Object.setPrototypeOf({},null);for(var r in t)nn(i,r,{get:t[r],enumerable:!0});return e&1||nn(i,Symbol.toStringTag,{value:"Module"}),e&2?i:Object.preventExtensions(i)},Ob=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(var n=QT(e),s=0,a=n.length,o;s<a;s++)o=n[s],!yc.call(t,o)&&o!==i&&nn(t,o,{get:(l=>e[l]).bind(null,o),enumerable:!(r=YT(e,o))||r.enumerable});return t},ir=(t,e,i)=>(i=t!=null?KT(JT(t)):{},Ob(e||!t||!t.__esModule||!yc.call(t,"default")?nn(i,"default",{value:t,enumerable:!0}):i,t)),Rb=t=>yc.call(t,"module.exports")?t["module.exports"]:Ob(nn({},"__esModule",{value:!0}),t)});function Hs(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}var XT,bc=w(()=>{ue();XT=Le((()=>{}));XT()});function Je(t,e,i){Hs(t,e),e.set(t,i)}var sn,_c=w(()=>{ue();bc();sn=Le((()=>{}));sn()});function mt(t,e,i){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:i;throw new TypeError("Private element is not present on this object")}var ZT,Gs=w(()=>{ue();ZT=Le((()=>{}));ZT()});function gt(t,e,i){return t.set(mt(t,e),i),i}var an,vc=w(()=>{ue();Gs();an=Le((()=>{}));an()});function ge(t,e){return t.get(mt(t,e))}var on,wc=w(()=>{ue();Gs();on=Le((()=>{}));on()});var Sc,W3,Nb=w(()=>{ue();Sc=ce(((t,e)=>{e.exports=i;function i(m,g){let[h]=p(m,"");for(let f of s(g))if(r(f,h))return!0;return!1}function r(m,g){for(let[h,f]of m)if(!u(g,f,h))return!1;return!0}function n(m){return m==="latest"&&(m=">=0"),m.match(/^([^\d+]*)(\d.*)$/)||[null,"","*.*.*"]}function s(m){let g=[],h=[],f=m.trim().split(/\s+/);for(let v=0;v<f.length;v++){let S=f[v];if(S==="-")continue;if(S==="||"){g.push(h),h=[];continue}if(/^[<>=~v^]+$/.test(S)&&v+1<f.length){f[v+1]=S+f[v+1];continue}let E=n(S),O=E[1]||"=";O.endsWith("v")&&(O=O.slice(0,-1));let[L,C]=p(E[2],O);if(v+2<f.length&&f[v+1]==="-"){let P=n(f[v+2]);f[v+2]="<="+(P[2].indexOf("-")===-1?P[2]+".*.*":P[2]),C=">="}if(C[0]==="~"){let P=E[2].split("-")[0].split(".").length;h.push([">=",L]),h.push(["<",P===1?a(L,0):a(L,1)])}else if(C[0]==="^"){let P=L[0]!==0?0:L[1]!==0?1:2;h.push([">=",L]),h.push(["<",P===0?a(L,0):P===1?a(L,1):a(L,2)])}else h.push([C.replace("~","").replace("^",""),L])}return h.length&&g.push(h),g}function a(m,g){let h=m.slice(0);if(m[g]===-1)return h;for(h[g++]++;g<3;g++)h[g]=0;return h}function o(m){return m==="x"||m==="X"||m==="*"||m==="latest"?-1:Number(m)}function l(m){return/^\d+$/.test(m)?Number(m):m}function c(m,g,h){return h===-1?m!=="<":m==="="?g===h:m===">"?g>h:m===">="?g>=h:m==="<"?g<h:m==="<="?g<=h:!1}function p(m,g){m=m.split("+")[0];let[h,f]=m.split("-"),v=h.split(".").map(o).slice(0,3),S=Math.max(v.length-1,0);return g===">"?(g=">=",v.push(0,0,0),v[S]++):g===""?v.push(0,0,0):v.push(-1,-1,-1),f?[v.slice(0,3).concat(f.split(".").map(l)),g]:[v.slice(0,3),g]}function u(m,g,h){if(!c("=",m[0],g[0]))return c(h,m[0],g[0]);if(!c("=",m[1],g[1]))return c(h,m[1],g[1]);if(!c("=",m[2],g[2])||m.length===3&&g.length===3)return c(h,m[2],g[2]);if(h[0]==="<"&&(g.length===3||m.length===3))return!1;if(h[0]===">"){if(m.length===3)return!0;if(g.length===3)return!1}for(let f=3;f<Math.max(m.length,g.length);f++)if(c(h,m[f]||"",g[f]||""))return!0;return!1}})),W3=Sc()});function Pb(t,e){Hs(t,e),e.add(t)}var kc,Cb=w(()=>{ue();bc();kc=Le((()=>{}));kc()});var Ws,Ec=w(()=>{Ws={}});var $s,Tc=w(()=>{$s={}});var Mb,Db=w(()=>{Mb={}});var Ic,t5,Lb=w(()=>{ue();Ec();Tc();Ic=ce(((t,e)=>{let i=Ws.v??{},{parse:r}=$s.v??{},n=I=>I.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",s=/[^\w]/g,a=I=>`tr_ch_apm$${I.replace(s,"_")}`;e.exports={tracingChannelImport({dcModule:I,moduleType:A},D){if(D.body.some(n))return;let k={module:A==="esm"},b=D.body.findIndex(F=>F.directive==="use strict"),q=A==="esm"?`import tr_ch_apm_dc from "${I}"`:`const tr_ch_apm_dc = require("${I}")`;D.body.splice(b+1,0,r(q,k).body[0],r("const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc",k).body[0],r(`const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
6
+ || ch.end.hasSubscribers
7
+ || ch.asyncStart.hasSubscribers
8
+ || ch.asyncEnd.hasSubscribers
9
+ || ch.error.hasSubscribers`,k).body[0])},tracingChannelDeclaration(I,A){let{channelName:D,module:{name:k}}=I,b=a(D);if(A.body.some(W=>W.declarations?.[0]?.id?.name===b))return;I.transforms.tracingChannelImport(I,A);let q=A.body.findIndex(n),F=`
10
+ const ${b} = tr_ch_apm_tracingChannel("orchestrion:${k}:${D}")
11
+ `;A.body.splice(q+1,0,r(F).body[0])},traceCallback:l,tracePromise:l,traceSync:l,traceAuto:l};function o(I){return[...(I||[]).filter(A=>A.type!=="RestElement"&&A.type!=="AssignmentPattern").map((A,D)=>({type:"Identifier",name:`__apm$arg${D}`})),{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}]}function l(I,A,D,k){let b=k[k.length-1];A.type==="ClassDeclaration"||A.type==="ClassExpression"?h(I,A,b):g(I,A,b)}function c(I,A){if(I.type!=="ReturnStatement")return!1;let D=I.argument?.type==="CallExpression"?I.argument.callee:null;return D?.type==="MemberExpression"&&D.property?.name==="runStores"&&D.object?.type==="MemberExpression"&&D.object.property?.name==="start"&&D.object.object?.type==="Identifier"&&D.object.object.name===A}function p(I){let A=(b,q)=>b?.find(F=>F.type==="VariableDeclaration"&&F.declarations.some(W=>W.id?.name===q))?.declarations.find(F=>F.id?.name===q)?.init??null,D=A(A(I,"__apm$traced")?.body?.body,"__apm$wrapped"),k=D?.type;return k==="FunctionExpression"||k==="ArrowFunctionExpression"||k==="FunctionDeclaration"?D:null}function u(I,A){let D=new Set,k=I;for(;k&&!D.has(k);){D.add(k);let b=k.body?.body;if(!Array.isArray(b))return!1;if(b.some(q=>c(q,A)))return!0;k=p(b)}return!1}function m(I,A){let D=I?.value?.body?.body;return Array.isArray(D)?D.some(k=>k.type==="VariableDeclaration"&&k.declarations.some(b=>b.id?.name===A)):!1}function g(I,A,D){if(u(A,a(I.channelName)))return;I.transforms.tracingChannelDeclaration(I,D);let{functionQuery:{methodName:k,privateMethodName:b,functionName:q,expressionName:F,propertyName:W}}=I,$=k==="constructor"||!k&&!b&&!q&&!F&&!W,x=$?"ArrowFunctionExpression":A.type,he=A.params,Y=`${a(I.channelName)}$self`;I.selfBinding=$&&S(A,Y)?Y:null,A.body=f(I,{type:x,params:he,body:A.body,async:A.async,expression:!1,generator:A.generator},D),A.params=o(he),A.generator=!1,A.async=!1,x!=="ArrowFunctionExpression"&&E(I,A)}function h(I,A,D){let{functionQuery:k,operator:b,channelName:q}=I,{methodName:F}=k;if(!F)return;let W=A.body;if(W.body.some(({key:ae})=>ae?.name===F))return;let $=W.body.find(({kind:ae})=>ae==="constructor"),x=`${a(q)}$${F}`;if($&&m($,x))return;I.transforms.tracingChannelDeclaration(I,D),$||($=r(A.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],W.body.unshift($));let he=r(`
12
+ const ${x} = this["${F}"]
13
+ this["${F}"] = function () {}
14
+ if (typeof ${x} === 'function') {
15
+ Object.defineProperty(this["${F}"], 'length', {
16
+ value: ${x}.length,
14
17
  configurable: true
15
18
  })
16
19
  }
17
- `).body,d=p[1].expression.right;d.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],d.async=n==="tracePromise",i.selfBinding=null,d.body=Ov(i,{type:"Identifier",name:c},t),Rv(i,d),a.value.body.body.push(...p)}function Ov(i,e,t){let{operator:r,moduleVersion:n,selfBinding:s}=i,{returnKind:o}=i.functionQuery,l=o?zA(i,o,t):"",a;r==="traceCallback"&&(a=Nv(i,e,l)),r==="tracePromise"&&(a=Cv(i,e,l)),r==="traceSync"&&(a=HA(i,e,l)),r==="traceAuto"&&(a=GA(i,e,l));let c=(e.params||[]).filter(b=>b.type!=="RestElement"&&b.type!=="AssignmentPattern").map((b,v)=>`__apm$arg${v}`).concat("...__apm$args").join(", "),p=a.body[0].body,d=s?`let ${s};`:"",g=Qe(d+(e.type==="ArrowFunctionExpression"?`
18
- const __apm$arguments = [${c}];
20
+ `).body,Y=he[1].expression.right;Y.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],Y.async=b==="tracePromise",I.selfBinding=null,Y.body=f(I,{type:"Identifier",name:x},D),E(I,Y),$.value.body.body.push(...he)}function f(I,A,D){let{operator:k,moduleVersion:b,selfBinding:q}=I,{returnKind:F}=I.functionQuery,W=F?N(I,F,D):"",$;k==="traceCallback"&&($=L(I,A,W)),k==="tracePromise"&&($=C(I,A,W)),k==="traceSync"&&($=P(I,A,W)),k==="traceAuto"&&($=O(I,A,W));let x=(A.params||[]).filter(Pe=>Pe.type!=="RestElement"&&Pe.type!=="AssignmentPattern").map((Pe,oi)=>`__apm$arg${oi}`).concat("...__apm$args").join(", "),he=$.body[0].body,Y=q?`let ${q};`:"",ae=r(Y+(A.type==="ArrowFunctionExpression"?`
21
+ const __apm$arguments = [${x}];
19
22
  const __apm$ctx = {
20
23
  arguments: __apm$arguments,
21
- moduleVersion: ${JSON.stringify(n)}
24
+ moduleVersion: ${JSON.stringify(b)}
22
25
  };
23
26
  const __apm$traced = () => {
24
27
  const __apm$wrapped = () => {};
25
28
  return __apm$wrapped(...__apm$arguments);
26
29
  };
27
30
  `:`
28
- const __apm$arguments = [${c}].slice(0, arguments.length);
31
+ const __apm$arguments = [${x}].slice(0, arguments.length);
29
32
  const __apm$ctx = {
30
33
  arguments: __apm$arguments,
31
34
  self: this,
32
- moduleVersion: ${JSON.stringify(n)}
35
+ moduleVersion: ${JSON.stringify(b)}
33
36
  };
34
37
  const __apm$traced = () => {
35
38
  const __apm$wrapped = () => {};
36
39
  return __apm$wrapped.apply(this, __apm$arguments);
37
40
  };
38
- `)).body;return p.body.unshift(...g),Rp.query(p,"[id.name=__apm$wrapped]")[0].init=e,p}function FA(i,e){let t=!1,r=(n,s)=>{let o=n[s];if(!(o===null||typeof o!="object")){if(Array.isArray(o)){for(let l=0;l<o.length;l++)r(o,l);return}if(typeof o.type=="string"&&!(o.type==="ClassBody"||o.type==="FunctionExpression"||o.type==="FunctionDeclaration")){if(o.type==="CallExpression"&&o.callee.type==="Super"){let l=Qe(`(0, ${e} = this)`).body[0].expression;l.expressions[0]=o,n[s]=l,t=!0;return}for(let l of Object.keys(o))r(o,l)}}};return r(i,"body"),t}function Rv(i,e){let t=new Set;Rp.traverse(e.body,Rp.parse("[object.type=Super]"),(r,n)=>{let{name:s}=r.property,o;if(n.callee){let{expression:l}=Qe(`__apm$super['${s}'].call(this)`).body[0];n.callee=o=l.callee,n.arguments.unshift(...l.arguments)}else n.expression=o=Qe(`__apm$super['${s}']`).body[0];o.computed=n.callee.computed,o.optional=n.callee.optional,t.add(s)});for(let r of t){let n=Qe(`
41
+ `)).body;return he.body.unshift(...ae),i.query(he,"[id.name=__apm$wrapped]")[0].init=A,he}let v=({selfBinding:I})=>I||"this";function S(I,A){let D=!1,k=(b,q)=>{let F=b[q];if(!(F===null||typeof F!="object")){if(Array.isArray(F)){for(let W=0;W<F.length;W++)k(F,W);return}if(typeof F.type=="string"&&!(F.type==="ClassBody"||F.type==="FunctionExpression"||F.type==="FunctionDeclaration")){if(F.type==="CallExpression"&&F.callee.type==="Super"){let W=r(`(0, ${A} = this)`).body[0].expression;W.expressions[0]=F,b[q]=W,D=!0;return}for(let W of Object.keys(F))k(F,W)}}};return k(I,"body"),D}function E(I,A){let D=new Set;i.traverse(A.body,i.parse("[object.type=Super]"),(k,b)=>{let{name:q}=k.property,F;if(b.callee){let{expression:W}=r(`__apm$super['${q}'].call(this)`).body[0];b.callee=F=W.callee,b.arguments.unshift(...W.arguments)}else b.expression=F=r(`__apm$super['${q}']`).body[0];F.computed=b.callee.computed,F.optional=b.callee.optional,D.add(q)});for(let k of D){let b=r(`
39
42
  class Wrapper {
40
43
  wrapper () {
41
- __apm$super['${r}'] = super['${r}']
44
+ __apm$super['${k}'] = super['${k}']
42
45
  }
43
46
  }
44
- `).body[0].body.body[0].value.body.body[0];e.body.body.unshift(n)}t.size>0&&e.body.body.unshift(Qe("const __apm$super = {}").body[0])}function GA(i,e,t=""){let r=Nv(i,e,t),n=Cv(i,e,t),[s,o,l,a,c,p]=r.body[0].body.body,d={type:"IfStatement",test:a.test,consequent:{type:"BlockStatement",body:n.body[0].body.body},alternate:null};return r.body[0].body.body=[s,d,o,l,c,p],r}function Nv(i,e,t=""){let{channelName:r,functionQuery:{callbackIndex:n=-1}}=i,s=Vt(r);return Qe(`
47
+ `).body[0].body.body[0].value.body.body[0];A.body.body.unshift(b)}D.size>0&&A.body.body.unshift(r("const __apm$super = {}").body[0])}function O(I,A,D=""){let k=L(I,A,D),b=C(I,A,D),[q,F,W,$,x,he]=k.body[0].body.body,Y={type:"IfStatement",test:$.test,consequent:{type:"BlockStatement",body:b.body[0].body.body},alternate:null};return k.body[0].body.body=[q,Y,F,W,x,he],k}function L(I,A,D=""){let{channelName:k,functionQuery:{callbackIndex:b=-1}}=I,q=a(k);return r(`
45
48
  function wrapper () {
46
- const __apm$cb = Array.prototype.at.call(__apm$arguments, ${n});
49
+ const __apm$cb = Array.prototype.at.call(__apm$arguments, ${b});
47
50
 
48
- if (!${s}.start.hasSubscribers) return __apm$traced();
51
+ if (!${q}.start.hasSubscribers) return __apm$traced();
49
52
 
50
53
  function __apm$wrappedCb(err, res) {
51
54
  if (err) {
52
55
  __apm$ctx.error = err;
53
- ${s}.error.publish(__apm$ctx);
56
+ ${q}.error.publish(__apm$ctx);
54
57
  } else {
55
58
  __apm$ctx.result = res;
56
- ${t}
59
+ ${D}
57
60
  }
58
61
 
59
- ${s}.asyncStart.runStores(__apm$ctx, () => {
62
+ ${q}.asyncStart.runStores(__apm$ctx, () => {
60
63
  try {
61
64
  if (__apm$cb) {
62
65
  return __apm$cb.apply(this, arguments);
63
66
  }
64
67
  } finally {
65
- ${s}.asyncEnd.publish(__apm$ctx);
68
+ ${q}.asyncEnd.publish(__apm$ctx);
66
69
  }
67
70
  });
68
71
  }
@@ -70,31 +73,31 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
70
73
  if (typeof __apm$cb !== 'function') {
71
74
  return __apm$traced();
72
75
  }
73
- Array.prototype.splice.call(__apm$arguments, ${n}, 1, __apm$wrappedCb);
76
+ Array.prototype.splice.call(__apm$arguments, ${b}, 1, __apm$wrappedCb);
74
77
 
75
- return ${s}.start.runStores(__apm$ctx, () => {
78
+ return ${q}.start.runStores(__apm$ctx, () => {
76
79
  try {
77
80
  return __apm$traced();
78
81
  } catch (err) {
79
82
  __apm$ctx.error = err;
80
- ${s}.error.publish(__apm$ctx);
83
+ ${q}.error.publish(__apm$ctx);
81
84
  throw err;
82
85
  } finally {
83
- __apm$ctx.self ??= ${Np(i)};
84
- ${s}.end.publish(__apm$ctx);
86
+ __apm$ctx.self ??= ${v(I)};
87
+ ${q}.end.publish(__apm$ctx);
85
88
  }
86
89
  });
87
90
  }
88
- `)}function Cv(i,e,t=""){let{channelName:r}=i,n=Vt(r);return Qe(`
91
+ `)}function C(I,A,D=""){let{channelName:k}=I,b=a(k);return r(`
89
92
  function wrapper () {
90
- if (!tr_ch_apm_hasSubscribers(${n})) return __apm$traced();
93
+ if (!tr_ch_apm_hasSubscribers(${b})) return __apm$traced();
91
94
 
92
- return ${n}.start.runStores(__apm$ctx, () => {
95
+ return ${b}.start.runStores(__apm$ctx, () => {
93
96
  try {
94
97
  let promise = __apm$traced();
95
98
  if (typeof promise?.then !== 'function') {
96
99
  __apm$ctx.result = promise;
97
- ${t}
100
+ ${D}
98
101
  return __apm$ctx.result;
99
102
  }
100
103
  // Mirror Node.js core diagnostics_channel behaviour: for native Promise
@@ -107,16 +110,16 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
107
110
  return promise.then(
108
111
  result => {
109
112
  __apm$ctx.result = result;
110
- ${t}
111
- ${n}.asyncStart.publish(__apm$ctx);
112
- ${n}.asyncEnd.publish(__apm$ctx);
113
+ ${D}
114
+ ${b}.asyncStart.publish(__apm$ctx);
115
+ ${b}.asyncEnd.publish(__apm$ctx);
113
116
  return __apm$ctx.result;
114
117
  },
115
118
  err => {
116
119
  __apm$ctx.error = err;
117
- ${n}.error.publish(__apm$ctx);
118
- ${n}.asyncStart.publish(__apm$ctx);
119
- ${n}.asyncEnd.publish(__apm$ctx);
120
+ ${b}.error.publish(__apm$ctx);
121
+ ${b}.asyncStart.publish(__apm$ctx);
122
+ ${b}.asyncEnd.publish(__apm$ctx);
120
123
  throw err;
121
124
  }
122
125
  );
@@ -124,48 +127,48 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
124
127
  promise.then(
125
128
  result => {
126
129
  __apm$ctx.result = result;
127
- ${t}
128
- ${n}.asyncStart.publish(__apm$ctx);
129
- ${n}.asyncEnd.publish(__apm$ctx);
130
+ ${D}
131
+ ${b}.asyncStart.publish(__apm$ctx);
132
+ ${b}.asyncEnd.publish(__apm$ctx);
130
133
  },
131
134
  err => {
132
135
  __apm$ctx.error = err;
133
- ${n}.error.publish(__apm$ctx);
134
- ${n}.asyncStart.publish(__apm$ctx);
135
- ${n}.asyncEnd.publish(__apm$ctx);
136
+ ${b}.error.publish(__apm$ctx);
137
+ ${b}.asyncStart.publish(__apm$ctx);
138
+ ${b}.asyncEnd.publish(__apm$ctx);
136
139
  }
137
140
  );
138
141
  return promise;
139
142
  } catch (err) {
140
143
  __apm$ctx.error = err;
141
- ${n}.error.publish(__apm$ctx);
144
+ ${b}.error.publish(__apm$ctx);
142
145
  throw err;
143
146
  } finally {
144
- __apm$ctx.self ??= ${Np(i)};
145
- ${n}.end.publish(__apm$ctx);
147
+ __apm$ctx.self ??= ${v(I)};
148
+ ${b}.end.publish(__apm$ctx);
146
149
  }
147
150
  });
148
151
  }
149
- `)}function HA(i,e,t=""){let{channelName:r}=i,n=Vt(r);return Qe(`
152
+ `)}function P(I,A,D=""){let{channelName:k}=I,b=a(k);return r(`
150
153
  function wrapper () {
151
- if (!tr_ch_apm_hasSubscribers(${n})) return __apm$traced();
154
+ if (!tr_ch_apm_hasSubscribers(${b})) return __apm$traced();
152
155
 
153
- return ${n}.start.runStores(__apm$ctx, () => {
156
+ return ${b}.start.runStores(__apm$ctx, () => {
154
157
  try {
155
158
  __apm$ctx.result = __apm$traced();
156
- ${t}
159
+ ${D}
157
160
  } catch (err) {
158
161
  __apm$ctx.error = err;
159
- ${n}.error.publish(__apm$ctx);
162
+ ${b}.error.publish(__apm$ctx);
160
163
  throw err;
161
164
  } finally {
162
- __apm$ctx.self ??= ${Np(i)};
163
- ${n}.end.publish(__apm$ctx);
165
+ __apm$ctx.self ??= ${v(I)};
166
+ ${b}.end.publish(__apm$ctx);
164
167
  }
165
168
  return __apm$ctx.result;
166
169
  });
167
170
  }
168
- `)}function WA(i,e){let{channelName:t,module:{name:r}}=i,n=Vt(t+":next");if(e.body.some(a=>a.declarations?.[0]?.id?.name===n))return;let s=Vt(t),o=e.body.findIndex(a=>a.declarations?.[0]?.id?.name===s),l=`const ${n} = tr_ch_apm_tracingChannel("orchestrion:${r}:${t}:next")`;e.body.splice(o+1,0,Qe(l).body[0])}function zA(i,e,t){let{channelName:r}=i,n=e==="Iterator"?"traceSync":"tracePromise",s=Vt(r+":next");return WA(i,t),`
171
+ `)}function G(I,A){let{channelName:D,module:{name:k}}=I,b=a(D+":next");if(A.body.some($=>$.declarations?.[0]?.id?.name===b))return;let q=a(D),F=A.body.findIndex($=>$.declarations?.[0]?.id?.name===q),W=`const ${b} = tr_ch_apm_tracingChannel("orchestrion:${k}:${D}:next")`;A.body.splice(F+1,0,r(W).body[0])}function N(I,A,D){let{channelName:k}=I,b=A==="Iterator"?"traceSync":"tracePromise",q=a(k+":next");return G(I,D),`
169
172
  const __apm$iter = __apm$ctx.result;
170
173
  if (__apm$iter != null && typeof __apm$iter.next === 'function') {
171
174
  const __apm$patchIter = function (method) {
@@ -173,76 +176,70 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
173
176
  if (typeof __apm$orig !== 'function') return;
174
177
  __apm$iter[method] = function () {
175
178
  const __apm$iterArgs = Array.prototype.slice.call(arguments);
176
- if (!tr_ch_apm_hasSubscribers(${s})) return __apm$orig.apply(this, __apm$iterArgs);
179
+ if (!tr_ch_apm_hasSubscribers(${q})) return __apm$orig.apply(this, __apm$iterArgs);
177
180
  __apm$ctx.method = method;
178
181
  __apm$ctx.arguments = __apm$iterArgs;
179
- return ${s}.${n}(__apm$orig, __apm$ctx, this, ...__apm$iterArgs);
182
+ return ${q}.${b}(__apm$orig, __apm$ctx, this, ...__apm$iterArgs);
180
183
  };
181
184
  };
182
185
  __apm$patchIter('next');
183
186
  __apm$patchIter('throw');
184
187
  __apm$patchIter('return');
185
188
  }
186
- `}var Rp,Qe,xv,PA,Vt,Av,Np,Pv=w(()=>{Ap();Op();Rp=zt,{parse:Qe}=Pa,xv=i=>i.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",PA=/[^\w]/g,Vt=i=>`tr_ch_apm$${i.replace(PA,"_")}`,Av={tracingChannelImport({dcModule:i,moduleType:e},t){if(t.body.some(xv))return;let r={module:e==="esm"},n=t.body.findIndex(a=>a.directive==="use strict"),s=e==="esm"?`import tr_ch_apm_dc from "${i}"`:`const tr_ch_apm_dc = require("${i}")`;t.body.splice(n+1,0,Qe(s,r).body[0],Qe("const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc",r).body[0],Qe(`const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
187
- || ch.end.hasSubscribers
188
- || ch.asyncStart.hasSubscribers
189
- || ch.asyncEnd.hasSubscribers
190
- || ch.error.hasSubscribers`,r).body[0])},tracingChannelDeclaration(i,e){let{channelName:t,module:{name:r}}=i,n=Vt(t);if(e.body.some(l=>l.declarations?.[0]?.id?.name===n))return;i.transforms.tracingChannelImport(i,e);let s=e.body.findIndex(xv),o=`
191
- const ${n} = tr_ch_apm_tracingChannel("orchestrion:${r}:${t}")
192
- `;e.body.splice(s+1,0,Qe(o).body[0])},traceCallback:Da,tracePromise:Da,traceSync:Da,traceAuto:Da};Np=({selfBinding:i})=>i||"this"});var Cp,Dv=w(()=>{Cp={}});var Uv,qp,$t,sr,jr,Br,Vn,Ma,$n,Fr,La,qa,Ai,jv,Bv,Fv,Mp,Gv,Mv,Lv,VA,qv,Pp,Dp,Lp,Hv,Wv=w(()=>{Ap();Pv();Iv();Op();Dv();Uv=i=>{throw TypeError(i)},qp=(i,e,t)=>e.has(i)||Uv("Cannot "+t),$t=(i,e,t)=>(qp(i,e,"read from private field"),t?t.call(i):e.get(i)),sr=(i,e,t)=>e.has(i)?Uv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),jr=(i,e,t,r)=>(qp(i,e,"write to private field"),e.set(i,t),t),Br=(i,e,t)=>(qp(i,e,"access private method"),t),Mv=zt,{parse:Lv}=Pa,{generate:VA}=Tv,qv=Av,Lp=class{constructor(e,t,r,n,s,o={}){sr(this,Ai),sr(this,Vn,null),sr(this,Ma,null),sr(this,$n,null),sr(this,Fr,[]),sr(this,La,null),sr(this,qa,{}),jr(this,Vn,e),jr(this,Ma,t),jr(this,$n,r),jr(this,Fr,n),jr(this,La,s),jr(this,qa,o)}free(){}get moduleName(){return $t(this,Vn)}get filePath(){return $t(this,$n)}transform(e,t,r,n){let s=n?.sourceFile||`${$t(this,Vn)}/${$t(this,$n)}`;if(Buffer.isBuffer(e)&&(e=e.toString()),!e)return{code:e};let o,l={},a=0,c={...qv,...$t(this,qa),defaults:{...qv}};for(let p of $t(this,Fr)){let{astQuery:d,functionQuery:g={}}=p;if(!o){let S={loc:!0,ranges:!0,raw:!0,module:t==="esm"};try{o=Lv(e,S)}catch{o=Lv(e,{...S,module:!S.module})}t==="esm"&&(l=Br(this,Ai,Fv).call(this,o))}let b=Br(this,Ai,Mp).call(this,g,l),v=d||Br(this,Ai,Gv).call(this,b),y={...p,dcModule:$t(this,La),moduleType:t,moduleVersion:$t(this,Ma),functionQuery:b,transforms:c};y.operator=Br(this,Ai,Bv).call(this,y),Mv.traverse(o,Mv.parse(v),(...S)=>{a++,Br(this,Ai,jv).call(this,y,...S)})}if(a===0&&$t(this,Fr).length>0){let p=$t(this,Fr).map(({astQuery:d,functionQuery:g={}})=>{if(d)return d;let b=Br(this,Ai,Mp).call(this,g,l),y=(I=>I.methodName||I.privateMethodName||I.functionName||I.expressionName||"constructor")(g),S=g.className||g.functionName||g.expressionName,T=b.className||b.functionName||b.expressionName;return S&&S!==T?`${S} (local name: ${T})`:y});throw new Error(`Failed to find injection points for: ${JSON.stringify(p)}`)}if(o){Pp??(Pp=Cp.SourceMapConsumer),Dp??(Dp=Cp.SourceMapGenerator);let p=new Dp({file:s});p.setSourceContent(s,e);let d=VA(o,{sourceMap:p});r&&p.applySourceMap(new Pp(r),s);let g=p.toString();return{code:d,map:g}}return{code:e}}};Vn=new WeakMap;Ma=new WeakMap;$n=new WeakMap;Fr=new WeakMap;La=new WeakMap;qa=new WeakMap;Ai=new WeakSet;jv=function(i,...e){let t=typeof i.transform=="function"?i.transform:i.transforms[i.operator],{index:r=0}=i.functionQuery,[n]=e,s=n.init?.type||n.type;s!=="ClassDeclaration"&&s!=="ClassExpression"&&(n.type==="VariableDeclarator"||(i.functionIndex=++i.functionIndex||0,r!==null&&r!==i.functionIndex))||t(i,...e)};Bv=function({transform:i,functionQuery:{kind:e}}){if(typeof i=="string")return i;switch(e){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}};Fv=function(i){let e={};for(let t of i.body)if(t.type==="ExportNamedDeclaration"&&!t.source){for(let r of t.specifiers)if(r.exported&&r.local){let n=r.exported.name??r.exported.value,s=r.local.name??r.local.value;n&&s&&(e[n]=s)}}return e};Mp=function(i,e){if(!i.isExportAlias)return i;let{functionName:t,expressionName:r,className:n}=i;return t&&e[t]?{...i,functionName:e[t]}:r&&e[r]?{...i,expressionName:e[r]}:n&&e[n]?{...i,className:e[n]}:i};Gv=function(i){let{functionName:e,expressionName:t,className:r,objectName:n,propertyName:s}=i,o=i.privateMethodName?"PrivateIdentifier":"Identifier",l=[],a=i.methodName||i.privateMethodName;if(r?(a??(a="constructor"),l.push(`[id.name="${r}"]`,`[id.name="${r}"] > ClassExpression`,`[id.name="${r}"] > ClassBody > [key.name="${a}"][key.type=${o}] > [async]`,`[id.name="${r}"] > ClassExpression > ClassBody > [key.name="${a}"][key.type=${o}] > [async]`)):a&&l.push(`ClassBody > [key.name="${a}"][key.type=${o}] > [async]`,`Property[key.name="${a}"][key.type=${o}] > [async]`),e?l.push(`FunctionDeclaration[id.name="${e}"][async]`):t&&l.push(`FunctionExpression[id.name="${t}"][async]`,`ArrowFunctionExpression[id.name="${t}"][async]`,`VariableDeclarator[id.name="${t}"] > FunctionExpression[async]`,`VariableDeclarator[id.name="${t}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.property.name="${t}"] > FunctionExpression[async]`,`AssignmentExpression[left.property.name="${t}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.name="${t}"] > FunctionExpression[async]`,`AssignmentExpression[left.name="${t}"] > ArrowFunctionExpression[async]`),n||s){if(!n||!s)throw new Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${n}, propertyName=${s})`);let c=n==="this"?"left.object.type=ThisExpression":`left.object.name="${n}"`;l.push(`AssignmentExpression[${c}][left.property.name="${s}"] > [async]`)}return l.join(", ")};Hv={Transformer:Lp}});var zv,Vv,Oi,Ua,Up,ja,Ba,ar,Fa,$A,YA,jp,$v,Yv=w(()=>{bv();Wv();zv=i=>{throw TypeError(i)},Vv=(i,e,t)=>e.has(i)||zv("Cannot "+t),Oi=(i,e,t)=>(Vv(i,e,"read from private field"),t?t.call(i):e.get(i)),Ua=(i,e,t)=>e.has(i)?zv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Up=(i,e,t,r)=>(Vv(i,e,"write to private field"),e.set(i,t),t),$A=mv,{Transformer:YA}=Hv,jp=class{constructor(e,t){Ua(this,ja,[]),Ua(this,Ba,null),Ua(this,ar,{}),Ua(this,Fa,{}),Up(this,ja,e),Up(this,Ba,t||"diagnostics_channel")}free(){Up(this,ar,{})}addTransform(e,t){Oi(this,Fa)[e]=t}getTransformer(e,t,r){r=r.replace(/\\/g,"/");let n=`${e}/${r}@${t}`;if(Oi(this,ar)[n])return Oi(this,ar)[n];let s=Oi(this,ja).filter(({module:o})=>o.name===e&&(typeof o.filePath=="string"?o.filePath===r:o.filePath.test(r))&&$A(t,o.versionRange));if(s.length!==0)return Oi(this,ar)[n]=new YA(e,t,r,s,Oi(this,Ba),Oi(this,Fa)),Oi(this,ar)[n]}};ja=new WeakMap;Ba=new WeakMap;ar=new WeakMap;Fa=new WeakMap;$v={InstrumentationMatcher:jp}});function QA(i,e){return new KA(i,e)}var KA,Kv,Qv=w(()=>{Yv();({InstrumentationMatcher:KA}=$v);Kv={create:QA}});var Ga,Bp=w(()=>{Qv();Ga=Kv});import JA from"node:path";var Fp,Gp,Jv,Hp=w(()=>{Wn();Fp=JA.sep,Gp=function(i){var e=i.split(Fp),t=e.lastIndexOf("node_modules");if(t!==-1&&e[t+1]){for(var r=e[t+1][0]==="@",n=r?e[t+1]+"/"+e[t+2]:e[t+1],s=r?3:2,o="",l=t+s-1,a=0;a<=l;a++)a===l?o+=e[a]:o+=e[a]+Fp;for(var c="",p=e.length-1,d=t+s;d<=p;d++)d===p?c+=e[d]:c+=e[d]+Fp;return{name:n,basedir:o,path:c}}},Jv=qr(Gp)});import XA from"node:fs";import ZA from"node:path";function i1(i){if(Wp.has(i))return Wp.get(i);try{let e=t1(i,"package.json"),t=e1(e),{version:r}=JSON.parse(t);return Wp.set(i,r),r}catch{return process.version.slice(1)}}var e1,t1,Wp,zp,Xv,Vp=w(()=>{Wn();({readFileSync:e1}=XA),{join:t1}=ZA,Wp=new Map;zp=i1,Xv=qr(zp)});function r1(i){$p=i}function n1(i){$p&&$p(i)}var $p,di,Ha=w(()=>{di={setDiagnosticsHook:r1,emitDiagnostics:n1}});var Kp={};Du(Kp,{default:()=>Yp});import{format as s1}from"node:util";function Yp(i){return(...e)=>{Y.isEnabled()&&Y.log(`[${i}]`,s1(...e))}}var Qp=w(()=>{Wt()});var Zv,e0=w(()=>{Qp();Wn();Zv=dv(Kp)});import a1 from"node:module";import o1 from"node:url";import l1 from"node:os";import c1 from"node:path";import p1 from"node:fs";function g1(i,e){let t=l1,r=c1,n=p1,s=process.env.TRACING_DUMP_DIR??t.tmpdir(),o=r.dirname(e),l=r.basename(e),a=r.join(s,o.slice(r.parse(o).root.length)),c=r.join(a,l);Wa("Dumping patched code to: %s",c),n.mkdirSync(a,{recursive:!0}),n.writeFileSync(c,i)}var d1,Jp,u1,t0,m1,i0,Wa,Xp,b1,Zp,r0=w(()=>{Wn();Bp();Hp();Vp();Ha();e0();({create:d1}=Ga),Jp=a1,u1=Gp,{pathToFileURL:t0}=o1,m1=zp,{emitDiagnostics:i0}=di,Wa=Zv("@apm-js-collab/tracing-hooks:module-patch"),Xp=class{constructor({instrumentations:e=[]}={}){this.packages=new Set(e.map(t=>t.module.name)),this.instrumentator=d1(e),this.compile=Jp.prototype._compile}patch(){let e=this;Jp.prototype._compile=function(...r){let[n,s]=r,o=u1(s);if(o&&e.packages.has(o.name)){Wa("found resolved module, checking if there is a transformer %s",s);let l=m1(o.basedir,o.name),a=e.instrumentator.getTransformer(o.name,l,o.path);if(a){Wa("transforming file %s",s);try{let c=a.transform(n,"cjs");r[0]=c?.code,i0({url:t0(s).href,moduleName:a.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&g1(r[0],s)}catch(c){Wa("Error transforming module %s: %o",s,c),i0({url:t0(s).href,moduleName:a.moduleName,error:c})}finally{a.free()}}}return e.compile.apply(this,r)}}unpatch(){Jp.prototype._compile=this.compile}};b1=Xp,Zp=qr(b1)});import{fileURLToPath as n0}from"node:url";import{dirname as s0,join as h1}from"node:path";import{MessageChannel as y1}from"node:worker_threads";import{readFileSync as a0}from"node:fs";function c0(){let{port1:i,port2:e}=new y1;return i.on("message",di.emitDiagnostics),i.unref(),e}function p0(i={}){let e=i?.instrumentations||[];l0=Ga.create(e),o0=new Set(e.map(t=>t.module.name)),Yn=new Map,id=i?.diagnosticsPort?f1(i.diagnosticsPort):di.emitDiagnostics}function f1(i){return e=>{try{let t=e.error===void 0||e.error instanceof Error?e.error:new Error(String(e.error));i.postMessage({...e,error:t})}catch(t){td("failed to post diagnostics for %s: %o",e.url,t)}}}function _1(i){if(!i.url.startsWith("file:"))return i;let e=Jv(n0(i.url));if(e&&o0.has(e.name)){let t=e.basedir,r=Xv(t),n=l0.getTransformer(e.name,r,e.path);n&&Yn.set(i.url,n)}return i}function d0(i,e,t){return _1(t(i,e))}function rd(i,e,t){let r=t(i,e);if(Yn.has(i)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??i);r.source??=a0(n)}return v1(i,r)}function v1(i,e){let t=e.source;if(t){let r=Yn.get(i);if(w1(i,e.format))return td("skipping json module %s",i),r.free(),Yn.delete(i),e;try{let n=typeof t=="string"?t:Buffer.from(t).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":E1(i,n),o=r.transform(n,s);e.source=o?.code,e.shortCircuit=!0,id({url:i,moduleName:r.moduleName})}catch(n){td("Error transforming module %s: %o",i,n),id({url:i,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function w1(i,e){return e==="json"||k1.test(i)}function E1(i,e){return T1(i)??(S1.test(e)?"esm":"cjs")}function T1(i){let e;try{e=n0(i)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let t=u0(s0(e));return t==="module"?"esm":t==="commonjs"?"cjs":void 0}function u0(i){if(ed.has(i))return ed.get(i);let e;try{e=JSON.parse(a0(h1(i,"package.json"),"utf8")).type}catch{let t=s0(i);t!==i&&(e=u0(t))}return ed.set(i,e),e}var td,Yn,o0,l0,id,k1,S1,ed,EH,m0=w(()=>{Qp();Bp();Hp();Vp();Ha();td=Yp("@apm-js-collab/tracing-hooks:esm-hook"),Yn=null,o0=null,l0=null,id=di.emitDiagnostics;k1=/\.json([?#]|$)/;S1=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;ed=new Map;EH=di.setDiagnosticsHook});import{createHash as g0}from"node:crypto";import{existsSync as y0,readFileSync as I1}from"node:fs";import*as x1 from"node:module";import{join as f0,dirname as Kn}from"node:path";import{pathToFileURL as za,fileURLToPath as sd}from"node:url";function O1(i){if(i)return!0;let{major:e=0,minor:t=0}=ml(process.versions.node??"0.0.0");return e>25||e===25&&t>=1||e===24&&t>=13}function _0(i){if(nd.has(i))return nd.get(i);let e,t=f0(i,"package.json");if(y0(t))try{e=JSON.parse(I1(t,"utf8")).type}catch{e=void 0}else Kn(i)!==i&&(e=_0(Kn(i)));return nd.set(i,e),e}function R1(i){if(i.endsWith(".json"))return"json";if(i.endsWith(".mjs")||i.startsWith("file:")&&i.endsWith(".js")&&_0(Kn(sd(i)))==="module")return"module"}function N1(i){return(e,t,r)=>i(e,t,(n,s)=>{let o=r(n,s);if(o&&o.format==null){let l=R1(n);l&&(o.format=l)}return o})}function v0(i){At(()=>{console.warn(`[Sentry] ${i}`)})}function k0(i){v0(`${i} See ${A1}`)}function C1(i,e){let t=e instanceof Error?e.message:String(e),r=/^[\w$]+ is not a function$/.test(t),n=t==="transform is not a function",s=(pe.__SENTRY_ORCHESTRION__?.runtime?.length??0)===0;if(!(r&&!n&&s)){if(h0.has(i))return;h0.add(i),v0(`Could not instrument \`${i}\` (${t}). Other instrumented dependencies are unaffected, so this is not a bundling problem. If \`${i}\` should be traced, please report it.`);return}b0||(b0=!0,k0(`\`@sentry/server-runtime-injection\` was bundled into your application, so \`${i}\` and any other instrumented dependency load uninstrumented (${t}). Keep \`@sentry/server-runtime-injection\` external in your server bundle, or use the Sentry bundler plugin for build-time instrumentation.`))}function w0(){var i;let e=(i=pe).__SENTRY_ORCHESTRION__??(i.__SENTRY_ORCHESTRION__={});if(e.runtime||e.runtimeUnavailable)return;let t=globalThis,r=O1(!!t.Deno),n=x1;di.setDiagnosticsHook(({url:s,moduleName:o,error:l})=>{var a;l?(l instanceof TypeError&&C1(o,l),Y.warn(`[instrumentation] failed to inject diagnostics-channel into ${o}:`,l)):(pe.__SENTRY_ORCHESTRION__=pe.__SENTRY_ORCHESTRION__||{},pe.__SENTRY_ORCHESTRION__.runtime=pe.__SENTRY_ORCHESTRION__.runtime||[],pe.__SENTRY_ORCHESTRION__.runtime.push(o),((a=pe.__SENTRY_ORCHESTRION__).runtimeFiles??(a.runtimeFiles={}))[o]=s,Ft()?.emit("orchestrion.module-injected",o))});try{if(typeof n.registerHooks=="function"&&r){p0({instrumentations:Hn});let s=new Map,o=t.Deno?N1(rd):rd;n.registerHooks({resolve:d0,load:(p,d,g)=>{let b=o(p,d,g),v=b?.format??d.format;if((v==null||v==="commonjs")&&b?.shortCircuit===!0&&b?.source!=null&&p.startsWith("file:")){let y=g0("sha256").update(b.source).digest("hex");s.set(za(sd(p)).href,y)}return b}});let l=n.Module.prototype,a=l._compile;new Zp({instrumentations:Hn}).patch();let c=l._compile;l._compile=function(p,d,...g){let b=za(d).href,v=s.get(b);return s.delete(b),(v!==void 0&&v===g0("sha256").update(p).digest("hex")?a:c).call(this,p,d,...g)},Y.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof n.register=="function"&&!t.Bun&&!t.Deno){let s=c0(),o;o=import.meta.url;let l;l=f0(Kn(sd(import.meta.url)),"hook.js");let a=y0(l);a||Y.warn(`No orchestrion ESM hook at ${l}; falling back to the package specifier.`);let c=a?za(l).href:"@sentry/server-runtime-injection/hook";if(a){let p=`${za(Kn(l)).href}/`;n.register(`data:text/javascript,${encodeURIComponent(`const d=${JSON.stringify(p)};export async function load(u,c,n){return n(u,u.startsWith(d)?{...c,format:'module'}:c)}`)}`)}n.register(c,{parentURL:o,data:{instrumentations:Hn,diagnosticsPort:s},transferList:[s]}),new Zp({instrumentations:Hn}).patch(),Y.log("Registered diagnostics-channel injection via Module.register()")}else{e.runtimeUnavailable=!0,Y.warn("No available Node API to register diagnostics-channel injection hooks; skipping.");return}}catch(s){e.runtimeUnavailable=!0;let o=s instanceof Error?s.message:String(s);k0(`Failed to register diagnostics-channel injection hooks (${o}), so channel-based integrations will not record spans.`),Y.warn("Diagnostics-channel injection registration error:",s);return}e.runtime=e.runtime||[]}var A1,nd,b0,h0,S0=w(()=>{Wt();Q_();r0();m0();Ha();A1="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";nd=new Map;b0=!1,h0=new Set});import*as E0 from"node:os";import{threadId as P1,isMainThread as D1}from"worker_threads";var M1,Qn,T0=w(()=>{hg();Oa();Wt();mc();pv();S0();J_();Z_();M1=6e4,Qn=class extends qn{constructor(e){let t=e.includeServerName===!1?void 0:e.serverName||global.process.env.SENTRY_NAME||E0.hostname(),r={...e,platform:"node",runtime:e.runtime||{name:"node",version:global.process.version},serverName:t};rc(r,"node"),Y.log(`Initializing Sentry: process: ${process.pid}, thread: ${D1?"main":`worker-${P1}`}.`),super(r),this._onExitFlushListener=()=>{this.emit("flush")},t&&this.on("beforeCaptureLog",n=>{n.attributes={...n.attributes,[bg]:t}}),process.on("beforeExit",this._onExitFlushListener),$l(this),cv(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&e.enableRuntimeChannelInjection!==!1&&w0()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=lv():this.asyncLocalStorageLookup={asyncLocalStorage:Tc()},super.init()}get tracer(){if(this._tracer)return this._tracer;let e="@sentry/node",t=yt,r=Ti.getTracer(e,t);return this._tracer=r,r}async flush(e){return await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports&&this._flushOutcomes(),super.flush(e)}async close(e){this._clientReportInterval&&clearInterval(this._clientReportInterval),this._clientReportOnExitFlushListener&&process.off("beforeExit",this._clientReportOnExitFlushListener),this._onExitFlushListener&&process.off("beforeExit",this._onExitFlushListener);let t=await super.close(e);return this.traceProvider&&await this.traceProvider.shutdown(),t}startClientReportTracking(){let e=this.getOptions();e.sendClientReports&&(this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{X_&&Y.log("Flushing client reports based on interval."),this._flushOutcomes()},e.clientReportFlushInterval??M1).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){ec(),super._setupIntegrations()}}});var I0=w(()=>{rv();T0()});var x0={};Du(x0,{NodeClient:()=>Qn,Scope:()=>Ze,createTransport:()=>Jl,defaultStackParser:()=>bp,linkedErrorsIntegration:()=>cc});var A0=w(()=>{"use strict";I0();Wt()});(function(){try{var i=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="9a5d0e7f-86cd-4bf7-a0ea-ce2309714b70",i._sentryDebugIdIdentifier="sentry-dbid-9a5d0e7f-86cd-4bf7-a0ea-ce2309714b70")}catch{}})();import{delimiter as bP,dirname as hP,join as tn,resolve as nn}from"node:path";import{readFileSync as yP,realpathSync as pu,watch as fP}from"node:fs";import{fileURLToPath as _P}from"node:url";import{DefaultPackageManager as Jw,getAgentDir as mt,ModelRuntime as vP,SessionManager as gu,SettingsManager as kP,VERSION as du}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as wP}from"@earendil-works/pi-ai";import{randomBytes as F0,randomUUID as ld,timingSafeEqual as $1}from"node:crypto";import{readFile as Y1,readdir as K1}from"node:fs/promises";import{createServer as Q1}from"node:http";import{join as cd}from"node:path";import{getAgentDir as J1}from"@earendil-works/pi-coding-agent";import{isAbsolute as BS,relative as FS}from"node:path";var at={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Mu={id:at.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 dS}from"node:child_process";import{realpath as uS}from"node:fs/promises";import{isAbsolute as Lu,relative as mS,sep as gS,win32 as bS}from"node:path";var X=class extends Error{status;reason;constructor(e,t=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=r}};function ve(i,e,t=2*1024*1024,r={}){let n=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,o)=>{let l,a=dS("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:i,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:t,windowsHide:!0},(c,p,d)=>{if(!c){if(l){o(new X("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 b=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";o(new X("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",b==="outcome_unknown"?503:409,b));return}let g=c.code;g==="ENOENT"?o(new X("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):g==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new X("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(d)?o(new X("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new X(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))});a.stdin?.on("error",c=>{l=c}),r.input!==void 0&&a.stdin?.end(r.input)})}async function ot(i){let e=await uS(i),t;try{t=(await ve(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(n){if(n instanceof X&&n.status===404)return{kind:"not-repository"};if(n instanceof X&&n.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw n}let r=mS(t,e).split(gS).join("/");if(r===".."||r.startsWith("../")||Lu(r))throw new X("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:r?`${r}/`:""}}function Hi(i){if(typeof i!="string"||!i||i.length>4096||i.includes("\0")||i.includes("\\")||Lu(i)||bS.isAbsolute(i)||i.split("/").some(e=>!e||e==="."||e===".."))throw new X("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as AS}from"node:crypto";import{lstat as zo,realpath as Qu}from"node:fs/promises";import{dirname as Ku,isAbsolute as OS,relative as RS,resolve as ln}from"node:path";import{lstat as TS}from"node:fs/promises";import{resolve as IS}from"node:path";import{createHash as hS}from"node:crypto";import{constants as Zt}from"node:fs";import{open as Go,opendir as yS,realpath as qu,stat as ws}from"node:fs/promises";import{isAbsolute as ju,relative as fS,resolve as _S,sep as vS,win32 as kS}from"node:path";var wS=1e3,SS={bytes:512*1024,lines:1e4},Ho={bytes:5*1024*1024,lines:2e5},Bu=8*1024*1024,ES=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Fo=i=>hS("sha256").update(i).digest("hex"),be=class extends Error{status;reason;constructor(e,t=400,r){super(e),this.name="WorkspaceFileError",this.status=t,this.reason=r}};function Uu(i,e){let t=fS(i,e);return t!==".."&&!t.startsWith(`..${vS}`)&&!ju(t)}async function an(i,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||ju(e)||kS.isAbsolute(e))throw new be("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await qu(i),r=_S(t,e);if(!Uu(t,r))throw new be("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await qu(r);if(!Uu(t,n))throw new be("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function Ss(i){try{return await i()}catch(e){if(e instanceof be)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new be("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new be("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function Fu(i,e){return Ss(async()=>{let t=await an(i,e),r=[],n=!1;for await(let s of await yS(t)){if(s.name===".git")continue;if(r.length===wS){n=!0;break}let o=e?`${e}/${s.name}`:s.name,l=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let a=await ws(await an(i,o));l=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}r.push({name:s.name,path:o,kind:l})}return r.sort((s,o)=>+(o.kind==="directory")-+(s.kind==="directory")||ES.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:r,truncated:n}})}function Gu(i){if(i.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(i[0]===255&&i[1]===216&&i[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(i.subarray(0,6).toString("ascii")))return"image/gif";if(i.subarray(0,4).toString("ascii")==="RIFF"&&i.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function on(i,e,t=SS){return Ss(async()=>{let r=await an(i,e);if(!(await ws(r)).isFile())throw new be("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await Go(r,Zt.O_RDONLY|Zt.O_NONBLOCK|(Zt.O_NOFOLLOW??0));try{let s=await n.stat();if(!s.isFile())throw new be("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let o={path:e,size:s.size},l=Buffer.alloc(16);await n.read(l,0,l.length,0);let a=Gu(l),c=a?Bu:t.bytes;if(s.size>c)return{...o,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:v}=await n.read(p,d,p.length-d,d);if(!v)break;d+=v}if(d>s.size)throw new be("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let g=p.subarray(0,d);if(a)return{...o,kind:"image",mimeType:a,data:g.toString("base64")};if(g.some(v=>v===0||v<32&&![9,10,12,13,27].includes(v)))return{...o,kind:"unsupported"};let b=1;for(let v=0;v<g.length-1;v++)if(g[v]===10&&++b>t.lines)return{...o,kind:"too-large",limit:t.lines,unit:"lines"};try{return{...o,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(g),version:Fo(g)}}catch{return{...o,kind:"unsupported"}}}finally{await n.close()}})}async function Hu(i,e){return Ss(async()=>{let t=await an(i,e);if(!(await ws(t)).isFile())throw new be("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Go(t,Zt.O_RDONLY|Zt.O_NONBLOCK|(Zt.O_NOFOLLOW??0));try{let n=await r.stat();if(!n.isFile())throw new be("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(n.size>Bu)throw new be("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(n.size+1),o=0;for(;o<s.length;){let{bytesRead:c}=await r.read(s,o,s.length-o,o);if(!c)break;o+=c}if(o>n.size)throw new be("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let l=s.subarray(0,o),a=Gu(l);if(!a)throw new be("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:l}}finally{await r.close()}})}async function Wu(i,e,t,r){if(typeof t!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new be("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let n=Buffer.from(t,"utf8"),{bytes:s,lines:o}=Ho;if(n.length>s)throw new be(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${s/1024/1024} MB`,413);let l=1;for(let a of n)if(a===10&&++l>o+1)throw new be(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${o} \u884C`,413);return Ss(async()=>{let a=await an(i,e);if(!(await ws(a)).isFile())throw new be("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await Go(a,Zt.O_RDWR|Zt.O_NONBLOCK|(Zt.O_NOFOLLOW??0));try{let p=await c.stat();if(!p.isFile())throw new be("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new be("\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),g=0;for(;g<d.length;){let{bytesRead:v}=await c.read(d,g,d.length-g,g);if(!v)break;g+=v}if(g>p.size||Fo(d.subarray(0,g))!==r)throw new be("\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 b=0;for(;b<n.length;)b+=(await c.write(n,b,n.length-b,b)).bytesWritten;return await c.sync(),{path:e,size:n.length,version:Fo(n)}}finally{await c.close()}})}var xS=1e3,zu=512*1024,Vu=1e4;function $u(i,e){return e.startsWith(i)&&e.slice(i.length)||void 0}async function yr(i){let e=await ot(i);if(e.kind!=="repository")return e;let{root:t,scope:r}=e,n=await ve(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:t,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=n.split("\0");for(let l=0;l<o.length;l++){let a=o[l];if(a.startsWith("# branch.oid ")){let T=a.slice(13);s.head=T==="(initial)"?null:T;continue}if(a.startsWith("# branch.head ")){let T=a.slice(14);s.branch=T==="(detached)"?null:T;continue}if(a.startsWith("# branch.upstream ")){s.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let T=a.match(/\+(\d+) -(\d+)/);T&&(s.ahead=Number(T[1]),s.behind=Number(T[2]));continue}let c=a[0];if(!["1","2","u","?"].includes(c??""))continue;let p=c==="?"?1:c==="1"?8:c==="2"?9:10,d=0;for(let T=0;T<p;T++)d=a.indexOf(" ",d)+1;let g=$u(r,a.slice(d)),b=c==="2"?o[++l]:void 0;if(!g)continue;if(s.entries.length===xS){s.truncated=!0;continue}let v=a.slice(0,d).split(" "),y={path:g,index:c==="?"?"?":v[1][0],worktree:c==="?"?"?":v[1][1],conflict:c==="u",untracked:c==="?",submodule:c!=="?"&&v[2]!=="N..."},S=b===void 0?void 0:$u(r,b);S&&(y.originalPath=S),s.entries.push(y)}return s}async function Yu(i,e,t){if(Hi(e),!["staged","unstaged","untracked"].includes(t))throw new X("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await yr(i);if(r.kind!=="repository")throw new X("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let n={path:e,area:t},s=r.entries.find(l=>l.path===e);if(!s)return{...n,kind:"empty"};if(s.conflict)return{...n,kind:"conflict"};if(s.submodule)return{...n,kind:"submodule"};if(t==="untracked"){if(!s.untracked)return{...n,kind:"empty"};if(!(await TS(IS(i,e))).isFile())return{...n,kind:"unsupported"};let l=await on(i,e);if(l.kind==="too-large")return{...n,kind:"too-large"};if(l.kind!=="text")return{...n,kind:"binary"};if(!l.text)return{...n,kind:"empty"};let a=l.text.split(`
193
- `),c=a.at(-1)==="";c&&a.pop();let p=`--- /dev/null
189
+ `}})),t5=Ic()});var Ac,Ub=w(()=>{Ac={}});var xc,f5,qb=w(()=>{ue();Cb();_c();vc();wc();Gs();Ec();Tc();Db();Lb();Ub();xc=ce(((t,e)=>{kc(),sn(),an(),on();let i=Ws.v??{},{parse:r}=$s.v??{},{generate:n}=Mb.v??{},s=Ic(),a,o;var l=new WeakMap,c=new WeakMap,p=new WeakMap,u=new WeakMap,m=new WeakMap,g=new WeakMap,h=new WeakSet,f=class{constructor(C,P,G,N,I,A={}){Pb(this,h),Je(this,l,null),Je(this,c,null),Je(this,p,null),Je(this,u,[]),Je(this,m,null),Je(this,g,{}),gt(l,this,C),gt(c,this,P),gt(p,this,G),gt(u,this,N),gt(m,this,I),gt(g,this,A)}free(){}get moduleName(){return ge(l,this)}get filePath(){return ge(p,this)}transform(C,P,G,N){let I=N?.sourceFile||`${ge(l,this)}/${ge(p,this)}`;if(Buffer.isBuffer(C)&&(C=C.toString()),!C)return{code:C};let A,D={},k=0,b={...s,...ge(g,this),defaults:{...s}};for(let q of ge(u,this)){let{astQuery:F,functionQuery:W={}}=q;if(!A){let Y={loc:!0,ranges:!0,raw:!0,module:P==="esm"};try{A=r(C,Y)}catch{A=r(C,{...Y,module:!Y.module})}P==="esm"&&(D=mt(h,this,E).call(this,A))}let $=mt(h,this,O).call(this,W,D),x=F||mt(h,this,L).call(this,$),he={...q,dcModule:ge(m,this),moduleType:P,moduleVersion:ge(c,this),functionQuery:$,transforms:b};he.operator=mt(h,this,S).call(this,he),i.traverse(A,i.parse(x),(...Y)=>{k++,mt(h,this,v).call(this,he,...Y)})}if(k===0&&ge(u,this).length>0){let q=ge(u,this).map(({astQuery:F,functionQuery:W={}})=>{if(F)return F;let $=mt(h,this,O).call(this,W,D),he=(Pe=>Pe.methodName||Pe.privateMethodName||Pe.functionName||Pe.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(q)}`)}if(A){a??(a=(Ac.v??{}).SourceMapConsumer),o??(o=(Ac.v??{}).SourceMapGenerator);let q=new o({file:I});q.setSourceContent(I,C);let F=n(A,{sourceMap:q});return G&&q.applySourceMap(new a(G),I),{code:F,map:q.toString()}}return{code:C}}};function v(C,...P){let G=typeof C.transform=="function"?C.transform:C.transforms[C.operator],{index:N=0}=C.functionQuery,[I]=P,A=I.init?.type||I.type;A!=="ClassDeclaration"&&A!=="ClassExpression"&&(I.type==="VariableDeclarator"||(C.functionIndex=++C.functionIndex||0,N!==null&&N!==C.functionIndex))||G(C,...P)}function S({transform:C,functionQuery:{kind:P}}){if(typeof C=="string")return C;switch(P){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}}function E(C){let P={};for(let G of C.body)if(G.type==="ExportNamedDeclaration"&&!G.source){for(let N of G.specifiers)if(N.exported&&N.local){let I=N.exported.name??N.exported.value,A=N.local.name??N.local.value;I&&A&&(P[I]=A)}}return P}function O(C,P){if(!C.isExportAlias)return C;let{functionName:G,expressionName:N,className:I}=C;return G&&P[G]?{...C,functionName:P[G]}:N&&P[N]?{...C,expressionName:P[N]}:I&&P[I]?{...C,className:P[I]}:C}function L(C){let{functionName:P,expressionName:G,className:N,objectName:I,propertyName:A}=C,D=C.privateMethodName?"PrivateIdentifier":"Identifier",k=[],b=C.methodName||C.privateMethodName;if(N?(b??(b="constructor"),k.push(`[id.name="${N}"]`,`[id.name="${N}"] > ClassExpression`,`[id.name="${N}"] > ClassBody > [key.name="${b}"][key.type=${D}] > [async]`,`[id.name="${N}"] > ClassExpression > ClassBody > [key.name="${b}"][key.type=${D}] > [async]`)):b&&k.push(`ClassBody > [key.name="${b}"][key.type=${D}] > [async]`,`Property[key.name="${b}"][key.type=${D}] > [async]`),P?k.push(`FunctionDeclaration[id.name="${P}"][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||A){if(!I||!A)throw new Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${I}, propertyName=${A})`);let q=I==="this"?"left.object.type=ThisExpression":`left.object.name="${I}"`;k.push(`AssignmentExpression[${q}][left.property.name="${A}"] > [async]`)}return k.join(", ")}e.exports={Transformer:f}})),f5=xc()});var Oc,E5,jb=w(()=>{ue();_c();vc();wc();Nb();qb();Oc=ce(((t,e)=>{sn(),an(),on();let i=Sc(),{Transformer:r}=xc();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,u){u=u.replace(/\\/g,"/");let m=`${c}/${u}@${p}`;if(ge(a,this)[m])return ge(a,this)[m];let g=ge(n,this).filter(({module:h})=>h.name===c&&(typeof h.filePath=="string"?h.filePath===u:h.filePath.test(u))&&i(p,h.versionRange));if(g.length!==0)return ge(a,this)[m]=new r(c,p,u,g,ge(s,this),ge(o,this)),ge(a,this)[m]}};e.exports={InstrumentationMatcher:l}})),E5=Oc()});var Rc,O5,Bb=w(()=>{ue();jb();Rc=ce(((t,e)=>{let{InstrumentationMatcher:i}=Oc();function r(n,s){return new i(n,s)}e.exports={create:r}})),O5=Rc()});var ln,C5,Nc=w(()=>{ue();Bb();ln=ce(((t,e)=>{e.exports=Rc()})),C5=ln()});import eI from"node:path";var cn,U5,Pc=w(()=>{ue();cn=ce(((t,e)=>{var i=eI.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,u=0;u<=p;u++)u===p?c+=n[u]:c+=n[u]+i;for(var m="",g=n.length-1,h=s+l;h<=g;h++)h===g?m+=n[h]:m+=n[h]+i;return{name:o,basedir:c,path:m}}}})),U5=cn()});import tI from"node:fs";import iI from"node:path";var pn,H5,Cc=w(()=>{ue();pn=ce(((t,e)=>{let{readFileSync:i}=tI,{join:r}=iI,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})),H5=pn()});var Ti,$5,Vs=w(()=>{ue();Ti=ce(((t,e)=>{let i;function r(s){i=s}function n(s){i&&i(s)}e.exports={setDiagnosticsHook:r,emitDiagnostics:n}})),$5=Ti()});import{format as rI}from"node:util";function nI(t){return(...e)=>{U.isEnabled()&&U.log(`[${t}]`,rI(...e))}}var Fb,Mc,Hb=w(()=>{ue();vt();Fb=xb({default:()=>nI});Mc=Le((()=>{}));Mc()});var dn,Z5,Dc=w(()=>{ue();Hb();dn=ce(((t,e)=>{e.exports=(Mc(),Rb(Fb)).default})),Z5=dn()});import sI from"node:module";import aI from"node:url";import oI from"node:os";import lI from"node:path";import cI from"node:fs";var Lc,uG,Gb=w(()=>{ue();Nc();Pc();Cc();Vs();Dc();Lc=ce(((t,e)=>{let{create:i}=ln(),r=sI,n=cn(),{pathToFileURL:s}=aI,a=pn(),{emitDiagnostics:o}=Ti(),l=dn()("@apm-js-collab/tracing-hooks:module-patch");var c=class{constructor({instrumentations:u=[]}={}){this.packages=new Set(u.map(m=>m.module.name)),this.instrumentator=i(u),this.compile=r.prototype._compile}patch(){let u=this;r.prototype._compile=function(...g){let[h,f]=g,v=n(f);if(v&&u.packages.has(v.name)){l("found resolved module, checking if there is a transformer %s",f);let S=a(v.basedir,v.name),E=u.instrumentator.getTransformer(v.name,S,v.path);if(E){l("transforming file %s",f);try{g[0]=E.transform(h,"cjs")?.code,o({url:s(f).href,moduleName:E.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&p(g[0],f)}catch(O){l("Error transforming module %s: %o",f,O),o({url:s(f).href,moduleName:E.moduleName,error:O})}finally{E.free()}}}return u.compile.apply(this,g)}}unpatch(){r.prototype._compile=this.compile}};function p(u,m){let g=oI,h=lI,f=cI,v=process.env.TRACING_DUMP_DIR??g.tmpdir(),S=h.dirname(m),E=h.basename(m),O=h.join(v,S.slice(h.parse(S).root.length)),L=h.join(O,E);l("Dumping patched code to: %s",L),f.mkdirSync(O,{recursive:!0}),f.writeFileSync(L,u)}e.exports=c})),uG=Lc()});import{readFileSync as Wb}from"node:fs";import{dirname as $b,join as pI}from"node:path";import{fileURLToPath as Vb}from"node:url";import{MessageChannel as dI}from"node:worker_threads";function Yb(){let{port1:t,port2:e}=new dI;return t.on("message",Bc.emitDiagnostics),t.unref(),e}function Qb(t={}){let e=t?.instrumentations||[];Kb=(0,mI.create)(e),zb=new Set(e.map(i=>i.module.name)),un=new Map,jc=t?.diagnosticsPort?hI(t.diagnosticsPort):Bc.emitDiagnostics}function hI(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){qc("failed to post diagnostics for %s: %o",e.url,i)}}}function yI(t){if(!t.url.startsWith("file:"))return t;let e=(0,gI.default)(Vb(t.url));if(e&&zb.has(e.name)){let i=e.basedir,r=(0,fI.default)(i),n=Kb.getTransformer(e.name,r,e.path);n&&un.set(t.url,n)}return t}function Jb(t,e,i){return yI(i(t,e))}function Fc(t,e,i){let r=i(t,e);if(un.has(t)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??t);r.source??(r.source=Wb(n))}return bI(t,r)}function bI(t,e){let i=e.source;if(i){let r=un.get(t);if(vI(t,e.format))return qc("skipping json module %s",t),r.free(),un.delete(t),e;try{let n=typeof i=="string"?i:Buffer.from(i).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":SI(t,n);e.source=r.transform(n,s)?.code,e.shortCircuit=!0,jc({url:t,moduleName:r.moduleName})}catch(n){qc("Error transforming module %s: %o",t,n),jc({url:t,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function vI(t,e){return e==="json"||_I.test(t)}function SI(t,e){return kI(t)??(wI.test(e)?"esm":"cjs")}function kI(t){let e;try{e=Vb(t)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let i=Xb($b(e));return i==="module"?"esm":i==="commonjs"?"cjs":void 0}function Xb(t){if(Uc.has(t))return Uc.get(t);let e;try{e=JSON.parse(Wb(pI(t,"package.json"),"utf8")).type}catch{let i=$b(t);i!==t&&(e=Xb(i))}return Uc.set(t,e),e}var uI,mI,gI,fI,Bc,qc,un,zb,Kb,jc,_I,wI,Uc,Zb=w(()=>{ue();Dc();Nc();Pc();Cc();Vs();uI=ir(dn(),1),mI=ln(),gI=ir(cn(),1),fI=ir(pn(),1),Bc=Ti(),qc=(0,uI.default)("@apm-js-collab/tracing-hooks:esm-hook"),un=null,zb=null,Kb=null,jc=Bc.emitDiagnostics;_I=/\.json([?#]|$)/;wI=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;Uc=new Map});import{createHash as e_}from"node:crypto";import{existsSync as n_,readFileSync as EI}from"node:fs";import*as TI from"node:module";import{dirname as zs,join as s_}from"node:path";import{fileURLToPath as Wc,pathToFileURL as Hc}from"node:url";function xI(t){if(t)return!0;let{major:e=0,minor:i=0}=po(process.versions.node??"0.0.0");return e>25||e===25&&i>=1||e===24&&i>=13}function a_(t){if(Gc.has(t))return Gc.get(t);let e,i=s_(t,"package.json");if(n_(i))try{e=JSON.parse(EI(i,"utf8")).type}catch{e=void 0}else zs(t)!==t&&(e=a_(zs(t)));return Gc.set(t,e),e}function OI(t){if(t.endsWith(".json"))return"json";if(t.endsWith(".mjs")||t.startsWith("file:")&&t.endsWith(".js")&&a_(zs(Wc(t)))==="module")return"module"}function RI(t){return(e,i,r)=>t(e,i,(n,s)=>{let a=r(n,s);if(a&&a.format==null){let o=OI(n);o&&(a.format=o)}return a})}function o_(t){st(()=>{console.warn(`[Sentry] ${t}`)})}function l_(t){o_(`${t} See ${AI}`)}function NI(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(r_.has(t))return;r_.add(t),o_(`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}i_||(i_=!0,l_(`\`@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 PI(){(0,II.setDiagnosticsHook)(({url:t,moduleName:e,error:i})=>{if(i)i instanceof TypeError&&NI(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 c_(){let t=Q.__SENTRY_ORCHESTRION__??(Q.__SENTRY_ORCHESTRION__={});if(t.runtime||t.runtimeUnavailable)return;let e=globalThis,i=xI(!!e.Deno),r=TI;PI();try{if(typeof r.registerHooks=="function"&&i){Qb({instrumentations:rn});let n=new Map,s=e.Deno?RI(Fc):Fc;r.registerHooks({resolve:Jb,load:(c,p,u)=>{let m=s(c,p,u),g=m?.format??p.format;if((g==null||g==="commonjs")&&m?.shortCircuit===!0&&m?.source!=null&&c.startsWith("file:")){let h=e_("sha256").update(m.source).digest("hex");n.set(Hc(Wc(c)).href,h)}return m}});let a=r.Module.prototype,o=a._compile;new t_.default({instrumentations:rn}).patch();let l=a._compile;a._compile=function(c,p,...u){let m=Hc(p).href,g=n.get(m);return n.delete(m),(g!==void 0&&g===e_("sha256").update(c).digest("hex")?o:l).call(this,c,p,...u)},U.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof r.register=="function"&&!e.Bun&&!e.Deno){let n=Yb(),s;s=import.meta.url;let a;a=s_(zs(Wc(import.meta.url)),"hook.js");let o=n_(a);o||U.warn(`No orchestrion loader hook at ${a}; falling back to the package specifier.`);let l=o?Hc(a).href:"@sentry/server-runtime-injection/hook";r.register(l,{parentURL:s,data:{instrumentations:rn,diagnosticsPort:n},transferList:[n]}),new t_.default({instrumentations:rn}).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);l_(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 t_,II,AI,Gc,i_,r_,p_=w(()=>{ue();Gb();Zb();Vs();vt();hb();t_=ir(Lc()),II=Ti(),AI="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";Gc=new Map;i_=!1,r_=new Set});import*as d_ from"node:os";import{isMainThread as CI,threadId as MI}from"worker_threads";var DI,$c,u_=w(()=>{Bu();_t();vt();ol();Us();yb();Ab();p_();DI=6e4,$c=class extends sl{constructor(t){let e=t.includeServerName===!1?void 0:t.serverName||global.process.env.SENTRY_NAME||d_.hostname(),i={...t,platform:"node",runtime:t.runtime||{name:"node",version:global.process.version},serverName:e};Jo(i,"node"),U.log(`Initializing Sentry: process: ${process.pid}, thread: ${CI?"main":`worker-${MI}`}.`),super(i),this._onExitFlushListener=()=>{this.emit("flush")},e&&this.on("beforeCaptureLog",r=>{r.attributes={...r.attributes,[as]:e}}),process.on("beforeExit",this._onExitFlushListener),jo(this),Ib(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&t.enableRuntimeChannelInjection!==!1&&c_()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=Tb():this.asyncLocalStorageLookup={asyncLocalStorage:_l()},super.init()}get tracer(){if(this._tracer)return this._tracer;let t="@sentry/node",e=At,i=zt.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(()=>{ju&&U.log("Flushing client reports based on interval."),this._flushOutcomes()},t.clientReportFlushInterval??DI).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){zo(),super._setupIntegrations()}}});var m_=w(()=>{wb();u_()});var g_={};Gw(g_,{NodeClient:()=>$c,Scope:()=>Ge,createTransport:()=>Wo,defaultStackParser:()=>cc,linkedErrorsIntegration:()=>rl});var f_=w(()=>{"use strict";m_();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]="33824641-b63b-4649-a41f-6147985ab046",t._sentryDebugIdIdentifier="sentry-dbid-33824641-b63b-4649-a41f-6147985ab046")}catch{}})();import{delimiter as hN,dirname as yN,join as hr,resolve as br}from"node:path";import{readFileSync as bN,realpathSync as Qp,watch as _N}from"node:fs";import{fileURLToPath as vN}from"node:url";import{DefaultPackageManager as qw,getAgentDir as Ke,ModelRuntime as wN,SessionManager as ed,SettingsManager as SN,VERSION as Jp}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as kN}from"@earendil-works/pi-ai";import{randomBytes as x_,randomUUID as Kc,timingSafeEqual as zI}from"node:crypto";import{readFile as KI,readdir as YI}from"node:fs/promises";import{createServer as QI}from"node:http";import{join as Yc}from"node:path";import{getAgentDir as JI}from"@earendil-works/pi-coding-agent";import{isAbsolute as _0,relative as v0}from"node:path";var je={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var sd={id:je.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 Ww}from"node:child_process";import{realpath as $w}from"node:fs/promises";import{isAbsolute as ad,relative as Vw,sep as zw,win32 as Kw}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=Ww("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,u)=>{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(u)?"index_locked":/already exists/i.test(u)?"branch_exists":/already checked out|used by worktree/i.test(u)?"branch_in_use":/would be overwritten|local changes/i.test(u)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(u)?"identity_missing":"git_failed";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(u)?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 Be(t){let e=await $w(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=Vw(i,e).split(zw).join("/");if(r===".."||r.startsWith("../")||ad(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 ci(t){if(typeof t!="string"||!t||t.length>4096||t.includes("\0")||t.includes("\\")||ad(t)||Kw.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 o0}from"node:crypto";import{lstat as Ba,realpath as vd}from"node:fs/promises";import{dirname as _d,isAbsolute as l0,relative as c0,resolve as Sr}from"node:path";import{lstat as n0}from"node:fs/promises";import{resolve as s0}from"node:path";import{createHash as Yw}from"node:crypto";import{constants as Et}from"node:fs";import{open as Ua,opendir as Qw,realpath as od,stat as Cn}from"node:fs/promises";import{isAbsolute as cd,relative as Jw,resolve as Xw,sep as Zw,win32 as e0}from"node:path";var t0=1e3,i0={bytes:512*1024,lines:1e4},qa={bytes:5*1024*1024,lines:2e5},pd=8*1024*1024,r0=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),La=t=>Yw("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 ld(t,e){let i=Jw(t,e);return i!==".."&&!i.startsWith(`..${Zw}`)&&!cd(i)}async function vr(t,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||cd(e)||e0.isAbsolute(e))throw new X("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let i=await od(t),r=Xw(i,e);if(!ld(i,r))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await od(r);if(!ld(i,n))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function Mn(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 dd(t,e){return Mn(async()=>{let i=await vr(t,e),r=[],n=!1;for await(let s of await Qw(i)){if(s.name===".git")continue;if(r.length===t0){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 Cn(await vr(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")||r0.compare(s.name,a.name)||s.name.localeCompare(a.name)),{path:e,entries:r,truncated:n}})}function ud(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 wr(t,e,i=i0){return Mn(async()=>{let r=await vr(t,e);if(!(await Cn(r)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await Ua(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=ud(o),c=l?pd: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)),u=0;for(;u<p.length;){let{bytesRead:h}=await n.read(p,u,p.length-u,u);if(!h)break;u+=h}if(u>s.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let m=p.subarray(0,u);if(l)return{...a,kind:"image",mimeType:l,data:m.toString("base64")};if(m.some(h=>h===0||h<32&&![9,10,12,13,27].includes(h)))return{...a,kind:"unsupported"};let g=1;for(let h=0;h<m.length-1;h++)if(m[h]===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:La(m)}}catch{return{...a,kind:"unsupported"}}}finally{await n.close()}})}async function md(t,e){return Mn(async()=>{let i=await vr(t,e);if(!(await Cn(i)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Ua(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>pd)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=ud(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 gd(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}=qa;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 Mn(async()=>{let l=await vr(t,e);if(!(await Cn(l)).isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await Ua(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 u=Buffer.alloc(p.size+1),m=0;for(;m<u.length;){let{bytesRead:h}=await c.read(u,m,u.length-m,m);if(!h)break;m+=h}if(m>p.size||La(u.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:La(n)}}finally{await c.close()}})}var a0=1e3,fd=512*1024,hd=1e4;function yd(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}async function Li(t){let e=await Be(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,u=0;for(let S=0;S<p;S++)u=l.indexOf(" ",u)+1;let m=yd(r,l.slice(u)),g=c==="2"?a[++o]:void 0;if(!m)continue;if(s.entries.length===a0){s.truncated=!0;continue}let h=l.slice(0,u).split(" "),f={path:m,index:c==="?"?"?":h[1][0],worktree:c==="?"?"?":h[1][1],conflict:c==="u",untracked:c==="?",submodule:c!=="?"&&h[2]!=="N..."},v=g===void 0?void 0:yd(r,g);v&&(f.originalPath=v),s.entries.push(f)}return s}async function bd(t,e,i){if(ci(e),!["staged","unstaged","untracked"].includes(i))throw new H("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await Li(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 n0(s0(t,e))).isFile())return{...n,kind:"unsupported"};let o=await wr(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
+ `),c=l.at(-1)==="";c&&l.pop();let p=`--- /dev/null
194
191
  +++ b/${e.replace(/[\r\n]/g," ")}
195
- @@ -0,0 +1,${a.length} @@
196
- ${a.map(d=>`+${d}`).join(`
192
+ @@ -0,0 +1,${l.length} @@
193
+ ${l.map(u=>`+${u}`).join(`
197
194
  `)}
198
195
  ${c?"":`\
199
- `}`;return Buffer.byteLength(p)>zu||a.length>Vu?{...n,kind:"too-large"}:{...n,kind:"text",patch:p}}if(s.untracked||(t==="staged"?s.index:s.worktree)===".")return{...n,kind:"empty"};let o=t==="staged"&&s.originalPath?[e,s.originalPath]:[e];try{let l=await ve(i,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...t==="staged"?["--cached"]:[],"--",...o],zu);return l?l.split(`
200
- `).length>Vu?{...n,kind:"too-large"}:/^Binary files /m.test(l)?{...n,kind:"binary"}:{...n,kind:"text",patch:l}:{...n,kind:"empty"}}catch(l){if(l instanceof X&&l.status===413)return{...n,kind:"too-large"};throw l}}var Wo=new Set,xe=(i,e=409)=>{throw new X("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,i)};async function NS(i){return Qu(ln(i,(await ve(i,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Vo(i,e,t=!1){let r=null;try{let n=await ot(i);n.kind==="repository"&&(r=await NS(n.cwd))}catch(n){if(!t)throw n}if(!r)return e();if(Wo.has(r))return xe("busy");Wo.add(r);try{return await e()}finally{Wo.delete(r)}}async function Es(i){let e=await ot(i),t={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return t;let r=await yr(e.root);if(r.kind!=="repository")return t;let[n,s,o]=await Promise.all([ve(e.cwd,["ls-files","--stage","-z"]),ve(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),ve(e.cwd,["rev-parse","--absolute-git-dir"])]),l=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],a=(await Promise.all(l.map(async b=>{try{return await zo(ln(o.replace(/\n$/,""),b)),b}catch(v){if(v.code==="ENOENT")return null;throw v}}))).filter(Boolean),c=await Promise.all(r.entries.map(async b=>{try{let v=await zo(ln(e.root,b.path));return[b.path,v.size,v.mtimeMs,v.ctimeMs,v.ino,v.mode]}catch(v){if(["ENOENT","ENOTDIR"].includes(v.code??""))return[b.path,"missing"];throw v}})),p=s.split(`
201
- `).filter(Boolean).map(b=>{let[v,,y]=b.split("\0");return{name:v,current:v===r.branch,occupied:!!y&&v!==r.branch}}),d=r.truncated||p.length>512?"too_many_changes":a.includes("index.lock")?"index_locked":a.length||r.entries.some(b=>b.conflict)?"operation_in_progress":null,g=AS("sha256").update(JSON.stringify({head:r.head,branch:r.branch,index:n,refs:s,entries:r.entries,files:c,present:a})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:r.head,branch:r.branch,version:g,staged:r.entries.filter(b=>!b.untracked&&b.index!==".").length,dirty:r.entries.length>0,blocked:d,branches:p.slice(0,512)}}async function CS(i,e){Hi(e);let t=Ku(ln(i.cwd,e));for(;;)try{let s=await Qu(t),o=RS(i.cwd,s);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||OS(o))return xe("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;t=Ku(t)}let r=await yr(i.cwd),n=r.kind==="repository"?r.entries.find(s=>s.path===e):void 0;if(!n||n.submodule||n.conflict)return xe("invalid_path",400);try{let s=await zo(ln(i.cwd,e));if(!s.isFile()&&!s.isSymbolicLink())return xe("invalid_path",400)}catch(s){if(s.code!=="ENOENT")throw s}return n}async function Ju(i,e,t){let r=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(r)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new X("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Vo(i,async()=>{let n=await ot(i);if(n.kind!=="repository")return xe("invalid_path",404);t(n.root);let s=await Es(n.cwd);if(s.version!==e.expected)return xe("state_changed");if(s.blocked)return xe(s.blocked);let o,l;if(r==="stage"||r==="unstage"){if(typeof e.path!="string")return xe("invalid_path",400);let p=await CS(n,e.path);if(r==="stage"&&!p.untracked&&p.worktree==="."||r==="unstage"&&(p.untracked||p.index==="."))return xe("state_changed");let d=[e.path];r==="unstage"&&p.originalPath&&(Hi(p.originalPath),d.push(p.originalPath)),o=r==="stage"?["add","--",...d]:s.head?["restore","--staged","--",...d]:["rm","--cached","-f","--ignore-unmatch","--",...d]}else if(r==="commit"){if(n.scope)return xe("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return xe("invalid_message",400);if(!s.staged)return xe("nothing_staged",400);l=e.message,o=["commit","--file=-","--cleanup=verbatim"]}else{if(!s.head)return xe("no_commits",400);if(typeof e.branch!="string"||!e.branch||e.branch.length>256||e.branch.startsWith("-")||e.branch.startsWith("refs/")||["HEAD","@"].includes(e.branch)||/[\0\r\n]|@\{/.test(e.branch))return xe("invalid_branch",400);try{await ve(n.cwd,["check-ref-format","--branch",e.branch])}catch{return xe("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return xe("invalid_branch",400);let p=s.branches.find(g=>g.name===e.branch),d=r==="switch-branch"||e.checkout===!0;if(r==="create-branch"&&p)return xe("branch_exists");if(r==="switch-branch"&&(!p||p.current))return xe("invalid_branch",400);if(d&&n.scope)return xe("root_required",400);if(d&&s.dirty)return xe("dirty_worktree");if(p?.occupied)return xe("branch_in_use");o=r==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:d?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let a=await Es(n.cwd);if(a.version!==e.expected||a.blocked)return xe(a.blocked??"state_changed");t(n.root),await ve(n.cwd,o,2*1024*1024,{write:!0,input:l});let c=(await ve(n.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:r,head:c}})}import{createHash as PS}from"node:crypto";var cn=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Xu="%H%x00%P%x00%an%x00%aI%x00%s",Zu=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function em(i){let[e,t,r]=await Promise.all([ve(i,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),ve(i,["rev-parse","--verify","--quiet","HEAD"]).then(l=>l.trim(),()=>null),ve(i,["symbolic-ref","-q","HEAD"]).then(l=>l.trim(),()=>null)]),n=[];for(let l of e.split(`
202
- `).filter(Boolean)){let[a,c,p,d,g]=l.split("\0"),b=c==="commit"?p:d==="commit"?g:void 0;if(!b||!cn.test(b))continue;let v=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";n.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:b,kind:v})}if(n.length>512)throw new X("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let s=[...new Set([...n.map(l=>l.hash),...t&&cn.test(t)?[t]:[]])].sort(),o=PS("sha256").update(JSON.stringify({refs:n,head:t,symbolic:r})).digest("hex");return{refs:n,tips:s,head:t,snapshot:o}}function tm(i){let[e,t,r,n,s]=i;if(!e||!cn.test(e)||!t?.split(" ").filter(Boolean).every(o=>cn.test(o)))throw new X("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:t.split(" ").filter(Boolean),author:r,authoredAt:n,subject:s}}async function im(i,e={}){let t=e.limit??50;if(!Number.isInteger(t)||t<1||t>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new X("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let r=await ot(i),n={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return n;let s=await em(r.cwd),o=0;if(e.cursor!==void 0){let d;try{d=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new X("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!d||typeof d.snapshot!="string"||!/^[a-f0-9]{64}$/.test(d.snapshot)||!Number.isInteger(d.offset)||d.offset<1||d.offset>1e4)throw new X("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(d.snapshot!==s.snapshot)throw new X("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);o=d.offset}let l={...n,root:r.root,scope:r.scope,head:s.head,snapshot:s.snapshot,refs:s.refs};if(!s.tips.length)return l;let c=(await ve(r.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${Xu}`,`--max-count=${t+1}`,`--skip=${o}`,...s.tips,"--"])).split("\0");if(c.at(-1)===""&&c.pop(),c.length%5)throw new X("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let p=[];for(let d=0;d<c.length;d+=5)p.push(tm(c.slice(d,d+5)));return l.commits=p.slice(0,t),p.length>t&&o+t<=1e4&&(l.nextCursor=Buffer.from(JSON.stringify({snapshot:s.snapshot,offset:o+t})).toString("base64url")),l}async function rm(i,e){if(typeof e!="string"||!cn.test(e))throw new X("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await ot(i);if(t.kind!=="repository")throw new X("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r=await em(t.cwd);if(!r.tips.length)throw new X("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await ve(t.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await ve(t.cwd,["rev-list","--max-count=1",e,"--not",...r.tips,"--"])).trim())throw new X("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return t}function nm(i,e,t){if(!Number.isInteger(t)||t<0||t>=Math.max(1,e.length))throw new X("\u7236\u63D0\u4EA4\u9009\u62E9\u65E0\u6548");return e.length?[e[t],i]:[i]}async function sm(i,e,t){let n=(await ve(i.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${Xu}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(n.at(-1)===""&&n.pop(),n.length!==10)throw new X("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let s=tm(n.slice(0,5)),o=nm(e,s.parents,t),l=["diff-tree","--root","-r","--no-commit-id",...Zu],[a,c]=await Promise.all([ve(i.cwd,[...l,"--name-status","-z",...o,"--","."]),ve(i.cwd,[...l,"--numstat","-z",...o,"--","."])]),p=new Map;for(let b of c.split("\0").filter(Boolean)){let v=b.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);v&&p.set(v[3],[v[1]==="-"?null:Number(v[1]),v[2]==="-"?null:Number(v[2])])}let d=a.split("\0");if(d.at(-1)===""&&d.pop(),d.length%2)throw new X("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let g=[];for(let b=0;b<d.length&&g.length<1e3;b+=2){let v=d[b+1],[y,S]=p.get(v)??[null,null];g.push({path:v,status:d[b],additions:y,deletions:S})}return{...s,email:n[5],committer:n[6],committerEmail:n[7],committedAt:n[8],message:n[9],root:i.root,scope:i.scope,parentIndex:t,files:g,truncated:d.length>2e3}}async function am(i,e,t=0){return sm(await rm(i,e),e,t)}async function om(i,e,t,r=0){Hi(t);let n=await rm(i,e),s=await sm(n,e,r),o=s.files.find(a=>a.path===t);if(!o)throw new X("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let l={hash:e,path:t,parentIndex:r,parentHash:s.parents[r]??null};if(o.additions===null)return{...l,kind:"binary"};try{let a=await ve(n.cwd,["diff-tree","--root","-r","--no-commit-id",...Zu,"--src-prefix=a/","--dst-prefix=b/","-p",...nm(e,s.parents,r),"--",t],524288);return a.split(`
203
- `).length>1e4?{...l,kind:"too-large"}:a?{...l,kind:"text",patch:a}:{...l,kind:"empty"}}catch(a){if(a instanceof X&&a.status===413)return{...l,kind:"too-large"};throw a}}var lm=["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff"];function cm(i,e,t){if(i.endsWith("/control"))return Es(e);if(i.endsWith("/status"))return yr(e);if(i.endsWith("/history")){if(t.limit!==void 0&&typeof t.limit!="number"||t.cursor!==void 0&&typeof t.cursor!="string")throw new X("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");return im(e,{limit:t.limit,cursor:t.cursor})}if(i.endsWith("/diff")){if(typeof t.path!="string"||!["staged","unstaged","untracked"].includes(t.area))throw new X("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return Yu(e,t.path,t.area)}if(typeof t.hash!="string"||t.parentIndex!==void 0&&(!Number.isInteger(t.parentIndex)||t.parentIndex<0))throw new X("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let r=t.parentIndex;if(i.endsWith("/commit-detail"))return am(e,t.hash,r);if(i.endsWith("/commit-diff")&&typeof t.path=="string")return om(e,t.hash,t.path,r);throw new X("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Is=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),DS=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),pm={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},MS=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),LS=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function dm(i){return i==="/api/message"||i==="/api/prompt-queue"||i.startsWith("/api/provider/")||i.startsWith("/api/workspace/files/")||i.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(i)}function lt(i){return i.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function Tt(i){let e={};for(let t of MS){let r=i[t];t==="toolName"?typeof r=="string"&&(Is.has(r)||r==="custom")&&(e[t]=r):t==="failureKind"?DS.has(r)&&(e[t]=r):t==="level"?(r==="warning"||r==="error")&&(e[t]=r):t==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(e[t]=r):t==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(e[t]=r):t==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(e[t]=r):t==="route"&&typeof r=="string"?e[t]=LS.has(r.split("?")[0])?r.split("?")[0]:"[route]":t==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[t]=r.split("/").map(lt).join("/"):typeof r=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(r)?r:lt(r).slice(0,t==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[t]=r)}return e}function $o(i){let e=i.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function fr(i,e=0){let t=i instanceof Error?i:new Error(typeof i=="string"?i:"Non-Error rejection"),r=new Error(lt(t.message));if(r.name=lt(t.name).slice(0,100),t.stack){let n=t.stack.split(`
204
- `).slice(1,31).map(s=>{let o=s.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${lt(s.slice(0,o.index))}${o[1]}:${o[2]}:${o[3]}${o[4]}`:lt(s)});r.stack=`${r.name}: ${r.message}
196
+ `}`;return Buffer.byteLength(p)>fd||l.length>hd?{...n,kind:"too-large"}:{...n,kind:"text",patch:p}}if(s.untracked||(i==="staged"?s.index:s.worktree)===".")return{...n,kind:"empty"};let a=i==="staged"&&s.originalPath?[e,s.originalPath]:[e];try{let o=await ee(t,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...i==="staged"?["--cached"]:[],"--",...a],fd);return o?o.split(`
197
+ `).length>hd?{...n,kind:"too-large"}:/^Binary files /m.test(o)?{...n,kind:"binary"}:{...n,kind:"text",patch:o}:{...n,kind:"empty"}}catch(o){if(o instanceof H&&o.status===413)return{...n,kind:"too-large"};throw o}}var ja=new Set,se=(t,e=409)=>{throw new H("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,t)};async function p0(t){return vd(Sr(t,(await ee(t,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Fa(t,e,i=!1){let r=null;try{let n=await Be(t);n.kind==="repository"&&(r=await p0(n.cwd))}catch(n){if(!i)throw n}if(!r)return e();if(ja.has(r))return se("busy");ja.add(r);try{return await e()}finally{ja.delete(r)}}async function Dn(t){let e=await Be(t),i={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return i;let r=await Li(e.root);if(r.kind!=="repository")return i;let[n,s,a]=await Promise.all([ee(e.cwd,["ls-files","--stage","-z"]),ee(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),ee(e.cwd,["rev-parse","--absolute-git-dir"])]),o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],l=(await Promise.all(o.map(async g=>{try{return await Ba(Sr(a.replace(/\n$/,""),g)),g}catch(h){if(h.code==="ENOENT")return null;throw h}}))).filter(Boolean),c=await Promise.all(r.entries.map(async g=>{try{let h=await Ba(Sr(e.root,g.path));return[g.path,h.size,h.mtimeMs,h.ctimeMs,h.ino,h.mode]}catch(h){if(["ENOENT","ENOTDIR"].includes(h.code??""))return[g.path,"missing"];throw h}})),p=s.split(`
198
+ `).filter(Boolean).map(g=>{let[h,,f]=g.split("\0");return{name:h,current:h===r.branch,occupied:!!f&&h!==r.branch}}),u=r.truncated||p.length>512?"too_many_changes":l.includes("index.lock")?"index_locked":l.length||r.entries.some(g=>g.conflict)?"operation_in_progress":null,m=o0("sha256").update(JSON.stringify({head:r.head,branch:r.branch,index:n,refs:s,entries:r.entries,files:c,present:l})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:r.head,branch:r.branch,version:m,staged:r.entries.filter(g=>!g.untracked&&g.index!==".").length,dirty:r.entries.length>0,blocked:u,branches:p.slice(0,512)}}async function d0(t,e){ci(e);let i=_d(Sr(t.cwd,e));for(;;)try{let s=await vd(i),a=c0(t.cwd,s);if(a===".."||a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||l0(a))return se("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;i=_d(i)}let r=await Li(t.cwd),n=r.kind==="repository"?r.entries.find(s=>s.path===e):void 0;if(!n||n.submodule||n.conflict)return se("invalid_path",400);try{let s=await Ba(Sr(t.cwd,e));if(!s.isFile()&&!s.isSymbolicLink())return se("invalid_path",400)}catch(s){if(s.code!=="ENOENT")throw s}return n}async function wd(t,e,i){let r=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(r)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new H("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Fa(t,async()=>{let n=await Be(t);if(n.kind!=="repository")return se("invalid_path",404);i(n.root);let s=await Dn(n.cwd);if(s.version!==e.expected)return se("state_changed");if(s.blocked)return se(s.blocked);let a,o;if(r==="stage"||r==="unstage"){if(typeof e.path!="string")return se("invalid_path",400);let p=await d0(n,e.path);if(r==="stage"&&!p.untracked&&p.worktree==="."||r==="unstage"&&(p.untracked||p.index==="."))return se("state_changed");let u=[e.path];r==="unstage"&&p.originalPath&&(ci(p.originalPath),u.push(p.originalPath)),a=r==="stage"?["add","--",...u]:s.head?["restore","--staged","--",...u]:["rm","--cached","-f","--ignore-unmatch","--",...u]}else if(r==="commit"){if(n.scope)return se("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return se("invalid_message",400);if(!s.staged)return se("nothing_staged",400);o=e.message,a=["commit","--file=-","--cleanup=verbatim"]}else{if(!s.head)return se("no_commits",400);if(typeof e.branch!="string"||!e.branch||e.branch.length>256||e.branch.startsWith("-")||e.branch.startsWith("refs/")||["HEAD","@"].includes(e.branch)||/[\0\r\n]|@\{/.test(e.branch))return se("invalid_branch",400);try{await ee(n.cwd,["check-ref-format","--branch",e.branch])}catch{return se("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return se("invalid_branch",400);let p=s.branches.find(m=>m.name===e.branch),u=r==="switch-branch"||e.checkout===!0;if(r==="create-branch"&&p)return se("branch_exists");if(r==="switch-branch"&&(!p||p.current))return se("invalid_branch",400);if(u&&n.scope)return se("root_required",400);if(u&&s.dirty)return se("dirty_worktree");if(p?.occupied)return se("branch_in_use");a=r==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:u?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let l=await Dn(n.cwd);if(l.version!==e.expected||l.blocked)return se(l.blocked??"state_changed");i(n.root),await ee(n.cwd,a,2*1024*1024,{write:!0,input:o});let c=(await ee(n.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:r,head:c}})}import{createHash as u0}from"node:crypto";var kr=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Sd="%H%x00%P%x00%an%x00%aI%x00%s",kd=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function Ed(t){let[e,i,r]=await Promise.all([ee(t,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),ee(t,["rev-parse","--verify","--quiet","HEAD"]).then(o=>o.trim(),()=>null),ee(t,["symbolic-ref","-q","HEAD"]).then(o=>o.trim(),()=>null)]),n=[];for(let o of e.split(`
199
+ `).filter(Boolean)){let[l,c,p,u,m]=o.split("\0"),g=c==="commit"?p:u==="commit"?m:void 0;if(!g||!kr.test(g))continue;let h=l.startsWith("refs/heads/")?"branch":l.startsWith("refs/remotes/")?"remote":"tag";n.push({name:l.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:g,kind:h})}if(n.length>512)throw new H("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let s=[...new Set([...n.map(o=>o.hash),...i&&kr.test(i)?[i]:[]])].sort(),a=u0("sha256").update(JSON.stringify({refs:n,head:i,symbolic:r})).digest("hex");return{refs:n,tips:s,head:i,snapshot:a}}function Td(t){let[e,i,r,n,s]=t;if(!e||!kr.test(e)||!i?.split(" ").filter(Boolean).every(a=>kr.test(a)))throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:i.split(" ").filter(Boolean),author:r,authoredAt:n,subject:s}}async function Id(t,e={}){let i=e.limit??50;if(!Number.isInteger(i)||i<1||i>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let r=await Be(t),n={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return n;let s=await Ed(r.cwd),a=0;if(e.cursor!==void 0){let u;try{u=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!u||typeof u.snapshot!="string"||!/^[a-f0-9]{64}$/.test(u.snapshot)||!Number.isInteger(u.offset)||u.offset<1||u.offset>1e4)throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(u.snapshot!==s.snapshot)throw new H("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);a=u.offset}let o={...n,root:r.root,scope:r.scope,head:s.head,snapshot:s.snapshot,refs:s.refs};if(!s.tips.length)return o;let c=(await ee(r.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${Sd}`,`--max-count=${i+1}`,`--skip=${a}`,...s.tips,"--"])).split("\0");if(c.at(-1)===""&&c.pop(),c.length%5)throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let p=[];for(let u=0;u<c.length;u+=5)p.push(Td(c.slice(u,u+5)));return o.commits=p.slice(0,i),p.length>i&&a+i<=1e4&&(o.nextCursor=Buffer.from(JSON.stringify({snapshot:s.snapshot,offset:a+i})).toString("base64url")),o}async function Ad(t,e){if(typeof e!="string"||!kr.test(e))throw new H("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let i=await Be(t);if(i.kind!=="repository")throw new H("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r=await Ed(i.cwd);if(!r.tips.length)throw new H("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await ee(i.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await ee(i.cwd,["rev-list","--max-count=1",e,"--not",...r.tips,"--"])).trim())throw new H("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return i}function xd(t,e,i){if(!Number.isInteger(i)||i<0||i>=Math.max(1,e.length))throw new H("\u7236\u63D0\u4EA4\u9009\u62E9\u65E0\u6548");return e.length?[e[i],t]:[t]}async function Od(t,e,i){let n=(await ee(t.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${Sd}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(n.at(-1)===""&&n.pop(),n.length!==10)throw new H("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let s=Td(n.slice(0,5)),a=xd(e,s.parents,i),o=["diff-tree","--root","-r","--no-commit-id",...kd],[l,c]=await Promise.all([ee(t.cwd,[...o,"--name-status","-z",...a,"--","."]),ee(t.cwd,[...o,"--numstat","-z",...a,"--","."])]),p=new Map;for(let g of c.split("\0").filter(Boolean)){let h=g.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);h&&p.set(h[3],[h[1]==="-"?null:Number(h[1]),h[2]==="-"?null:Number(h[2])])}let u=l.split("\0");if(u.at(-1)===""&&u.pop(),u.length%2)throw new H("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let m=[];for(let g=0;g<u.length&&m.length<1e3;g+=2){let h=u[g+1],[f,v]=p.get(h)??[null,null];m.push({path:h,status:u[g],additions:f,deletions:v})}return{...s,email:n[5],committer:n[6],committerEmail:n[7],committedAt:n[8],message:n[9],root:t.root,scope:t.scope,parentIndex:i,files:m,truncated:u.length>2e3}}async function Rd(t,e,i=0){return Od(await Ad(t,e),e,i)}async function Nd(t,e,i,r=0){ci(i);let n=await Ad(t,e),s=await Od(n,e,r),a=s.files.find(l=>l.path===i);if(!a)throw new H("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let o={hash:e,path:i,parentIndex:r,parentHash:s.parents[r]??null};if(a.additions===null)return{...o,kind:"binary"};try{let l=await ee(n.cwd,["diff-tree","--root","-r","--no-commit-id",...kd,"--src-prefix=a/","--dst-prefix=b/","-p",...xd(e,s.parents,r),"--",i],524288);return l.split(`
200
+ `).length>1e4?{...o,kind:"too-large"}:l?{...o,kind:"text",patch:l}:{...o,kind:"empty"}}catch(l){if(l instanceof H&&l.status===413)return{...o,kind:"too-large"};throw l}}var Pd=["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff"];function Cd(t,e,i){if(t.endsWith("/control"))return Dn(e);if(t.endsWith("/status"))return Li(e);if(t.endsWith("/history")){if(i.limit!==void 0&&typeof i.limit!="number"||i.cursor!==void 0&&typeof i.cursor!="string")throw new H("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");return Id(e,{limit:i.limit,cursor:i.cursor})}if(t.endsWith("/diff")){if(typeof i.path!="string"||!["staged","unstaged","untracked"].includes(i.area))throw new H("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return bd(e,i.path,i.area)}if(typeof i.hash!="string"||i.parentIndex!==void 0&&(!Number.isInteger(i.parentIndex)||i.parentIndex<0))throw new H("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let r=i.parentIndex;if(t.endsWith("/commit-detail"))return Rd(e,i.hash,r);if(t.endsWith("/commit-diff")&&typeof i.path=="string")return Nd(e,i.hash,i.path,r);throw new H("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Un=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),m0=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Md={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},g0=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),f0=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function Dd(t){return t==="/api/message"||t==="/api/prompt-queue"||t.startsWith("/api/provider/")||t.startsWith("/api/workspace/files/")||t.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(t)}function Fe(t){return t.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function tt(t){let e={};for(let i of g0){let r=t[i];i==="toolName"?typeof r=="string"&&(Un.has(r)||r==="custom")&&(e[i]=r):i==="failureKind"?m0.has(r)&&(e[i]=r):i==="level"?(r==="warning"||r==="error")&&(e[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(e[i]=r):i==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(e[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(e[i]=r):i==="route"&&typeof r=="string"?e[i]=f0.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[i]=r.split("/").map(Fe).join("/"):typeof r=="string"?e[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:Fe(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[i]=r)}return e}function Ha(t){let e=t.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function Ui(t,e=0){let i=t instanceof Error?t:new Error(typeof t=="string"?t:"Non-Error rejection"),r=new Error(Fe(i.message));if(r.name=Fe(i.name).slice(0,100),i.stack){let n=i.stack.split(`
201
+ `).slice(1,31).map(s=>{let a=s.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return a?`${Fe(s.slice(0,a.index))}${a[1]}:${a[2]}:${a[3]}${a[4]}`:Fe(s)});r.stack=`${r.name}: ${r.message}
205
202
  ${n.join(`
206
- `)}`}else r.stack=void 0;return e<3&&t.cause!==void 0&&(r.cause=fr(t.cause,e+1)),r}function ei(i,e){let t=new Error(e);return i instanceof Error&&(t.name=i.name,i.stack&&(t.stack=`${t.name}: ${e}
207
- ${i.stack.split(`
203
+ `)}`}else r.stack=void 0;return e<3&&i.cause!==void 0&&(r.cause=Ui(i.cause,e+1)),r}function Tt(t,e){let i=new Error(e);return t instanceof Error&&(i.name=t.name,t.stack&&(i.stack=`${i.name}: ${e}
204
+ ${t.stack.split(`
208
205
  `).slice(1).join(`
209
- `)}`)),t}function qS(i){return{...i.filename?{filename:$o(i.filename)}:{},...i.abs_path?{abs_path:$o(i.abs_path)}:{},...i.function?{function:lt(i.function)}:{},lineno:i.lineno,colno:i.colno,in_app:i.in_app}}function US(i){let e=Tt(i.contexts?.diagnostic??{}),t=um(e);return{event_id:i.event_id,timestamp:i.timestamp,platform:i.platform,level:i.level,release:i.release,dist:i.dist,environment:lt(i.environment??"production"),...i.message?{message:lt(i.message)}:{},exception:i.exception?{values:i.exception.values?.slice(0,4).map(r=>({type:lt(r.type??"Error"),value:lt(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(qS)}}:{},...r.mechanism?{mechanism:{type:r.mechanism.type,handled:r.mechanism.handled}}:{}}))}:void 0,tags:{side:i.tags?.side,buildId:i.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...t?{fingerprint:t}:{},contexts:{diagnostic:e},breadcrumbs:i.breadcrumbs?.slice(-100).map(r=>({timestamp:r.timestamp,category:lt(r.category??"app"),data:Tt(r.data??{})})),debug_meta:i.debug_meta?{images:i.debug_meta.images?.slice(0,10).map(r=>({type:r.type,debug_id:r.debug_id,...r.code_file?{code_file:$o(r.code_file)}:{}}))}:void 0}}function um(i){if(!(i.stage!=="tool"||i.originalStackAvailable!==!1||!i.toolName||!i.failureKind))return["pi-webapp-tool-result",String(i.toolName),String(i.toolId??"builtin"),String(i.failureKind),String(i.errorCode??"unknown")]}function mm(i,e){return e.attachments=[],US(i)}var pn=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let r={timestamp:Date.now()/1e3,category:lt(e),data:Tt(t)},n=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:n}),this.bytes+=n;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},Yo=class{windowAt=-1;total=0;seen=new Map;take(e,t=Date.now()){(this.windowAt<0||t-this.windowAt>=6e4)&&(this.windowAt=t,this.total=0);let r=this.seen.get(e);if(r&&t-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:t,repeats:0}),{repeats:r?.repeats??0}}},jS=new Set(["\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0","\u4F1A\u8BDD\u5DF2\u5207\u6362","Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u4F1A\u8BDD","\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A","\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88","\u5DF2\u6709\u767B\u5F55\u6B63\u5728\u8FDB\u884C","\u6A21\u578B\u4E0D\u53EF\u7528","\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6","\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55","\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279","\u8BF7\u5148\u9009\u62E9\u6A21\u578B","\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B","\u63D2\u4EF6\u672A\u542F\u7528","\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362","\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728","\u6587\u4EF6\u8D85\u8FC7 20 MB","\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927","\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A","\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548","\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F","\u4F1A\u8BDD\u4E0D\u5B58\u5728","\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664","\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664"]);function Wi(i){return i instanceof Error&&(i.name==="AbortError"||jS.has(i.message))}var Ts=class{budget=new Yo;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,r,n,s=new pn){this.client=e,this.side=t,this.buildId=r,this.scopeClass=n.Scope,this.breadcrumbs=s,e.addIntegration(n.linkedErrorsIntegration({limit:4}))}setState(e){this.state=Tt(e)}capture(e,t={},r){try{if(Wi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let n=fr(e),s=Tt({...this.state,...t}),o=um(s),l=o?JSON.stringify(o):`${n.name}:${n.message}:${n.stack?.split(`
210
- `)[1]??""}:${t.stage??""}`,a=this.budget.take(l);if(!a)return;let c=new this.scopeClass;c.setClient(this.client),c.setTags({side:this.side,buildId:this.buildId}),s.level==="warning"&&c.setLevel("warning"),o&&c.setFingerprint(o),c.setContext("diagnostic",{...s,repeats:a.repeats});for(let p of this.breadcrumbs.snapshot())c.addBreadcrumb(p,100);return c.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function gm(i,e){return i({...e,bufferSize:20},async({body:t})=>{let r=await fetch(e.url,{method:"POST",body:t,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}var bm={metadata:Mu,routes:lm,coordinateStart:(i,e)=>Vo(i,e,!0),requestFailure:i=>i instanceof X?{status:i.status,body:{error:i.message,errorCode:"validation_error",reason:i.reason}}:null,async handle({path:i,body:e,snapshot:t,busyWorkspaces:r,json:n}){let s=t();if(e.sessionId!==s.sessionId){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let o=p=>!t().idle||r().some(d=>{let g=(b,v)=>{let y=FS(b,v);return y!==".."&&!y.startsWith("../")&&!y.startsWith("..\\")&&!BS(y)};return g(p,d)||g(d,p)}),l=p=>{let d=t();if(d.sessionId!==s.sessionId||d.cwd!==s.cwd)throw new X("\u4F1A\u8BDD\u5DF2\u5207\u6362",409,"session_changed");if(o(p))throw new X("\u5171\u7528\u6B64\u5DE5\u4F5C\u6811\u7684\u804A\u5929\u6B63\u5728\u8FD0\u884C",409,"agent_busy")},a=i.endsWith("/write"),c=a?await Ju(s.cwd,e,l):await cm(i,s.cwd,e);if(!a){let p=t();if(p.sessionId!==s.sessionId||p.cwd!==s.cwd){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(i.endsWith("/control")){let d=c;d.root&&o(d.root)&&(d.blocked??="agent_busy")}}n(200,c)}catch(o){if(o instanceof X||o instanceof be)n(o.status,{error:o.message,errorCode:"validation_error",...o instanceof X?{reason:o.reason}:{}});else throw ei(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var hm={id:at.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u3001\u641C\u7D22\u5DE5\u4F5C\u533A\u6587\u4EF6\uFF0C\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\uFF0C\u5E76\u7F16\u8F91\u6587\u672C\u6587\u4EF6\u3002",en:"Browse and search workspace files, preview code, Markdown and images, and edit text files."}};import{lstat as GS,open as HS,opendir as WS,realpath as zS}from"node:fs/promises";import{join as _m}from"node:path";var VS=5e3,Ko=2e4,ym=100,fm=200,$S=5e3,YS=512*1024,KS=4e3,QS=240,JS=new Set([".git","node_modules",".hg",".svn"]);function XS(i,e){return e.startsWith(i)&&e.slice(i.length)||void 0}function ZS(i,e){return i==="D"||e==="D"?i==="A"?"added":"deleted":i==="A"&&(e==="."||e==="M")?"added":"modified"}async function vm(i){let e;try{e=await ot(i)}catch(s){if(s instanceof X)return{kind:"unavailable",entries:[],truncated:!1};throw s}if(e.kind!=="repository")return{kind:e.kind,entries:[],truncated:!1};let t;try{t=await ve(e.cwd,["status","--porcelain=v2","-z","--untracked-files=normal","--ignored=matching","--","."],8*1024*1024)}catch(s){if(s instanceof X)return{kind:"unavailable",entries:[],truncated:!1};throw s}let r={kind:"repository",entries:[],truncated:!1},n=t.split("\0");for(let s=0;s<n.length;s++){let o=n[s],l=o[0];if(!["1","2","u","?","!"].includes(l??""))continue;let a=l==="?"||l==="!"?1:l==="1"?8:l==="2"?9:10,c=0;for(let b=0;b<a;b++)c=o.indexOf(" ",c)+1;l==="2"&&s++;let p=XS(e.scope,o.slice(c));if(!p)continue;if(r.entries.length===VS){r.truncated=!0;break}let d=o.slice(2,4),g=l==="?"?"untracked":l==="!"?"ignored":l==="u"?"conflict":ZS(d[0],d[1]);r.entries.push({path:p,state:g})}return r}async function eE(i){let e=await zS(i),t;try{t=await ot(e)}catch{t=void 0}if(t?.kind==="repository")try{let o=(await ve(e,["ls-files","-z","--cached","--others","--exclude-standard","--deduplicate","--","."],33554432)).split("\0").filter(Boolean);return{root:e,paths:o.slice(0,Ko),truncated:o.length>Ko}}catch(s){if(!(s instanceof X))throw s}let r=[],n=[""];for(;n.length;){let s=n.shift(),o;try{o=await WS(_m(e,s))}catch{continue}for await(let l of o){let a=s?`${s}/${l.name}`:l.name;if(l.isDirectory())JS.has(l.name)||n.push(a);else if(l.isFile()){if(r.length===Ko)return{root:e,paths:r,truncated:!0};r.push(a)}}}return{root:e,paths:r,truncated:!1}}function tE(i,e){let t=i.toLowerCase(),r=t.slice(t.lastIndexOf("/")+1);if(r===e)return 0;if(r.startsWith(e))return 1;if(r.includes(e))return 2;if(t.includes(e))return 3;let n=0;for(let s of e)if(n=t.indexOf(s,n)+1,!n)return;return 4}async function km(i,e,t){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new be("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(t!=="name"&&t!=="content")throw new be("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:n,paths:s,truncated:o}=await eE(i);if(t==="name"){let d=s.flatMap(g=>{let b=tE(g,r);return b===void 0?[]:[{path:g,score:b}]}).sort((g,b)=>g.score-b.score||g.path.length-b.path.length||g.path.localeCompare(b.path));return{kind:"name",results:d.slice(0,ym).map(({path:g})=>({path:g})),truncated:o||d.length>ym}}let l=[],a=Date.now()+KS,c=0,p=o;for(let d of s){if(l.length>=fm||c>=$S||Date.now()>a){p=!0;break}let g=_m(n,d);try{let b=await GS(g);if(!b.isFile()||b.size===0||b.size>YS)continue;c++;let v=await HS(g,"r"),y;try{y=await v.readFile()}finally{await v.close()}if(y.includes(0))continue;let S=y.toString("utf8").split(`
211
- `);for(let T=0;T<S.length;T++){let I=S[T],x=I.toLowerCase().indexOf(r);if(x<0)continue;let P=Math.max(0,x-60);if(l.push({path:d,line:T+1,text:(P?"\u2026":"")+I.slice(P,P+QS).replace(/\r$/u,"")}),l.length>=fm)break}}catch{}}return{kind:"content",results:l,truncated:p}}var wm={metadata:hm,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search"],async handle({path:i,body:e,snapshot:t,json:r,res:n}){let s=t();if(e.sessionId!==s.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let o=i.slice(i.lastIndexOf("/")+1);if(!(o==="status"||o==="search")&&(typeof e.path!="string"||e.path.length>4096)){r(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}let a=e.path,c=()=>{let p=t();return p.sessionId!==s.sessionId||p.cwd!==s.cwd};try{if(o==="raw"){let d=await Hu(s.cwd,a);if(c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}n.writeHead(200,{"Content-Type":d.mimeType,"Content-Length":d.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),n.end(d.bytes);return}if(o==="write"&&c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let p=o==="list"?await Fu(s.cwd,a):o==="write"?await Wu(s.cwd,a,e.text,e.version):o==="status"?await vm(s.cwd):o==="search"?await km(s.cwd,e.query,e.mode):await on(s.cwd,a,Ho);if(o!=="write"&&c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r(200,p)}catch(p){if(p instanceof be)r(p.status,{error:p.message,errorCode:"validation_error",...p.reason?{reason:p.reason}:{}});else throw ei(p,o==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var Sm={id:at.terminal,kind:"builtin",version:"1.0.0",name:{zh:"\u7EC8\u7AEF",en:"Terminal"},description:{zh:"\u5728\u5DE5\u4F5C\u533A\u8FD0\u884C\u4EA4\u4E92\u5F0F Shell\u3002\u505C\u7528\u4F1A\u7ED3\u675F\u6B64\u670D\u52A1\u7684\u6240\u6709\u7EC8\u7AEF\u8FDB\u7A0B\u3002",en:"Run an interactive shell in the workspace. Disabling ends all terminals on this service."}};import{accessSync as Im,constants as Qo,statSync as xm}from"node:fs";import{createRequire as pE}from"node:module";import{execFile as Am}from"node:child_process";import{accessSync as iE,chmodSync as rE,constants as nE,statSync as sE}from"node:fs";import{createRequire as aE}from"node:module";import{dirname as oE,join as lE}from"node:path";var Em=aE(import.meta.url);function cE(i){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=lE(i,e,"spawn-helper"),r;try{r=sE(t).mode}catch(n){if(n.code==="ENOENT")continue;throw n}try{iE(t,nE.X_OK)}catch{rE(t,r|73)}}}function Tm(...i){return cE(oE(Em.resolve("node-pty/package.json"))),Em("node-pty").spawn(...i)}var ti=class extends Error{reason;constructor(e,t,r){super(t,{cause:r}),this.reason=e}},Om=pE(import.meta.url),Jo=class{pid;pty;screen;serializer;followers=new Set;outputListeners=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,t,r,n,s,o,l,a){this.sessionId=e,this.abandoned=l,this.graceMs=a;let{Terminal:c}=Om("@xterm/headless"),{SerializeAddon:p}=Om("@xterm/addon-serialize");this.screen=new c({cols:r,rows:n,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let d=Object.fromEntries(Object.entries(process.env).filter(([g,b])=>b!==void 0&&!/^PI_WEBAPP_RESTART_/.test(g)));try{this.pty=Tm(s,o,{name:"xterm-256color",cwd:t,cols:r,rows:n,env:{...d,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(g){throw this.screen.dispose(),new ti("terminal_runtime_unavailable","\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684 node-pty \u4F9D\u8D56",g)}this.pid=this.pty.pid,this.screen.onData(g=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(g)}),this.pty.onData(g=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(b=>{if(this.disposed){b();return}this.screen.write(g,()=>{this.broadcast({type:"output",data:g});for(let v of this.outputListeners)v(g);b()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(g=>this.pty.onExit(({exitCode:b,signal:v})=>{this.exit={type:"exit",exitCode:b,signal:v},this.pending.then(()=>{this.broadcast(this.exit);for(let y of this.outputListeners)y("");g()})})),this.scheduleExpiry()}broadcast(e){for(let t of this.followers)t(e)||this.followers.delete(t);this.followers.size||this.scheduleExpiry()}scheduleExpiry(){this.expire||this.disposed||(this.expire=setTimeout(this.abandoned,this.graceMs).unref())}async attach(e){if(await this.pending,this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u5173\u95ED");return clearTimeout(this.expire),this.expire=void 0,e({type:"snapshot",screen:this.serializer.serialize(),cols:this.screen.cols,rows:this.screen.rows})?(this.exit&&e(this.exit),this.followers.add(e)):this.scheduleExpiry(),()=>{this.followers.delete(e),this.followers.size||this.scheduleExpiry()}}write(e){if(this.exit||this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u9000\u51FA");this.pty.write(e)}get exitCode(){return this.exit?.exitCode}get running(){return!this.exit&&!this.disposed}settle(e,t,r,n){return new Promise(s=>{let o,l="",a=!n,c=()=>{clearTimeout(o),clearTimeout(d),this.outputListeners.delete(p),r?.removeEventListener("abort",c),s()},p=g=>{if(!this.running){c();return}!a&&l.length<64*1024&&(l+=g,a=n(l)),clearTimeout(o),a&&(o=setTimeout(c,e))},d=setTimeout(c,t);this.outputListeners.add(p),r?.addEventListener("abort",c,{once:!0}),r?.aborted?c():p("")})}async text(e){if(await this.pending,this.disposed)throw new Error("Terminal closed");let t=this.screen.buffer.active,r=t.length-1;for(;r>=0&&!t.getLine(r)?.translateToString(!0).trim();)r--;let n=[];for(let s=Math.max(0,r-e*4);s<=r;s++){let o=t.getLine(s);if(!o)continue;let l=o.translateToString(!0);o.isWrapped&&n.length?n[n.length-1]+=l:n.push(l)}return n.slice(-e).join(`
212
- `)}resize(e,t){this.exit||this.disposed||(this.pty.resize(e,t),this.pending=this.pending.then(()=>{this.disposed||(this.screen.resize(e,t),this.broadcast({type:"resize",cols:e,rows:t}))}))}close(){return this.closing??=this.dispose()}async dispose(){if(this.disposed=!0,clearTimeout(this.expire),!this.exit){if(process.platform==="win32")await new Promise(e=>Am("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(n=>Am("ps",["-axo","pid=,ppid="],(s,o)=>n(s?"":o)))).trim().split(`
213
- `).map(n=>n.trim().split(/\s+/).map(Number)),r=n=>t.filter(([,s])=>s===n).flatMap(([s])=>[...r(s),s]);for(let n of[...r(this.pid),this.pid])try{process.kill(n,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending;for(let e of this.outputListeners)e("");this.followers.clear(),this.screen.dispose()}},xs=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,t,r,n,s){if(this.stopped)throw new Error("\u7EC8\u7AEF\u670D\u52A1\u5DF2\u505C\u6B62");if(this.terminals.has(e))return this.get(e,t);if(this.terminals.size>=32||[...this.terminals.values()].filter(c=>c.sessionId===t).length>=8)throw new ti("terminal_limit","\u7EC8\u7AEF\u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u5173\u95ED\u4E0D\u7528\u7684\u7EC8\u7AEF");let o=this.options.shell??(process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/sh");try{if(Im(o,Qo.X_OK),!xm(o).isFile())throw new Error("Not a shell file")}catch(c){throw new ti("terminal_shell_unavailable","\u9ED8\u8BA4 shell \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u6267\u884C\uFF0C\u8BF7\u4FEE\u6B63 SHELL\uFF08Windows \u4E3A COMSPEC\uFF09\u540E\u91CD\u542F\u5E94\u7528",c)}try{if(!xm(r).isDirectory())throw new Error("Not a directory");Im(r,Qo.R_OK|Qo.X_OK)}catch(c){throw new ti("terminal_workspace_unavailable","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8BF7\u5207\u6362\u5230\u6709\u6548\u5DE5\u4F5C\u533A\u540E\u65B0\u5EFA\u7EC8\u7AEF",c)}let l=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),a=new Jo(t,r,n,s,o,l,()=>{this.remove(e,t)},this.options.graceMs??5*6e4);return this.terminals.set(e,a),a}get(e,t){let r=this.terminals.get(e);if(!r||r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return r}resolve(e,t){if(e!==void 0)return{id:e,terminal:this.get(e,t)};let r=[...this.terminals].filter(([,n])=>n.sessionId===t&&n.running);if(r.length===1)return{id:r[0][0],terminal:r[0][1]};throw new Error(r.length?`This session has ${r.length} open terminals (${r.map(([n])=>n).join(", ")}); pass terminalId.`:"This session has no open terminal. Ask the user to open one in the workspace panel.")}async remove(e,t){let r=this.terminals.get(e);if(r){if(r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await r.close(),this.terminals.get(e)===r&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var Rm=(i,e)=>Number.isInteger(i)&&Number.isInteger(e)&&Number(i)>=2&&Number(i)<=500&&Number(e)>=1&&Number(e)<=300,Nm="terminal-input";async function Cm(i,e,t,r,n,s){let o=(c,p)=>{t.writeHead(c,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(p))};if(typeof e.id!="string"||!/^[a-f0-9-]{36}$/i.test(e.id)){o(400,{error:"\u7EC8\u7AEF\u6807\u8BC6\u65E0\u6548"});return}let l=i.slice(14),a=r();if(l!=="close"&&e.sessionId!==a.sessionId){o(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((l==="create"||l==="resize")&&!Rm(e.cols,e.rows)){o(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(l==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){o(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(l==="create"){n.create(e.id,e.sessionId,a.cwd,e.cols,e.rows),o(201,{id:e.id});return}if(l==="close"){await n.remove(e.id,e.sessionId),o(200,{closed:!0});return}let c=n.get(e.id,e.sessionId);if(l==="attach"){let p=!1,d;t.once("close",()=>{p=!0,d?.(),s.delete(t)}),d=await c.attach(g=>p?!1:(t.headersSent||t.writeHead(200,{"Content-Type":"application/x-ndjson","Cache-Control":"no-store","X-Accel-Buffering":"no"}),t.writableLength>1024*1024?(t.destroy(),!1):(t.write(`${JSON.stringify(g)}
214
- `),!0))),p?d():s.add(t);return}if(l==="input")c.write(e.data);else if(l==="resize")c.resize(e.cols,e.rows);else{o(404,{error:"\u672A\u77E5\u7EC8\u7AEF\u64CD\u4F5C"});return}o(200,{accepted:!0})}catch(c){t.headersSent?t.end():o(400,{error:c instanceof ti?c.message:l==="create"?"\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684\u7EC8\u7AEF\u4F9D\u8D56":"\u7EC8\u7AEF\u4E0D\u53EF\u7528\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF",reason:c instanceof ti?c.reason:l==="create"?"terminal_runtime_unavailable":void 0})}}var dE=/^[a-f0-9-]{36}$/i,Pm=32*1024,uE=300,mE=3e4,Lm=i=>i<32||i>=127&&i<=159,qm=i=>{if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid terminal tool input");return i};function Um(i){if(i!==void 0){if(typeof i!="string"||!dE.test(i))throw new Error("terminalId must be the terminal tab's contentId");return i}}function Xo(i,e,t,r,n){if(i===void 0)return e;if(!Number.isInteger(i)||i<t||i>r)throw new Error(`${n} must be an integer from ${t} to ${r}`);return i}function Os(i){let e=qm(i);if(typeof e.text!="string")throw new Error("text must be a string");let t=e.text.replace(/\r\n?/g,`
215
- `);if(Buffer.byteLength(t)>4096)throw new Error(`text is longer than ${4096} bytes`);if([...t].some(n=>n!==" "&&n!==`
216
- `&&Lm(n.charCodeAt(0))))throw new Error("text may not contain control characters other than tab and newline");if(e.enter!==void 0&&typeof e.enter!="boolean")throw new Error("enter must be a boolean");let r=e.enter??!0;if(!t&&!r)throw new Error("Nothing to send");return{terminalId:Um(e.terminalId),text:t,enter:r,waitMs:Xo(e.waitMs,3e3,0,mE,"waitMs"),lines:Xo(e.lines,40,1,500,"lines")}}function Dm(i){let e="";for(let t=0;t<i.length;t++){let r=i.charCodeAt(t);if(r===27){let n=i[t+1];if(n==="]"){for(t+=2;t<i.length&&i.charCodeAt(t)!==7&&i.charCodeAt(t)!==27;)t++;i.charCodeAt(t)===27&&t++}else if(n==="[")for(t+=2;t<i.length&&(i.charCodeAt(t)<64||i.charCodeAt(t)>126);)t++;else t+=n==="("||n===")"?2:1;continue}r===8?e=e.slice(0,-1):!Lm(r)&&!/\s/u.test(i[t])&&(e+=i[t])}return e}var gE=i=>{let e=Dm(i);return t=>{let r=Dm(t);return!!r&&!e.startsWith(r)}};async function Mm(i,e,t){let r=await e.text(t),n=r.length>Pm;return{terminalId:i,output:n?r.slice(-Pm):r,truncated:n,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}}async function jm(i,e,t,r,n){if(t==="prepare"){let s=Os(r),{id:o,terminal:l}=i.resolve(s.terminalId,e);if(!l.running)throw new Error("The terminal's shell has exited. Ask the user to open a new terminal.");return{terminalId:o}}if(t==="send"){let s=Os(r);if(!s.terminalId)throw new Error("terminalId is required");let{id:o,terminal:l}=i.resolve(s.terminalId,e);return n?.throwIfAborted(),l.write(s.text.replace(/\n/g,"\r")+(s.enter?"\r":"")),s.waitMs&&await l.settle(uE,s.waitMs,n,gE(s.text)),Mm(o,l,s.lines)}if(t==="read"){let s=qm(r),{id:o,terminal:l}=i.resolve(Um(s.terminalId),e);return Mm(o,l,Xo(s.lines,100,1,500,"lines"))}throw new Error(`Unknown terminal action: ${t}`)}function Bm(){let i=new xs,e=new Set,t=async()=>{for(let r of e)r.end();e.clear(),await i.clear()};return{metadata:Sm,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),agentAction:(r,n,s,o,l)=>jm(i,n,s,o,l),handle:r=>Cm(r.path,r.body,r.res,r.snapshot,i,e),restartBlocker:()=>i.size?`\u6709 ${i.size} \u4E2A\u7EC8\u7AEF\u6B63\u5728\u8FD0\u884C\uFF0C\u5347\u7EA7\u4F1A\u5173\u95ED\u5B83\u4EEC`:null,releaseForRestart:t,disable:t,async close(){await t(),await i.close()}}}import{randomUUID as bE}from"node:crypto";import{Type as ht}from"@earendil-works/pi-ai";var Fm=ht.String({pattern:"^[a-fA-F0-9-]{36}$",description:`The terminal tab's contentId, for example from the [pi-web workspace tab in view] line of kind "terminal". Optional when this session has exactly one open terminal.`}),Gm=i=>ht.Optional(ht.Integer({minimum:1,maximum:500,description:`How many trailing lines of the terminal to return (default ${i}).`}));function Hm(i,e=""){let t=i.exitCode===void 0?"":` The shell has exited with code ${i.exitCode}.`;return{content:[{type:"text",text:`${e}Terminal ${i.terminalId}${i.truncated?" (output truncated to the most recent part)":""}:${t}
217
- ${i.output}`}],details:i}}function Wm(i){return[{name:"terminal_send",label:"terminal_send",description:`Type a command into one of the user's open workspace terminal tabs (their live interactive shell) and return the terminal's recent output. Use this when the user asks you to run something in "this"/"the" terminal they are looking at; for your own work use bash instead. The user must approve each call in the Web UI before anything is typed, so send one complete command at a time and do not assume it ran if the call fails. Enter is pressed after the text unless enter is false. Output is read after the terminal is quiet for a moment or waitMs passes; for long-running commands call terminal_read later.`,parameters:ht.Object({terminalId:ht.Optional(Fm),text:ht.String({maxLength:4096,description:"Text to type. Newlines separate lines; no other control characters."}),enter:ht.Optional(ht.Boolean({description:"Press Enter after the text (default true)."})),waitMs:ht.Optional(ht.Integer({minimum:0,maximum:3e4,description:"Longest time to wait for output before returning (default 3000)."})),lines:Gm(40)}),async execute(e,t,r,n,s){r?.throwIfAborted();let o=s.sessionManager.getSessionId(),l=Os(t),{terminalId:a}=await i.run(s.cwd,o,"prepare",t,r),c={terminalId:a,text:l.text,enter:l.enter},p=await i.ask({requestId:bE(),sessionId:o,pluginId:at.terminal,kind:Nm,data:c},r);if(!p||typeof p!="object"||p.allow!==!0)throw new Error("The user declined; nothing was typed into the terminal.");return Hm(await i.run(s.cwd,o,"send",{...l,terminalId:a},r),"Sent after the user approved. ")}},{name:"terminal_read",label:"terminal_read",description:"Read the recent text of one of the user's open workspace terminal tabs (scrollback included, plain text). Use it to see what the user is looking at in a terminal or to check on a command started with terminal_send. Does not type anything.",parameters:ht.Object({terminalId:ht.Optional(Fm),lines:Gm(100)}),async execute(e,t,r,n,s){return r?.throwIfAborted(),Hm(await i.run(s.cwd,s.sessionManager.getSessionId(),"read",t,r))}}]}function zm(i){let e={run:(...t)=>i.run(at.terminal,...t),ask:i.ask};return Wm(e)}function Vm(){return[wm,Bm(),bm]}import{createHash as hE,randomUUID as yE}from"node:crypto";import{mkdir as fE,open as _E,readFile as vE,rename as kE,rm as $m,writeFile as wE}from"node:fs/promises";import{dirname as SE}from"node:path";var De=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},Ns=class i{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await vE(this.file,"utf8"));if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("disabled"in e)||!Array.isArray(e.disabled)||!e.disabled.every(t=>typeof t=="string"&&t.length>0&&t.length<=200))throw new De("\u63D2\u4EF6\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u4FEE\u590D\u914D\u7F6E\u540E\u91CD\u542F",503);this.disabled=new Set(e.disabled)}catch(e){if(e.code!=="ENOENT")throw e}}enabled(e){return!this.disabled.has(e)}revision(){return hE("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,t,r,n){if(this.changing)throw new De("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let s=`${this.file}.${yE()}.tmp`,o=`${this.file}.lock`,l;try{if(r!==this.revision())throw new De("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");n();let a=new Set(this.disabled);t?a.delete(e):a.add(e),await fE(SE(this.file),{recursive:!0});try{l=await _E(o,"wx",384)}catch(p){throw p.code==="EEXIST"?new De("\u63D2\u4EF6\u914D\u7F6E\u9501\u5B9A\u6587\u4EF6\u4ECD\u5B58\u5728\uFF0C\u5237\u65B0\u4E0D\u4F1A\u89E3\u9664\u3002\u8BF7\u5148\u505C\u6B62\u4F7F\u7528\u6B64\u914D\u7F6E\u7684\u5168\u90E8 Pi \u670D\u52A1\uFF0C\u518D\u5220\u9664 pi-web/plugins.json.lock \u540E\u91CD\u542F\uFF1B\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u670D\u52A1\u7684\u9501"):p}await l.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
218
- `);let c=new i(this.file);if(await c.load(),c.revision()!==r)throw new De("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await wE(s,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
219
- `,{mode:384}),n(),await kE(s,this.file),this.disabled=a}finally{this.changing=!1;try{await $m(s,{force:!0})}finally{l&&(await l.close(),await $m(o,{force:!0}))}}}};var Cs=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,t){if(this.plugins=e,this.preferences=t,this.routes=e.flatMap(r=>[...r.routes]),new Set(e.map(r=>r.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,t){return this.plugins.find(r=>r.metadata.id===e)?.routes.find(r=>r.split("/").at(-1)===t&&!r.endsWith("/attach"))}external(e){let t=new Set(this.plugins.map(r=>r.metadata.id));return{plugins:e.plugins.filter(r=>!t.has(r.id)),errors:[...e.errors,...e.plugins.filter(r=>t.has(r.id)).map(r=>`Plugin ID reserved by host: ${r.id}`)]}}catalog(e){let t=this.external(e);return{...t,plugins:[...this.plugins.filter(r=>this.preferences.enabled(r.metadata.id)).map(r=>({id:r.metadata.id,client:`builtin:${r.metadata.id}`})),...t.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(t=>({...t.metadata,enabled:this.preferences.enabled(t.metadata.id),managed:!0})),...this.external(e).plugins.map(t=>({id:t.id,name:t.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,t,r,n){if(!this.plugins.some(s=>s.metadata.id===e))throw new De("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(s=>s>0))throw new De("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,t,r,n),t||await this.plugins.find(s=>s.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let t=this.plugins.find(n=>n.routes.includes(e.path));if(!t)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(t.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let r=t.metadata.id;this.running.set(r,(this.running.get(r)??0)+1);try{await t.handle(e)}finally{this.running.set(r,this.running.get(r)-1)}return!0}async runAgentAction(e,t,r,n,s,o){let l=this.plugins.find(a=>a.metadata.id===e);if(!l?.agentAction||!this.preferences.enabled(e))throw new De("\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new De("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await l.agentAction(t,r,n,s,o)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,t){if(this.changing)throw new De("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let n=t;for(let s of this.plugins)if(s.coordinateStart&&this.preferences.enabled(s.metadata.id)){let o=n;n=()=>s.coordinateStart(e,o)}try{return await n()}finally{this.running.set(r,this.running.get(r)-1)}}requestFailure(e){if(e instanceof De)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let t of this.plugins){let r=t.requestFailure?.(e);if(r)return r}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as EE,opendir as TE,stat as IE}from"node:fs/promises";import{homedir as xE}from"node:os";import{basename as AE,dirname as Ym,join as Km,posix as OE,resolve as Qm,win32 as RE}from"node:path";function Jm(i){return process.platform==="win32"?RE.isAbsolute(i)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(i):OE.isAbsolute(i)}function NE(i,e,t){if(i.length===t&&e.name.localeCompare(i[i.length-1].name)>=0)return!0;let r=0,n=i.length;for(;r<n;){let s=r+n>>>1;e.name.localeCompare(i[s].name)<0?n=s:r=s+1}return i.splice(r,0,e),i.length<=t?!1:(i.pop(),!0)}async function Xm(i){if(i!==void 0&&!Jm(i))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=xE(),t=Qm(i??e),r=[];for(let a=t;;a=Ym(a)){let c=Ym(a);if(r.unshift({name:c===a?a:AE(a),path:a,hidden:!1}),c===a)break}let n=[],s=!1,o=await TE(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||NE(n,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(s=!0);let l=[];for(let a of n){let c=Km(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await IE(c)).isDirectory())continue}catch{continue}if(l.length===1e3){s=!0;break}l.push({name:a.name,path:c,hidden:a.name.startsWith(".")})}return{path:t,home:e,crumbs:r,entries:l,truncated:s}}async function Zm(i,e){if(!Jm(i))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let t=Km(Qm(i),e);return await EE(t),t}import{execFile as CE}from"node:child_process";import{accessSync as PE,constants as DE}from"node:fs";import{delimiter as ME,join as LE}from"node:path";var qE=(i,e,t)=>new Promise((r,n)=>{CE(i,[...e],{encoding:"utf8",signal:t,windowsHide:!0},(s,o,l)=>{s?n(Object.assign(new Error(s.message,{cause:s}),{code:s.code,stdout:o,stderr:l})):r({stdout:o,stderr:l})})});function UE(i){for(let e of(i??"").split(ME))if(e)for(let t of["zenity","kdialog"])try{return PE(LE(e,t),DE.X_OK),!0}catch{}return!1}function eg(i=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":i==="darwin"||i==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&UE(e.PATH)?"native":"browse"}function Ps(i){if(!(typeof i!="object"||i===null||!("code"in i)))return typeof i.code=="string"||typeof i.code=="number"?i.code:void 0}function jE(i){return typeof i=="object"&&i!==null&&"stderr"in i&&typeof i.stderr=="string"?i.stderr:""}function Zo(i){return i.replace(/[\r\n]+$/,"")||null}async function tg(i,e=process.platform,t=qE){if(e==="darwin")try{let r=await t("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],i);return Zo(r.stdout)}catch(r){if(!i.aborted&&Ps(r)===1&&/(?:User canceled|-128)/i.test(jE(r)))return null;throw r}if(e==="linux"){try{return Zo((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],i)).stdout)}catch(r){if(i.aborted)throw r;if(Ps(r)===1)return null;if(Ps(r)!=="ENOENT")throw r}try{return Zo((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],i)).stdout)}catch(r){if(i.aborted)throw r;if(Ps(r)===1)return null;throw r}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as BE,randomUUID as FE}from"node:crypto";import{mkdir as GE,readFile as HE,writeFile as WE}from"node:fs/promises";import{join as ig}from"node:path";import{getAgentDir as zE}from"@earendil-works/pi-coding-agent";var Ds=20*1024*1024,rg=20,VE=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function $E(i){let e=i.indexOf("."),t=(e<0?i:i.slice(0,e)).replace(/[. ]+$/u,"");return VE.test(t)}function YE(i,e){let t=0,r="";for(let n of Buffer.from(i).toString("utf8")){let s=Buffer.byteLength(n);if(t+s>e)break;r+=n,t+=s}return r}function KE(i){if(i===void 0)return"file";let t=i.slice(Math.max(i.lastIndexOf("/"),i.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return $E(t)&&(t=`_${t}`),t=YE(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function QE(i){return i.length>=8&&i.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":i.length>=3&&i.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":i.length>=6&&["GIF87a","GIF89a"].includes(i.toString("ascii",0,6))?"image/gif":i.length>=12&&i.toString("ascii",0,4)==="RIFF"&&i.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function ng(i,e,t,r){if(r.byteLength===0||r.byteLength>Ds)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let n=KE(e),s=BE("sha256").update(r).digest("hex"),o=ig(zE(),"pi-web","attachments",s);await GE(o,{recursive:!0});let l=ig(o,n);try{await WE(l,r,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:FE(),name:n,bytes:r.byteLength,path:l,mediaType:QE(r)??t.replace(/^image\//,"application/"),sessionId:i}}async function sg(i){return{type:"image",data:(await HE(i.path)).toString("base64"),mimeType:i.mediaType}}import{randomBytes as JE}from"node:crypto";function ag(i,e,t){return i!=="openai-codex"||e!=="oauth"?t:{...t,prompt:r=>r.type==="select"&&r.options.some(n=>n.id==="browser")&&r.options.some(n=>n.id==="device_code")?Promise.resolve("browser"):t.prompt(r)}}var Ms=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,t,r,n,s){let o=this.getActive();if(o){if(o.providerId===e&&o.method===t&&n===void 0)return o;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let l=JE(18).toString("base64url"),a={view:{id:l,providerId:e,method:t,status:"running"},controller:new AbortController};return this.flows.set(l,a),r(e,t,{signal:a.controller.signal,notify:c=>{a.view={...a.view,event:c,...c.type==="auth_url"||c.type==="device_code"?{authorization:c}:{}}},prompt:c=>{if(c.type==="secret"&&n!==void 0){let p=n;return n=void 0,Promise.resolve(p)}return new Promise((p,d)=>{let{signal:g,...b}=c;a.answer=p,a.reject=d,a.view={...a.view,status:"waiting",prompt:b},g?.aborted?d(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):g?.addEventListener("abort",()=>d(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{a.view.status!=="cancelled"&&(a.view={id:l,providerId:e,method:t,status:"done"})}).catch(c=>{if(a.view.status!=="cancelled"){let p=new Error("Provider login failed");c instanceof Error&&c.stack&&(p.stack=`${p.message}
206
+ `)}`)),i}function h0(t){return{...t.filename?{filename:Ha(t.filename)}:{},...t.abs_path?{abs_path:Ha(t.abs_path)}:{},...t.function?{function:Fe(t.function)}:{},lineno:t.lineno,colno:t.colno,in_app:t.in_app}}function y0(t){let e=tt(t.contexts?.diagnostic??{}),i=Ld(e);return{event_id:t.event_id,timestamp:t.timestamp,platform:t.platform,level:t.level,release:t.release,dist:t.dist,environment:Fe(t.environment??"production"),...t.message?{message:Fe(t.message)}:{},exception:t.exception?{values:t.exception.values?.slice(0,4).map(r=>({type:Fe(r.type??"Error"),value:Fe(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(h0)}}:{},...r.mechanism?{mechanism:{type:r.mechanism.type,handled:r.mechanism.handled}}:{}}))}:void 0,tags:{side:t.tags?.side,buildId:t.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...i?{fingerprint:i}:{},contexts:{diagnostic:e},breadcrumbs:t.breadcrumbs?.slice(-100).map(r=>({timestamp:r.timestamp,category:Fe(r.category??"app"),data:tt(r.data??{})})),debug_meta:t.debug_meta?{images:t.debug_meta.images?.slice(0,10).map(r=>({type:r.type,debug_id:r.debug_id,...r.code_file?{code_file:Ha(r.code_file)}:{}}))}:void 0}}function Ld(t){if(!(t.stage!=="tool"||t.originalStackAvailable!==!1||!t.toolName||!t.failureKind))return["pi-webapp-tool-result",String(t.toolName),String(t.toolId??"builtin"),String(t.failureKind),String(t.errorCode??"unknown")]}function Ud(t,e){return e.attachments=[],y0(t)}var Er=class{items=[];bytes=0;encoder=new TextEncoder;add(e,i={}){let r={timestamp:Date.now()/1e3,category:Fe(e),data:tt(i)},n=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:n}),this.bytes+=n;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},Ga=class{windowAt=-1;total=0;seen=new Map;take(e,i=Date.now()){(this.windowAt<0||i-this.windowAt>=6e4)&&(this.windowAt=i,this.total=0);let r=this.seen.get(e);if(r&&i-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:i,repeats:0}),{repeats:r?.repeats??0}}},b0=new Set(["\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0","\u4F1A\u8BDD\u5DF2\u5207\u6362","Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u4F1A\u8BDD","\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A","\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88","\u5DF2\u6709\u767B\u5F55\u6B63\u5728\u8FDB\u884C","\u6A21\u578B\u4E0D\u53EF\u7528","\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6","\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55","\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279","\u8BF7\u5148\u9009\u62E9\u6A21\u578B","\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B","\u63D2\u4EF6\u672A\u542F\u7528","\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362","\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728","\u6587\u4EF6\u8D85\u8FC7 20 MB","\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927","\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A","\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548","\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F","\u4F1A\u8BDD\u4E0D\u5B58\u5728","\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664","\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664"]);function pi(t){return t instanceof Error&&(t.name==="AbortError"||b0.has(t.message))}var Ln=class{budget=new Ga;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,i,r,n,s=new Er){this.client=e,this.side=i,this.buildId=r,this.scopeClass=n.Scope,this.breadcrumbs=s,e.addIntegration(n.linkedErrorsIntegration({limit:4}))}setState(e){this.state=tt(e)}capture(e,i={},r){try{if(pi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let n=Ui(e),s=tt({...this.state,...i}),a=Ld(s),o=a?JSON.stringify(a):`${n.name}:${n.message}:${n.stack?.split(`
207
+ `)[1]??""}:${i.stage??""}`,l=this.budget.take(o);if(!l)return;let c=new this.scopeClass;c.setClient(this.client),c.setTags({side:this.side,buildId:this.buildId}),s.level==="warning"&&c.setLevel("warning"),a&&c.setFingerprint(a),c.setContext("diagnostic",{...s,repeats:l.repeats});for(let p of this.breadcrumbs.snapshot())c.addBreadcrumb(p,100);return c.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function qd(t,e){return t({...e,bufferSize:20},async({body:i})=>{let r=await fetch(e.url,{method:"POST",body:i,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}var jd={metadata:sd,routes:Pd,coordinateStart:(t,e)=>Fa(t,e,!0),requestFailure:t=>t instanceof H?{status:t.status,body:{error:t.message,errorCode:"validation_error",reason:t.reason}}:null,async handle({path:t,body:e,snapshot:i,busyWorkspaces:r,json:n}){let s=i();if(e.sessionId!==s.sessionId){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let a=p=>!i().idle||r().some(u=>{let m=(g,h)=>{let f=v0(g,h);return f!==".."&&!f.startsWith("../")&&!f.startsWith("..\\")&&!_0(f)};return m(p,u)||m(u,p)}),o=p=>{let u=i();if(u.sessionId!==s.sessionId||u.cwd!==s.cwd)throw new H("\u4F1A\u8BDD\u5DF2\u5207\u6362",409,"session_changed");if(a(p))throw new H("\u5171\u7528\u6B64\u5DE5\u4F5C\u6811\u7684\u804A\u5929\u6B63\u5728\u8FD0\u884C",409,"agent_busy")},l=t.endsWith("/write"),c=l?await wd(s.cwd,e,o):await Cd(t,s.cwd,e);if(!l){let p=i();if(p.sessionId!==s.sessionId||p.cwd!==s.cwd){n(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(t.endsWith("/control")){let u=c;u.root&&a(u.root)&&(u.blocked??="agent_busy")}}n(200,c)}catch(a){if(a instanceof H||a instanceof X)n(a.status,{error:a.message,errorCode:"validation_error",...a instanceof H?{reason:a.reason}:{}});else throw Tt(a,"Git \u64CD\u4F5C\u5931\u8D25")}}};var Bd={id:je.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u3001\u641C\u7D22\u5DE5\u4F5C\u533A\u6587\u4EF6\uFF0C\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\uFF0C\u5E76\u7F16\u8F91\u6587\u672C\u6587\u4EF6\u3002",en:"Browse and search workspace files, preview code, Markdown and images, and edit text files."}};import{lstat as w0,open as S0,opendir as k0,realpath as E0}from"node:fs/promises";import{join as Gd}from"node:path";var T0=5e3,Wa=2e4,Fd=100,Hd=200,I0=5e3,A0=512*1024,x0=4e3,O0=240,R0=new Set([".git","node_modules",".hg",".svn"]);function N0(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}function P0(t,e){return t==="D"||e==="D"?t==="A"?"added":"deleted":t==="A"&&(e==="."||e==="M")?"added":"modified"}async function Wd(t){let e;try{e=await Be(t)}catch(s){if(s instanceof H)return{kind:"unavailable",entries:[],truncated:!1};throw s}if(e.kind!=="repository")return{kind:e.kind,entries:[],truncated:!1};let i;try{i=await ee(e.cwd,["status","--porcelain=v2","-z","--untracked-files=normal","--ignored=matching","--","."],8*1024*1024)}catch(s){if(s instanceof H)return{kind:"unavailable",entries:[],truncated:!1};throw s}let r={kind:"repository",entries:[],truncated:!1},n=i.split("\0");for(let s=0;s<n.length;s++){let a=n[s],o=a[0];if(!["1","2","u","?","!"].includes(o??""))continue;let l=o==="?"||o==="!"?1:o==="1"?8:o==="2"?9:10,c=0;for(let g=0;g<l;g++)c=a.indexOf(" ",c)+1;o==="2"&&s++;let p=N0(e.scope,a.slice(c));if(!p)continue;if(r.entries.length===T0){r.truncated=!0;break}let u=a.slice(2,4),m=o==="?"?"untracked":o==="!"?"ignored":o==="u"?"conflict":P0(u[0],u[1]);r.entries.push({path:p,state:m})}return r}async function C0(t){let e=await E0(t),i;try{i=await Be(e)}catch{i=void 0}if(i?.kind==="repository")try{let a=(await ee(e,["ls-files","-z","--cached","--others","--exclude-standard","--deduplicate","--","."],33554432)).split("\0").filter(Boolean);return{root:e,paths:a.slice(0,Wa),truncated:a.length>Wa}}catch(s){if(!(s instanceof H))throw s}let r=[],n=[""];for(;n.length;){let s=n.shift(),a;try{a=await k0(Gd(e,s))}catch{continue}for await(let o of a){let l=s?`${s}/${o.name}`:o.name;if(o.isDirectory())R0.has(o.name)||n.push(l);else if(o.isFile()){if(r.length===Wa)return{root:e,paths:r,truncated:!0};r.push(l)}}}return{root:e,paths:r,truncated:!1}}function M0(t,e){let i=t.toLowerCase(),r=i.slice(i.lastIndexOf("/")+1);if(r===e)return 0;if(r.startsWith(e))return 1;if(r.includes(e))return 2;if(i.includes(e))return 3;let n=0;for(let s of e)if(n=i.indexOf(s,n)+1,!n)return;return 4}async function $d(t,e,i){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new X("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(i!=="name"&&i!=="content")throw new X("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:n,paths:s,truncated:a}=await C0(t);if(i==="name"){let u=s.flatMap(m=>{let g=M0(m,r);return g===void 0?[]:[{path:m,score:g}]}).sort((m,g)=>m.score-g.score||m.path.length-g.path.length||m.path.localeCompare(g.path));return{kind:"name",results:u.slice(0,Fd).map(({path:m})=>({path:m})),truncated:a||u.length>Fd}}let o=[],l=Date.now()+x0,c=0,p=a;for(let u of s){if(o.length>=Hd||c>=I0||Date.now()>l){p=!0;break}let m=Gd(n,u);try{let g=await w0(m);if(!g.isFile()||g.size===0||g.size>A0)continue;c++;let h=await S0(m,"r"),f;try{f=await h.readFile()}finally{await h.close()}if(f.includes(0))continue;let v=f.toString("utf8").split(`
208
+ `);for(let S=0;S<v.length;S++){let E=v[S],O=E.toLowerCase().indexOf(r);if(O<0)continue;let L=Math.max(0,O-60);if(o.push({path:u,line:S+1,text:(L?"\u2026":"")+E.slice(L,L+O0).replace(/\r$/u,"")}),o.length>=Hd)break}}catch{}}return{kind:"content",results:o,truncated:p}}var Vd={metadata:Bd,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search"],async handle({path:t,body:e,snapshot:i,json:r,res:n}){let s=i();if(e.sessionId!==s.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let a=t.slice(t.lastIndexOf("/")+1);if(!(a==="status"||a==="search")&&(typeof e.path!="string"||e.path.length>4096)){r(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}let l=e.path,c=()=>{let p=i();return p.sessionId!==s.sessionId||p.cwd!==s.cwd};try{if(a==="raw"){let u=await md(s.cwd,l);if(c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}n.writeHead(200,{"Content-Type":u.mimeType,"Content-Length":u.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),n.end(u.bytes);return}if(a==="write"&&c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let p=a==="list"?await dd(s.cwd,l):a==="write"?await gd(s.cwd,l,e.text,e.version):a==="status"?await Wd(s.cwd):a==="search"?await $d(s.cwd,e.query,e.mode):await wr(s.cwd,l,qa);if(a!=="write"&&c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r(200,p)}catch(p){if(p instanceof X)r(p.status,{error:p.message,errorCode:"validation_error",...p.reason?{reason:p.reason}:{}});else throw Tt(p,a==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var zd={id:je.terminal,kind:"builtin",version:"1.0.0",name:{zh:"\u7EC8\u7AEF",en:"Terminal"},description:{zh:"\u5728\u5DE5\u4F5C\u533A\u8FD0\u884C\u4EA4\u4E92\u5F0F Shell\u3002\u505C\u7528\u4F1A\u7ED3\u675F\u6B64\u670D\u52A1\u7684\u6240\u6709\u7EC8\u7AEF\u8FDB\u7A0B\u3002",en:"Run an interactive shell in the workspace. Disabling ends all terminals on this service."}};import{accessSync as Qd,constants as $a,statSync as Jd}from"node:fs";import{createRequire as G0}from"node:module";import{execFile as Xd}from"node:child_process";import{accessSync as D0,chmodSync as L0,constants as U0,statSync as q0}from"node:fs";import{createRequire as j0}from"node:module";import{dirname as B0,join as F0}from"node:path";var Kd=j0(import.meta.url);function H0(t){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let i=F0(t,e,"spawn-helper"),r;try{r=q0(i).mode}catch(n){if(n.code==="ENOENT")continue;throw n}try{D0(i,U0.X_OK)}catch{L0(i,r|73)}}}function Yd(...t){return H0(B0(Kd.resolve("node-pty/package.json"))),Kd("node-pty").spawn(...t)}var It=class extends Error{reason;constructor(e,i,r){super(i,{cause:r}),this.reason=e}},Zd=G0(import.meta.url),Va=class{pid;pty;screen;serializer;followers=new Set;outputListeners=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,i,r,n,s,a,o,l){this.sessionId=e,this.abandoned=o,this.graceMs=l;let{Terminal:c}=Zd("@xterm/headless"),{SerializeAddon:p}=Zd("@xterm/addon-serialize");this.screen=new c({cols:r,rows:n,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let u=Object.fromEntries(Object.entries(process.env).filter(([m,g])=>g!==void 0&&!/^PI_WEBAPP_RESTART_/.test(m)));try{this.pty=Yd(s,a,{name:"xterm-256color",cwd:i,cols:r,rows:n,env:{...u,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(m){throw this.screen.dispose(),new It("terminal_runtime_unavailable","\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684 node-pty \u4F9D\u8D56",m)}this.pid=this.pty.pid,this.screen.onData(m=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(m)}),this.pty.onData(m=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(g=>{if(this.disposed){g();return}this.screen.write(m,()=>{this.broadcast({type:"output",data:m});for(let h of this.outputListeners)h(m);g()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(m=>this.pty.onExit(({exitCode:g,signal:h})=>{this.exit={type:"exit",exitCode:g,signal:h},this.pending.then(()=>{this.broadcast(this.exit);for(let f of this.outputListeners)f("");m()})})),this.scheduleExpiry()}broadcast(e){for(let i of this.followers)i(e)||this.followers.delete(i);this.followers.size||this.scheduleExpiry()}scheduleExpiry(){this.expire||this.disposed||(this.expire=setTimeout(this.abandoned,this.graceMs).unref())}async attach(e){if(await this.pending,this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u5173\u95ED");return clearTimeout(this.expire),this.expire=void 0,e({type:"snapshot",screen:this.serializer.serialize(),cols:this.screen.cols,rows:this.screen.rows})?(this.exit&&e(this.exit),this.followers.add(e)):this.scheduleExpiry(),()=>{this.followers.delete(e),this.followers.size||this.scheduleExpiry()}}write(e){if(this.exit||this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u9000\u51FA");this.pty.write(e)}get exitCode(){return this.exit?.exitCode}get running(){return!this.exit&&!this.disposed}settle(e,i,r,n){return new Promise(s=>{let a,o="",l=!n,c=()=>{clearTimeout(a),clearTimeout(u),this.outputListeners.delete(p),r?.removeEventListener("abort",c),s()},p=m=>{if(!this.running){c();return}!l&&o.length<64*1024&&(o+=m,l=n(o)),clearTimeout(a),l&&(a=setTimeout(c,e))},u=setTimeout(c,i);this.outputListeners.add(p),r?.addEventListener("abort",c,{once:!0}),r?.aborted?c():p("")})}async text(e){if(await this.pending,this.disposed)throw new Error("Terminal closed");let i=this.screen.buffer.active,r=i.length-1;for(;r>=0&&!i.getLine(r)?.translateToString(!0).trim();)r--;let n=[];for(let s=Math.max(0,r-e*4);s<=r;s++){let a=i.getLine(s);if(!a)continue;let o=a.translateToString(!0);a.isWrapped&&n.length?n[n.length-1]+=o:n.push(o)}return n.slice(-e).join(`
209
+ `)}resize(e,i){this.exit||this.disposed||(this.pty.resize(e,i),this.pending=this.pending.then(()=>{this.disposed||(this.screen.resize(e,i),this.broadcast({type:"resize",cols:e,rows:i}))}))}close(){return this.closing??=this.dispose()}async dispose(){if(this.disposed=!0,clearTimeout(this.expire),!this.exit){if(process.platform==="win32")await new Promise(e=>Xd("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let i=(await new Promise(n=>Xd("ps",["-axo","pid=,ppid="],(s,a)=>n(s?"":a)))).trim().split(`
210
+ `).map(n=>n.trim().split(/\s+/).map(Number)),r=n=>i.filter(([,s])=>s===n).flatMap(([s])=>[...r(s),s]);for(let n of[...r(this.pid),this.pid])try{process.kill(n,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending;for(let e of this.outputListeners)e("");this.followers.clear(),this.screen.dispose()}},qn=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,i,r,n,s){if(this.stopped)throw new Error("\u7EC8\u7AEF\u670D\u52A1\u5DF2\u505C\u6B62");if(this.terminals.has(e))return this.get(e,i);if(this.terminals.size>=32||[...this.terminals.values()].filter(c=>c.sessionId===i).length>=8)throw new It("terminal_limit","\u7EC8\u7AEF\u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u5173\u95ED\u4E0D\u7528\u7684\u7EC8\u7AEF");let a=this.options.shell??(process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/sh");try{if(Qd(a,$a.X_OK),!Jd(a).isFile())throw new Error("Not a shell file")}catch(c){throw new It("terminal_shell_unavailable","\u9ED8\u8BA4 shell \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u6267\u884C\uFF0C\u8BF7\u4FEE\u6B63 SHELL\uFF08Windows \u4E3A COMSPEC\uFF09\u540E\u91CD\u542F\u5E94\u7528",c)}try{if(!Jd(r).isDirectory())throw new Error("Not a directory");Qd(r,$a.R_OK|$a.X_OK)}catch(c){throw new It("terminal_workspace_unavailable","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8BF7\u5207\u6362\u5230\u6709\u6548\u5DE5\u4F5C\u533A\u540E\u65B0\u5EFA\u7EC8\u7AEF",c)}let o=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),l=new Va(i,r,n,s,a,o,()=>{this.remove(e,i)},this.options.graceMs??5*6e4);return this.terminals.set(e,l),l}get(e,i){let r=this.terminals.get(e);if(!r||r.sessionId!==i)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return r}resolve(e,i){if(e!==void 0)return{id:e,terminal:this.get(e,i)};let r=[...this.terminals].filter(([,n])=>n.sessionId===i&&n.running);if(r.length===1)return{id:r[0][0],terminal:r[0][1]};throw new Error(r.length?`This session has ${r.length} open terminals (${r.map(([n])=>n).join(", ")}); pass terminalId.`:"This session has no open terminal. Ask the user to open one in the workspace panel.")}async remove(e,i){let r=this.terminals.get(e);if(r){if(r.sessionId!==i)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await r.close(),this.terminals.get(e)===r&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var eu=(t,e)=>Number.isInteger(t)&&Number.isInteger(e)&&Number(t)>=2&&Number(t)<=500&&Number(e)>=1&&Number(e)<=300,tu="terminal-input";async function iu(t,e,i,r,n,s){let a=(c,p)=>{i.writeHead(c,{"Content-Type":"application/json","Cache-Control":"no-store"}),i.end(JSON.stringify(p))};if(typeof e.id!="string"||!/^[a-f0-9-]{36}$/i.test(e.id)){a(400,{error:"\u7EC8\u7AEF\u6807\u8BC6\u65E0\u6548"});return}let o=t.slice(14),l=r();if(o!=="close"&&e.sessionId!==l.sessionId){a(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((o==="create"||o==="resize")&&!eu(e.cols,e.rows)){a(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(o==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){a(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(o==="create"){n.create(e.id,e.sessionId,l.cwd,e.cols,e.rows),a(201,{id:e.id});return}if(o==="close"){await n.remove(e.id,e.sessionId),a(200,{closed:!0});return}let c=n.get(e.id,e.sessionId);if(o==="attach"){let p=!1,u;i.once("close",()=>{p=!0,u?.(),s.delete(i)}),u=await c.attach(m=>p?!1:(i.headersSent||i.writeHead(200,{"Content-Type":"application/x-ndjson","Cache-Control":"no-store","X-Accel-Buffering":"no"}),i.writableLength>1024*1024?(i.destroy(),!1):(i.write(`${JSON.stringify(m)}
211
+ `),!0))),p?u():s.add(i);return}if(o==="input")c.write(e.data);else if(o==="resize")c.resize(e.cols,e.rows);else{a(404,{error:"\u672A\u77E5\u7EC8\u7AEF\u64CD\u4F5C"});return}a(200,{accepted:!0})}catch(c){i.headersSent?i.end():a(400,{error:c instanceof It?c.message:o==="create"?"\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684\u7EC8\u7AEF\u4F9D\u8D56":"\u7EC8\u7AEF\u4E0D\u53EF\u7528\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF",reason:c instanceof It?c.reason:o==="create"?"terminal_runtime_unavailable":void 0})}}var W0=/^[a-f0-9-]{36}$/i,ru=32*1024,$0=300,V0=3e4,au=t=>t<32||t>=127&&t<=159,ou=t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid terminal tool input");return t};function lu(t){if(t!==void 0){if(typeof t!="string"||!W0.test(t))throw new Error("terminalId must be the terminal tab's contentId");return t}}function za(t,e,i,r,n){if(t===void 0)return e;if(!Number.isInteger(t)||t<i||t>r)throw new Error(`${n} must be an integer from ${i} to ${r}`);return t}function Bn(t){let e=ou(t);if(typeof e.text!="string")throw new Error("text must be a string");let i=e.text.replace(/\r\n?/g,`
212
+ `);if(Buffer.byteLength(i)>4096)throw new Error(`text is longer than ${4096} bytes`);if([...i].some(n=>n!==" "&&n!==`
213
+ `&&au(n.charCodeAt(0))))throw new Error("text may not contain control characters other than tab and newline");if(e.enter!==void 0&&typeof e.enter!="boolean")throw new Error("enter must be a boolean");let r=e.enter??!0;if(!i&&!r)throw new Error("Nothing to send");return{terminalId:lu(e.terminalId),text:i,enter:r,waitMs:za(e.waitMs,3e3,0,V0,"waitMs"),lines:za(e.lines,40,1,500,"lines")}}function nu(t){let e="";for(let i=0;i<t.length;i++){let r=t.charCodeAt(i);if(r===27){let n=t[i+1];if(n==="]"){for(i+=2;i<t.length&&t.charCodeAt(i)!==7&&t.charCodeAt(i)!==27;)i++;t.charCodeAt(i)===27&&i++}else if(n==="[")for(i+=2;i<t.length&&(t.charCodeAt(i)<64||t.charCodeAt(i)>126);)i++;else i+=n==="("||n===")"?2:1;continue}r===8?e=e.slice(0,-1):!au(r)&&!/\s/u.test(t[i])&&(e+=t[i])}return e}var z0=t=>{let e=nu(t);return i=>{let r=nu(i);return!!r&&!e.startsWith(r)}};async function su(t,e,i){let r=await e.text(i),n=r.length>ru;return{terminalId:t,output:n?r.slice(-ru):r,truncated:n,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}}async function cu(t,e,i,r,n){if(i==="prepare"){let s=Bn(r),{id:a,terminal:o}=t.resolve(s.terminalId,e);if(!o.running)throw new Error("The terminal's shell has exited. Ask the user to open a new terminal.");return{terminalId:a}}if(i==="send"){let s=Bn(r);if(!s.terminalId)throw new Error("terminalId is required");let{id:a,terminal:o}=t.resolve(s.terminalId,e);return n?.throwIfAborted(),o.write(s.text.replace(/\n/g,"\r")+(s.enter?"\r":"")),s.waitMs&&await o.settle($0,s.waitMs,n,z0(s.text)),su(a,o,s.lines)}if(i==="read"){let s=ou(r),{id:a,terminal:o}=t.resolve(lu(s.terminalId),e);return su(a,o,za(s.lines,100,1,500,"lines"))}throw new Error(`Unknown terminal action: ${i}`)}function pu(){let t=new qn,e=new Set,i=async()=>{for(let r of e)r.end();e.clear(),await t.clear()};return{metadata:zd,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),agentAction:(r,n,s,a,o)=>cu(t,n,s,a,o),handle:r=>iu(r.path,r.body,r.res,r.snapshot,t,e),restartBlocker:()=>t.size?`\u6709 ${t.size} \u4E2A\u7EC8\u7AEF\u6B63\u5728\u8FD0\u884C\uFF0C\u5347\u7EA7\u4F1A\u5173\u95ED\u5B83\u4EEC`:null,releaseForRestart:i,disable:i,async close(){await i(),await t.close()}}}import{randomUUID as K0}from"node:crypto";import{Type as Ye}from"@earendil-works/pi-ai";var du=Ye.String({pattern:"^[a-fA-F0-9-]{36}$",description:`The terminal tab's contentId, for example from the [pi-web workspace tab in view] line of kind "terminal". Optional when this session has exactly one open terminal.`}),uu=t=>Ye.Optional(Ye.Integer({minimum:1,maximum:500,description:`How many trailing lines of the terminal to return (default ${t}).`}));function mu(t,e=""){let i=t.exitCode===void 0?"":` The shell has exited with code ${t.exitCode}.`;return{content:[{type:"text",text:`${e}Terminal ${t.terminalId}${t.truncated?" (output truncated to the most recent part)":""}:${i}
214
+ ${t.output}`}],details:t}}function gu(t){return[{name:"terminal_send",label:"terminal_send",description:`Type a command into one of the user's open workspace terminal tabs (their live interactive shell) and return the terminal's recent output. Use this when the user asks you to run something in "this"/"the" terminal they are looking at; for your own work use bash instead. The user must approve each call in the Web UI before anything is typed, so send one complete command at a time and do not assume it ran if the call fails. Enter is pressed after the text unless enter is false. Output is read after the terminal is quiet for a moment or waitMs passes; for long-running commands call terminal_read later.`,parameters:Ye.Object({terminalId:Ye.Optional(du),text:Ye.String({maxLength:4096,description:"Text to type. Newlines separate lines; no other control characters."}),enter:Ye.Optional(Ye.Boolean({description:"Press Enter after the text (default true)."})),waitMs:Ye.Optional(Ye.Integer({minimum:0,maximum:3e4,description:"Longest time to wait for output before returning (default 3000)."})),lines:uu(40)}),async execute(e,i,r,n,s){r?.throwIfAborted();let a=s.sessionManager.getSessionId(),o=Bn(i),{terminalId:l}=await t.run(s.cwd,a,"prepare",i,r),c={terminalId:l,text:o.text,enter:o.enter},p=await t.ask({requestId:K0(),sessionId:a,pluginId:je.terminal,kind:tu,data:c},r);if(!p||typeof p!="object"||p.allow!==!0)throw new Error("The user declined; nothing was typed into the terminal.");return mu(await t.run(s.cwd,a,"send",{...o,terminalId:l},r),"Sent after the user approved. ")}},{name:"terminal_read",label:"terminal_read",description:"Read the recent text of one of the user's open workspace terminal tabs (scrollback included, plain text). Use it to see what the user is looking at in a terminal or to check on a command started with terminal_send. Does not type anything.",parameters:Ye.Object({terminalId:Ye.Optional(du),lines:uu(100)}),async execute(e,i,r,n,s){return r?.throwIfAborted(),mu(await t.run(s.cwd,s.sessionManager.getSessionId(),"read",i,r))}}]}function fu(t){let e={run:(...i)=>t.run(je.terminal,...i),ask:t.ask};return gu(e)}function hu(){return[Vd,pu(),jd]}import{createHash as Y0,randomUUID as Q0}from"node:crypto";import{mkdir as J0,open as X0,readFile as Z0,rename as eS,rm as yu,writeFile as tS}from"node:fs/promises";import{dirname as iS}from"node:path";var be=class extends Error{status;constructor(e,i=409){super(e),this.status=i}},Hn=class t{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Z0(this.file,"utf8"));if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("disabled"in e)||!Array.isArray(e.disabled)||!e.disabled.every(i=>typeof i=="string"&&i.length>0&&i.length<=200))throw new be("\u63D2\u4EF6\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u4FEE\u590D\u914D\u7F6E\u540E\u91CD\u542F",503);this.disabled=new Set(e.disabled)}catch(e){if(e.code!=="ENOENT")throw e}}enabled(e){return!this.disabled.has(e)}revision(){return Y0("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,i,r,n){if(this.changing)throw new be("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let s=`${this.file}.${Q0()}.tmp`,a=`${this.file}.lock`,o;try{if(r!==this.revision())throw new be("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");n();let l=new Set(this.disabled);i?l.delete(e):l.add(e),await J0(iS(this.file),{recursive:!0});try{o=await X0(a,"wx",384)}catch(p){throw p.code==="EEXIST"?new be("\u63D2\u4EF6\u914D\u7F6E\u9501\u5B9A\u6587\u4EF6\u4ECD\u5B58\u5728\uFF0C\u5237\u65B0\u4E0D\u4F1A\u89E3\u9664\u3002\u8BF7\u5148\u505C\u6B62\u4F7F\u7528\u6B64\u914D\u7F6E\u7684\u5168\u90E8 Pi \u670D\u52A1\uFF0C\u518D\u5220\u9664 pi-web/plugins.json.lock \u540E\u91CD\u542F\uFF1B\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u670D\u52A1\u7684\u9501"):p}await o.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
215
+ `);let c=new t(this.file);if(await c.load(),c.revision()!==r)throw new be("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await tS(s,JSON.stringify({version:1,disabled:[...l].sort()},null,2)+`
216
+ `,{mode:384}),n(),await eS(s,this.file),this.disabled=l}finally{this.changing=!1;try{await yu(s,{force:!0})}finally{o&&(await o.close(),await yu(a,{force:!0}))}}}};var Gn=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,i){if(this.plugins=e,this.preferences=i,this.routes=e.flatMap(r=>[...r.routes]),new Set(e.map(r=>r.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,i){return this.plugins.find(r=>r.metadata.id===e)?.routes.find(r=>r.split("/").at(-1)===i&&!r.endsWith("/attach"))}external(e){let i=new Set(this.plugins.map(r=>r.metadata.id));return{plugins:e.plugins.filter(r=>!i.has(r.id)),errors:[...e.errors,...e.plugins.filter(r=>i.has(r.id)).map(r=>`Plugin ID reserved by host: ${r.id}`)]}}catalog(e){let i=this.external(e);return{...i,plugins:[...this.plugins.filter(r=>this.preferences.enabled(r.metadata.id)).map(r=>({id:r.metadata.id,client:`builtin:${r.metadata.id}`})),...i.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(i=>({...i.metadata,enabled:this.preferences.enabled(i.metadata.id),managed:!0})),...this.external(e).plugins.map(i=>({id:i.id,name:i.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,i,r,n){if(!this.plugins.some(s=>s.metadata.id===e))throw new be("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(s=>s>0))throw new be("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,i,r,n),i||await this.plugins.find(s=>s.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let i=this.plugins.find(n=>n.routes.includes(e.path));if(!i)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(i.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let r=i.metadata.id;this.running.set(r,(this.running.get(r)??0)+1);try{await i.handle(e)}finally{this.running.set(r,this.running.get(r)-1)}return!0}async runAgentAction(e,i,r,n,s,a){let o=this.plugins.find(l=>l.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new be("\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new be("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(i,r,n,s,a)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,i){if(this.changing)throw new be("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let n=i;for(let s of this.plugins)if(s.coordinateStart&&this.preferences.enabled(s.metadata.id)){let a=n;n=()=>s.coordinateStart(e,a)}try{return await n()}finally{this.running.set(r,this.running.get(r)-1)}}requestFailure(e){if(e instanceof be)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let i of this.plugins){let r=i.requestFailure?.(e);if(r)return r}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as rS,opendir as nS,stat as sS}from"node:fs/promises";import{homedir as aS}from"node:os";import{basename as oS,dirname as bu,join as _u,posix as lS,resolve as vu,win32 as cS}from"node:path";function wu(t){return process.platform==="win32"?cS.isAbsolute(t)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(t):lS.isAbsolute(t)}function pS(t,e,i){if(t.length===i&&e.name.localeCompare(t[t.length-1].name)>=0)return!0;let r=0,n=t.length;for(;r<n;){let s=r+n>>>1;e.name.localeCompare(t[s].name)<0?n=s:r=s+1}return t.splice(r,0,e),t.length<=i?!1:(t.pop(),!0)}async function Su(t){if(t!==void 0&&!wu(t))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=aS(),i=vu(t??e),r=[];for(let l=i;;l=bu(l)){let c=bu(l);if(r.unshift({name:c===l?l:oS(l),path:l,hidden:!1}),c===l)break}let n=[],s=!1,a=await nS(i);for await(let l of a)!l.isDirectory()&&!l.isSymbolicLink()||pS(n,{name:l.name,isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()},1001)&&(s=!0);let o=[];for(let l of n){let c=_u(i,l.name);if(!l.isDirectory&&l.isSymbolicLink)try{if(!(await sS(c)).isDirectory())continue}catch{continue}if(o.length===1e3){s=!0;break}o.push({name:l.name,path:c,hidden:l.name.startsWith(".")})}return{path:i,home:e,crumbs:r,entries:o,truncated:s}}async function ku(t,e){if(!wu(t))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let i=_u(vu(t),e);return await rS(i),i}import{execFile as dS}from"node:child_process";import{accessSync as uS,constants as mS}from"node:fs";import{delimiter as gS,join as fS}from"node:path";var hS=(t,e,i)=>new Promise((r,n)=>{dS(t,[...e],{encoding:"utf8",signal:i,windowsHide:!0},(s,a,o)=>{s?n(Object.assign(new Error(s.message,{cause:s}),{code:s.code,stdout:a,stderr:o})):r({stdout:a,stderr:o})})});function yS(t){for(let e of(t??"").split(gS))if(e)for(let i of["zenity","kdialog"])try{return uS(fS(e,i),mS.X_OK),!0}catch{}return!1}function Eu(t=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":t==="darwin"||t==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&yS(e.PATH)?"native":"browse"}function Wn(t){if(!(typeof t!="object"||t===null||!("code"in t)))return typeof t.code=="string"||typeof t.code=="number"?t.code:void 0}function bS(t){return typeof t=="object"&&t!==null&&"stderr"in t&&typeof t.stderr=="string"?t.stderr:""}function Ka(t){return t.replace(/[\r\n]+$/,"")||null}async function Tu(t,e=process.platform,i=hS){if(e==="darwin")try{let r=await i("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],t);return Ka(r.stdout)}catch(r){if(!t.aborted&&Wn(r)===1&&/(?:User canceled|-128)/i.test(bS(r)))return null;throw r}if(e==="linux"){try{return Ka((await i("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],t)).stdout)}catch(r){if(t.aborted)throw r;if(Wn(r)===1)return null;if(Wn(r)!=="ENOENT")throw r}try{return Ka((await i("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],t)).stdout)}catch(r){if(t.aborted)throw r;if(Wn(r)===1)return null;throw r}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as _S,randomUUID as vS}from"node:crypto";import{mkdir as wS,readFile as SS,writeFile as kS}from"node:fs/promises";import{join as Iu}from"node:path";import{getAgentDir as ES}from"@earendil-works/pi-coding-agent";var $n=20*1024*1024,Au=20,TS=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function IS(t){let e=t.indexOf("."),i=(e<0?t:t.slice(0,e)).replace(/[. ]+$/u,"");return TS.test(i)}function AS(t,e){let i=0,r="";for(let n of Buffer.from(t).toString("utf8")){let s=Buffer.byteLength(n);if(i+s>e)break;r+=n,i+=s}return r}function xS(t){if(t===void 0)return"file";let i=t.slice(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return IS(i)&&(i=`_${i}`),i=AS(i,255).replace(/[. ]+$/u,""),i===""||i==="."||i===".."?"file":i}function OS(t){return t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":t.length>=3&&t.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":t.length>=6&&["GIF87a","GIF89a"].includes(t.toString("ascii",0,6))?"image/gif":t.length>=12&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function xu(t,e,i,r){if(r.byteLength===0||r.byteLength>$n)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let n=xS(e),s=_S("sha256").update(r).digest("hex"),a=Iu(ES(),"pi-web","attachments",s);await wS(a,{recursive:!0});let o=Iu(a,n);try{await kS(o,r,{flag:"wx",mode:384})}catch(l){if(!(l instanceof Error&&"code"in l&&l.code==="EEXIST"))throw l}return{id:vS(),name:n,bytes:r.byteLength,path:o,mediaType:OS(r)??i.replace(/^image\//,"application/"),sessionId:t}}async function Ou(t){return{type:"image",data:(await SS(t.path)).toString("base64"),mimeType:t.mediaType}}import{randomBytes as RS}from"node:crypto";function Ru(t,e,i){return t!=="openai-codex"||e!=="oauth"?i:{...i,prompt:r=>r.type==="select"&&r.options.some(n=>n.id==="browser")&&r.options.some(n=>n.id==="device_code")?Promise.resolve("browser"):i.prompt(r)}}var Vn=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,i,r,n,s){let a=this.getActive();if(a){if(a.providerId===e&&a.method===i&&n===void 0)return a;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let o=RS(18).toString("base64url"),l={view:{id:o,providerId:e,method:i,status:"running"},controller:new AbortController};return this.flows.set(o,l),r(e,i,{signal:l.controller.signal,notify:c=>{l.view={...l.view,event:c,...c.type==="auth_url"||c.type==="device_code"?{authorization:c}:{}}},prompt:c=>{if(c.type==="secret"&&n!==void 0){let p=n;return n=void 0,Promise.resolve(p)}return new Promise((p,u)=>{let{signal:m,...g}=c;l.answer=p,l.reject=u,l.view={...l.view,status:"waiting",prompt:g},m?.aborted?u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):m?.addEventListener("abort",()=>u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{l.view.status!=="cancelled"&&(l.view={id:o,providerId:e,method:i,status:"done"})}).catch(c=>{if(l.view.status!=="cancelled"){let p=new Error("Provider login failed");c instanceof Error&&c.stack&&(p.stack=`${p.message}
220
217
  ${c.stack.split(`
221
218
  `).slice(1).join(`
222
- `)}`);let d=this.reportError(p,{...s,stage:"provider_login"});a.view={id:l,providerId:e,method:t,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:d}}}),{...a.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(s=>s.id===t))return!1;let n=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},n(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as XE}from"node:crypto";import{readFile as ZE,rename as eT,rm as tT,stat as iT,writeFile as rT,mkdir as nT}from"node:fs/promises";import{dirname as sT}from"node:path";var aT=["openai-completions","openai-responses","anthropic-messages"];function el(i){if(!i||typeof i!="object")return!1;let e=i;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||!aT.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let t=new URL(e.baseUrl);return(t.protocol==="https:"||t.protocol==="http:")&&!!t.hostname&&!t.username&&!t.password&&!t.hash}catch{return!1}}async function og(i,e){if(!el(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let t;try{t=await ZE(i,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}let r;if(t===void 0)r={providers:{}};else{try{r=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let n={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await nT(sT(i),{recursive:!0});let s=t===void 0?384:(await iT(i)).mode&511,o=`${i}.pi-web-${XE(6).toString("hex")}.tmp`;try{await rT(o,`${JSON.stringify(n,null,2)}
223
- `,{mode:s,flag:"wx"}),await eT(o,i)}finally{await tT(o,{force:!0})}}import{randomBytes as oT}from"node:crypto";import{mkdir as lT,readFile as cT,rename as pT,rm as dT,stat as uT,writeFile as mT}from"node:fs/promises";import{dirname as gT}from"node:path";function lg(i){if(!i||i.length>2048)return!1;try{let e=new URL(i);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function cg(i){if(!i||typeof i!="object")return!1;let e=i;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&pg(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&lg(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function pg(i){if(!i||typeof i!="object")return!1;let e=i;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let t of[e.contextWindow,e.maxTokens])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(t=>t==="text"||t==="image")&&new Set(e.input).size===e.input.length}async function dg(i){let e;try{e=await cT(i,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function bT(i,e,t){await lT(gT(i),{recursive:!0});let r=t===void 0?384:(await uT(i)).mode&511,n=`${i}.pi-web-${oT(6).toString("hex")}.tmp`;try{await mT(n,`${JSON.stringify(e,null,2)}
224
- `,{mode:r,flag:"wx"}),await pT(n,i)}finally{await dT(n,{force:!0})}}async function ug(i,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await dg(i),n=r.providers[e],s=new Set(n?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:n?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:s.has(o.id)?"custom":"builtin",overridden:!!n?.modelOverrides?.[o.id]}))}}async function mg(i,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await dg(i),o={...n.providers[e]??{}},l=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!lg(t.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");t.baseUrl===null?delete o.baseUrl:o.baseUrl=t.baseUrl}else if(t.action==="save"){if(!pg(t.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let c={id:t.model.id.trim(),...t.model.name===void 0?{}:{name:t.model.name},...t.model.contextWindow===void 0?{}:{contextWindow:t.model.contextWindow},...t.model.maxTokens===void 0?{}:{maxTokens:t.model.maxTokens},...t.model.input===void 0?{}:{input:t.model.input}},p=t.originalId,d=p===void 0?-1:l.findIndex(g=>g.id===p);if(p===void 0&&(l.some(g=>g.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(d>=0){if(c.id!==p&&(l.some(b=>b.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let g={...l[d],...c};for(let b of["name","contextWindow","maxTokens","input"])c[b]===void 0&&delete g[b];l[d]=g}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:g,...b}=c;a[p]={...a[p],...b};for(let v of["name","contextWindow","maxTokens","input"])c[v]===void 0&&delete a[p][v]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");l.push(c)}}else{let c=l.findIndex(p=>p.id===t.id);if(c>=0)l.splice(c,1);else if(Object.hasOwn(a,t.id))delete a[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}l.length?o.models=l:delete o.models,Object.keys(a).length?o.modelOverrides=a:delete o.modelOverrides,Object.keys(o).length?n.providers[e]=o:delete n.providers[e],await bT(i,n,s)}function gg(i){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(i.trim())}import{randomBytes as O0,createHash as L1}from"node:crypto";import{fileURLToPath as q1}from"node:url";var dn="pi-webapp@0.1.56+6f956b602975404b747f",It="6f956b602975404b747f";var U1="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function Va(i=process.env,e=console.warn){let t=r=>{let n={enabled:!1,environment:i.PI_WEB_SENTRY_ENVIRONMENT||"production",release:dn,buildId:It},s=i[`PI_WEB_SENTRY_${r}_DSN`]??i.PI_WEB_SENTRY_DSN??U1;if(i.PI_WEB_SENTRY_ENABLED!=="true"||!s)return n;try{let o=new URL(s);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...n,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),n}};return{browser:t("BROWSER"),node:t("NODE")}}var Yt=class{config;ready;reporter;client;salt=O0(16);breadcrumbs=new pn;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=Va(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=q1(import.meta.url).replace(/\\/g,"/"),r=t.lastIndexOf("/src/"),n=r>=0?t.slice(0,r+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:n)&&this.capture(s,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=Promise.resolve().then(()=>(A0(),x0)).then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:It,integrations:[],transport:e.transport??(r=>gm(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:mm,sendClientReports:!1,dataCollection:{...pm,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Ts(this.client,"node",It,t,this.breadcrumbs),this.reporter.setState(this.state);for(let r of this.early)this.reporter.capture(r.error,r.context,r.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||Wi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let r=O0(16).toString("hex");return this.early.push({error:fr(e),context:Tt(t),eventId:r}),r}catch{return}}setState(e){this.state=Tt({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return L1("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(r=>{t=setTimeout(r,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as X1}from"@earendil-works/pi-coding-agent";function Ri(i,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(i.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!i.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as F1}from"node:crypto";var R0="[pi-web workspace tab in view] ",N0=' \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 j1(i){return{title:i.title,kind:i.kind,contentId:i.contentId,...i.plugin?{plugin:i.plugin}:{},...i.detail?{detail:i.detail}:{},...i.reference?{reference:i.reference}:{}}}function B1(i){let e=i.endsWith(N0)?i.slice(0,-N0.length):i;try{let t=JSON.parse(e);if(typeof t.title!="string"||typeof t.kind!="string"||typeof t.contentId!="string")return null;for(let r of["plugin","detail","reference"])if(t[r]!==void 0&&typeof t[r]!="string")return null;return j1(t)}catch{return null}}function Jn(i){let e=[],t=i;for(;;){let n=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);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)}),t=t.slice(0,n.index)}let r=t.lastIndexOf(R0);if(r!==-1&&(r===0||t.slice(r-2,r)===`
219
+ `)}`);let u=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:u}}}),{...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 NS}from"node:crypto";import{readFile as PS,rename as CS,rm as MS,stat as DS,writeFile as LS,mkdir as US}from"node:fs/promises";import{dirname as qS}from"node:path";var jS=["openai-completions","openai-responses","anthropic-messages"];function Ya(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||!jS.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 Nu(t,e){if(!Ya(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 PS(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 US(qS(t),{recursive:!0});let s=i===void 0?384:(await DS(t)).mode&511,a=`${t}.pi-web-${NS(6).toString("hex")}.tmp`;try{await LS(a,`${JSON.stringify(n,null,2)}
220
+ `,{mode:s,flag:"wx"}),await CS(a,t)}finally{await MS(a,{force:!0})}}import{randomBytes as BS}from"node:crypto";import{mkdir as FS,readFile as HS,rename as GS,rm as WS,stat as $S,writeFile as VS}from"node:fs/promises";import{dirname as zS}from"node:path";function Pu(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 Cu(t){if(!t||typeof t!="object")return!1;let e=t;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&Mu(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&Pu(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function Mu(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 Du(t){let e;try{e=await HS(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 KS(t,e,i){await FS(zS(t),{recursive:!0});let r=i===void 0?384:(await $S(t)).mode&511,n=`${t}.pi-web-${BS(6).toString("hex")}.tmp`;try{await VS(n,`${JSON.stringify(e,null,2)}
221
+ `,{mode:r,flag:"wx"}),await GS(n,t)}finally{await WS(n,{force:!0})}}async function Lu(t,e,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Du(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 Uu(t,e,i,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await Du(t),a={...n.providers[e]??{}},o=[...a.models??[]],l={...a.modelOverrides??{}};if(i.action==="base_url"){if(i.baseUrl!==null&&!Pu(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(!Mu(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,u=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(u>=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[u],...c};for(let g of["name","contextWindow","maxTokens","input"])c[g]===void 0&&delete m[g];o[u]=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 h of["name","contextWindow","maxTokens","input"])c[h]===void 0&&delete l[p][h]}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 KS(t,n,s)}function qu(t){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(t.trim())}import{randomBytes as h_,createHash as LI}from"node:crypto";import{fileURLToPath as UI}from"node:url";var Tr="pi-webapp@0.1.57-alpha.2+b1695323f1f50457e7e6",it="b1695323f1f50457e7e6";var qI="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function Ks(t=process.env,e=console.warn){let i=r=>{let n={enabled:!1,environment:t.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Tr,buildId:it},s=t[`PI_WEB_SENTRY_${r}_DSN`]??t.PI_WEB_SENTRY_DSN??qI;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=h_(16);breadcrumbs=new Er;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=Ks(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let i=UI(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(()=>(f_(),g_)).then(i=>{if(!this.closed){this.client=new i.NodeClient({...this.config.node,dist:it,integrations:[],transport:e.transport??(r=>qd(i.createTransport,r)),stackParser:i.defaultStackParser,beforeSend:Ud,sendClientReports:!1,dataCollection:{...Md,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Ln(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||pi(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=h_(16).toString("hex");return this.early.push({error:Ui(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 LI("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 XI}from"@earendil-works/pi-coding-agent";function Qt(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 FI}from"node:crypto";var y_="[pi-web workspace tab in view] ",b_=' \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 jI(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 BI(t){let e=t.endsWith(b_)?t.slice(0,-b_.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 jI(i)}catch{return null}}function mn(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(y_);if(r!==-1&&(r===0||i.slice(r-2,r)===`
225
222
 
226
- `)&&!t.slice(r).includes(`
227
- `)){let n=B1(t.slice(r+R0.length));if(n)return{text:t.slice(0,Math.max(0,r-2)),attachments:e,context:n}}return{text:t,attachments:e}}var Xn=i=>Buffer.byteLength(i.text)+i.images.reduce((e,t)=>e+t.data.length,0),tt=class extends Error{status=409},Ni=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,...Jn(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],r){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((n,s)=>n+Xn(s),Xn({text:e,images:t}))>64*1024*1024)throw new tt("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:F1(),revision:1,text:e,images:t.map(n=>({...n})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new tt("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let r=this.entries.find(n=>n.id===e);if(!r||r.revision!==t)throw new tt("\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 tt("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,t,r,n){let s=this.find(e,t);if(r.kind==="remove"){this.entries=this.entries.filter(o=>o!==s),this.changed();return}if(r.kind==="edit"){let o=Jn(s.text),l=s.text.slice(o.text.length).replace(/^\n\n/u,""),a=[r.text.trim(),l].filter(Boolean).join(`
223
+ `)&&!i.slice(r).includes(`
224
+ `)){let n=BI(i.slice(r+y_.length));if(n)return{text:i.slice(0,Math.max(0,r-2)),attachments:e,context:n}}return{text:i,attachments:e}}var gn=t=>Buffer.byteLength(t.text)+t.images.reduce((e,i)=>e+i.data.length,0),Ce=class extends Error{status=409},Jt=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,...mn(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+gn(s),gn({text:e,images:i}))>64*1024*1024)throw new Ce("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:FI(),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 Ce("\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 Ce("\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 Ce("\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=mn(s.text),o=s.text.slice(a.text.length).replace(/^\n\n/u,""),l=[r.text.trim(),o].filter(Boolean).join(`
228
225
 
229
- `);if(this.validateText(a),this.entries.reduce((c,p)=>c+Xn(p),0)-Xn(s)+Xn({text:a,images:s.images})>64*1024*1024)throw new tt("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=a,s.revision++,delete s.error,this.changed();return}await this.deliver(s,n)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,t){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var f=class extends Error{code;status;reason;constructor(e,t,r={}){super(t),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};function Ne(i){let e=i&&typeof i=="object"?i:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:i instanceof Error?i.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var Ci=i=>i.code==="ENOENT";var C0=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function ad(i,e,t,r){if(!i)throw new f("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return i.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new f("invalid_input","Expected plugin request object",{status:400});let n=t;if(e==="/api/hosted-plugins/views"){if(r?.draining&&!["poll","pollMany","change","ack","close","reconcile","status","cancel-initialization"].includes(String(n.operation)))throw new f("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(n.operation!=="pollMany")return i.views(n);if(!Array.isArray(n.views)||!n.views.length||n.views.length>64||n.views.some(s=>!s||typeof s!="object"||Array.isArray(s)||s.operation!=="poll"))throw new f("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(n.views.map(async s=>{try{return{reply:await i.views({...s,operation:"poll",immediate:!0})}}catch(o){return{failure:$a(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new f("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof n.id!="string"||!/^[a-f0-9-]{36}$/.test(n.id)||n.decision!=="allow"&&n.decision!=="deny")throw new f("invalid_input","Invalid approval decision",{status:400});if(!i.decide)throw new f("hosted_unavailable","Approvals are not available in this runtime",{status:503});return i.decide(n.id,n.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new f("host_restarting","Host is updating; secret changes are fenced",{status:409});if(n.auth!==void 0){if(!i.secretAuth)throw new f("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(n.auth==="start"&&typeof n.pluginId=="string"&&n.pluginId.length<=214&&typeof n.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(n.name))return i.secretAuth({phase:"start",pluginId:n.pluginId,name:n.name});if((n.auth==="poll"||n.auth==="cancel")&&typeof n.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(n.deviceId))return i.secretAuth({phase:n.auth,deviceId:n.deviceId});throw new f("invalid_input","Invalid sign-in request",{status:400})}if(typeof n.pluginId!="string"||n.pluginId.length>214||typeof n.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(n.name)||!(n.value===null||typeof n.value=="string"&&n.value.length>=1&&n.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(n.value)))throw new f("invalid_input","Invalid secret request",{status:400});if(!i.secret)throw new f("hosted_unavailable","Secrets are not available in this runtime",{status:503});return i.secret(n.pluginId,n.name,n.value)}if(typeof n.pluginId!="string"||n.pluginId.length>214)throw new f("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new f("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof n.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(n.operation)||n.version!==void 0&&(typeof n.version!="string"||!/^\d+\.\d+\.\d+$/.test(n.version)))throw new f("invalid_input","Invalid plugin management request",{status:400});if(n.downloadId!==void 0&&(typeof n.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(n.downloadId))||n.operation==="cancel-download"&&!n.downloadId)throw new f("invalid_input","Exact download identity required",{status:400});if(n.reopenEditors!==void 0&&typeof n.reopenEditors!="boolean")throw new f("invalid_input","Invalid editor reopen consent",{status:400});if(n.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(n.updatePolicy)||n.operation==="policy"&&(typeof n.updatePolicy!="string"||n.updatePolicy==="pinned"&&!n.version))throw new f("invalid_input","Invalid update policy or missing exact pin",{status:400});return i.manage({pluginId:n.pluginId,operation:n.operation,...typeof n.downloadId=="string"?{downloadId:n.downloadId}:{},...typeof n.updatePolicy=="string"?{updatePolicy:n.updatePolicy}:{},...typeof n.version=="string"?{version:n.version}:{},...typeof n.reopenEditors=="boolean"?{reopenEditors:n.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof n.sessionId!="string"||!n.sessionId||n.sessionId.length>200||!Number.isSafeInteger(n.generation)||Number(n.generation)<1||typeof n.action!="string"||!/^[\w.-]{1,80}$/.test(n.action))throw new f("invalid_input","Invalid plugin action request",{status:400});if(n.viewToken!==void 0&&(typeof n.viewToken!="string"||n.viewToken.length>200)||n.mountId!==void 0&&(typeof n.mountId!="string"||n.mountId.length>200))throw new f("invalid_input","Invalid view flush capability",{status:400});return i.action({sessionId:n.sessionId,pluginId:n.pluginId,generation:Number(n.generation),action:n.action,input:n.input??{},...typeof n.viewToken=="string"?{viewToken:n.viewToken}:{},...typeof n.mountId=="string"?{mountId:n.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new f("invalid_route","Unknown hosted plugin route",{status:404})}function $a(i){let e=Ne(i);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as P0}from"node:fs/promises";import{join as D0}from"node:path";async function M0(i){try{let e=JSON.parse(await P0(D0(i,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await P0(D0(i,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!s||typeof s!="object"))for(let o of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let n={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(s=>[`/${s}`,{path:s,type:n[s.split(".").pop()]}]))}catch{return{}}}import{access as H1,readFile as U0,realpath as Qa,rename as hW,rm as yW,writeFile as fW}from"node:fs/promises";import{dirname as Ka,join as ui,resolve as W1,sep as q0}from"node:path";import{createRequire as z1}from"node:module";var G1=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function Kt(i){let e=typeof i=="string"&&G1.exec(i);if(!e||e[0]!==i)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||r.some(n=>/^\d+$/.test(n)&&n.length>1&&n[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:r}}function pt(i,e){let t=Kt(i),r=Kt(e);for(let n=0;n<3;n++)if(t.core[n]!==r.core[n])return t.core[n]>r.core[n]?1:-1;if(!t.prerelease.length||!r.prerelease.length)return+!t.prerelease.length-+!r.prerelease.length;for(let n=0;n<Math.max(t.prerelease.length,r.prerelease.length);n++){let s=t.prerelease[n],o=r.prerelease[n];if(s===void 0||o===void 0)return s===void 0?-1:1;if(s===o)continue;let l=/^\d+$/.test(s),a=/^\d+$/.test(o);return l!==a?l?-1:1:l&&s.length!==o.length?s.length>o.length?1:-1:s>o?1:-1}return 0}function L0(i){try{return Kt(i).prerelease.length===0}catch{return!1}}function Ya(i){try{return Kt(i),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(i)}catch{return!1}}var Pi=1;async function Gr(i,e){let t=z1(ui(i,"package.json"));for(let r of t.resolve.paths(e)??[]){let n=ui(r,e);try{if(JSON.parse(await U0(ui(n,"package.json"),"utf8")).name===e)return await Qa(n)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function od(i,e){if(pt(e?.version,e?.version),e.desktopProtocolVersion!==Pi||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await Qa(W1(Ka(e.launcher),"..")),r=await Qa(ui(i,"pi-web","releases")),n=Ka(Ka(t));if(await Qa(e.launcher)!==ui(t,"bin","pi-webapp.mjs")||Ka(n)!==r||!n.startsWith(r+q0)||!n.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(n.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await U0(ui(t,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==Pi)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let o=await Gr(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(n+q0))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let l=ui(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,l,ui(t,"dist","extension.js"),ui(t,"web","dist","index.html")].map(a=>H1(a))),e.fallbackVersion!==void 0&&Kt(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:l,desktopProtocolVersion:Pi,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var Ja="default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'",V1="browser.wasm";function j0(i={}){return i.wasm?Ja.replace("script-src 'self'","script-src 'self' 'wasm-unsafe-eval'"):Ja}function B0(i){let e=i;return!!e&&e.browser?.wasm===!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(V1)}var Z1={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function O(i,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:i.getHeader("X-Request-ID"),operationId:i.getHeader("X-Operation-ID")}),i.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),i.end(JSON.stringify(t))}function eO(i,e){let t=i.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let r=Buffer.from(t.slice(7),"utf8");return r.length===e.length&&$1(r,e)}async function G0(i,e=64*1024){let t=0,r=[];for await(let n of i){let s=Buffer.isBuffer(n)?n:Buffer.from(n);if(t+=s.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function tO(i){let e=0,t=[];for await(let r of i){let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=n.length,e>Ds)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(n)}return Buffer.concat(t)}async function iO(i,e=0){await new Promise((r,n)=>{i.once("error",n),i.listen(e,"127.0.0.1",()=>{i.off("error",n),r()})});let t=i.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function H0(i,e,t=new Yt,r={}){t.setState({piVersion:X1});let n=process.env.PI_WEBAPP_RESTART_TOKEN,s=n&&/^[A-Za-z0-9_-]{32}$/.test(n)?n:F0(24).toString("base64url"),o=Buffer.from(s),l=eg(),a=new Set,c=new Ns(r.pluginSettingsFile??cd(J1(),"pi-web","plugins.json"));try{await c.load()}catch(k){throw await t.close(),k}let p=new Cs(Vm(),c),d=async()=>await i.plugins?.()??{plugins:[],errors:[]},g=()=>({type:"plugin_state",disabled:p.plugins.filter(k=>!c.enabled(k.metadata.id)).map(k=>k.metadata.id)}),b=()=>{for(let k of a)k.write(`${JSON.stringify(g())}
230
- `)},v=new Map,y=new Ms((k,h)=>t.capture(k,h)),S=k=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(k.sessionId),idle:k.idle,model:k.model,thinkingLevel:k.thinkingLevel,messageCount:k.messages.length}),T="",I=!1,x=!1,P={...Z1,...await M0(e)};for(let k of await K1(cd(e,"assets")).catch(()=>[])){let h=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(k);if(!h)continue;let M={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};P[`/assets/${k}`]={path:`assets/${k}`,type:M[h[1]]}}let U=Q1(async(k,h)=>{let M=F0(18).toString("base64"),Z=fe=>typeof fe=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(fe),re=Z(k.headers["x-request-id"])?k.headers["x-request-id"]:ld(),ae={requestId:re,operationId:Z(k.headers["x-operation-id"])?k.headers["x-operation-id"]:void 0};h.setHeader("X-Request-ID",re),ae.operationId&&h.setHeader("X-Operation-ID",ae.operationId);let C="/",Se=performance.now(),me=(fe,_,D)=>{let ie=!Wi(fe)&&dm(C)?ei(fe,"Agent or provider operation failed"):fe,ue=t.capture(ie,{...ae,route:C,method:k.method,status:_,stage:"http"});O(h,_,{error:D,errorId:ue,errorReported:t.enabled,errorCode:Wi(fe)?"validation_error":"unexpected_error"})};h.once("finish",()=>{C.startsWith("/api/telemetry/")||t.breadcrumb("request",{...ae,route:C,method:k.method,status:h.statusCode,durationMs:Math.round(performance.now()-Se)})});try{h.setHeader("X-Content-Type-Options","nosniff"),h.setHeader("Referrer-Policy","no-referrer"),h.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${M}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${t.config.browser.dsn?` ${new URL(t.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{C=new URL(k.url??"/",T).pathname}catch{O(h,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let fe=P[C];if(k.method==="GET"&&fe){try{let _=await Y1(cd(e,fe.path));h.writeHead(200,{"Content-Type":fe.type,"Cache-Control":"no-store"}),h.end(C==="/"?_.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${M}">`):_)}catch(_){me(_,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&C.startsWith("/hosted-plugins/")){try{let _=await i.hosted?.asset(C);if(!_){O(h,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}h.setHeader("Content-Security-Policy",_.csp??Ja),h.writeHead(200,{"Content-Type":_.mime,"Cache-Control":"private, no-store"}),h.end(_.bytes)}catch{O(h,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(k.method==="GET"&&C.startsWith("/plugins/")){try{let _=await i.pluginAsset?.(k.url??C);if(!_){O(h,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}h.writeHead(200,{"Content-Type":_.type,"Cache-Control":"no-store"}),h.end(_.bytes)}catch(_){me(_,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!C.startsWith("/api/")){O(h,404,{error:"\u672A\u627E\u5230"});return}if(!eO(k,o)){O(h,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(k.method==="GET"&&C==="/api/hosted-plugins"){try{O(h,200,await ad(i.hosted,C,void 0))}catch(_){let D=$a(_);O(h,D.status,D.body)}return}if(k.method==="POST"&&C0.includes(C)){if(k.headers.origin!==void 0&&k.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){O(h,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let _;try{_=await G0(k,2*1024*1024)}catch(D){O(h,D instanceof Error&&D.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{O(h,200,await ad(i.hosted,C,_,{draining:I}))}catch(D){let V=$a(D);O(h,V.status,V.body)}return}if(k.method==="GET"&&C==="/api/telemetry/config"){O(h,200,t.config.browser);return}if(k.method==="GET"&&C==="/api/update/version"){try{O(h,200,{current:await i.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Pi,...i.selfUpdate?.launcherIdentity?{launcher:i.selfUpdate.launcherIdentity(),desktopHandoffProtocol:i.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(_){me(_,503,_ instanceof Error?_.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(k.method==="GET"&&C==="/api/update"){try{O(h,200,await i.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(_){me(_,503,_ instanceof Error?_.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(k.method==="GET"&&C==="/api/image"){let _=new URL(k.url??C,T),D=_.searchParams.get("sessionId")??"",V=_.searchParams.get("messageId")??"",ie=Number(_.searchParams.get("index"));if(!D||D!==i.snapshot().sessionId||!V||!Number.isInteger(ie)||ie<0||ie>100){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let ue=i.image?.(D,V,ie);if(!ue||!["image/png","image/jpeg","image/webp","image/gif"].includes(ue.mimeType)){O(h,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}h.writeHead(200,{"Content-Type":ue.mimeType,"Cache-Control":"private, no-store"}),h.end(ue.data);return}if(k.method==="POST"&&C==="/api/attachment"){if(k.headers.origin!==void 0&&k.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let _=new URL(k.url??C,T),D=_.searchParams.get("sessionId"),V=_.searchParams.get("name");try{if(!D||!V||V.length>1024||D!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(k.headers["content-length"]??0)>Ds){O(h,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let ie=await ng(D,V,k.headers["content-type"]??"application/octet-stream",await tO(k));if(D!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}v.set(ie.id,ie),O(h,201,{id:ie.id,name:ie.name,bytes:ie.bytes})}catch(ie){me(ie,400,ie instanceof Error?ie.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(k.method==="GET"&&C==="/api/session"){try{let _=i.snapshot();S(_),O(h,200,_)}catch(_){me(_,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&C==="/api/plugin-management"){try{O(h,200,p.inventory(await d()))}catch(_){me(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&C==="/api/plugins"){try{O(h,200,p.catalog(await d()))}catch(_){me(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&C==="/api/providers"){try{O(h,200,await i.providers?.()??[])}catch(_){me(_,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&C==="/api/provider/models"){let _=new URL(k.url??C,T).searchParams.get("providerId")??"";try{if(!_||!i.providerModels){O(h,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}O(h,200,await i.providerModels(_))}catch(D){me(D,400,D instanceof Error?D.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&C==="/api/provider/login/active"){O(h,200,{active:y.getActive()??null});return}if(k.method==="GET"&&C==="/api/provider/login"){let _=new URL(k.url??C,T).searchParams.get("id")??"",D=y.get(_);O(h,D?200:404,D??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(k.method==="GET"&&(C==="/api/models"||C==="/api/config"||C==="/api/workspaces"||C==="/api/commands")){try{O(h,200,C==="/api/models"?await i.models():C==="/api/config"?await i.config():C==="/api/commands"?i.commands?.()??[]:await i.workspaces())}catch(_){me(_,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&C==="/api/directory/capability"){O(h,200,{kind:l});return}if(k.method==="GET"&&C==="/api/events"){let _;try{_=i.snapshot(),S(_)}catch(D){me(D,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}h.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),a.add(h),h.write(`${JSON.stringify({type:"snapshot",session:_})}
231
- `),h.on("close",()=>a.delete(h));return}if(k.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/session/rename","/api/session/delete","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(C)){if(k.headers.origin!==void 0&&k.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){O(h,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let _;try{_=await G0(k,C==="/api/plugin-action"?544*1024:64*1024)}catch(D){if(D instanceof Error&&D.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){O(h,413,{error:D.message});return}if(D instanceof SyntaxError||Wi(D)){O(h,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw D}if(C==="/api/desktop/handoff"){let D=_;if(!D||typeof D.nonce!="string"||typeof D.requestId!="string"){O(h,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!i.selfUpdate?.requestLauncherHandoff){O(h,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(I||x||y.getActive()){O(h,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let V=p.restartBlocker()??p.restartConfirmations()[0];if(!i.snapshot().idle||(i.busyGitWorkspaces?.()??[]).length||V){O(h,409,{error:V??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}I=!0;try{await i.selfUpdate.requestLauncherHandoff(D.nonce,D.requestId)}catch(ie){throw I=!1,ie}O(h,202,{accepted:!0,protocol:1,requestId:D.requestId});return}if(typeof _!="object"||_===null||!("sessionId"in _)||typeof _.sessionId!="string"){O(h,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(I&&C!=="/api/update/cancel"){O(h,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(C==="/api/plugin-management"){let D=_;if(typeof D.id!="string"||D.id.length>200||typeof D.enabled!="boolean"||typeof D.expected!="string"){O(h,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let V=()=>{if(i.snapshot().sessionId!==_.sessionId)throw new De("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.snapshot().idle||(i.busyGitWorkspaces?.()??[]).length)throw new De("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(D.id,D.enabled,D.expected,V),O(h,200,p.inventory(await d()))}catch(ie){if(ie instanceof De)O(h,ie.status,{error:ie.message});else throw ie}finally{b()}return}if(p.mutating&&C!=="/api/abort"){O(h,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(await p.dispatch({path:C,body:_,res:h,snapshot:()=>i.snapshot(),busyWorkspaces:()=>i.busyGitWorkspaces?.()??[],json:(D,V)=>O(h,D,V)}))return;if(C==="/api/plugin-interaction"){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("requestId"in _)||typeof _.requestId!="string"||_.requestId.length>200||!i.resolvePluginInteraction||!("value"in _)){O(h,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(i.snapshot().cwd,async()=>i.resolvePluginInteraction(_.sessionId,_.pluginId,_.requestId,_.value)),O(h,200,{accepted:!0});return}if(C==="/api/plugin-action"){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("action"in _)||typeof _.action!="string"||_.action.length>100){O(h,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(ie=>ie.metadata.id===_.pluginId)){let ie=p.actionRoute(_.pluginId,_.action);if(!ie){O(h,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let ue="input"in _?_.input:{};if(!ue||typeof ue!="object"||Array.isArray(ue)){O(h,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:ie,body:{...ue,sessionId:_.sessionId},res:h,snapshot:()=>i.snapshot(),busyWorkspaces:()=>i.busyGitWorkspaces?.()??[],json:(je,qt)=>O(h,je,je>=200&&je<300?{value:qt}:qt)});return}if(!i.invokePluginAction){O(h,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let V=await p.coordinateStart(i.snapshot().cwd,async()=>i.invokePluginAction(_.sessionId,_.pluginId,_.action,"input"in _?_.input:void 0));O(h,200,{value:V});return}if(C==="/api/update/channel"){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in _)||_.channel!=="stable"&&_.channel!=="alpha"){O(h,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!i.selfUpdate?.setChannel){O(h,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}O(h,200,await i.selfUpdate.setChannel(_.channel));return}if(C==="/api/update/cancel"){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!i.selfUpdate?.cancel){O(h,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await i.selfUpdate.cancel(),O(h,200,{cancelled:!0,dataPreserved:!0});return}if(C==="/api/update"){if(x){O(h,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!i.snapshot().idle){O(h,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!i.selfUpdate){O(h,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let D=p.restartBlocker();if((i.busyGitWorkspaces?.()??[]).length||D){O(h,409,{error:D??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let V=_,ie="channel"in V||"version"in V||"allowDowngrade"in V;if(ie&&(V.channel!=="stable"&&V.channel!=="alpha"||typeof V.version!="string"||V.allowDowngrade!==void 0&&typeof V.allowDowngrade!="boolean")){O(h,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if(V.force!==void 0&&typeof V.force!="boolean"){O(h,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let ue=V.force===!0,je=ge=>O(h,409,{error:ge.join("\uFF1B"),reason:"update_confirm_required"}),qt=p.restartConfirmations();if(qt.length&&!ue){je(qt);return}x=!0;let gi;try{gi=await i.selfUpdate.prepare(ie?{channel:V.channel,version:V.version,allowDowngrade:V.allowDowngrade}:void 0);let ge=p.restartBlocker();if(!i.snapshot().idle||(i.busyGitWorkspaces?.()??[]).length||ge)throw new Error(ge??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let St=p.restartConfirmations();if(St.length&&!ue){je(St);return}ue&&await p.releaseForRestart(),I=!0;try{await i.selfUpdate.requestRestart(gi,{force:ue})}catch(ys){let sn=ys?.code;if(!ue&&(sn==="view_barrier"||sn==="drain_pending")){I=!1,je(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw ys}}catch(ge){throw I=!1,ge}finally{x=!1}O(h,202,{accepted:!0,version:gi.version});return}if(C==="/api/provider/custom"){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in _)||!el(_.provider)||!i.addCustomProvider){O(h,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await i.addCustomProvider(_.sessionId,_.provider),O(h,201,{accepted:!0});return}if(C==="/api/provider/models"||C==="/api/provider/logout"){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in _)||typeof _.providerId!="string"){O(h,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(C==="/api/provider/models"){if(!("change"in _)||!cg(_.change)||!i.updateProviderModel){O(h,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await i.updateProviderModel(_.sessionId,_.providerId,_.change)}else{if(!i.logoutProvider){O(h,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await i.logoutProvider(_.sessionId,_.providerId)}O(h,200,{accepted:!0});return}if(C.startsWith("/api/provider/login")){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(C==="/api/provider/login"){if(!("providerId"in _)||typeof _.providerId!="string"||!("method"in _)||_.method!=="api_key"&&_.method!=="oauth"||!i.loginProvider||!i.providers){O(h,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await i.providers()).some(ue=>ue.id===_.providerId&&ue.methods.includes(_.method))){O(h,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let V="initialSecret"in _?_.initialSecret:void 0;if(V!==void 0&&(_.method!=="api_key"||typeof V!="string"||!V.trim()||V.length>16384)){O(h,400,{error:"API Key \u65E0\u6548"});return}let ie=y.start(_.providerId,_.method,i.loginProvider,V,ae);O(h,202,{id:ie.id});return}if(!("id"in _)||typeof _.id!="string"){O(h,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(C==="/api/provider/login/cancel"){O(h,y.cancel(_.id)?202:404,{accepted:!0});return}if(!("value"in _)||typeof _.value!="string"||_.value.length>16384||!y.respond(_.id,_.value)){O(h,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}O(h,202,{accepted:!0});return}if(C==="/api/attachment/remove"){if(!("id"in _)||typeof _.id!="string"||_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}v.get(_.id)?.sessionId===_.sessionId&&v.delete(_.id),O(h,202,{accepted:!0});return}if(C==="/api/directory/pick"){if(l!=="native"){O(h,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let D=new AbortController;h.once("close",()=>D.abort()),O(h,200,{path:await tg(D.signal)});return}if(C==="/api/directory/list"){if("path"in _&&(typeof _.path!="string"||_.path.length>4096)){O(h,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}O(h,200,await Xm("path"in _?_.path:void 0));return}if(C==="/api/directory/create"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("name"in _)||typeof _.name!="string"||_.name.length>255){O(h,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}O(h,200,{path:await Zm(_.path,_.name)});return}if(C==="/api/workspace/add"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("create"in _)||typeof _.create!="boolean"){O(h,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await i.addWorkspace(_.path,_.create),O(h,202,{accepted:!0});return}if(C==="/api/workspace/select"||C==="/api/workspace/remove"||C==="/api/workspace/new-session"){if(!("id"in _)||typeof _.id!="string"){O(h,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}C==="/api/workspace/select"?await i.selectWorkspace(_.id):C==="/api/workspace/new-session"?await i.newSessionInWorkspace(_.id):await i.removeWorkspace(_.id),O(h,202,{accepted:!0});return}if(C==="/api/session/select"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"){O(h,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await i.selectSession(_.workspaceId,_.id,_.path),O(h,202,{accepted:!0});return}if(C==="/api/session/rename"||C==="/api/session/delete"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"||_.path.length>4096){O(h,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(C==="/api/session/rename"){if(!("name"in _)||typeof _.name!="string"){O(h,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!i.renameSession){O(h,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await i.renameSession(_.workspaceId,_.id,_.path,_.name)}else{if(!i.deleteSession){O(h,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await i.deleteSession(_.workspaceId,_.id,_.path)}O(h,202,{accepted:!0});return}if(C==="/api/thinking-level"){if(!("level"in _)||typeof _.level!="string"){O(h,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await i.setThinkingLevel(_.sessionId,_.level)}else if(C==="/api/model"){if(!("provider"in _)||typeof _.provider!="string"||!("id"in _)||typeof _.id!="string"){O(h,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await i.setModel(_.sessionId,_.provider,_.id)}else if(C==="/api/config"){let D=_;if(!["packages","extensions","skills"].includes(D.kind)||!["global","project"].includes(D.scope)||!["add","remove"].includes(D.action)||typeof D.value!="string"||!D.value.trim()||D.value.length>2048){O(h,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(D.action==="add"&&D.kind!=="packages"&&gg(D.value)){O(h,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}O(h,200,await i.updateConfig(D));return}else if(C==="/api/prompt-queue"){let D=_,V=D.action;if(typeof D.id!="string"||D.id.length>100||!Number.isSafeInteger(D.revision)||D.revision<1||!V||typeof V!="object"||!["edit","remove","steer"].includes(V.kind)||V.kind==="edit"&&(typeof V.text!="string"||V.text.length>32e3)){O(h,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let ie=i.snapshot();if(D.sessionId!==ie.sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(V.kind==="steer"&&ie.idle){O(h,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(V.kind==="steer"&&ie.interactions?.length){O(h,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!i.updateQueuedPrompt){O(h,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(ie.cwd,async()=>i.updateQueuedPrompt(_.sessionId,D.id,D.revision,V))}else if(C==="/api/message"){let D="delivery"in _?_.delivery:void 0;if(D!==void 0&&D!=="steer"&&D!=="followUp"){O(h,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let V="attachments"in _?_.attachments:[];if(!Array.isArray(V)||V.length>rg||V.some(ge=>typeof ge!="string")||new Set(V).size!==V.length){O(h,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let ie=V.map(ge=>v.get(ge));if(ie.some(ge=>!ge||ge.sessionId!==_.sessionId)){O(h,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in _)||typeof _.text!="string"||!_.text.trim()&&V.length===0||_.text.length>32e3){O(h,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let ue=i.snapshot();if(_.sessionId!==ue.sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{Ri(ue,_.text,D)}catch(ge){O(h,409,{error:ge.message});return}let je=ie,qt=[_.text.trim(),...je.map(ge=>`\u9644\u4EF6 ${JSON.stringify(ge.name)}\uFF1A${ge.path}`)].filter(Boolean).join(`
226
+ `);if(this.validateText(l),this.entries.reduce((c,p)=>c+gn(p),0)-gn(s)+gn({text:l,images:s.images})>64*1024*1024)throw new Ce("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=l,s.revision++,delete s.error,this.changed();return}await this.deliver(s,n)}async deliver(e,i){e.status="sending",e.revision++,delete e.error,this.changed();try{await i(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,i){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,i)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,i)}})()}))}};var y=class extends Error{code;status;reason;constructor(e,i,r={}){super(i),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};function me(t){let e=t&&typeof t=="object"?t:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:t instanceof Error?t.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var Xt=t=>t.code==="ENOENT";var __=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function Vc(t,e,i,r){if(!t)throw new y("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return t.inventory();if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_input","Expected plugin request object",{status:400});let n=i;if(e==="/api/hosted-plugins/views"){if(r?.draining&&!["poll","pollMany","change","ack","close","reconcile","status","cancel-initialization"].includes(String(n.operation)))throw new y("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(n.operation!=="pollMany")return t.views(n);if(!Array.isArray(n.views)||!n.views.length||n.views.length>64||n.views.some(s=>!s||typeof s!="object"||Array.isArray(s)||s.operation!=="poll"))throw new y("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(n.views.map(async s=>{try{return{reply:await t.views({...s,operation:"poll",immediate:!0})}}catch(a){return{failure:Ys(a)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new y("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof n.id!="string"||!/^[a-f0-9-]{36}$/.test(n.id)||n.decision!=="allow"&&n.decision!=="deny")throw new y("invalid_input","Invalid approval decision",{status:400});if(!t.decide)throw new y("hosted_unavailable","Approvals are not available in this runtime",{status:503});return t.decide(n.id,n.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new y("host_restarting","Host is updating; secret changes are fenced",{status:409});if(n.auth!==void 0){if(!t.secretAuth)throw new y("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(n.auth==="start"&&typeof n.pluginId=="string"&&n.pluginId.length<=214&&typeof n.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(n.name))return t.secretAuth({phase:"start",pluginId:n.pluginId,name:n.name});if((n.auth==="poll"||n.auth==="cancel")&&typeof n.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(n.deviceId))return t.secretAuth({phase:n.auth,deviceId:n.deviceId});throw new y("invalid_input","Invalid sign-in request",{status:400})}if(typeof n.pluginId!="string"||n.pluginId.length>214||typeof n.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(n.name)||!(n.value===null||typeof n.value=="string"&&n.value.length>=1&&n.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(n.value)))throw new y("invalid_input","Invalid secret request",{status:400});if(!t.secret)throw new y("hosted_unavailable","Secrets are not available in this runtime",{status:503});return t.secret(n.pluginId,n.name,n.value)}if(typeof n.pluginId!="string"||n.pluginId.length>214)throw new y("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new y("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof n.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(n.operation)||n.version!==void 0&&(typeof n.version!="string"||!/^\d+\.\d+\.\d+$/.test(n.version)))throw new y("invalid_input","Invalid plugin management request",{status:400});if(n.downloadId!==void 0&&(typeof n.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(n.downloadId))||n.operation==="cancel-download"&&!n.downloadId)throw new y("invalid_input","Exact download identity required",{status:400});if(n.reopenEditors!==void 0&&typeof n.reopenEditors!="boolean")throw new y("invalid_input","Invalid editor reopen consent",{status:400});if(n.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(n.updatePolicy)||n.operation==="policy"&&(typeof n.updatePolicy!="string"||n.updatePolicy==="pinned"&&!n.version))throw new y("invalid_input","Invalid update policy or missing exact pin",{status:400});return t.manage({pluginId:n.pluginId,operation:n.operation,...typeof n.downloadId=="string"?{downloadId:n.downloadId}:{},...typeof n.updatePolicy=="string"?{updatePolicy:n.updatePolicy}:{},...typeof n.version=="string"?{version:n.version}:{},...typeof n.reopenEditors=="boolean"?{reopenEditors:n.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof n.sessionId!="string"||!n.sessionId||n.sessionId.length>200||!Number.isSafeInteger(n.generation)||Number(n.generation)<1||typeof n.action!="string"||!/^[\w.-]{1,80}$/.test(n.action))throw new y("invalid_input","Invalid plugin action request",{status:400});if(n.viewToken!==void 0&&(typeof n.viewToken!="string"||n.viewToken.length>200)||n.mountId!==void 0&&(typeof n.mountId!="string"||n.mountId.length>200))throw new y("invalid_input","Invalid view flush capability",{status:400});return t.action({sessionId:n.sessionId,pluginId:n.pluginId,generation:Number(n.generation),action:n.action,input:n.input??{},...typeof n.viewToken=="string"?{viewToken:n.viewToken}:{},...typeof n.mountId=="string"?{mountId:n.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new y("invalid_route","Unknown hosted plugin route",{status:404})}function Ys(t){let e=me(t);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as v_}from"node:fs/promises";import{join as w_}from"node:path";async function S_(t){try{let e=JSON.parse(await v_(w_(t,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let i=new Set,r=await v_(w_(t,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!s||typeof s!="object"))for(let a of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof a=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(a)&&i.add(a);let n={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...i].map(s=>[`/${s}`,{path:s,type:n[s.split(".").pop()]}]))}catch{return{}}}import{access as GI,readFile as T_,realpath as Xs,rename as bW,rm as _W,writeFile as vW}from"node:fs/promises";import{dirname as Js,join as Ut,resolve as WI,sep as E_}from"node:path";import{createRequire as $I}from"node:module";var HI=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function St(t){let e=typeof t=="string"&&HI.exec(t);if(!e||e[0]!==t)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let i=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!i.every(Number.isSafeInteger)||r.some(n=>/^\d+$/.test(n)&&n.length>1&&n[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:i,prerelease:r}}function $e(t,e){let i=St(t),r=St(e);for(let n=0;n<3;n++)if(i.core[n]!==r.core[n])return i.core[n]>r.core[n]?1:-1;if(!i.prerelease.length||!r.prerelease.length)return+!i.prerelease.length-+!r.prerelease.length;for(let n=0;n<Math.max(i.prerelease.length,r.prerelease.length);n++){let s=i.prerelease[n],a=r.prerelease[n];if(s===void 0||a===void 0)return s===void 0?-1:1;if(s===a)continue;let o=/^\d+$/.test(s),l=/^\d+$/.test(a);return o!==l?o?-1:1:o&&s.length!==a.length?s.length>a.length?1:-1:s>a?1:-1}return 0}function k_(t){try{return St(t).prerelease.length===0}catch{return!1}}function Qs(t){try{return St(t),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(t)}catch{return!1}}var Zt=1;async function rr(t,e){let i=$I(Ut(t,"package.json"));for(let r of i.resolve.paths(e)??[]){let n=Ut(r,e);try{if(JSON.parse(await T_(Ut(n,"package.json"),"utf8")).name===e)return await Xs(n)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function zc(t,e){if($e(e?.version,e?.version),e.desktopProtocolVersion!==Zt||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let i=await Xs(WI(Js(e.launcher),"..")),r=await Xs(Ut(t,"pi-web","releases")),n=Js(Js(i));if(await Xs(e.launcher)!==Ut(i,"bin","pi-webapp.mjs")||Js(n)!==r||!n.startsWith(r+E_)||!n.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(n.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await T_(Ut(i,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==Zt)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let a=await rr(i,"@earendil-works/pi-coding-agent");if(!a.startsWith(n+E_))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let o=Ut(a,"dist","bundle","cli.js");return await Promise.all([e.launcher,o,Ut(i,"dist","extension.js"),Ut(i,"web","dist","index.html")].map(l=>GI(l))),e.fallbackVersion!==void 0&&St(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:o,desktopProtocolVersion:Zt,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var Zs="default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'",VI="browser.wasm";function I_(t={}){return t.wasm?Zs.replace("script-src 'self'","script-src 'self' 'wasm-unsafe-eval'"):Zs}function A_(t){let e=t;return!!e&&e.browser?.wasm===!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(VI)}var ZI={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function T(t,e,i){typeof i=="object"&&i!==null&&"error"in i&&(i={errorCode:e>=500?"server_error":"validation_error",...i,requestId:t.getHeader("X-Request-ID"),operationId:t.getHeader("X-Operation-ID")}),t.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),t.end(JSON.stringify(i))}function eA(t,e){let i=t.headers.authorization;if(typeof i!="string"||!i.startsWith("Bearer "))return!1;let r=Buffer.from(i.slice(7),"utf8");return r.length===e.length&&zI(r,e)}async function O_(t,e=64*1024){let i=0,r=[];for await(let n of t){let s=Buffer.isBuffer(n)?n:Buffer.from(n);if(i+=s.length,i>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function tA(t){let e=0,i=[];for await(let r of t){let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=n.length,e>$n)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");i.push(n)}return Buffer.concat(i)}function iA(t){if(!(!t||!/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/i.test(t)))try{return new URL(`http://${t}`).origin}catch{return}}async function rA(t,e,i){await new Promise((n,s)=>{t.once("error",s),t.listen(e,i,()=>{t.off("error",s),n()})});let r=t.address();if(r===null||typeof r=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return r.port}async function R_(t,e,i=new wt,r={}){i.setState({piVersion:XI});let n=process.env.PI_WEBAPP_RESTART_TOKEN,s=n&&/^[A-Za-z0-9_-]{32}$/.test(n)?n:x_(24).toString("base64url"),a=Buffer.from(s),o=Eu(),l=new Set,c=new Hn(r.pluginSettingsFile??Yc(JI(),"pi-web","plugins.json"));try{await c.load()}catch(k){throw await i.close(),k}let p=new Gn(hu(),c),u=async()=>await t.plugins?.()??{plugins:[],errors:[]},m=()=>({type:"plugin_state",disabled:p.plugins.filter(k=>!c.enabled(k.metadata.id)).map(k=>k.metadata.id)}),g=()=>{for(let k of l)k.write(`${JSON.stringify(m())}
227
+ `)},h=new Map,f=new Vn((k,b)=>i.capture(k,b)),v=k=>i.setState({nodeVersion:process.version,platform:process.platform,session:i.session(k.sessionId),idle:k.idle,model:k.model,thinkingLevel:k.thinkingLevel,messageCount:k.messages.length}),S=process.env.PI_WEBAPP_LISTEN_HOST==="0.0.0.0"?"0.0.0.0":"127.0.0.1",E="",O=!1,L=!1,C={...ZI,...await S_(e)};for(let k of await YI(Yc(e,"assets")).catch(()=>[])){let b=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(k);if(!b)continue;let q={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};C[`/assets/${k}`]={path:`assets/${k}`,type:q[b[1]]}}let P=QI(async(k,b)=>{let q=x_(18).toString("base64"),F=ae=>typeof ae=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(ae),W=F(k.headers["x-request-id"])?k.headers["x-request-id"]:Kc(),$={requestId:W,operationId:F(k.headers["x-operation-id"])?k.headers["x-operation-id"]:void 0};b.setHeader("X-Request-ID",W),$.operationId&&b.setHeader("X-Operation-ID",$.operationId);let x="/",he=performance.now(),Y=(ae,Pe,oi)=>{let R=!pi(ae)&&Dd(x)?Tt(ae,"Agent or provider operation failed"):ae,j=i.capture(R,{...$,route:x,method:k.method,status:Pe,stage:"http"});T(b,Pe,{error:oi,errorId:j,errorReported:i.enabled,errorCode:pi(ae)?"validation_error":"unexpected_error"})};b.once("finish",()=>{x.startsWith("/api/telemetry/")||i.breadcrumb("request",{...$,route:x,method:k.method,status:b.statusCode,durationMs:Math.round(performance.now()-he)})});try{let ae=S==="0.0.0.0"?iA(k.headers.host):E;if(ae===void 0){T(b,403,{error:"\u4E3B\u673A\u5730\u5740\u4E0D\u5339\u914D"});return}let Pe=k.headers.origin===void 0||k.headers.origin===ae;b.setHeader("X-Content-Type-Options","nosniff"),b.setHeader("Referrer-Policy","no-referrer"),b.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${q}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${i.config.browser.dsn?` ${new URL(i.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{x=new URL(k.url??"/",E).pathname}catch{T(b,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let oi=C[x];if(k.method==="GET"&&oi){try{let _=await KI(Yc(e,oi.path));b.writeHead(200,{"Content-Type":oi.type,"Cache-Control":"no-store"}),b.end(x==="/"?_.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${q}">`):_)}catch(_){Y(_,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x.startsWith("/hosted-plugins/")){try{let _=await t.hosted?.asset(x);if(!_){T(b,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}b.setHeader("Content-Security-Policy",_.csp??Zs),b.writeHead(200,{"Content-Type":_.mime,"Cache-Control":"private, no-store"}),b.end(_.bytes)}catch{T(b,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(k.method==="GET"&&x.startsWith("/plugins/")){try{let _=await t.pluginAsset?.(k.url??x);if(!_){T(b,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}b.writeHead(200,{"Content-Type":_.type,"Cache-Control":"no-store"}),b.end(_.bytes)}catch(_){Y(_,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){T(b,404,{error:"\u672A\u627E\u5230"});return}if(!eA(k,a)){T(b,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(k.method==="GET"&&x==="/api/hosted-plugins"){try{T(b,200,await Vc(t.hosted,x,void 0))}catch(_){let R=Ys(_);T(b,R.status,R.body)}return}if(k.method==="POST"&&__.includes(x)){if(!Pe){T(b,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){T(b,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let _;try{_=await O_(k,2*1024*1024)}catch(R){T(b,R instanceof Error&&R.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{T(b,200,await Vc(t.hosted,x,_,{draining:O}))}catch(R){let j=Ys(R);T(b,j.status,j.body)}return}if(k.method==="GET"&&x==="/api/telemetry/config"){T(b,200,i.config.browser);return}if(k.method==="GET"&&x==="/api/update/version"){try{T(b,200,{current:await t.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Zt,...t.selfUpdate?.launcherIdentity?{launcher:t.selfUpdate.launcherIdentity(),desktopHandoffProtocol:t.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(_){Y(_,503,_ instanceof Error?_.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(k.method==="GET"&&x==="/api/update"){try{T(b,200,await t.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(_){Y(_,503,_ instanceof Error?_.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(k.method==="GET"&&x==="/api/image"){let _=new URL(k.url??x,E),R=_.searchParams.get("sessionId")??"",j=_.searchParams.get("messageId")??"",K=Number(_.searchParams.get("index"));if(!R||R!==t.snapshot().sessionId||!j||!Number.isInteger(K)||K<0||K>100){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let oe=t.image?.(R,j,K);if(!oe||!["image/png","image/jpeg","image/webp","image/gif"].includes(oe.mimeType)){T(b,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}b.writeHead(200,{"Content-Type":oe.mimeType,"Cache-Control":"private, no-store"}),b.end(oe.data);return}if(k.method==="POST"&&x==="/api/attachment"){if(!Pe){T(b,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let _=new URL(k.url??x,E),R=_.searchParams.get("sessionId"),j=_.searchParams.get("name");try{if(!R||!j||j.length>1024||R!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(k.headers["content-length"]??0)>$n){T(b,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let K=await xu(R,j,k.headers["content-type"]??"application/octet-stream",await tA(k));if(R!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}h.set(K.id,K),T(b,201,{id:K.id,name:K.name,bytes:K.bytes})}catch(K){Y(K,400,K instanceof Error?K.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(k.method==="GET"&&x==="/api/session"){try{let _=t.snapshot();v(_),T(b,200,_)}catch(_){Y(_,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/plugin-management"){try{T(b,200,p.inventory(await u()))}catch(_){Y(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/plugins"){try{T(b,200,p.catalog(await u()))}catch(_){Y(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/providers"){try{T(b,200,await t.providers?.()??[])}catch(_){Y(_,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/provider/models"){let _=new URL(k.url??x,E).searchParams.get("providerId")??"";try{if(!_||!t.providerModels){T(b,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}T(b,200,await t.providerModels(_))}catch(R){Y(R,400,R instanceof Error?R.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/provider/login/active"){T(b,200,{active:f.getActive()??null});return}if(k.method==="GET"&&x==="/api/provider/login"){let _=new URL(k.url??x,E).searchParams.get("id")??"",R=f.get(_);T(b,R?200:404,R??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(k.method==="GET"&&(x==="/api/models"||x==="/api/config"||x==="/api/workspaces"||x==="/api/commands")){try{T(b,200,x==="/api/models"?await t.models():x==="/api/config"?await t.config():x==="/api/commands"?t.commands?.()??[]:await t.workspaces())}catch(_){Y(_,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/directory/capability"){T(b,200,{kind:o});return}if(k.method==="GET"&&x==="/api/events"){let _;try{_=t.snapshot(),v(_)}catch(R){Y(R,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}b.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),l.add(b),b.write(`${JSON.stringify({type:"snapshot",session:_})}
228
+ `),b.on("close",()=>l.delete(b));return}if(k.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/session/rename","/api/session/delete","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(x)){if(!Pe){T(b,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){T(b,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let _;try{_=await O_(k,x==="/api/plugin-action"?544*1024:64*1024)}catch(R){if(R instanceof Error&&R.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){T(b,413,{error:R.message});return}if(R instanceof SyntaxError||pi(R)){T(b,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw R}if(x==="/api/desktop/handoff"){let R=_;if(!R||typeof R.nonce!="string"||typeof R.requestId!="string"){T(b,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!t.selfUpdate?.requestLauncherHandoff){T(b,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(O||L||f.getActive()){T(b,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let j=p.restartBlocker()??p.restartConfirmations()[0];if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length||j){T(b,409,{error:j??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}O=!0;try{await t.selfUpdate.requestLauncherHandoff(R.nonce,R.requestId)}catch(K){throw O=!1,K}T(b,202,{accepted:!0,protocol:1,requestId:R.requestId});return}if(typeof _!="object"||_===null||!("sessionId"in _)||typeof _.sessionId!="string"){T(b,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(O&&x!=="/api/update/cancel"){T(b,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(x==="/api/plugin-management"){let R=_;if(typeof R.id!="string"||R.id.length>200||typeof R.enabled!="boolean"||typeof R.expected!="string"){T(b,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let j=()=>{if(t.snapshot().sessionId!==_.sessionId)throw new be("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length)throw new be("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(R.id,R.enabled,R.expected,j),T(b,200,p.inventory(await u()))}catch(K){if(K instanceof be)T(b,K.status,{error:K.message});else throw K}finally{g()}return}if(p.mutating&&x!=="/api/abort"){T(b,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(await p.dispatch({path:x,body:_,res:b,snapshot:()=>t.snapshot(),busyWorkspaces:()=>t.busyGitWorkspaces?.()??[],json:(R,j)=>T(b,R,j)}))return;if(x==="/api/plugin-interaction"){if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("requestId"in _)||typeof _.requestId!="string"||_.requestId.length>200||!t.resolvePluginInteraction||!("value"in _)){T(b,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(t.snapshot().cwd,async()=>t.resolvePluginInteraction(_.sessionId,_.pluginId,_.requestId,_.value)),T(b,200,{accepted:!0});return}if(x==="/api/plugin-action"){if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in _)||typeof _.pluginId!="string"||_.pluginId.length>200||!("action"in _)||typeof _.action!="string"||_.action.length>100){T(b,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(K=>K.metadata.id===_.pluginId)){let K=p.actionRoute(_.pluginId,_.action);if(!K){T(b,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let oe="input"in _?_.input:{};if(!oe||typeof oe!="object"||Array.isArray(oe)){T(b,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:K,body:{...oe,sessionId:_.sessionId},res:b,snapshot:()=>t.snapshot(),busyWorkspaces:()=>t.busyGitWorkspaces?.()??[],json:(et,li)=>T(b,et,et>=200&&et<300?{value:li}:li)});return}if(!t.invokePluginAction){T(b,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let j=await p.coordinateStart(t.snapshot().cwd,async()=>t.invokePluginAction(_.sessionId,_.pluginId,_.action,"input"in _?_.input:void 0));T(b,200,{value:j});return}if(x==="/api/update/channel"){if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in _)||_.channel!=="stable"&&_.channel!=="alpha"){T(b,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!t.selfUpdate?.setChannel){T(b,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}T(b,200,await t.selfUpdate.setChannel(_.channel));return}if(x==="/api/update/cancel"){if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!t.selfUpdate?.cancel){T(b,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await t.selfUpdate.cancel(),T(b,200,{cancelled:!0,dataPreserved:!0});return}if(x==="/api/update"){if(L){T(b,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!t.snapshot().idle){T(b,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!t.selfUpdate){T(b,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let R=p.restartBlocker();if((t.busyGitWorkspaces?.()??[]).length||R){T(b,409,{error:R??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let j=_,K="channel"in j||"version"in j||"allowDowngrade"in j;if(K&&(j.channel!=="stable"&&j.channel!=="alpha"||typeof j.version!="string"||j.allowDowngrade!==void 0&&typeof j.allowDowngrade!="boolean")){T(b,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if(j.force!==void 0&&typeof j.force!="boolean"){T(b,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let oe=j.force===!0,et=le=>T(b,409,{error:le.join("\uFF1B"),reason:"update_confirm_required"}),li=p.restartConfirmations();if(li.length&&!oe){et(li);return}L=!0;let _r;try{_r=await t.selfUpdate.prepare(K?{channel:j.channel,version:j.version,allowDowngrade:j.allowDowngrade}:void 0);let le=p.restartBlocker();if(!t.snapshot().idle||(t.busyGitWorkspaces?.()??[]).length||le)throw new Error(le??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let id=p.restartConfirmations();if(id.length&&!oe){et(id);return}oe&&await p.releaseForRestart(),O=!0;try{await t.selfUpdate.requestRestart(_r,{force:oe})}catch(rd){let nd=rd?.code;if(!oe&&(nd==="view_barrier"||nd==="drain_pending")){O=!1,et(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw rd}}catch(le){throw O=!1,le}finally{L=!1}T(b,202,{accepted:!0,version:_r.version});return}if(x==="/api/provider/custom"){if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in _)||!Ya(_.provider)||!t.addCustomProvider){T(b,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await t.addCustomProvider(_.sessionId,_.provider),T(b,201,{accepted:!0});return}if(x==="/api/provider/models"||x==="/api/provider/logout"){if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in _)||typeof _.providerId!="string"){T(b,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(x==="/api/provider/models"){if(!("change"in _)||!Cu(_.change)||!t.updateProviderModel){T(b,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await t.updateProviderModel(_.sessionId,_.providerId,_.change)}else{if(!t.logoutProvider){T(b,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await t.logoutProvider(_.sessionId,_.providerId)}T(b,200,{accepted:!0});return}if(x.startsWith("/api/provider/login")){if(_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(x==="/api/provider/login"){if(!("providerId"in _)||typeof _.providerId!="string"||!("method"in _)||_.method!=="api_key"&&_.method!=="oauth"||!t.loginProvider||!t.providers){T(b,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await t.providers()).some(oe=>oe.id===_.providerId&&oe.methods.includes(_.method))){T(b,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let j="initialSecret"in _?_.initialSecret:void 0;if(j!==void 0&&(_.method!=="api_key"||typeof j!="string"||!j.trim()||j.length>16384)){T(b,400,{error:"API Key \u65E0\u6548"});return}let K=f.start(_.providerId,_.method,t.loginProvider,j,$);T(b,202,{id:K.id});return}if(!("id"in _)||typeof _.id!="string"){T(b,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(x==="/api/provider/login/cancel"){T(b,f.cancel(_.id)?202:404,{accepted:!0});return}if(!("value"in _)||typeof _.value!="string"||_.value.length>16384||!f.respond(_.id,_.value)){T(b,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}T(b,202,{accepted:!0});return}if(x==="/api/attachment/remove"){if(!("id"in _)||typeof _.id!="string"||_.sessionId!==t.snapshot().sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}h.get(_.id)?.sessionId===_.sessionId&&h.delete(_.id),T(b,202,{accepted:!0});return}if(x==="/api/directory/pick"){if(o!=="native"){T(b,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let R=new AbortController;b.once("close",()=>R.abort()),T(b,200,{path:await Tu(R.signal)});return}if(x==="/api/directory/list"){if("path"in _&&(typeof _.path!="string"||_.path.length>4096)){T(b,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}T(b,200,await Su("path"in _?_.path:void 0));return}if(x==="/api/directory/create"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("name"in _)||typeof _.name!="string"||_.name.length>255){T(b,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}T(b,200,{path:await ku(_.path,_.name)});return}if(x==="/api/workspace/add"){if(!("path"in _)||typeof _.path!="string"||_.path.length>4096||!("create"in _)||typeof _.create!="boolean"){T(b,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await t.addWorkspace(_.path,_.create),T(b,202,{accepted:!0});return}if(x==="/api/workspace/select"||x==="/api/workspace/remove"||x==="/api/workspace/new-session"){if(!("id"in _)||typeof _.id!="string"){T(b,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}x==="/api/workspace/select"?await t.selectWorkspace(_.id):x==="/api/workspace/new-session"?await t.newSessionInWorkspace(_.id):await t.removeWorkspace(_.id),T(b,202,{accepted:!0});return}if(x==="/api/session/select"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"){T(b,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await t.selectSession(_.workspaceId,_.id,_.path),T(b,202,{accepted:!0});return}if(x==="/api/session/rename"||x==="/api/session/delete"){if(!("workspaceId"in _)||typeof _.workspaceId!="string"||!("id"in _)||typeof _.id!="string"||!("path"in _)||typeof _.path!="string"||_.path.length>4096){T(b,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(x==="/api/session/rename"){if(!("name"in _)||typeof _.name!="string"){T(b,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!t.renameSession){T(b,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await t.renameSession(_.workspaceId,_.id,_.path,_.name)}else{if(!t.deleteSession){T(b,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await t.deleteSession(_.workspaceId,_.id,_.path)}T(b,202,{accepted:!0});return}if(x==="/api/thinking-level"){if(!("level"in _)||typeof _.level!="string"){T(b,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await t.setThinkingLevel(_.sessionId,_.level)}else if(x==="/api/model"){if(!("provider"in _)||typeof _.provider!="string"||!("id"in _)||typeof _.id!="string"){T(b,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await t.setModel(_.sessionId,_.provider,_.id)}else if(x==="/api/config"){let R=_;if(!["packages","extensions","skills"].includes(R.kind)||!["global","project"].includes(R.scope)||!["add","remove"].includes(R.action)||typeof R.value!="string"||!R.value.trim()||R.value.length>2048){T(b,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(R.action==="add"&&R.kind!=="packages"&&qu(R.value)){T(b,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}T(b,200,await t.updateConfig(R));return}else if(x==="/api/prompt-queue"){let R=_,j=R.action;if(typeof R.id!="string"||R.id.length>100||!Number.isSafeInteger(R.revision)||R.revision<1||!j||typeof j!="object"||!["edit","remove","steer"].includes(j.kind)||j.kind==="edit"&&(typeof j.text!="string"||j.text.length>32e3)){T(b,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let K=t.snapshot();if(R.sessionId!==K.sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(j.kind==="steer"&&K.idle){T(b,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(j.kind==="steer"&&K.interactions?.length){T(b,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!t.updateQueuedPrompt){T(b,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(K.cwd,async()=>t.updateQueuedPrompt(_.sessionId,R.id,R.revision,j))}else if(x==="/api/message"){let R="delivery"in _?_.delivery:void 0;if(R!==void 0&&R!=="steer"&&R!=="followUp"){T(b,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let j="attachments"in _?_.attachments:[];if(!Array.isArray(j)||j.length>Au||j.some(le=>typeof le!="string")||new Set(j).size!==j.length){T(b,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let K=j.map(le=>h.get(le));if(K.some(le=>!le||le.sessionId!==_.sessionId)){T(b,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in _)||typeof _.text!="string"||!_.text.trim()&&j.length===0||_.text.length>32e3){T(b,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let oe=t.snapshot();if(_.sessionId!==oe.sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{Qt(oe,_.text,R)}catch(le){T(b,409,{error:le.message});return}let et=K,li=[_.text.trim(),...et.map(le=>`\u9644\u4EF6 ${JSON.stringify(le.name)}\uFF1A${le.path}`)].filter(Boolean).join(`
232
229
 
233
- `),gi=await Promise.all(je.filter(ge=>["image/png","image/jpeg","image/webp","image/gif"].includes(ge.mediaType)).map(sg));ae.operationId??=ld(),h.setHeader("X-Operation-ID",ae.operationId),t.breadcrumb("send",{...ae,attachmentCount:je.length}),await p.coordinateStart(ue.cwd,async()=>i.send(_.sessionId,qt,gi,ae,D));for(let ge of V)v.delete(ge)}else if(C==="/api/compact"){if(!i.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await i.compact(_.sessionId)}else if(C==="/api/resume"){let D=i.snapshot();if(_.sessionId!==D.sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!D.idle){O(h,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!D.paused){O(h,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(D.interactions?.length){O(h,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!i.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");ae.operationId??=ld(),h.setHeader("X-Operation-ID",ae.operationId),t.breadcrumb("resume",{...ae}),await p.coordinateStart(D.cwd,async()=>i.resume(_.sessionId,ae))}else C==="/api/abort"?await i.abort(_.sessionId):await i.newSession(_.sessionId);O(h,202,{accepted:!0})}catch(_){if(_ instanceof tt){O(h,_.status,{error:_.message});return}let D=p.requestFailure(_);if(D){O(h,D.status,D.body);return}let V=_ instanceof Error?_.message:"\u8BF7\u6C42\u5931\u8D25";me(_,V==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,V)}return}O(h,404,{error:"\u672A\u627E\u5230"})}catch(fe){h.headersSent?(t.capture(fe,{...ae,route:C,stage:"http_stream"}),h.end()):me(fe,500,"\u8BF7\u6C42\u5931\u8D25")}}),B=Number(process.env.PI_WEBAPP_RESTART_PORT),N;try{N=await iO(U,Number.isInteger(B)&&B>0&&B<65536&&n===s?B:0)}catch(k){throw t.capture(k,{stage:"listen"}),await t.close(),k}return T=`http://127.0.0.1:${N}`,{protocolVersion:7,buildId:It,runPluginTool:(k,h,M,Z,re,ae)=>p.runAgentAction(k,h,M,Z,re,ae),reportError(k,h){return t.capture(k,h)},breadcrumb(k,h){t.breadcrumb(k,h)},url:`${T}/#${s}`,publish(k){if(k.type==="snapshot"&&S(k.session),k.type==="error"&&!k.errorCode&&(k={...k,errorCode:"unexpected_error",errorId:t.capture(new Error("Agent execution failed"),{stage:"agent",requestId:k.requestId,operationId:k.operationId})}),k.type==="error"&&(k={...k,errorReported:k.errorReported??t.enabled}),k.type==="snapshot")for(let[M,Z]of v)Z.sessionId!==k.session.sessionId&&v.delete(M);let h=`${JSON.stringify(k)}
234
- `;for(let M of a)M.write(h)},async close(k){y.close(),await p.close();for(let M of a)M.end(`${JSON.stringify({type:"shutdown",reconnect:k?.reconnect??I})}
235
- `);a.clear();let h;try{await new Promise((M,Z)=>{U.close(re=>re?Z(re):M()),h=setTimeout(()=>U.closeAllConnections(),50).unref()})}finally{clearTimeout(h),await t.close()}}}}import{getSupportedThinkingLevels as rO}from"@earendil-works/pi-ai";var Zn="pi-webapp/paused",pd="pi-webapp/resume";function Hr(i){for(let e=i.length-1;e>=0;e--){let t=i[e];if(t.type==="custom_message"&&t.customType===pd)return!1;if(t.type==="custom"&&t.customType===Zn)return!0;if(t.type==="message"){if(t.message.role==="user")return!1;if(t.message.role==="assistant"){if(t.message.stopReason==="aborted")return!0;if(t.message.stopReason==="stop"||t.message.stopReason==="length"||t.message.stopReason==="error")return!1}}}return!1}function dd(i,e){let t=[],r;for(let n of i){if(n.type==="message"&&(r=n.id),n.type!=="custom")continue;let s=e.find(o=>n.customType.startsWith(`${o}/`));if(s){try{if(JSON.stringify(n.data).length>128*1024)continue}catch{continue}t.push({id:n.id,pluginId:s,kind:n.customType,data:n.data,timestamp:n.timestamp,...r?{afterMessageId:r}:{}})}}return t}function or(i){return typeof i=="string"?[{kind:"text",text:i}]:i.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function es(i){if(i.type==="custom_message")return i.display?{id:i.id,role:"notice",timestamp:i.timestamp,blocks:or(i.content)}:null;if(i.type!=="message")return null;let{message:e}=i;return e.role==="user"||e.role==="assistant"?{id:i.id,role:e.role,timestamp:i.timestamp,blocks:or(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:i.id,role:"tool",timestamp:i.timestamp,blocks:or(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function Xa(i,e){let t=i?.trim();if(t)return t;let r=e.find(s=>s.role==="user");return Jn(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function W0(i,e,t=[]){let r=i.sessionManager.getBranch().flatMap(n=>{let s=es(n);return s?[s]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:i.cwd,name:Xa(e,r),model:i.model?`${i.model.provider}/${i.model.id}`:null,thinkingLevel:i.thinkingLevel??null,thinkingLevels:i.model?rO(i.model):["off"],idle:i.isIdle(),paused:Hr(i.sessionManager.getBranch()),contextUsage:i.getContextUsage()??null,messages:r,pluginEntries:dd(i.sessionManager.getBranch(),t)}}import{randomUUID as ud}from"node:crypto";import{mkdir as z0,readFile as nO,realpath as md,rename as sO,rm as aO,stat as gd,writeFile as oO}from"node:fs/promises";import{basename as V0,dirname as lO,isAbsolute as $0,join as cO}from"node:path";var ts=class extends Error{constructor(){super("\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0")}};async function lr(i){try{let e=await md(i);return(await gd(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Qt(i){let e=await lr(i);if(e===null)throw new ts;return e}var Za=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await nO(this.file,"utf8")),t,r=[];if(Array.isArray(e)?t=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(t=e.items,r=e.hiddenPaths),!Array.isArray(t)||!Array.isArray(r))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=t.filter(n=>typeof n=="object"&&n!==null&&typeof n.id=="string"&&typeof n.path=="string"&&typeof n.title=="string"),this.hiddenPaths=r.filter(n=>typeof n=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(t=>t.id===e)}async add(e,t=!1){if(!$0(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await z0(e,{recursive:!0});let r=await md(e);if(!(await gd(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let n=this.hiddenPaths.filter(a=>a!==r),s=this.items.find(a=>a.path===r);if(s)return n.length!==this.hiddenPaths.length&&(await this.save(this.items,n),this.hiddenPaths=n),s;let o={id:ud(),path:r,title:V0(r)||r},l=[o,...this.items];return await this.save(l,n),this.items=l,this.hiddenPaths=n,o})}async discover(e){let t=(await Promise.all([...new Set(e)].filter($0).map(async r=>{try{let n=await md(r);return(await gd(n)).isDirectory()?n:null}catch{return null}}))).filter(r=>r!==null);await this.mutate(async()=>{let r=new Set([...this.items.map(o=>o.path),...this.hiddenPaths]),n=[];for(let o of t)r.has(o)||(r.add(o),n.push({id:ud(),path:o,title:V0(o)||o}));if(n.length===0)return;let s=[...this.items,...n];await this.save(s,this.hiddenPaths),this.items=s})}async remove(e){await this.mutate(async()=>{let t=this.get(e);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=this.items.filter(s=>s.id!==e),n=[...new Set([...this.hiddenPaths,t.path])];await this.save(r,n),this.items=r,this.hiddenPaths=n})}mutate(e){let t=this.mutationChain.then(e,e);return this.mutationChain=t.then(()=>{},()=>{}),t}async save(e,t){await z0(lO(this.file),{recursive:!0});let r=`${this.file}.${ud()}.tmp`;try{await oO(r,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await sO(r,this.file)}catch(n){throw await aO(r,{force:!0}),n}}};function Y0(i){return cO(i,"pi-web","workspaces.json")}import{createAgentSession as QO,createEventBus as JO,DefaultResourceLoader as XO,getAgentDir as ZO,SessionManager as ns,VERSION as no}from"@earendil-works/pi-coding-agent";function is(i,e){return!!i?.has(e)||Object.values(at).includes(e)}var K0="pi-webapp:interaction-open:v1",Q0="pi-webapp:interaction-accept:v1",bd="pi-webapp:interaction-settle:v1",J0="pi-webapp:interaction-cancel:v1",hd=class extends Error{};function eo(i,e,t,r=300){return new Promise((n,s)=>{let o=!1,l,a=(g,b)=>{o||(o=!0,clearTimeout(l),p(),d(),t?.removeEventListener("abort",c),g?s(g):n(b))},c=()=>{i.emit(J0,e),a(new Error("Interaction cancelled"))},p=i.on(Q0,g=>{g?.requestId===e.requestId&&clearTimeout(l)}),d=i.on(bd,g=>{let b=g;b?.requestId===e.requestId&&a(b.error?new Error(b.error):null,b.value)});l=setTimeout(()=>a(new hd("No Web interaction host")),r),t?.addEventListener("abort",c,{once:!0}),t?.aborted?c():i.emit(K0,e)})}var Wr=class{bus;accepts;changed;requests=new Map;detach;constructor(e,t,r){this.bus=e,this.accepts=t,this.changed=r,this.detach=[e.on(K0,n=>{!pO(n)||!t(n)||this.requests.has(n.requestId)||(this.requests.set(n.requestId,n),e.emit(Q0,{requestId:n.requestId}),r())}),e.on(J0,n=>{let s=n,o=this.requests.get(s?.requestId);o&&o.sessionId===s.sessionId&&o.pluginId===s.pluginId&&(this.requests.delete(s.requestId),r())})]}pending(e){return[...this.requests.values()].filter(t=>t.sessionId===e)}resolve(e,t,r,n){let s=this.requests.get(r);if(!s||s.sessionId!==e||s.pluginId!==t||!this.accepts(s))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(bd,{requestId:r,value:n}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(bd,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function pO(i){if(!i||typeof i!="object")return!1;let e=i;for(let t of["requestId","sessionId","pluginId","kind"])if(typeof e[t]!="string"||!e[t]||e[t].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function cr(i){return typeof i=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(i)&&i.length<=512&&!i.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function Di(i){if(!i||typeof i!="object"||Array.isArray(i))return!1;let e=i;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&cr(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&cr(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&cr(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&cr(e.resourcesManifest)&&/\.json$/.test(e.resourcesManifest)&&Number.isSafeInteger(e.dataSchemaVersion)&&e.dataSchemaVersion>0&&Array.isArray(e.supportedDataSchemas)&&e.supportedDataSchemas.length>0&&e.supportedDataSchemas.length<=32&&e.supportedDataSchemas.every(t=>Number.isSafeInteger(t)&&t>0)&&e.supportedDataSchemas.includes(e.dataSchemaVersion)&&Array.isArray(e.capabilities)&&e.capabilities.length<=64&&e.capabilities.every(t=>typeof t=="string"&&/^[a-z][a-z0-9.-]{0,79}$/.test(t))}var dO=1,uO="pi-webapp:action:v1",mO="pi-webapp:action-response:v1",to="pi-webapp:plugin-changed:v1";function X0(i){if(!i||typeof i!="object")return!1;let e=i;return e.apiVersion===dO&&typeof e.client=="string"&&/^\.\/dist\/[\w.-]+\.js$/.test(e.client)&&(e.style===void 0||typeof e.style=="string"&&/^\.\/dist\/[\w.-]+\.css$/.test(e.style))}function io(i,e,t=15e3,r){return new Promise((n,s)=>{let o=!1,l=(d,g)=>{o||(o=!0,clearTimeout(c),a(),r?.removeEventListener("abort",p),d?s(d):n(g))},a=i.on(mO,d=>{let g=d;g?.requestId===e.requestId&&l(g.ok?null:new Error(g.error??"Plugin action failed"),g.value)}),c=setTimeout(()=>l(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),t),p=()=>l(new Error("Plugin action runtime unloaded"));if(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{i.emit(uO,e)}catch(d){l(d instanceof Error?d:new Error(String(d)))}})}import{realpath as eR}from"node:fs/promises";import{readFile as yd,realpath as ik,stat as rk}from"node:fs/promises";import{createHash as gO}from"node:crypto";import{dirname as Z0,isAbsolute as bO,join as fd,parse as hO,resolve as yO,sep as fO,delimiter as _O}from"node:path";import{DefaultPackageManager as vO,getAgentDir as kO,SettingsManager as wO}from"@earendil-works/pi-coding-agent";async function ek(i,e){let t=await yd(i),r=e?await yd(e):void 0;if(t.length>8*1024*1024||(r?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let n=gO("sha256").update(t).update("\0").update(r??"").digest("hex");return{clientBytes:t,styleBytes:r,revision:n}}function SO(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(_O).filter(Boolean).map(i=>yO(i))}async function EO(i){let e=Z0(i);for(;e!==hO(e).root;)try{return await rk(fd(e,"package.json")),e}catch{e=Z0(e)}return null}async function tk(i,e){let t=await ik(fd(i,e));if(!t.startsWith(i+fO))throw new Error("Asset escapes package root");let r=await rk(t);if(!r.isFile()||r.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return t}var pr=class i{plugins;errors;extensionRoots;constructor(e,t,r){this.plugins=e,this.errors=t,this.extensionRoots=r}static async discover(e,t,r=SO()){let n=wO.create(e,void 0,{projectTrusted:t}),s=new vO({cwd:e,agentDir:kO(),settingsManager:n}),o=await s.resolve(async()=>"skip"),l=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},a=new Set;for(let b of[...o.extensions,...l.extensions]){if(!b.enabled)continue;let v=await EO(b.path);v&&a.add(v)}for(let b of r)bO(b)&&a.add(b);let c=[],p=[],d=[],g=new Set;for(let b of a)try{let v=await ik(b),y=JSON.parse(await yd(fd(v,"package.json"),"utf8"));if(y.piWebapp===void 0)continue;if(typeof y.name!="string"||!y.name)throw new Error("Missing package name");if(!X0(y.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(g.has(y.name))throw new Error(`Duplicate plugin id: ${y.name}`);let S=await tk(v,y.piWebapp.client),T=y.piWebapp.style?await tk(v,y.piWebapp.style):void 0;g.add(y.name),c.push({id:y.name,root:v,manifest:y.piWebapp,clientPath:S,stylePath:T,...await ek(S,T)}),d.push(v)}catch(v){p.push(`${b}: ${v instanceof Error?v.message:String(v)}`)}return c.sort((b,v)=>b.id.localeCompare(v.id)),new i(c,p,d)}has(e){return this.plugins.some(t=>t.id===e)}ids(){return this.plugins.map(e=>e.id)}async refreshAssets(){for(let e of this.plugins)Object.assign(e,await ek(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let t=new URL(e,"http://localhost"),r=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(t.pathname);if(!r)return null;let n;try{n=decodeURIComponent(r[1])}catch{return null}let s=this.plugins.find(l=>l.id===n);if(!s||t.searchParams.has("v")&&t.searchParams.get("v")!==s.revision)return null;let o=r[2]==="client.js"?s.clientBytes:s.styleBytes;return o?{bytes:o,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as TO}from"node:fs/promises";import{SessionManager as IO}from"@earendil-works/pi-coding-agent";async function zr(i,e){let t=await Qt(i),r=e??await IO.listAll(),n=await Promise.all(r.map(async s=>s.cwd!==""&&await TO(s.cwd).catch(()=>null)===t));return r.filter((s,o)=>n[o])}var dr=class{tail=Promise.resolve();run(e){let t=this.tail.then(e);return this.tail=t.catch(()=>{}),t}wrap(e){return(...t)=>this.run(()=>e(...t))}},nk=new WeakMap;function sk(i,e,t,r=5e3,n=()=>{}){let s=nk.get(i);if(s)return s;let o=(async()=>{let l;try{await Promise.race([i.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((a,c)=>{l=setTimeout(()=>c(new Error("Plugin shutdown timed out")),r)})])}catch(a){t(a instanceof Error?a.message:String(a))}finally{clearTimeout(l);try{n()}finally{i.dispose()}}})();return nk.set(i,o),o}function ro(i){let t=[...i].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
236
- `);return{customType:pd,display:!1,details:{action:"resume"},content:"The user clicked Continue for the interrupted turn. Continue the response to the latest user request from the interrupted point. Preserve completed work and do not repeat text already delivered. Check existing task progress when needed."+(t?`
230
+ `),_r=await Promise.all(et.filter(le=>["image/png","image/jpeg","image/webp","image/gif"].includes(le.mediaType)).map(Ou));$.operationId??=Kc(),b.setHeader("X-Operation-ID",$.operationId),i.breadcrumb("send",{...$,attachmentCount:et.length}),await p.coordinateStart(oe.cwd,async()=>t.send(_.sessionId,li,_r,$,R));for(let le of j)h.delete(le)}else if(x==="/api/compact"){if(!t.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await t.compact(_.sessionId)}else if(x==="/api/resume"){let R=t.snapshot();if(_.sessionId!==R.sessionId){T(b,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!R.idle){T(b,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!R.paused){T(b,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(R.interactions?.length){T(b,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!t.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");$.operationId??=Kc(),b.setHeader("X-Operation-ID",$.operationId),i.breadcrumb("resume",{...$}),await p.coordinateStart(R.cwd,async()=>t.resume(_.sessionId,$))}else x==="/api/abort"?await t.abort(_.sessionId):await t.newSession(_.sessionId);T(b,202,{accepted:!0})}catch(_){if(_ instanceof Ce){T(b,_.status,{error:_.message});return}let R=p.requestFailure(_);if(R){T(b,R.status,R.body);return}let j=_ instanceof Error?_.message:"\u8BF7\u6C42\u5931\u8D25";Y(_,j==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,j)}return}T(b,404,{error:"\u672A\u627E\u5230"})}catch(ae){b.headersSent?(i.capture(ae,{...$,route:x,stage:"http_stream"}),b.end()):Y(ae,500,"\u8BF7\u6C42\u5931\u8D25")}}),G=k=>Number.isInteger(k)&&k>=1&&k<=65535,N=Number(process.env.PI_WEBAPP_LISTEN_PORT),I=Number(process.env.PI_WEBAPP_RESTART_PORT),A=G(N)?N:n===s&&G(I)?I:0,D;try{D=await rA(P,A,S)}catch(k){throw i.capture(k,{stage:"listen"}),await i.close(),k?.code==="EADDRINUSE"?new Error(`\u7AEF\u53E3 ${A} \u5DF2\u88AB\u5360\u7528\uFF08EADDRINUSE\uFF09`,{cause:k}):new Error(`\u65E0\u6CD5\u76D1\u542C ${S}:${A}\uFF1A${k instanceof Error?k.message:String(k)}`,{cause:k})}return E=new URL(`http://127.0.0.1:${D}`).origin,{protocolVersion:7,buildId:it,runPluginTool:(k,b,q,F,W,$)=>p.runAgentAction(k,b,q,F,W,$),reportError(k,b){return i.capture(k,b)},breadcrumb(k,b){i.breadcrumb(k,b)},url:`${E}/#${s}`,publish(k){if(k.type==="snapshot"&&v(k.session),k.type==="error"&&!k.errorCode&&(k={...k,errorCode:"unexpected_error",errorId:i.capture(new Error("Agent execution failed"),{stage:"agent",requestId:k.requestId,operationId:k.operationId})}),k.type==="error"&&(k={...k,errorReported:k.errorReported??i.enabled}),k.type==="snapshot")for(let[q,F]of h)F.sessionId!==k.session.sessionId&&h.delete(q);let b=`${JSON.stringify(k)}
231
+ `;for(let q of l)q.write(b)},async close(k){f.close(),await p.close();for(let q of l)q.end(`${JSON.stringify({type:"shutdown",reconnect:k?.reconnect??O})}
232
+ `);l.clear();let b;try{await new Promise((q,F)=>{P.close(W=>W?F(W):q()),b=setTimeout(()=>P.closeAllConnections(),50).unref()})}finally{clearTimeout(b),await i.close()}}}}import{getSupportedThinkingLevels as nA}from"@earendil-works/pi-ai";var fn="pi-webapp/paused",Qc="pi-webapp/resume";function nr(t){for(let e=t.length-1;e>=0;e--){let i=t[e];if(i.type==="custom_message"&&i.customType===Qc)return!1;if(i.type==="custom"&&i.customType===fn)return!0;if(i.type==="message"){if(i.message.role==="user")return!1;if(i.message.role==="assistant"){if(i.message.stopReason==="aborted")return!0;if(i.message.stopReason==="stop"||i.message.stopReason==="length"||i.message.stopReason==="error")return!1}}}return!1}function Jc(t,e){let i=[],r;for(let n of t){if(n.type==="message"&&(r=n.id),n.type!=="custom")continue;let s=e.find(a=>n.customType.startsWith(`${a}/`));if(s){try{if(JSON.stringify(n.data).length>128*1024)continue}catch{continue}i.push({id:n.id,pluginId:s,kind:n.customType,data:n.data,timestamp:n.timestamp,...r?{afterMessageId:r}:{}})}}return i}function Ii(t){return typeof t=="string"?[{kind:"text",text:t}]:t.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function hn(t){if(t.type==="custom_message")return t.display?{id:t.id,role:"notice",timestamp:t.timestamp,blocks:Ii(t.content)}:null;if(t.type!=="message")return null;let{message:e}=t;return e.role==="user"||e.role==="assistant"?{id:t.id,role:e.role,timestamp:t.timestamp,blocks:Ii(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:t.id,role:"tool",timestamp:t.timestamp,blocks:Ii(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function ea(t,e){let i=t?.trim();if(i)return i;let r=e.find(s=>s.role==="user");return mn(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function N_(t,e,i=[]){let r=t.sessionManager.getBranch().flatMap(n=>{let s=hn(n);return s?[s]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:t.cwd,name:ea(e,r),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel??null,thinkingLevels:t.model?nA(t.model):["off"],idle:t.isIdle(),paused:nr(t.sessionManager.getBranch()),contextUsage:t.getContextUsage()??null,messages:r,pluginEntries:Jc(t.sessionManager.getBranch(),i)}}import{randomUUID as Xc}from"node:crypto";import{mkdir as P_,readFile as sA,realpath as Zc,rename as aA,rm as oA,stat as ep,writeFile as lA}from"node:fs/promises";import{basename as C_,dirname as cA,isAbsolute as M_,join as pA}from"node:path";var yn=class extends Error{constructor(){super("\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0")}};async function Ai(t){try{let e=await Zc(t);return(await ep(e)).isDirectory()?e:null}catch(e){let i=e.code;if(i==="ENOENT"||i==="ENOTDIR")return null;throw e}}async function kt(t){let e=await Ai(t);if(e===null)throw new yn;return e}var ta=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await sA(this.file,"utf8")),i,r=[];if(Array.isArray(e)?i=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(i=e.items,r=e.hiddenPaths),!Array.isArray(i)||!Array.isArray(r))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=i.filter(n=>typeof n=="object"&&n!==null&&typeof n.id=="string"&&typeof n.path=="string"&&typeof n.title=="string"),this.hiddenPaths=r.filter(n=>typeof n=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(i=>i.id===e)}async add(e,i=!1){if(!M_(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");i&&await P_(e,{recursive:!0});let r=await Zc(e);if(!(await ep(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let n=this.hiddenPaths.filter(l=>l!==r),s=this.items.find(l=>l.path===r);if(s)return n.length!==this.hiddenPaths.length&&(await this.save(this.items,n),this.hiddenPaths=n),s;let a={id:Xc(),path:r,title:C_(r)||r},o=[a,...this.items];return await this.save(o,n),this.items=o,this.hiddenPaths=n,a})}async discover(e){let i=(await Promise.all([...new Set(e)].filter(M_).map(async r=>{try{let n=await Zc(r);return(await ep(n)).isDirectory()?n:null}catch{return null}}))).filter(r=>r!==null);await this.mutate(async()=>{let r=new Set([...this.items.map(a=>a.path),...this.hiddenPaths]),n=[];for(let a of i)r.has(a)||(r.add(a),n.push({id:Xc(),path:a,title:C_(a)||a}));if(n.length===0)return;let s=[...this.items,...n];await this.save(s,this.hiddenPaths),this.items=s})}async remove(e){await this.mutate(async()=>{let i=this.get(e);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=this.items.filter(s=>s.id!==e),n=[...new Set([...this.hiddenPaths,i.path])];await this.save(r,n),this.items=r,this.hiddenPaths=n})}mutate(e){let i=this.mutationChain.then(e,e);return this.mutationChain=i.then(()=>{},()=>{}),i}async save(e,i){await P_(cA(this.file),{recursive:!0});let r=`${this.file}.${Xc()}.tmp`;try{await lA(r,JSON.stringify({version:2,items:e,hiddenPaths:i},null,2),{mode:384}),await aA(r,this.file)}catch(n){throw await oA(r,{force:!0}),n}}};function D_(t){return pA(t,"pi-web","workspaces.json")}import{createAgentSession as JA,createEventBus as XA,DefaultResourceLoader as ZA,getAgentDir as ex,SessionManager as vn,VERSION as aa}from"@earendil-works/pi-coding-agent";function bn(t,e){return!!t?.has(e)||Object.values(je).includes(e)}var L_="pi-webapp:interaction-open:v1",U_="pi-webapp:interaction-accept:v1",tp="pi-webapp:interaction-settle:v1",q_="pi-webapp:interaction-cancel:v1",ip=class extends Error{};function ia(t,e,i,r=300){return new Promise((n,s)=>{let a=!1,o,l=(m,g)=>{a||(a=!0,clearTimeout(o),p(),u(),i?.removeEventListener("abort",c),m?s(m):n(g))},c=()=>{t.emit(q_,e),l(new Error("Interaction cancelled"))},p=t.on(U_,m=>{m?.requestId===e.requestId&&clearTimeout(o)}),u=t.on(tp,m=>{let g=m;g?.requestId===e.requestId&&l(g.error?new Error(g.error):null,g.value)});o=setTimeout(()=>l(new ip("No Web interaction host")),r),i?.addEventListener("abort",c,{once:!0}),i?.aborted?c():t.emit(L_,e)})}var sr=class{bus;accepts;changed;requests=new Map;detach;constructor(e,i,r){this.bus=e,this.accepts=i,this.changed=r,this.detach=[e.on(L_,n=>{!dA(n)||!i(n)||this.requests.has(n.requestId)||(this.requests.set(n.requestId,n),e.emit(U_,{requestId:n.requestId}),r())}),e.on(q_,n=>{let s=n,a=this.requests.get(s?.requestId);a&&a.sessionId===s.sessionId&&a.pluginId===s.pluginId&&(this.requests.delete(s.requestId),r())})]}pending(e){return[...this.requests.values()].filter(i=>i.sessionId===e)}resolve(e,i,r,n){let s=this.requests.get(r);if(!s||s.sessionId!==e||s.pluginId!==i||!this.accepts(s))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(tp,{requestId:r,value:n}),this.changed()}cancelAll(e="Session changed"){for(let i of this.requests.values())this.bus.emit(tp,{requestId:i.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function dA(t){if(!t||typeof t!="object")return!1;let e=t;for(let i of["requestId","sessionId","pluginId","kind"])if(typeof e[i]!="string"||!e[i]||e[i].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function xi(t){return typeof t=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(t)&&t.length<=512&&!t.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function ei(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&xi(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&xi(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&xi(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&xi(e.resourcesManifest)&&/\.json$/.test(e.resourcesManifest)&&Number.isSafeInteger(e.dataSchemaVersion)&&e.dataSchemaVersion>0&&Array.isArray(e.supportedDataSchemas)&&e.supportedDataSchemas.length>0&&e.supportedDataSchemas.length<=32&&e.supportedDataSchemas.every(i=>Number.isSafeInteger(i)&&i>0)&&e.supportedDataSchemas.includes(e.dataSchemaVersion)&&Array.isArray(e.capabilities)&&e.capabilities.length<=64&&e.capabilities.every(i=>typeof i=="string"&&/^[a-z][a-z0-9.-]{0,79}$/.test(i))}var uA=1,mA="pi-webapp:action:v1",gA="pi-webapp:action-response:v1",ra="pi-webapp:plugin-changed:v1";function j_(t){if(!t||typeof t!="object")return!1;let e=t;return e.apiVersion===uA&&typeof e.client=="string"&&/^\.\/dist\/[\w.-]+\.js$/.test(e.client)&&(e.style===void 0||typeof e.style=="string"&&/^\.\/dist\/[\w.-]+\.css$/.test(e.style))}function na(t,e,i=15e3,r){return new Promise((n,s)=>{let a=!1,o=(u,m)=>{a||(a=!0,clearTimeout(c),l(),r?.removeEventListener("abort",p),u?s(u):n(m))},l=t.on(gA,u=>{let m=u;m?.requestId===e.requestId&&o(m.ok?null:new Error(m.error??"Plugin action failed"),m.value)}),c=setTimeout(()=>o(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),i),p=()=>o(new Error("Plugin action runtime unloaded"));if(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{t.emit(mA,e)}catch(u){o(u instanceof Error?u:new Error(String(u)))}})}import{realpath as tx}from"node:fs/promises";import{readFile as rp,realpath as G_,stat as W_}from"node:fs/promises";import{createHash as fA}from"node:crypto";import{dirname as B_,isAbsolute as hA,join as np,parse as yA,resolve as bA,sep as _A,delimiter as vA}from"node:path";import{DefaultPackageManager as wA,getAgentDir as SA,SettingsManager as kA}from"@earendil-works/pi-coding-agent";async function F_(t,e){let i=await rp(t),r=e?await rp(e):void 0;if(i.length>8*1024*1024||(r?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let n=fA("sha256").update(i).update("\0").update(r??"").digest("hex");return{clientBytes:i,styleBytes:r,revision:n}}function EA(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(vA).filter(Boolean).map(t=>bA(t))}async function TA(t){let e=B_(t);for(;e!==yA(e).root;)try{return await W_(np(e,"package.json")),e}catch{e=B_(e)}return null}async function H_(t,e){let i=await G_(np(t,e));if(!i.startsWith(t+_A))throw new Error("Asset escapes package root");let r=await W_(i);if(!r.isFile()||r.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return i}var Oi=class t{plugins;errors;extensionRoots;constructor(e,i,r){this.plugins=e,this.errors=i,this.extensionRoots=r}static async discover(e,i,r=EA()){let n=kA.create(e,void 0,{projectTrusted:i}),s=new wA({cwd:e,agentDir:SA(),settingsManager:n}),a=await s.resolve(async()=>"skip"),o=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},l=new Set;for(let g of[...a.extensions,...o.extensions]){if(!g.enabled)continue;let h=await TA(g.path);h&&l.add(h)}for(let g of r)hA(g)&&l.add(g);let c=[],p=[],u=[],m=new Set;for(let g of l)try{let h=await G_(g),f=JSON.parse(await rp(np(h,"package.json"),"utf8"));if(f.piWebapp===void 0)continue;if(typeof f.name!="string"||!f.name)throw new Error("Missing package name");if(!j_(f.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(m.has(f.name))throw new Error(`Duplicate plugin id: ${f.name}`);let v=await H_(h,f.piWebapp.client),S=f.piWebapp.style?await H_(h,f.piWebapp.style):void 0;m.add(f.name),c.push({id:f.name,root:h,manifest:f.piWebapp,clientPath:v,stylePath:S,...await F_(v,S)}),u.push(h)}catch(h){p.push(`${g}: ${h instanceof Error?h.message:String(h)}`)}return c.sort((g,h)=>g.id.localeCompare(h.id)),new t(c,p,u)}has(e){return this.plugins.some(i=>i.id===e)}ids(){return this.plugins.map(e=>e.id)}async refreshAssets(){for(let e of this.plugins)Object.assign(e,await F_(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let i=new URL(e,"http://localhost"),r=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(i.pathname);if(!r)return null;let n;try{n=decodeURIComponent(r[1])}catch{return null}let s=this.plugins.find(o=>o.id===n);if(!s||i.searchParams.has("v")&&i.searchParams.get("v")!==s.revision)return null;let a=r[2]==="client.js"?s.clientBytes:s.styleBytes;return a?{bytes:a,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as IA}from"node:fs/promises";import{SessionManager as AA}from"@earendil-works/pi-coding-agent";async function ar(t,e){let i=await kt(t),r=e??await AA.listAll(),n=await Promise.all(r.map(async s=>s.cwd!==""&&await IA(s.cwd).catch(()=>null)===i));return r.filter((s,a)=>n[a])}var Ri=class{tail=Promise.resolve();run(e){let i=this.tail.then(e);return this.tail=i.catch(()=>{}),i}wrap(e){return(...i)=>this.run(()=>e(...i))}},$_=new WeakMap;function V_(t,e,i,r=5e3,n=()=>{}){let s=$_.get(t);if(s)return s;let a=(async()=>{let o;try{await Promise.race([t.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((l,c)=>{o=setTimeout(()=>c(new Error("Plugin shutdown timed out")),r)})])}catch(l){i(l instanceof Error?l.message:String(l))}finally{clearTimeout(o);try{n()}finally{t.dispose()}}})();return $_.set(t,a),a}function sa(t){let i=[...t].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
233
+ `);return{customType:Qc,display:!1,details:{action:"resume"},content:"The user clicked Continue for the interrupted turn. Continue the response to the latest user request from the interrupted point. Preserve completed work and do not repeat text already delivered. Check existing task progress when needed."+(i?`
237
234
  Already displayed assistant text (reference data):
238
- ${JSON.stringify(t)}`:"")}}import{createHash as xO}from"node:crypto";import{readFile as ok,realpath as ak,writeFile as AO,unlink as OO}from"node:fs/promises";import{basename as RO,dirname as _d,extname as NO,isAbsolute as CO,join as lk,parse as PO,relative as DO,sep as MO}from"node:path";import{DefaultPackageManager as ck,getAgentDir as pk,SettingsManager as dk}from"@earendil-works/pi-coding-agent";var rs=new Map;async function LO(i){let e=_d(i);for(;e!==PO(e).root;){try{let t=JSON.parse(await ok(lk(e,"package.json"),"utf8"));if(typeof t.name=="string")return t.name}catch{}e=_d(e)}return null}function qO(i,e){let t=DO(i,e);return t===""||t!==".."&&!t.startsWith(`..${MO}`)&&!CO(t)}async function uk(i,e,t){let r=dk.create(i,void 0,{projectTrusted:t}),s=await new ck({cwd:i,agentDir:pk(),settingsManager:r}).resolve(async()=>"skip"),o=await Promise.all(e.map(c=>ak(c))),l=new Set;for(let c of s.extensions){if(!c.enabled||c.path.startsWith("builtin:"))continue;let p=await ak(c.path);await LO(p)!=="pi-webapp"&&(o.some(d=>qO(d,p))||l.add(p))}let a=await UO(i,o);return{paths:[...a.paths,...l],release:a.release}}async function UO(i,e){let r=await new ck({cwd:i,agentDir:pk(),settingsManager:dk.create(i)}).resolveExtensionSources([...e],{temporary:!0}),n=[],s=[],o=async()=>{for(let a of n.splice(0)){let c=(rs.get(a)??1)-1;c?rs.set(a,c):(rs.delete(a),await OO(a).catch(()=>{}))}},l=new Set;try{for(let a of r.extensions){if(!a.enabled||l.has(a.path))continue;l.add(a.path);let c=NO(a.path);if(![".js",".mjs"].includes(c)){s.push(a.path);continue}let p=await ok(a.path),d=xO("sha256").update(p).digest("hex"),g=lk(_d(a.path),`.pi-web-runtime-${RO(a.path,c)}-${d}${c}`);await AO(g,p,{flag:"wx"}).catch(b=>{if(b.code!=="EEXIST")throw b}),rs.set(g,(rs.get(g)??0)+1),n.push(g),s.push(g)}return{paths:s,release:o}}catch(a){throw await o(),a}}import{createHash as jO}from"node:crypto";var vd={ENOENT:{kind:"not_found",summary:"no such file or directory"},ENOTDIR:{kind:"not_found",summary:"not a directory"},EACCES:{kind:"permission",summary:"permission denied"},EPERM:{kind:"permission",summary:"operation not permitted"},ETIMEDOUT:{kind:"timeout",summary:"operation timed out"},EINVAL:{kind:"validation",summary:"invalid argument"}},Mi=i=>i!==null&&typeof i=="object"?i:void 0,BO=[{pattern:/^Could not find (?:the exact text in [^\r\n]+\. The old text|edits\[\d+\] in [^\r\n]+\. The oldText) must match exactly including all whitespace and newlines\.$/,code:"edit_text_not_found",summary:"Edit text does not match the file"},{pattern:/^Found \d+ occurrences of (?:the text in [^\r\n]+\. The text|edits\[\d+\] in [^\r\n]+\. Each oldText) must be unique\. Please provide more context to make it unique\.$/,code:"edit_text_ambiguous",summary:"Edit text matches multiple locations"},{pattern:/^(?:edits\[\d+\]\.)?oldText must not be empty in [^\r\n]+\.$/,code:"invalid_arguments",summary:"Edit oldText must not be empty"},{pattern:/^No changes made to [^\r\n]+\. (?:The replacement produced identical content\. This might indicate an issue with special characters or the text not existing as expected\.|The replacements produced identical content\.)$/,code:"edit_no_change",summary:"Edit replacement produced no changes"},{pattern:/^edits\[\d+\] and edits\[\d+\] overlap in [^\r\n]+\. Merge them into one edit or target disjoint regions\.$/,code:"edit_overlap",summary:"Edit replacements overlap"}];function gk(i,e){let t=i instanceof Error?i:Mi(i)?.error instanceof Error?Mi(i).error:void 0,r={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!t?.stack,level:"error"},n=(p,d,g)=>{Object.assign(r,{failureKind:p,errorCode:d,errorSummary:g.slice(0,512),summaryOmitted:!1,level:t?"error":"warning"}),delete r.summaryOmittedReason},s=Mi(t)?.code;if(typeof s=="string"&&vd[s]){let p=vd[s];return n(p.kind,s,`${s}: ${p.summary}`),r}let o=t?.message??"";if(!t){let p=Mi(i)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(d=>{let g=Mi(d);return g?.type==="text"&&typeof g.text=="string"?[g.text.length>16384?`${g.text.slice(0,8192)}
235
+ ${JSON.stringify(i)}`:"")}}import{createHash as xA}from"node:crypto";import{readFile as K_,realpath as z_,writeFile as OA,unlink as RA}from"node:fs/promises";import{basename as NA,dirname as sp,extname as PA,isAbsolute as CA,join as Y_,parse as MA,relative as DA,sep as LA}from"node:path";import{DefaultPackageManager as Q_,getAgentDir as J_,SettingsManager as X_}from"@earendil-works/pi-coding-agent";var _n=new Map;async function UA(t){let e=sp(t);for(;e!==MA(e).root;){try{let i=JSON.parse(await K_(Y_(e,"package.json"),"utf8"));if(typeof i.name=="string")return i.name}catch{}e=sp(e)}return null}function qA(t,e){let i=DA(t,e);return i===""||i!==".."&&!i.startsWith(`..${LA}`)&&!CA(i)}async function Z_(t,e,i){let r=X_.create(t,void 0,{projectTrusted:i}),s=await new Q_({cwd:t,agentDir:J_(),settingsManager:r}).resolve(async()=>"skip"),a=await Promise.all(e.map(c=>z_(c))),o=new Set;for(let c of s.extensions){if(!c.enabled||c.path.startsWith("builtin:"))continue;let p=await z_(c.path);await UA(p)!=="pi-webapp"&&(a.some(u=>qA(u,p))||o.add(p))}let l=await jA(t,a);return{paths:[...l.paths,...o],release:l.release}}async function jA(t,e){let r=await new Q_({cwd:t,agentDir:J_(),settingsManager:X_.create(t)}).resolveExtensionSources([...e],{temporary:!0}),n=[],s=[],a=async()=>{for(let l of n.splice(0)){let c=(_n.get(l)??1)-1;c?_n.set(l,c):(_n.delete(l),await RA(l).catch(()=>{}))}},o=new Set;try{for(let l of r.extensions){if(!l.enabled||o.has(l.path))continue;o.add(l.path);let c=PA(l.path);if(![".js",".mjs"].includes(c)){s.push(l.path);continue}let p=await K_(l.path),u=xA("sha256").update(p).digest("hex"),m=Y_(sp(l.path),`.pi-web-runtime-${NA(l.path,c)}-${u}${c}`);await OA(m,p,{flag:"wx"}).catch(g=>{if(g.code!=="EEXIST")throw g}),_n.set(m,(_n.get(m)??0)+1),n.push(m),s.push(m)}return{paths:s,release:a}}catch(l){throw await a(),l}}import{createHash as BA}from"node:crypto";var ap={ENOENT:{kind:"not_found",summary:"no such file or directory"},ENOTDIR:{kind:"not_found",summary:"not a directory"},EACCES:{kind:"permission",summary:"permission denied"},EPERM:{kind:"permission",summary:"operation not permitted"},ETIMEDOUT:{kind:"timeout",summary:"operation timed out"},EINVAL:{kind:"validation",summary:"invalid argument"}},ti=t=>t!==null&&typeof t=="object"?t:void 0,FA=[{pattern:/^Could not find (?:the exact text in [^\r\n]+\. The old text|edits\[\d+\] in [^\r\n]+\. The oldText) must match exactly including all whitespace and newlines\.$/,code:"edit_text_not_found",summary:"Edit text does not match the file"},{pattern:/^Found \d+ occurrences of (?:the text in [^\r\n]+\. The text|edits\[\d+\] in [^\r\n]+\. Each oldText) must be unique\. Please provide more context to make it unique\.$/,code:"edit_text_ambiguous",summary:"Edit text matches multiple locations"},{pattern:/^(?:edits\[\d+\]\.)?oldText must not be empty in [^\r\n]+\.$/,code:"invalid_arguments",summary:"Edit oldText must not be empty"},{pattern:/^No changes made to [^\r\n]+\. (?:The replacement produced identical content\. This might indicate an issue with special characters or the text not existing as expected\.|The replacements produced identical content\.)$/,code:"edit_no_change",summary:"Edit replacement produced no changes"},{pattern:/^edits\[\d+\] and edits\[\d+\] overlap in [^\r\n]+\. Merge them into one edit or target disjoint regions\.$/,code:"edit_overlap",summary:"Edit replacements overlap"}];function tv(t,e){let i=t instanceof Error?t:ti(t)?.error instanceof Error?ti(t).error:void 0,r={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!i?.stack,level:"error"},n=(p,u,m)=>{Object.assign(r,{failureKind:p,errorCode:u,errorSummary:m.slice(0,512),summaryOmitted:!1,level:i?"error":"warning"}),delete r.summaryOmittedReason},s=ti(i)?.code;if(typeof s=="string"&&ap[s]){let p=ap[s];return n(p.kind,s,`${s}: ${p.summary}`),r}let a=i?.message??"";if(!i){let p=ti(t)?.content;Array.isArray(p)&&(a=p.slice(0,8).flatMap(u=>{let m=ti(u);return m?.type==="text"&&typeof m.text=="string"?[m.text.length>16384?`${m.text.slice(0,8192)}
239
236
  [truncated]
240
- ${g.text.slice(-8192)}`:g.text]:[]}).join(`
241
- `))}let l=e==="bash"||e==="powershell",a=o.slice(-8192).trimEnd().split(/\r?\n/).at(-1)??"";if(l){let p=a.match(/^Command exited with code (-?\d{1,10})$/),d=a.match(/^Command timed out after (\d+(?:\.\d+)?) seconds$/);if(p&&Number.isSafeInteger(Number(p[1]))&&Number(p[1])!==0)return n("process_exit","nonzero_exit",a),r.exitCode=Number(p[1]),r;if(d&&Number.isFinite(Number(d[1]))&&Number(d[1])>0)return n("timeout","timeout",a),r.timeoutMs=Number(d[1])*1e3,r;if(a==="Command aborted")return n("cancelled","cancelled",a),r}let c=o.slice(0,8192).split(/\r?\n/,1)[0]??"";if(o==="Operation aborted"||t?.name==="AbortError")n("cancelled","cancelled","Operation aborted");else if(o==="Tool execution was blocked")n("blocked","blocked",o);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(o))n("not_found","ENOENT","Working directory does not exist");else if(!l||!o.includes(`
242
- `)||/^Validation failed for tool\b/.test(c)){let p=c.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let d=vd[p[1]],g=c.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);n(d.kind,p[1],`${p[1]}: ${d.summary}${g?`; operation=${g[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(o))n("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(c)||c==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(c))n("validation","invalid_arguments",c.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(o))n("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let d=BO.find(g=>g.pattern.test(o));d&&n("validation",d.code,d.summary)}}return r}var FO=256;function mk(i,e,t){i.delete(e),i.set(e,t),i.size>FO&&i.delete(i.keys().next().value)}var Vr=class{options;pending=new Map;completed=new Map;constructor(e){this.options=e}enabled(){return this.options.enabled()?!0:(this.clear(),!1)}identity(e){return{toolName:Is.has(e.toolName)?e.toolName:"custom",...Is.has(e.toolName)?{}:{toolId:jO("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,t){try{this.options.breadcrumb(e,t)}catch{}}start(e,t={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let r=e.toolName==="bash"||e.toolName==="powershell"?Mi(e.args)?.timeout:void 0,n=typeof r=="number"&&r>0&&Number.isFinite(r*1e3)?r*1e3:void 0,s={...Tt(t),...this.identity(e),stage:"tool"};mk(this.pending,e.toolCallId,{context:s,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:n}),this.breadcrumb("tool_start",s)}catch{}}end(e,t={}){this.finish(e,t,"tool_execution_end")}message(e,t={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},t,"message_end")}catch{}}finish(e,t,r){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let n=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),mk(this.completed,e.toolCallId,!0);let s={...n?.context??{...Tt(t),...this.identity(e),stage:"tool"},diagnosticSource:r};if(n&&(s.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-n.started)),n.timeoutMs!==void 0&&(s.timeoutMs=n.timeoutMs)),!e.isError){this.breadcrumb("tool_end",s);return}let o=e.result instanceof Error?e.result:Mi(e.result)?.error instanceof Error?Mi(e.result).error:void 0,l=n?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:gk(e.result,e.toolName);if(Object.assign(s,l,{code:"tool_failed"}),this.breadcrumb(l.failureKind==="cancelled"?"tool_cancelled":l.failureKind==="blocked"?"tool_blocked":"tool_failed",s),l.failureKind==="cancelled"||l.failureKind==="blocked")return;let a;o?a=bk(o,e.toolName):(a=new Error(`${s.toolName}: ${l.failureKind} (${l.errorCode??"unknown"})`),a.name="ToolResultFailure",a.stack=void 0),this.options.capture(a,s)}catch{}}cancel(){try{if(!this.enabled())return;for(let e of this.pending.values())e.cancelled=!0}catch{}}clear(){this.pending.clear(),this.completed.clear()}};function bk(i,e,t=0){let r=gk(i,e),n=new Error(r.errorSummary??"Tool exception (diagnostic text unavailable)");return n.name=i.name,n.stack=i.stack?`${n.name}: ${n.message}
243
- ${i.stack.split(`
237
+ ${m.text.slice(-8192)}`:m.text]:[]}).join(`
238
+ `))}let o=e==="bash"||e==="powershell",l=a.slice(-8192).trimEnd().split(/\r?\n/).at(-1)??"";if(o){let p=l.match(/^Command exited with code (-?\d{1,10})$/),u=l.match(/^Command timed out after (\d+(?:\.\d+)?) seconds$/);if(p&&Number.isSafeInteger(Number(p[1]))&&Number(p[1])!==0)return n("process_exit","nonzero_exit",l),r.exitCode=Number(p[1]),r;if(u&&Number.isFinite(Number(u[1]))&&Number(u[1])>0)return n("timeout","timeout",l),r.timeoutMs=Number(u[1])*1e3,r;if(l==="Command aborted")return n("cancelled","cancelled",l),r}let c=a.slice(0,8192).split(/\r?\n/,1)[0]??"";if(a==="Operation aborted"||i?.name==="AbortError")n("cancelled","cancelled","Operation aborted");else if(a==="Tool execution was blocked")n("blocked","blocked",a);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(a))n("not_found","ENOENT","Working directory does not exist");else if(!o||!a.includes(`
239
+ `)||/^Validation failed for tool\b/.test(c)){let p=c.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let u=ap[p[1]],m=c.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);n(u.kind,p[1],`${p[1]}: ${u.summary}${m?`; operation=${m[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(a))n("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(c)||c==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(c))n("validation","invalid_arguments",c.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(a))n("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let u=FA.find(m=>m.pattern.test(a));u&&n("validation",u.code,u.summary)}}return r}var HA=256;function ev(t,e,i){t.delete(e),t.set(e,i),t.size>HA&&t.delete(t.keys().next().value)}var or=class{options;pending=new Map;completed=new Map;constructor(e){this.options=e}enabled(){return this.options.enabled()?!0:(this.clear(),!1)}identity(e){return{toolName:Un.has(e.toolName)?e.toolName:"custom",...Un.has(e.toolName)?{}:{toolId:BA("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,i){try{this.options.breadcrumb(e,i)}catch{}}start(e,i={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let r=e.toolName==="bash"||e.toolName==="powershell"?ti(e.args)?.timeout:void 0,n=typeof r=="number"&&r>0&&Number.isFinite(r*1e3)?r*1e3:void 0,s={...tt(i),...this.identity(e),stage:"tool"};ev(this.pending,e.toolCallId,{context:s,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:n}),this.breadcrumb("tool_start",s)}catch{}}end(e,i={}){this.finish(e,i,"tool_execution_end")}message(e,i={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},i,"message_end")}catch{}}finish(e,i,r){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let n=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),ev(this.completed,e.toolCallId,!0);let s={...n?.context??{...tt(i),...this.identity(e),stage:"tool"},diagnosticSource:r};if(n&&(s.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-n.started)),n.timeoutMs!==void 0&&(s.timeoutMs=n.timeoutMs)),!e.isError){this.breadcrumb("tool_end",s);return}let a=e.result instanceof Error?e.result:ti(e.result)?.error instanceof Error?ti(e.result).error:void 0,o=n?.cancelled&&!a?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:tv(e.result,e.toolName);if(Object.assign(s,o,{code:"tool_failed"}),this.breadcrumb(o.failureKind==="cancelled"?"tool_cancelled":o.failureKind==="blocked"?"tool_blocked":"tool_failed",s),o.failureKind==="cancelled"||o.failureKind==="blocked")return;let l;a?l=iv(a,e.toolName):(l=new Error(`${s.toolName}: ${o.failureKind} (${o.errorCode??"unknown"})`),l.name="ToolResultFailure",l.stack=void 0),this.options.capture(l,s)}catch{}}cancel(){try{if(!this.enabled())return;for(let e of this.pending.values())e.cancelled=!0}catch{}}clear(){this.pending.clear(),this.completed.clear()}};function iv(t,e,i=0){let r=tv(t,e),n=new Error(r.errorSummary??"Tool exception (diagnostic text unavailable)");return n.name=t.name,n.stack=t.stack?`${n.name}: ${n.message}
240
+ ${t.stack.split(`
244
241
  `).slice(1).join(`
245
- `)}`:void 0,t<3&&i.cause instanceof Error&&(n.cause=bk(i.cause,e,t+1)),fr(n)}import{randomUUID as fk}from"node:crypto";import{randomUUID as GO}from"node:crypto";import{EnvHttpProxyAgent as HO,getGlobalDispatcher as P8,setGlobalDispatcher as D8}from"undici";var hk=i=>({httpProxy:i.http_proxy??i.HTTP_PROXY??i.all_proxy??i.ALL_PROXY??"",httpsProxy:i.https_proxy??i.HTTPS_PROXY??i.all_proxy??i.ALL_PROXY??"",noProxy:i.no_proxy??i.NO_PROXY??""});function WO(i,e){let t=hk(i),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let n=t.noProxy.toLowerCase();if(n==="*")return!1;let s=Number(r.port)||(r.protocol==="https:"?443:80),o=r.hostname.toLowerCase();return!n.split(/[,\s]/).filter(Boolean).some(l=>{let a=l.match(/^(.+):(\d+)$/),c=(a?.[1]??l).replace(/^\*?\./,"");return(!a||Number(a[2])===s)&&(o===c||o.endsWith("."+c))})}function zO(i){let e=hk(i);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new HO(e)}function kd({env:i=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:r=!1}={}){let n,s=new Set,o=t===globalThis.fetch,l=(p,d)=>{try{e(p,d)}catch{}},a=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,d)=>{let g={requestId:GO(),phase:"headers",proxied:o&&WO(i,p)},b=r?void 0:n,v=!1,y=d?.signal??(p instanceof Request?p.signal:void 0),S=()=>T(),T=()=>{y?.removeEventListener("abort",S),!v&&r&&(v=!0,a(b).catch(()=>{}))},I;try{o?(b??=zO(i),s.add(b),r||(n=b),I=await t(p,{...d,dispatcher:b})):I=await t(p,d)}catch(B){throw l(B,g),T(),B}if(I.ok||l(void 0,{...g,status:I.status}),!I.body)return T(),I;let x=I.body.getReader();y?.addEventListener("abort",S,{once:!0}),y?.aborted&&T();let P=new ReadableStream({async pull(B){try{let N=await x.read();N.done?(B.close(),x.releaseLock(),T()):B.enqueue(N.value)}catch(N){l(N,{...g,phase:"body"}),B.error(N),x.releaseLock(),T()}},async cancel(B){try{await x.cancel(B)}finally{x.releaseLock(),T()}}}),U=new Response(P,{status:I.status,statusText:I.statusText,headers:I.headers});return Object.defineProperties(U,{url:{value:I.url},redirected:{value:I.redirected},type:{value:I.type}}),U},close:async()=>{await Promise.all([...s].map(a))}}}var yk=(i,e)=>kd({autoClose:!0}).fetch(i,e);var VO=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),$O=i=>typeof i=="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(i)?i:void 0;function wd(i,e={}){let t=[],r=new Set,n=(a,c=0)=>{if(!a||c>4||r.has(a)||t.length>=8)return;r.add(a);let p=$O(a.code);if(t.push({name:VO.has(a.name)?a.name:"Error",...p?{code:p}:{}}),n(a.cause,c+1),a instanceof AggregateError)for(let d of a.errors.slice(0,4))n(d,c+1)};n(i);let s=t.flatMap(a=>a.code?[a.code]:[]),o=e.stage==="model_admission"||s.some(a=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(a))?"lifecycle":s.some(a=>/CERT|TLS|SSL/.test(a))?"tls":s.some(a=>/^PROXY_/.test(a))||e.proxied&&s.some(a=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(a))?"proxy":s.some(a=>/TIMEOUT|ETIMEDOUT/.test(a))||t.some(a=>/TimeoutError$/.test(a.name))?"timeout":t.some(a=>a.name==="AbortError"||a.code==="ABORT_ERR"||a.code==="UND_ERR_ABORTED")?"cancelled":s.some(a=>/ENOTFOUND|EAI_AGAIN/.test(a))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",l=a=>typeof a=="string"&&/^[\w-]{1,80}$/.test(a)?a:void 0;return{errorId:fk(),requestId:l(e.requestId)??fk(),...l(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:o,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:t}}function _k({env:i=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return kd({env:i,fetchRequest:t,onFailure:(r,n)=>e(wd(r,{...n,stage:n.phase==="body"?"model_stream":"model_headers"}))})}function YO(i){let e={...process.env,...i};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])i&&t.toUpperCase()in i&&!(t in i)&&delete e[t];return e}var KO=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function vk(i,e,t=()=>{}){let r=i.agent.streamFunction;i.agent.streamFunction=async(n,s,o)=>{if(!KO.has(n.api))return r(n,s,o);let l=t(),a=_k({env:YO(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:c=>{let p={...c,...l?{operationId:l}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let c=await r(n,s,{...o,fetch:a.fetch});return c.result().finally(()=>a.close()).catch(()=>{}),c}catch(c){throw await a.close(),c}}}function $r(i,e,t){try{i()}catch(r){let n=wd(r,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...n})),t?.(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 tR=["read","grep","find","ls"];var kk=200,so=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new dr;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,t,r=()=>!1,n=()=>{},s={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},l=[],a){this.hosted=a,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=r,this.reportError=n,this.onSessionsChanged=o,this.customTools=l,this.offHosted=a?.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,t){return this.queue.run(async()=>{this.ensureAvailable();let r=await Qt(e),n=t==="continue"?this.selectedByWorkspace.get(r):typeof t=="object"&&"sessionId"in t?this.runtimes.get(t.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 t=="object"&&"sessionId"in t)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let s;if(t==="new")s=ns.create(r);else if(t==="continue"){let l=(await zr(r))[0];s=l?ns.open(l.path):ns.create(r)}else s="sessionManager"in t?t.sessionManager:ns.open(t.sessionFile);if(await eR(s.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(s.getSessionId());if(o){if(o.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(r,s,t==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let t=this.selectedByWorkspace.get(await Qt(e));return!t||!this.blank(t)?!1:(this.activate(t),!0)})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let t=this.runtimes.get(e);return!this.disposed&&t&&!t.closing?{cwd:t.cwd,sessionId:e}:null}hasSession(e,t){return this.runtimes.get(t)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:t,cwd:r,prompts:n}=e,s=t.sessionManager.getBranch(),o=s.flatMap(l=>{let a=es(l);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:r,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!n.sending,name:Xa(t.sessionManager.getSessionName(),o),modified:s.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(t=>es(t)?.role==="user")}rename(e,t){let r=this.runtimes.get(e);if(!r||r.closing)return!1;if(r.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return r.session.setSessionName(t),!0}discard(e){return this.queue.run(async()=>{let t=this.runtimes.get(e);if(!t||t.closing)return null;if(t.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!t.session.isIdle||t.prompts.sending||t.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=this.active===t,n=t.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(t.cwd)===t&&this.selectedByWorkspace.delete(t.cwd),r&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged(),{path:n,cwd:t.cwd,wasActive:r}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,r,n){let s=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${n}`;console.error(s),this.publishFor(e,{type:"error",message:s})}async replace(e,t,r,n){let s=this.runtimes.get(t.getSessionId()),o=await pr.discover(e,this.isProjectTrusted(e)),l=JO(),a=await uk(e,o.extensionRoots,this.isProjectTrusted(e)),c=new XO({cwd:e,agentDir:ZO(),noExtensions:!0,additionalExtensionPaths:a.paths,eventBus:l,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,t.getSessionId()))]:[]}),p=null;try{await c.reload();let d=c.getExtensions().errors;if(d.length)throw new Error(d.map(k=>`${k.path}: ${k.error}`).join("; "));let g=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:b}=await QO({cwd:e,sessionManager:t,model:g,resourceLoader:c,customTools:this.customTools}),v=new Vr({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(k,h)=>this.telemetry.breadcrumb(k,h),anonymize:k=>this.telemetry.anonymize(k)}),y={session:b,cwd:e,catalog:o,bus:l,generation:++this.generation,activityId:0,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:v,streaming:null,prompts:null,detached:n?{owner:n,events:[],seq:0,lastText:"",restoreTools:null}:void 0};y.prompts=s?.prompts??new Ni(()=>{let k=this.runtimes.get(t.getSessionId())??y;this.publishFor(k,{type:"snapshot",session:this.snapshotOf(k)}),!this.disposed&&!k.closing&&this.onSessionsChanged()}),p=y,vk(b,k=>{y.networkDiagnostic=k},()=>y.operation?.operationId);let S=k=>this.publishFor(y,k),T=y.detached,I=(k,h)=>{T&&(T.events.push({seq:++T.seq,type:k,...h===void 0?{}:{text:h}}),T.events.length>kk&&T.events.splice(0,T.events.length-kk))};y.interactions=new Wr(l,k=>!y.closing&&k.sessionId===b.sessionManager.getSessionId()&&is(o,k.pluginId),()=>S({type:"snapshot",session:this.snapshotOf(y)}));let x=0,P=l.on(to,()=>S({type:"snapshot",session:this.snapshotOf(y)})),U=b.subscribe(k=>{if(T&&!y.closing&&(k.type==="message_end"&&k.message.role==="assistant"&&(k.message.stopReason==="error"?I("error",k.message.errorMessage??"Agent response failed"):T.lastText=k.message.content.flatMap(h=>h.type==="text"?[h.text]:[]).join(`
246
- `)),k.type==="agent_settled"&&I("turn_end",T.lastText)),!this.disposed&&!y.closing){let h={...y.operation,session:this.telemetry.anonymize(b.sessionManager.getSessionId()),piVersion:no,model:b.model?`${b.model.provider}/${b.model.id}`:null,thinkingLevel:b.thinkingLevel};if(k.type==="agent_start"&&(y.activityId++,this.telemetry.breadcrumb("agent_start",h)),k.type==="tool_execution_start"&&v.start(k,h),k.type==="tool_execution_end"&&v.end(k,h),k.type==="message_end"&&k.message.role==="assistant"&&k.message.stopReason==="error"){y.agentErrorReported=!0;let M=y.networkDiagnostic,Z=this.reportError(new Error("Agent response failed"),{...y.operation,stage:"agent",code:"agent_failed",piVersion:no,...M?{networkKind:M.kind,networkStage:M.stage,causeCodes:M.causes.flatMap(re=>re.code?[re.code]:[]).join(","),requestId:M.requestId}:{}})??M?.errorId;S({type:"error",message:k.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:Z,inTranscript:!0,...y.operation})}k.type==="message_end"&&k.message.role==="toolResult"&&v.message(k.message,h),k.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",h),v.clear(),y.operation=void 0)}k.type==="message_update"&&k.message.role==="assistant"&&(y.streaming={id:"stream",role:"assistant",timestamp:new Date(k.message.timestamp).toISOString(),blocks:or(k.message.content)},Date.now()-x>=60&&(x=Date.now(),S({type:"stream",message:y.streaming}))),k.type==="agent_settled"&&this.scheduleQueued(y),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(k.type)&&((k.type==="message_end"&&k.message.role==="assistant"||k.type==="agent_settled")&&(y.streaming=null,S({type:"stream",message:null})),S({type:"snapshot",session:this.snapshotOf(y)}),!this.disposed&&!y.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(k.type)&&this.onSessionsChanged())});y.detach=()=>{P(),U()},y.releaseHosted=this.hosted?.adapter.attach(b);let B=[],N=!0;if(await b.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:k=>{N&&B.push(k.error),this.diagnostic(y,o.plugins.find(h=>k.extensionPath.startsWith(h.root+"/"))?.id??k.extensionPath,k.event??"runtime",k.error)}}),N=!1,B.length)throw new Error(B.join("; "));if(this.ensureAvailable(),s&&(!s.session.isIdle||s.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(s&&await this.close(s,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");y.detached&&(y.detached.restoreTools=b.getActiveToolNames(),b.setActiveToolsByName(tR)),this.runtimes.set(b.sessionManager.getSessionId(),y),p=null,y.detached?this.onSessionsChanged():this.activate(y)}catch(d){throw this.hosted?.adapter.releasePending(t.getSessionId()),p?await this.close(p,"quit"):(l.clear(),await a.release()),d}}async close(e,t){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await sk(e.session,t,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:r,catalog:n}=e,s=t.sessionManager.getBranch().flatMap(o=>{let l=es(o);return l?[l]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:Xa(t.sessionManager.getSessionName(),s),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:Hr(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:dd(t.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 t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=t.session.extensionRunner,n=await io(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||r!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),n}requestInteraction(e,t){let r=this.runtimes.get(e.sessionId);return this.disposed||!r||r.closing?Promise.reject(new Error("\u4F1A\u8BDD\u4E0D\u53EF\u7528")):eo(r.bus,e,t)}resolveInteraction(e,t,r,n){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,r,n)}async send(e,t=[],r,n){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(Ri(this.snapshot(),e,n),n==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,t,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new tt("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,t,r,n)}async prompt(e,t,r,n,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");$r(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),Ri({...this.snapshotOf(e),idle:e.session.isIdle},t,s);let o=e.session,l=o.isIdle;l&&(e.operation=n,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...n,piVersion:no});let a=!1,c,p,d=new Promise((g,b)=>{c=g,p=b});o.prompt(t,{images:r,streamingBehavior:s,preflightResult:g=>{g&&(a=!0,c())}}).then(()=>{a||c()}).catch(g=>{if(!a)p(g);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let b=this.reportError(ei(g,"Agent response failed"),{...n,stage:"agent",code:"agent_failed",piVersion:no});this.publishFor(e,{type:"error",message:g instanceof Error?g.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:b,...n})}});try{await d}catch(g){throw l&&(e.operation=void 0),g}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!Hr(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(t,r,n)=>this.prompt(e,t,r,n))}async updateQueuedPrompt(e,t,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 tt("\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,t,r,(s,o,l)=>this.prompt(n,s,o,l,"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(Zn),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let t=this.active;if(this.disposed||!t||t.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");$r(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=t.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!Hr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!Hr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=ro(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let l=this.reportError(ei(o,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(t,{type:"error",message:o instanceof Error?o.message:"\u7EE7\u7EED\u5931\u8D25",errorId:l,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(t=>({provider:t.provider,id:t.id,name:t.name}))}async setModel(e,t){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let n=r.session.modelRuntime.getModel(e,t);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,t,r){return this.queue.run(async()=>{this.ensureAvailable();let n=await Qt(e),s=ns.create(n);return await this.replace(n,s,"new",t),this.runtimes.get(s.getSessionId()).session.setSessionName(r),s.getSessionId()})}detachedRuntime(e){let t=this.runtimes.get(e);return!this.disposed&&t?.detached&&!t.closing?t:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(t=>t.detached?.owner===e&&!t.closing).length}async sendDetached(e,t,r){let 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(t,[],void 0),this.scheduleQueued(n);return}await this.prompt(n,t,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let t=this.detachedRuntime(e);t&&(this.runtimes.delete(e),this.active===t&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged())})}detachedEvents(e,t){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(n=>n.seq>t),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{copyFile as iR,mkdir as rR,rename as nR,unlink as sR}from"node:fs/promises";import{basename as aR,join as wk}from"node:path";var oR=i=>wk(i,"pi-web","trash");async function Sk(i,e){let t=oR(e);await rR(t,{recursive:!0});let r=wk(t,`${Date.now()}_${aR(i)}`);try{await nR(i,r)}catch(n){let s=n.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw n;await iR(i,r),await sR(i)}return r}import{basename as Sd,dirname as lR}from"node:path";function Ek(i,e){let t=r=>e[r].map(n=>({name:r==="skills"&&Sd(n.path).toLowerCase()==="skill.md"?Sd(lR(n.path)):Sd(n.path),path:n.path,source:n.metadata.source,scope:n.metadata.scope,enabled:n.enabled}));return{packages:i.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as cR}from"node:child_process";var pR=(i,e)=>new Promise((t,r)=>{cR(i,[...e],{windowsHide:!0},n=>{n?r(n):t()})});async function Ed(i,e=process.platform,t=process.env,r=pR){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let n=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return n===null?!1:(await r(n,[i]),!0)}import{execFile as oN}from"node:child_process";import{randomUUID as Gd}from"node:crypto";import{existsSync as ew}from"node:fs";import{access as lN,mkdir as ls,mkdtemp as cN,readFile as qi,realpath as pN,rename as tw,rm as iw,writeFile as rw}from"node:fs/promises";import{join as Oe}from"node:path";import{createHash as xd}from"node:crypto";import{readdir as fR,realpath as Rk,rename as _R,stat as vR}from"node:fs/promises";import{join as Li}from"node:path";import{constants as Td}from"node:fs";import{DatabaseSync as dR}from"node:sqlite";import{lstat as xk,mkdir as uR,open as ss,rename as mR,unlink as Ak}from"node:fs/promises";import{dirname as gR,join as Tk,resolve as bR}from"node:path";import{randomUUID as hR}from"node:crypto";import{setTimeout as yR}from"node:timers/promises";async function Le(i){await uR(i,{recursive:!0,mode:448});let e=await xk(i);if(!e.isDirectory()||e.isSymbolicLink())throw new f("invalid_storage","Plugin storage must be a real directory")}async function Ce(i,e){let t;try{t=await ss(i,Td.O_RDONLY|Td.O_NONBLOCK|(Td.O_NOFOLLOW??0))}catch(r){if(Ci(r))return null;throw r}try{let r=await t.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new f("invalid_storage","Invalid storage record size or type");let n=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<n.length;){let o=await t.read(n,s,n.length-s,s);if(!o.bytesRead)break;s+=o.bytesRead}if(s>e||s!==r.size)throw new f("invalid_storage","Storage record changed during read");return n.subarray(0,s)}finally{await t.close()}}async function qe(i,e=2*1024*1024){let t=await Ce(i,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new f("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function dt(i){let e=await Ce(i,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new f("gc_recovery_required",`Invalid journal ${i}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new f("gc_recovery_required",`Invalid journal ${i}; original bytes preserved`);return t}async function ye(i,e){let t=`${i}.${hR()}.tmp`,r=await ss(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await mR(t,i);let n;try{n=await ss(gR(i),"r"),await n.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await n?.close()}}finally{await Ak(t).catch(()=>{})}}var Ok='{"version":2,"mechanism":"sqlite-exclusive"}',Ik=i=>i.toString("utf8")===Ok,ao=new Set;async function Id(i,e,t=0){await Le(i);let r=Tk(i,`${e}.lock`),n=Tk(i,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new f(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),l;try{l=await ss(n,"wx",384)}catch(v){if(v.code!=="EEXIST")throw v}finally{await l?.close()}let a=await xk(n);if(!a.isFile()||a.isSymbolicLink()||a.nlink!==1||a.size>1024*1024)throw new f("invalid_storage","Ownership database must be a small, single-link regular file");let c=new dR(n,{allowExtension:!1}),p=bR(n),d=Date.now()+t,g=!1;try{for(;;){if(!ao.has(p))try{c.exec("BEGIN EXCLUSIVE"),ao.add(p),g=!0;break}catch(y){if(y.errcode!==5)throw y}if(Date.now()>=d)throw new f(s,"Another host owns this plugin storage; wait for it to stop before retrying");await yR(10)}let v=await Ce(r,4096);if(v===null){let y;try{y=await ss(r,"wx",384),await y.writeFile(Ok),await y.sync()}catch(S){if(S.code!=="EEXIST")throw S}finally{await y?.close()}v=await Ce(r,4096)}if(v===null||!Ik(v))throw o()}catch(v){throw c.close(),g&&ao.delete(p),v}let b=!1;return async()=>{if(b)return;let v=await Ce(r,4096);if(v===null||!Ik(v))throw new f("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Ak(r),c.close(),ao.delete(p),b=!0}}async function Ue(i,e,t=2e3){let r=await Id(i,"transaction",t);try{return await e()}finally{await r()}}var oo=i=>Li(i,"host-pair"),kR=i=>xd("sha256").update(JSON.stringify(i)).digest("hex"),wR=10*6e4;async function SR(i){let e=xd("sha256"),t=0,r=0;async function n(s){let o=(await fR(Li(i,s),{withFileTypes:!0})).sort((l,a)=>l.name<a.name?-1:l.name>a.name?1:0);for(let l of o){if(!s&&l.name==="node_modules")continue;let a=s?`${s}/${l.name}`:l.name;if(l.isSymbolicLink()||!l.isFile()&&!l.isDirectory())throw new f("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new f("host_pair_required","Candidate package resource budget exceeded");if(l.isDirectory()){await n(a);continue}let c=await Ce(Li(i,a),64*1024*1024);if(!c||(r+=c.length)>256*1024*1024)throw new f("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,xd("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function Ad(i,e){let t=await Rk(e),r=Li(e,"dist","hosted-worker.js");if(await Rk(r)!==Li(t,"dist","hosted-worker.js"))throw new f("host_pair_required","Candidate worker must remain inside the staged host");let n=await Ce(Li(e,"package.json"),512*1024);if(!n)throw new f("host_pair_required","Candidate package metadata missing");let s=JSON.parse(n.toString("utf8")),o=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==i||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(a=>o.capabilities.includes(a)))throw new f("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let l=await Ce(r,32*1024*1024);if(!l)throw new f("host_pair_required","Candidate worker missing");return kR([n.toString("base64"),l.toString("base64"),await SR(e)])}async function lo(i){await _R(i,`${i}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var ER=i=>i.schema===1&&/^[a-f0-9-]{36}$/.test(i.id)&&typeof i.version=="string"&&typeof i.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(i.hostDigest)&&/^[a-f0-9]{64}$/.test(i.fingerprint)&&Array.isArray(i.selections)&&!i.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(i.selection&&(typeof i.selection.path!="string"||!/^[a-f0-9]{64}$/.test(i.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(i.phase);async function Od(i){let e=Li(oo(i),"intent.json"),t,r=!0;try{t=await dt(e)}catch{t=null,r=!1}if(!r||t&&!ER(t))return await lo(e),null;if(t){let{lifecyclePhase:n,...s}=t,o=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await vR(e).then(l=>l.mtime.toISOString(),()=>new Date(0).toISOString());t={...s,updatedAt:o,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 t}async function co(i,e){let{lifecyclePhase:t,...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 ye(Li(oo(i),"intent.json"),n)}var Rd=i=>i&&["selecting","selected","restart-requested"].includes(i.phase),Nk=(i,e=Date.now())=>!!i&&!!Rd(i)&&e-Date.parse(i.updatedAt??"")<wR;import{promisify as dN}from"node:util";import{realpathSync as Dk,statSync as TR}from"node:fs";import{basename as IR,delimiter as xR,dirname as Ck,join as Nd,resolve as AR}from"node:path";function Pk(i){if(!i)return null;try{let e=Dk(i);return IR(e)==="npm-cli.js"&&TR(e).isFile()?e:null}catch{return null}}function OR({execPath:i=process.execPath,env:e=process.env}={}){let t=Pk(e.npm_execpath);if(t)return t;let r=new Set([Ck(i)]);try{r.add(Ck(Dk(i)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(xR).filter(Boolean))r.add(AR(s));for(let s of r)for(let o of[Nd(s,"node_modules","npm","bin","npm-cli.js"),Nd(s,"..","lib","node_modules","npm","bin","npm-cli.js"),Nd(s,"npm")]){let l=Pk(o);if(l)return l}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 Mk(i){return{file:process.execPath,args:[OR(),...i]}}import{randomUUID as RR}from"node:crypto";import{mkdir as Uk,readFile as NR,rename as Pd,rm as CR,unlink as qz,writeFile as PR}from"node:fs/promises";import{isAbsolute as Lk,join as as}from"node:path";var Dd=1,DR=1440*6e4,po=i=>as(i,"pi-web","upgrade"),Md=i=>as(po(i),"candidate.json"),MR=i=>as(po(i),"transaction.json"),qk=i=>as(po(i),"history"),jk=/^[a-f0-9-]{36}$/i;async function LR(i,e){let t=`${i}.${RR()}.tmp`;try{await PR(t,e,{mode:384}),await Pd(t,i)}finally{await CR(t,{force:!0})}}var qR=(i,e)=>LR(i,JSON.stringify(e));async function Cd(i,e){await Pd(i,`${i}.${e}-${Date.now()}`).catch(t=>{if(t?.code!=="ENOENT")throw t})}async function Bk(i,e,t=()=>!1){let r;try{r=JSON.parse(await NR(i,"utf8"))}catch(n){return n?.code==="ENOENT"||await Cd(i,"invalid"),null}return e(r)?t(r)?(await Cd(i,"expired"),null):r:(await Cd(i,"invalid"),null)}function Fk(i){if(!i||typeof i!="object"||i.schema!==Dd||!jk.test(i.id??""))return!1;try{Kt(i.version)}catch{return!1}return typeof i.launcher=="string"&&Lk(i.launcher)&&typeof i.packageRoot=="string"&&Lk(i.packageRoot)&&["stable","alpha"].includes(i.channel)&&typeof i.downgrade=="boolean"&&!Number.isNaN(Date.parse(i.createdAt??""))}async function uo(i,e=Date.now()){return Bk(Md(i),Fk,t=>e-Date.parse(t.createdAt)>DR)}async function Gk(i,e){let t={schema:Dd,createdAt:new Date().toISOString(),...e};if(!Fk(t))throw new Error("Invalid upgrade candidate");return await Uk(po(i),{recursive:!0,mode:448}),await qR(Md(i),t),t}async function Ld(i,e,t){let r=await uo(i);!r||e&&r.id!==e||(await Uk(qk(i),{recursive:!0,mode:448}),await Pd(Md(i),as(qk(i),`${r.id}-candidate-${t}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var UR=["selected","committed","rolled-back"];function jR(i){return!!i&&typeof i=="object"&&i.schema===Dd&&jk.test(i.id??"")&&UR.includes(i.phase)&&typeof i.version=="string"&&typeof i.from=="string"&&!Number.isNaN(Date.parse(i.updatedAt??""))}async function Hk(i){return Bk(MR(i),jR)}import{readFile as BR,rename as FR,writeFile as GR,unlink as HR}from"node:fs/promises";import{join as WR}from"node:path";import{randomUUID as zR}from"node:crypto";var qd=1,Wk=i=>WR(i,"pi-web","launcher-handoff.json");function zk(i){return i?.protocol===qd&&typeof i.nonce=="string"&&i.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(i.requestId)&&Number.isSafeInteger(i.pid)&&i.pid>0&&["requested","draining","stopped","refused","failed"].includes(i.phase)}async function Ud(i){try{let e=JSON.parse(await BR(Wk(i),"utf8"));if(!zk(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 VR(i,e){let t=`${i}.${zR()}.tmp`;try{await GR(t,JSON.stringify(e),{mode:384}),await FR(t,i)}finally{await HR(t).catch(()=>{})}}async function Vk(i,e){if(!zk(e))throw new Error("Invalid launcher handoff receipt");await VR(Wk(i),e)}import{execFile as $R}from"node:child_process";import{cp as YR,readFile as jd,realpath as KR,rm as QR}from"node:fs/promises";import{join as Yr,sep as JR}from"node:path";import{promisify as XR}from"node:util";var $k=XR($R),Bd=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Fd(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=i;return Bd.map(t=>{let r=e[t];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${r}`})}async function mo(i){return Promise.all(Bd.map(async e=>{let t=await Gr(i,e),r=JSON.parse(await jd(Yr(t,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function Yk(i,e){let t=JSON.parse(await jd(Yr(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=t.peerDependencies===void 0?await mo(i):Fd(t.peerDependencies);if(JSON.stringify(await mo(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 Gr(i,"node-pty"),s=await Gr(e,"node-pty"),o=await KR(Yr(e,"../.."));if(n===s||!s.startsWith(o+JR))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let l=async d=>JSON.parse(await jd(Yr(d,"package.json"),"utf8")).version;if(await l(n)!==await l(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 QR(s,{recursive:!0,force:!0}),await YR(n,s,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await $k(process.execPath,[Yr(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await Gr(e,Bd[0]),{stdout:p}=await $k(process.execPath,[Yr(c,"dist","bundle","cli.js"),"--version"],{cwd:e,env:a,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}import{lstat as Qk,readdir as Jk,readFile as ZR,realpath as Kk,rm as eN}from"node:fs/promises";import{join as os,relative as tN,sep as Xk}from"node:path";var iN=1440*6e4,rN=1024*1024,nN=4,sN=i=>i==="releases"||i==="history"||i.endsWith("-history");async function aN(i,e){let t=new Set,r=[...new Set(e.flatMap(o=>[o+Xk,o+"/"]))],n=o=>{if(typeof o=="string")for(let l of r){let a=o.indexOf(l);a>=0&&t.add(o.slice(a+l.length).split(/[\\/]/)[0])}else Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&Object.values(o).forEach(n)},s=async(o,l)=>{let a=await Jk(o,{withFileTypes:!0}).catch(()=>[]);for(let c of a){let p=os(o,c.name);if(c.isDirectory()){l<nN&&!sN(c.name)&&await s(p,l+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await Qk(p)).size>rN)continue;n(JSON.parse(await ZR(p,"utf8")))}catch{}}};return await s(i,0),t}async function Zk(i){let e=os(i.agentDir,"pi-web"),t;try{t=await Kk(os(e,"releases"))}catch{return[]}let r=i.now??Date.now(),n=i.graceMs??iN,s=await aN(e,[os(e,"releases"),t]);try{let l=tN(t,await Kk(i.packageRoot));l&&!l.startsWith("..")&&s.add(l.split(Xk)[0])}catch{}let o=[];for(let l of await Jk(t,{withFileTypes:!0}).catch(()=>[])){if(!l.isDirectory()||s.has(l.name))continue;let a=os(t,l.name);try{if(r-(await Qk(a)).mtimeMs<n)continue;await eN(a,{recursive:!0,force:!0}),o.push(l.name)}catch{}}return o}var uN=dN(oN),Kr=i=>["committed","cancelled","failed"].includes(i);function nw(i){let e=i.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 mN(i,e){try{let t=Mk(i),{stdout:r}=await uN(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(t){let r=t;throw new Error(r.stderr?.trim()||r.message)}}var go=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??mN,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let r=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return mo(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Fd(s)},this.verifyPackage=e.verifyPackage??Yk,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"?qd:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!Kr(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=Oe(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await qi(n,"utf8")),o=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let l=await Ud(this.agentDir);if(l?.nonce===e&&["requested","draining"].includes(l.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let a,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(a=await this.beforeRestart(),!o(JSON.parse(await qi(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:t,pid:s.pid,phase:"requested"};try{await Vk(this.agentDir,p),c=!0}catch(d){let g=await Ud(this.agentDir).catch(()=>null);if(c=g?.nonce===e&&g?.requestId===t&&["requested","draining","stopped"].includes(g.phase),!c)throw d}this.restartPending=!0}finally{!c&&a&&await a()}}async current(){let e=JSON.parse(await qi(Oe(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return Kt(e.version),e.version}async pruneReleases(){if(this.preparing||this.preparedUpdate||this.restartPending||this.cancellation)return[];let e=await this.transaction();return e&&!Kr(e.phase)?[]:Zk({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),t=await this.transaction();if(!t||Kr(t.phase)||t.id===this.ownTransaction)return e;if(t.version===e&&["selecting","selected","restart-requested"].includes(t.phase))await this.record({...t,phase:"committed",message:"Selected version is running"});else if(t.phase==="restart-requested"){let r=await Hk(this.agentDir);await this.record({...t,phase:"failed",message:r?.id===t.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Ld(this.agentDir,t.id,"superseded"),await this.record({...t,phase:"failed",message:`Interrupted while ${t.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return Oe(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await dt(this.transactionPath)}catch{return await lo(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 lo(this.transactionPath),null):e:null}async record(e){if(await ls(Oe(this.agentDir,"pi-web"),{recursive:!0}),await ye(this.transactionPath,e),Kr(e.phase)){let t=Oe(this.agentDir,"pi-web","update-history");await ls(t,{recursive:!0}),await ye(Oe(t,`${e.id}-${e.phase}.json`),e)}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),t=await uo(this.agentDir);t&&(!e||t.id===e.id)&&await Ld(this.agentDir,t.id,"cancelled"),e&&!Kr(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 Oe(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await qi(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${Gd()}.tmp`;try{await ls(Oe(this.agentDir,"pi-web"),{recursive:!0}),await rw(t,JSON.stringify({channel:e}),{mode:384}),await tw(t,this.preferencePath)}finally{this.savingPreference=!1,await iw(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=ew(Oe(this.packageRoot,".git")),n={current:e,channel:t,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&&!Kr(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&&t==="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 o=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),l=Array.isArray(o)&&o.length===1?o[0]:o,a=t==="alpha"?l:{latest:l};if(!a||!L0(a.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let c=a.latest;if(t==="alpha"&&a.alpha!==void 0){if(!Ya(a.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");pt(a.alpha,c)>0&&(c=a.alpha)}if(n.latest=c,n.downgrade=pt(c,e)<0,n.available=t==="stable"?pt(c,e)!==0:pt(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&&pt(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(o){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`)}return n}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(ew(Oe(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=Oe(this.agentDir,"pi-web","releases");await ls(r,{recursive:!0});let n=await cN(Oe(await pN(r),`${t.latest}-`)),s=Oe(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:Gd(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};this.ownTransaction=o.id,await this.record(o);try{let l=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...l,"--prefix",n,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let a=Oe(n,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:a},await this.record(o);let c=JSON.parse(await qi(Oe(a,"package.json"),"utf8"));if(c.name!=="pi-webapp"||c.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await qi(Oe(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&nw(c)!==nw(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=Oe(a,"bin","pi-webapp.mjs");return await Promise.all([d,Oe(a,"dist","extension.js"),Oe(a,"web","dist","index.html")].map(g=>lN(g))),this.desktopManaged&&(await od(this.agentDir,{version:t.latest,launcher:d,desktopProtocolVersion:Pi}),await this.verifyPackage(this.packageRoot,a)),await this.prefetchPlugins?.(t.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await Gk(this.agentDir,{id:o.id,version:t.latest,launcher:d,packageRoot:a,channel:t.channel??"stable",downgrade:!!t.downgrade}),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={id:o.id,update:{version:t.latest,launcher:d},channel:t.channel??"stable"},{version:t.latest,launcher:d}}catch(l){await iw(n,{recursive:!0,force:!0});let a=(l instanceof Error?l.message:String(l)).slice(0,500);throw await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${a}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),l}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:t=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let n,s=!1,o=Oe(this.agentDir,"pi-web","launcher.restart");try{if(n=await this.beforeRestart?.(t),(await uo(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 l=await this.transaction();l?.id===r.id&&await this.record({...l,phase:"restart-requested"});try{if(JSON.parse(await qi(o,"utf8"))?.nonce!==this.launcherNonce){let c=Oe(this.agentDir,"pi-web","restart-history");await ls(c,{recursive:!0,mode:448}),await tw(o,Oe(c,`stale-${Gd()}.json`))}}catch{}try{await rw(o,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(a){try{let c=JSON.parse(await qi(o,"utf8"));s=c.nonce===this.launcherNonce&&c.candidate===r.id}catch{}if(!s)throw a}this.restartPending=!0}catch(l){if(s){this.restartPending=!0;return}let a=await this.transaction();throw a?.id===r.id&&a.phase==="restart-requested"&&await this.record({...a,phase:"prepared"}),n&&await n(),l}}};import{createHash as $w,randomUUID as SP}from"node:crypto";import{randomUUID as XC}from"node:crypto";import{join as lu}from"node:path";import{randomUUID as ow}from"node:crypto";import{randomUUID as gN}from"node:crypto";function sw(i){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof i[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let r=`__pi_web_contract_${gN().replaceAll("-","")}`,n;try{if(n=i.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{i.registerTool(s),i.setActiveTools([...n,r]),(i.getAllTools().find(l=>l.name===r)?.exposure!=="hidden"||i.getActiveTools().includes(r))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};i.registerTool({...s,parameters:o}),i.getAllTools().find(l=>l.name===r)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{i.setActiveTools(n)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var bN;function aw(){return bN??=hN().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function hN(){let{createAgentSession:i,DefaultResourceLoader:e,SessionManager:t}=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:o}=await import("node:os"),{join:l}=await import("node:path"),a=await n(l(o(),"pi-sdk-contract-")),c,p=[],d=0,g=0,b=!1,v=!1;try{let y=(U,B,N)=>({name:U,label:U,description:"Inert host SDK contract check",exposure:B,parameters:{type:"object",properties:{}},execute:N}),S=()=>({content:[],details:void 0}),T=new e({cwd:a,agentDir:a,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[U=>{U.on("tool_call",B=>{if(B.toolName==="__contract_direct"&&(b=!!B.parentToolCallId),B.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let B of["hidden","model-only"])U.registerTool(y(`__contract_${B.replace("-","_")}`,B,async()=>(g++,S())));U.registerTool(y("__contract_protected","direct",async()=>(g++,S()))),U.registerTool(y("__contract_direct","direct",async()=>(d++,S()))),U.registerTool(y("__contract_driver","direct",async(B,N,k,h,M)=>{let Z=await M.executeTool("__contract_hidden",{}),re=await M.executeTool("__contract_model_only",{}),ae=await M.executeTool("__contract_direct",{}),C=await M.executeTool("__contract_protected",{});return(!Z.isError||!re.isError)&&p.push("nested-tool-exposure"),(ae.isError||d!==1)&&p.push("nested-tool-execution"),(!C.isError||g!==0)&&p.push("nested-tool-permission-guard"),b||p.push("nested-parent-identity"),v=!0,S()}))}]});await T.reload(),{session:c}=await i({cwd:a,agentDir:a,sessionManager:t.inMemory(a),resourceLoader:T}),await c.bindExtensions({mode:"print"});let I=c.modelRuntime.getModels("openai")[0];if(!I)return{supported:!1,missing:["sdk-model-contract"]};await c.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await c.setModel(I);let x=0;c.agent.streamFunction=async U=>{let B=x++===0,N={role:"assistant",api:U.api,provider:U.provider,model:U.id,timestamp:Date.now(),content:B?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:B?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},k=r();return k.push({type:"start",partial:N}),k.push({type:"done",reason:B?"toolUse":"stop",message:N}),k.end(N),k};let P;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((U,B)=>{P=setTimeout(()=>B(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(P)}return v||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(a,{recursive:!0,force:!0})}}var bo=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??=aw().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,n)=>{t=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(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let r=this.install(e,t);r.ready=!0;try{this.publish(r)}catch(n){throw this.release(r),n}return()=>this.release(r)}install(e,t){let r={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let 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 o=r.owned.get(s.toolName);if(!o)return;let l=this.descriptors.get(o)?.find(a=>a.name===s.toolName);if(!l||!this.allowed(r,o,l,!!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 t=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(r=>{r.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(r){throw this.release(t),r}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,r,n=!1){let s=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!n||s.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(n=>n.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(t);this.validateChange(e,r),this.descriptors.set(e,r);for(let n of this.bindings)n.ready&&this.publish(n)}validateChange(e,t){for(let n of this.bindings)if(n.compatible!==!1)for(let[s,o]of n.owned)this.assertOwner(n,o,s);let r=new Set;for(let n of t){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,o]of this.descriptors)if(s!==e&&o.some(l=>l.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,t,r){let n=e.owned.get(r);if(n&&n!==t)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(o=>o.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=sw(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 t=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;t.add(s.name);let o=this.service.policy(r,e.scope),l=o.exposure??"direct",a=!o.allowNested&&l==="direct"?"model-only":l,c={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:a,execute:async(p,d,g)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:ow(),scope:{...e.scope},kind:"tool",action:s.action,input:d},g)}};e.pi.registerTool(c),e.definitions.set(s.name,c)}for(let r of e.owned.keys())if(!t.has(r)){let n={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:yN};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,t,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(l=>l.scope.sessionId===t.sessionId&&l.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let o=this.service.policy(e,t);if(!o.enabled||o.planMode||o.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:ow(),scope:t,kind:"action",action:r,input:n},s)}};async function yN(){throw new Error("Hosted tool unavailable")}import{randomBytes as IC,randomUUID as xC,timingSafeEqual as AC}from"node:crypto";import{join as wt}from"node:path";var fN=30,lw=/^[a-z][a-z0-9-]{0,63}$/,_N=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,cs=i=>{throw new f("invalid_package",i)},Hd=(i,e)=>i===void 0?[]:!Array.isArray(i)||i.length>32?cs(`Invalid ${e} declaration`):i;function Qr(i){let e=i&&typeof i=="object"?i:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(l=>typeof l=="string"):[]),r=t.has("secrets")?Hd(e.secrets,"secrets").map(l=>{let a=l?.name;return typeof a=="string"&&lw.test(a)?a:cs("Invalid secret name")}):[],n=e.network,s=t.has("network")?Hd(n?.hosts,"network").map(l=>typeof l=="string"&&_N.test(l)?l:cs("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Hd(e.schedules,"schedules").map(l=>{let a=l;return!a||typeof a.id!="string"||!lw.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<fN||a.intervalSec>86400?cs("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(l=>l.id)).size!==o.length&&cs("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:o,sessions:t.has("sessions")}}import{lookup as vN}from"node:dns/promises";import{isIP as kN}from"node:net";var wN=new Set(["GET","POST","PATCH","PUT","DELETE"]),SN=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),EN=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),ho=(i,e)=>{throw new f("network_denied",i,{status:403,reason:e})};function TN(i){let e=i.toLowerCase().replace(/^::ffff:/,"");if(kN(e)===4){let[t,r]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&r===254||t===172&&r>=16&&r<=31||t===192&&r===168||t===100&&r>=64&&r<=127||t>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function cw(i,e,t,r,n){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new f("invalid_input","Invalid network request");let o;try{o=new URL(s.url)}catch{throw new f("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&ho("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||ho("Host is not declared by the plugin","host");let l=(s.method??"GET").toUpperCase();if(!wN.has(l))throw new f("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new f("invalid_input","Invalid body");let a={};for(let[I,x]of Object.entries(s.headers??{})){if(typeof x!="string"||SN.has(I.toLowerCase())||!/^[\w-]{1,64}$/.test(I)||/[\r\n]/.test(x))throw new f("invalid_input",`Header not allowed: ${I.slice(0,64)}`);a[I]=x}let c=null;if(s.secret!==void 0){if(t.includes(s.secret)||ho("Secret is not declared by the plugin","secret"),c=await n.secrets.get(i,s.secret),!c)throw new f("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${c}`}let p=await(n.resolve??(async I=>(await vN(I,{all:!0})).map(x=>x.address)))(o.hostname);(!p.length||p.some(TN))&&ho("Host resolves to a non-public address","address");let d=n.timeoutMs??2e4,g=n.maxResponseBytes??2*1024*1024,b=await(n.fetch??fetch)(o,{method:l,headers:a,body:s.body,redirect:"manual",signal:AbortSignal.timeout(d)}),v=[],y=0;if(b.body)for await(let I of b.body){if(y+=I.byteLength,y>g)throw new f("response_too_large","Network response exceeds limit",{status:502});v.push(Buffer.from(I))}let S=Buffer.concat(v).toString("utf8"),T={};return b.headers.forEach((I,x)=>{EN.has(x.toLowerCase())&&(T[x.toLowerCase()]=I)}),c&&(S=S.split(c).join("[redacted]")),{status:b.status,headers:T,body:S}}var yo=(i,e,t)=>{if(typeof i!="string"||!i||i.length>e)throw new f("invalid_input",`Invalid ${t}`);return i};async function pw(i,e,t,r,n,s){let o=n&&typeof n=="object"&&!Array.isArray(n)?n:{};if(r==="sessions.create"){if(o.mode!=="plan")throw new f("invalid_input","Plugin sessions must start in plan mode");if(i.activeCount(e)>=s)throw new f("quota_exceeded","Too many active plugin sessions",{status:429});return i.create({pluginId:e,cwd:t,title:yo(o.title,200,"title"),prompt:yo(o.prompt,64*1024,"prompt"),mode:"plan"})}let l=yo(o.sessionId,200,"sessionId");if(i.ownerOf(l)!==e)throw new f("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new f("invalid_input","Invalid mode");return await i.send(l,yo(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await i.release(l),{ok:!0};case"sessions.abort":return await i.abort(l),{ok:!0};case"sessions.events":return i.events(l,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new f("method_denied","Unknown sessions method")}}var IN=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),fo=class{options;constructor(e){this.options=e}handles(e){return IN.has(e)}async call(e,t,r,n,s){let o=Qr(t);if(n==="network.fetch"){if(!o.networkHosts.length)throw new f("capability_denied","Plugin did not declare network access",{status:403});return cw(e,o.networkHosts,o.secrets,s,this.options)}if(!o.sessions||!this.options.sessions)throw new f("capability_denied","Sessions capability is unavailable",{status:403});return pw(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var _o=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let r=this.deps.setInterval??((n,s)=>{let o=setInterval(n,s);return o.unref(),o});this.timers.set(e,t.map(n=>r(()=>{this.tick(e,n)},n.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])t(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let r=`${e}\0${t.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,t),!0}catch(n){return this.deps.onError?.(e,t,n),!1}finally{this.running.delete(r)}}};import{createHash as iu,timingSafeEqual as rC}from"node:crypto";import{lstat as xw,mkdtemp as tu,readdir as nC,readFile as sC,realpath as aC,rename as oC,rm as Ui,writeFile as lC}from"node:fs/promises";import{tmpdir as cC}from"node:os";import{join as Ie}from"node:path";import{gunzipSync as PN}from"node:zlib";import{mkdir as DN,writeFile as MN}from"node:fs/promises";import{dirname as LN,join as qN}from"node:path";import{constants as Wd}from"node:fs";import{lstat as mw,open as xN,readdir as dw,realpath as gw}from"node:fs/promises";import{createHash as AN}from"node:crypto";import{join as bw,relative as ON,resolve as RN,sep as NN}from"node:path";var Re={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},CN={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"]},Te=i=>AN("sha256").update(i).digest("hex");function Ee(i){throw new f("invalid_package",i)}async function ur(i,e,t){let r=e.split("/");(!r.length||r.some(l=>!l||l==="."||l===".."||!/^[\w.-]+$/.test(l)))&&Ee("Invalid resource path");let n=i;for(let l=0;l<r.length;l++){n=bw(n,r[l]);let a=await mw(n);(a.isSymbolicLink()||(l<r.length-1?!a.isDirectory():!a.isFile()||a.nlink!==1))&&Ee("Links and non-regular package files are forbidden")}let s=await gw(n);(s!==RN(i,e)||ON(i,s).startsWith(`..${NN}`))&&Ee("Resource escapes package root");let o=await xN(n,Wd.O_RDONLY|Wd.O_NONBLOCK|(Wd.O_NOFOLLOW??0));try{let l=await o.stat();(!l.isFile()||l.nlink!==1||l.size>t)&&Ee("Oversized or non-regular package file");let a=Buffer.alloc(Math.min(l.size+1,t+1)),c=0;for(;c<a.length;){let p=await o.read(a,c,a.length-c,c);if(!p.bytesRead)break;c+=p.bytesRead}return(c>t||c!==l.size)&&Ee("Package resource changed during read"),a.subarray(0,c)}finally{await o.close()}}function uw(i){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{return Ee("Invalid package JSON")}}async function mr(i,e){let t=await gw(i);(await mw(i)).isSymbolicLink()&&Ee("Package root cannot be a symlink");let r=uw(await ur(t,"package.json",Re.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&Ee("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&Ee("Invalid package version"),Di(r.piWebapp)||Ee("Unsupported hosted manifest"),r.type!=="module"&&Ee("Hosted package must declare ESM module type");for(let d of await dw(t,{withFileTypes:!0}))d.name==="dist"&&d.isDirectory()||(!d.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(d.name))&&Ee("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(d=>/^(?:preinstall|install|postinstall|prepare)$/.test(d))&&Ee("Hosted packages cannot run install lifecycle scripts");for(let d of["dependencies","optionalDependencies"]){let g=r[d];g&&(typeof g!="object"||Object.keys(g).length>0)&&Ee("Hosted packages must contain all runtime dependencies")}let n=r.piWebapp,s=uw(await ur(t,n.resourcesManifest.slice(2),Re.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>Re.files)&&Ee("Invalid resource manifest");let o=new Map,l=0;for(let d of s.files){(!d||typeof d!="object")&&Ee("Invalid resource entry");let g=d,b={...g,path:typeof g.path=="string"&&g.path.startsWith("./")?g.path.slice(2):g.path};(!cr(`./${b.path}`)||typeof b.sha256!="string"||!/^[a-f0-9]{64}$/.test(b.sha256)||!Number.isSafeInteger(b.bytes)||b.bytes<0||o.has(b.path))&&Ee("Invalid or duplicate resource");let v=b.path.split(".").at(-1);CN[v]?.includes(b.mime)||Ee("Unsupported resource MIME");let y=v==="js"||v==="mjs"||v==="cjs"?Re.js:v==="css"?Re.css:["woff","woff2","ttf","otf"].includes(v)?Re.font:v==="wasm"?Re.wasm:Re.other;(b.bytes>y||(l+=b.bytes)>Re.total)&&Ee("Resource budget exceeded");let S=await ur(t,b.path,y);(S.length!==b.bytes||Te(S)!==b.sha256)&&Ee("Resource integrity mismatch"),o.set(b.path,Object.freeze({...b}))}for(let d of[n.backend.entry,n.frontend.document,n.frontend.controller])o.has(d.slice(2))||Ee("Entrypoint is absent from resource manifest");let a=0;async function c(d,g=0){g>16&&Ee("Package directory nesting limit exceeded");for(let b of await dw(bw(t,d),{withFileTypes:!0})){++a>Re.files*2&&Ee("Too many package entries");let v=`${d}/${b.name}`;(b.isSymbolicLink()||!b.isDirectory()&&!b.isFile())&&Ee("Invalid archive member"),b.isDirectory()?await c(v,g+1):v!==n.resourcesManifest.slice(2)&&!o.has(v)&&Ee("Undeclared distribution asset")}}await c("dist");let p=Te(JSON.stringify({id:r.name,version:r.version,manifest:n,resources:[...o.values()].sort((d,g)=>d.path.localeCompare(g.path))}));return{id:r.name,version:r.version,root:t,manifest:n,resources:o,digest:p}}async function hw(i,e,t){if(t!==i.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!cr(`./${r}`))return null;let n=i.resources.get(r);if(!n||r===i.manifest.backend.entry.slice(2))return null;let s=await ur(i.root,r,n.bytes);if(s.length!==n.bytes||Te(s)!==n.sha256)throw new f("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:n.mime}}var vo=64*1024*1024,UN=Re.total+Re.files*2048,we=i=>{throw new f("invalid_archive",i)};function Jr(i){let e=i.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?i:i.subarray(0,e))}catch{return we("Archive has invalid UTF-8 paths")}}function yw(i){let e=Jr(i).trim();if(!/^[0-7]+$/.test(e))return we("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:we("Archive number exceeds limits")}function jN(i){let e=i.endsWith("/")?i.slice(0,-1):i;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return we("Archive must have one package root");let t=e.slice(8);return t.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?we("Archive path is not a safe relative package path"):t}function BN(i){let e={},t=0;for(;t<i.length;){let r=i.indexOf(32,t);if(r<0)return we("Invalid PAX header");let n=i.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(n))return we("Invalid PAX record length");let s=Number(n),o=t+s;if(o>i.length||o<=r+2||i[o-1]!==10)return we("Truncated PAX record");let l=Jr(i.subarray(r+1,o-1)),a=l.indexOf("=");if(a<1)return we("Invalid PAX record");let c=l.slice(0,a),p=l.slice(a+1);if(Object.hasOwn(e,c)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(c))return we("Unsupported PAX feature");e[c]=p,t=o}return e}function FN(i){if(!i.length||i.length>vo)return we("Compressed archive exceeds budget");let e;try{e=PN(i,{maxOutputLength:UN})}catch{return we("Invalid or oversized gzip archive")}let t=[],r=new Set,n=0,s=0,o=0,l=0,a=null,c=!1;for(;n+512<=e.length;){let d=e.subarray(n,n+512);if(n+=512,d.every(P=>P===0)){if(a||e.subarray(n).some(P=>P!==0))return we("Unexpected archive data after end marker");c=!0;break}if(++l>Re.files*2)return we("Too many archive headers");let g=0;for(let P=0;P<512;P++)g+=P>=148&&P<156?32:d[P];if(yw(d.subarray(148,156))!==g)return we("Invalid tar header checksum");let b=Jr(d.subarray(257,263));if(b&&b!=="ustar"&&b!=="ustar ")return we("Unsupported tar format");let v=d[156],y=Jr(d.subarray(345,500)),S=(y?y+"/":"")+Jr(d.subarray(0,100)),T=yw(d.subarray(124,136));if(a&&(a.path!==void 0&&(S=a.path),a.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(a.size))return we("Invalid PAX size");T=Number(a.size)}if(!Number.isSafeInteger(T)||T<0||T>Re.total||n+T>e.length)return we("Truncated or oversized tar member");let I=e.subarray(n,n+T);if(n+=Math.ceil(T/512)*512,v===120){if(a||T>8192)return we("Oversized or chained PAX header");a=BN(I);continue}if(a=null,v!==0&&v!==48&&v!==53)return we("Links and special archive members are forbidden");let x=v===53;if(x&&T!==0||Jr(d.subarray(157,257)))return we("Invalid archive link or directory");if(S=jN(S),!S&&!x)return we("Invalid package root member");if(r.has(S))return we("Duplicate archive member");if(r.add(S),++s>Re.files||(o+=T)>Re.total)return we("Unpacked archive exceeds budget");t.push({path:S,data:I,directory:x})}if(!c||!r.has("package.json"))return we("Archive is incomplete or has no package.json");let p=new Set(t.filter(d=>!d.directory).map(d=>d.path));for(let d of t){let g=d.path.split("/");for(let b=1;b<g.length;b++)if(p.has(g.slice(0,b).join("/")))return we("Archive file/directory collision")}return t}async function zd(i,e){let t=FN(i);for(let r of t){if(!r.path)continue;let n=qN(e,r.path);await DN(r.directory?n:LN(n),{recursive:!0,mode:448}),r.directory||await MN(n,r.data,{flag:"wx",mode:384})}}import{lstat as GN,mkdir as HN,readdir as WN,realpath as zN,writeFile as VN}from"node:fs/promises";import{dirname as $N,join as Vd}from"node:path";async function fw(i,e){let t=await zN(i),r=await ur(t,"package.json",Re.other),n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new f("invalid_package","package.json is not valid JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new f("invalid_package","package.json must be an object");let s=[],o=0,l=0;async function a(g,b){if(b>16)throw new f("invalid_package","Package directory nesting limit exceeded");for(let v of await WN(Vd(t,g),{withFileTypes:!0})){let y=`${g}/${v.name}`;if(++o>Re.files)throw new f("invalid_package","Too many package entries");if(v.isDirectory()){await a(y,b+1);continue}if(!v.isFile())throw new f("invalid_package",`Links and non-regular files are forbidden: ${y}`);let S=await ur(t,y,Re.js);if((l+=S.length)>Re.total)throw new f("invalid_package","Resource budget exceeded");let T=Vd(e,y);await HN($N(T),{recursive:!0,mode:448}),await VN(T,S,{flag:"wx",mode:384}),s.push([y,Te(S)])}}let c;try{c=await GN(Vd(t,"dist"))}catch(g){throw g.code==="ENOENT"?new f("dist_missing","dist/ does not exist yet; build the plugin first"):g}if(!c.isDirectory())throw new f("invalid_package","dist must be a real directory");await a("dist",0);let{version:p,...d}=n;return s.sort((g,b)=>g[0].localeCompare(b[0])),{contentHash:Te(JSON.stringify({package:d,files:s})),packageJson:n}}function nt(i){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(i);return!e||e[0]!==i||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Lt(i,e){let t=nt(i),r=nt(e);if(!t||!r)throw new f("invalid_version","Only exact stable semantic versions are supported");return t.major-r.major||t.minor-r.minor||t.patch-r.patch}function _w(i){let e=nt(i);if(e)return e;if(!Ya(i))return null;let[t,r]=i.split("-alpha."),n=nt(t),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function $d(i){return!!_w(i)}function Xr(i,e){if(!$d(i)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(n=>!n.trim()))return!1;let r=[];for(let n of t){let s=n.trim().split(/\s+/),o=!0;for(let l of s){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(l),c=a&&_w(a[2]);if(!a||!c)return!1;let p=a[2],d=pt(i,p);switch(a[1]??"="){case"=":o&&=d===0;break;case">=":o&&=d>=0;break;case"<=":o&&=d<=0;break;case">":o&&=d>0;break;case"<":o&&=d<0;break;case"~":o&&=d>=0&&pt(i,`${c.major}.${c.minor+1}.0-0`)<0;break;case"^":{let g=c.major?`${c.major+1}.0.0`:c.minor?`0.${c.minor+1}.0`:`0.0.${c.patch+1}`;o&&=d>=0&&pt(i,`${g}-0`)<0;break}}}r.push(o)}return r.some(Boolean)}var Yd=64*1024*1024,Kd=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);function Qd(i,e){let t=i.get(e);if(!t)throw new f("unreviewed_plugin","No trusted tool policy for this package");return t}function vw(i,e){let t=i.get(e)?.workspace?.files??Kd;for(let r of t)if(!/^\.[a-z0-9]{1,16}$/.test(r.extension)||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0||r.maxBytes>Yd||r.createDirectory!==void 0&&!/^[A-Za-z0-9_-]{1,64}$/.test(r.createDirectory))throw new f("invalid_policy","Invalid workspace file rule");return t}function kw(i,e){let t=i.get(e)?.runtime?.invokeTimeoutMs;return t===void 0?void 0:Math.min(Math.max(t,1e3),18e4)}var ww=["drawing","design"],YN=/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,KN=/^[a-z][a-z0-9.-]{0,79}$/,Jd=/^[a-z][a-z0-9_]{0,63}$/,gr=/^[a-z][a-z0-9_-]{0,63}$/,QN=/^[a-z][a-z0-9-]{0,63}$/,ps=class{where;constructor(e){this.where=e}fail(e,t){throw new f("invalid_catalog",`${this.where}: ${e} ${t}`)}object(e,t,r,n=r){(!e||typeof e!="object"||Array.isArray(e))&&this.fail(t,"must be an object");let s=e;for(let o of Object.keys(s))r.includes(o)||this.fail(`${t}.${o}`,"is not a known field");for(let o of n)s[o]===void 0&&this.fail(`${t}.${o}`,"is required");return s}string(e,t,r=200,n){return(typeof e!="string"||!e.trim()||e.length>r)&&this.fail(t,`must be a non-empty string of at most ${r} characters`),n&&!n.test(e)&&this.fail(t,`has an invalid format (${JSON.stringify(e)})`),e}strings(e,t,r,n=64){(!Array.isArray(e)||e.length>n)&&this.fail(t,`must be an array of at most ${n} strings`);let s=e.map((o,l)=>this.string(o,`${t}[${l}]`,80,r));return new Set(s).size!==s.length&&this.fail(t,"contains duplicates"),s}text(e,t,r=500){let n=this.object(e,t,["zh","en"]);return{zh:this.string(n.zh,`${t}.zh`,r),en:this.string(n.en,`${t}.en`,r)}}integer(e,t,r,n){return(!Number.isSafeInteger(e)||e<r||e>n)&&this.fail(t,`must be an integer from ${r} to ${n}`),e}https(e,t,r){let n=this.string(e,t,2048),s;try{s=new URL(n)}catch{this.fail(t,"must be an absolute URL")}return(s.protocol!=="https:"||s.username||s.password||s.hash||r!==void 0&&s.hostname!==r)&&this.fail(t,`must be an https URL${r?` on ${r}`:""} without credentials or fragment`),n}subset(e,t,r,n){for(let s of e)t.includes(s)||this.fail(r,`lists "${s}", which is not one of its ${n}`)}};function JN(i,e,t){let r=i.object(e,t,["entry","panels","artifactTools","toolViews","panelAlias"]),n=i.object(r.entry,`${t}.entry`,["label","description","kind"]),s=i.object(r.panelAlias,`${t}.panelAlias`,["prefix","kind","title"]);return{entry:{label:i.string(n.label,`${t}.entry.label`,64),description:i.text(n.description,`${t}.entry.description`,120),kind:i.string(n.kind,`${t}.entry.kind`,32,gr)},panels:i.strings(r.panels,`${t}.panels`,gr,16),artifactTools:i.strings(r.artifactTools,`${t}.artifactTools`,Jd,128),toolViews:i.strings(r.toolViews,`${t}.toolViews`,Jd,128),panelAlias:{prefix:i.string(s.prefix,`${t}.panelAlias.prefix`,32,/^[a-z][a-z0-9-]{0,30}:$/),kind:i.string(s.kind,`${t}.panelAlias.kind`,32,gr),title:i.string(s.title,`${t}.panelAlias.title`,64)}}}function XN(i,e,t){return(!Array.isArray(e)||e.length<1||e.length>16)&&i.fail(t,"must be an array of 1 to 16 rules"),e.map((r,n)=>{let s=`${t}[${n}]`,o=i.object(r,s,["extension","binary","maxBytes","createDirectory"],["extension","binary","maxBytes"]);return typeof o.binary!="boolean"&&i.fail(`${s}.binary`,"must be a boolean"),{extension:i.string(o.extension,`${s}.extension`,17,/^\.[a-z0-9]{1,16}$/),binary:o.binary,maxBytes:i.integer(o.maxBytes,`${s}.maxBytes`,1,Yd),...o.createDirectory!==void 0?{createDirectory:i.string(o.createDirectory,`${s}.createDirectory`,64,/^[A-Za-z0-9_-]{1,64}$/)}:{}}})}function ZN(i,e,t){let r=i.object(e,t,Object.keys(e&&typeof e=="object"?e:{}),[]);return Object.keys(r).length>16&&i.fail(t,"declares more than 16 secrets"),Object.fromEntries(Object.entries(r).map(([n,s])=>{let o=`${t}.${n}`;i.string(n,`${t} key`,64,QN);let l=i.object(s,o,["provider","scope","createUrl","clientId"],["provider","scope","createUrl"]);return l.provider!=="github"&&i.fail(`${o}.provider`,'must be "github" (the only sign-in the host implements)'),[n,{provider:"github",scope:i.string(l.scope,`${o}.scope`,200,/^[\w:. -]+$/),createUrl:i.https(l.createUrl,`${o}.createUrl`,"github.com"),...l.clientId!==void 0?{clientId:i.string(l.clientId,`${o}.clientId`,64,/^[A-Za-z0-9._-]+$/)}:{}}]}))}function eC(i,e,t="policy"){let r=new ps(e),n=r.object(i,t,["tools","readonlyActions","actions","checkpointActions","contribution","browser","workspace","runtime","secrets"],["tools","readonlyActions","actions","checkpointActions","contribution"]),s=r.object(n.tools,`${t}.tools`,Object.keys(n.tools&&typeof n.tools=="object"?n.tools:{}),[]);Object.keys(s).length>128&&r.fail(`${t}.tools`,"declares more than 128 tools");for(let[b,v]of Object.entries(s))r.string(b,`${t}.tools key`,64,Jd),r.string(v,`${t}.tools.${b}`,64,gr);let o=Object.keys(s),l=Object.values(s),a=r.strings(n.readonlyActions,`${t}.readonlyActions`,gr),c=r.strings(n.actions,`${t}.actions`,gr),p=r.strings(n.checkpointActions,`${t}.checkpointActions`,gr);r.subset(a,l,`${t}.readonlyActions`,"tool actions"),r.subset(p,c,`${t}.checkpointActions`,"actions");let d=JN(r,n.contribution,`${t}.contribution`);r.subset(d.artifactTools,o,`${t}.contribution.artifactTools`,"tools"),r.subset(d.toolViews,o,`${t}.contribution.toolViews`,"tools");let g={tools:s,readonlyActions:a,actions:c,checkpointActions:p,contribution:d};if(n.browser!==void 0){let b=r.object(n.browser,`${t}.browser`,["wasm"],[]);b.wasm!==void 0&&typeof b.wasm!="boolean"&&r.fail(`${t}.browser.wasm`,"must be a boolean"),g.browser=b.wasm===void 0?{}:{wasm:b.wasm}}if(n.workspace!==void 0&&(g.workspace={files:XN(r,r.object(n.workspace,`${t}.workspace`,["files"]).files,`${t}.workspace.files`)}),n.runtime!==void 0){let b=r.object(n.runtime,`${t}.runtime`,["invokeTimeoutMs"],[]);g.runtime=b.invokeTimeoutMs===void 0?{}:{invokeTimeoutMs:r.integer(b.invokeTimeoutMs,`${t}.runtime.invokeTimeoutMs`,1e3,18e4)}}return n.secrets!==void 0&&(g.secrets=ZN(r,n.secrets,`${t}.secrets`)),g}var tC=["id","name","icon","description","registry","recommendedVersion","requiredCapabilities","reviewed","policy"];function Xd(i,e,t="plugin"){let r=new ps(e),n=r.object(i,t,tC,["id","name","description","registry","recommendedVersion","requiredCapabilities","policy"]),s=r.string(n.id,`${t}.id`,214,YN);n.icon!==void 0&&!ww.includes(n.icon)&&r.fail(`${t}.icon`,`must be one of ${ww.join(", ")}`);let o=r.https(n.registry,`${t}.registry`);new URL(o).origin!==o&&r.fail(`${t}.registry`,"must be a bare origin such as https://registry.npmjs.org");let l=r.string(n.recommendedVersion,`${t}.recommendedVersion`,64);return nt(l)||r.fail(`${t}.recommendedVersion`,"must be a stable x.y.z version"),n.reviewed!==void 0&&r.string(n.reviewed,`${t}.reviewed`,1e3),{id:s,name:r.string(n.name,`${t}.name`,64),...n.icon!==void 0?{icon:n.icon}:{},description:r.text(n.description,`${t}.description`),registry:o,recommendedVersion:l,requiredCapabilities:r.strings(n.requiredCapabilities,`${t}.requiredCapabilities`,KN),policy:eC(n.policy,e,`${t}.policy`)}}function Sw(i,e){let t=new ps(e),r=t.object(i,"catalog",["schemaVersion","plugins"]);r.schemaVersion!==1&&t.fail("catalog.schemaVersion","must be 1"),(!Array.isArray(r.plugins)||r.plugins.length>64)&&t.fail("catalog.plugins","must be an array of at most 64 entries");let n=r.plugins.map((o,l)=>Xd(o,e,`catalog.plugins[${l}]`)),s=n.map(o=>o.id);for(let[o,l]of s.entries())s.indexOf(l)!==o&&t.fail(`catalog.plugins[${o}].id`,`duplicates ${l}`);return n}function Zd(i){if(i&&typeof i=="object"&&!Object.isFrozen(i)){Object.freeze(i);for(let e of Object.values(i))Zd(e)}return i}var Ew={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 Tw=Zd(Sw(Ew,"official-plugins.json")),kt=Object.freeze(Tw.map(({policy:i,...e})=>Object.freeze(e))),ko=new Map(Tw.map(i=>[i.id,i.policy]));function ut(i,e=kt){let t=e.find(r=>r.id===i);if(!t)throw new f("unknown_plugin","Plugin is not in the trusted official catalog");return t}function eu(i,e,t){let r=i.piWebapp;return i.name===e.id&&!!nt(i.version)&&!i.deprecated&&Di(r)&&Xr(t,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function Iw(i,e,t,r,n){if(!i||typeof i!="object"||!("versions"in i)||!i.versions||typeof i.versions!="object"||Array.isArray(i.versions))throw new f("registry_invalid","Invalid registry version catalog");let s=Object.entries(i.versions);if(s.length>1e4)throw new f("registry_invalid","Registry version catalog exceeds budget");let l=s.flatMap(([a,c])=>{if(!c||typeof c!="object")return[];let p=c;return p.version===a&&eu(p,e,t)&&(!n||a===n)&&(!r||Lt(a,r)>=0)?[p]:[]}).sort((a,c)=>Lt(c.version,a.version))[0];if(!l)throw new f("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!l.dist||typeof l.dist.tarball!="string"||typeof l.dist.integrity!="string")throw new f("registry_invalid","Release is missing its immutable tarball integrity");return l}function pC(i,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new f("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(t[1],"base64"),n=iu("sha512").update(i).digest();if(r.length!==n.length||!rC(r,n))throw new f("integrity_mismatch","Downloaded package failed integrity verification")}var Zr=class{root;hostVersion;catalog;fetcher;constructor(e){if(!$d(e.hostVersion))throw new f("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??kt,this.fetcher=e.fetch??yk}async index(){let e=await qe(Ie(this.root,"installed.json"));if(!e){if(await Ce(Ie(this.root,"installed.json"),2*1024*1024))throw new f("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new f("invalid_storage","Invalid plugin installation index");for(let[t,r]of Object.entries(e.versions))if(this.catalog.some(n=>n.id===t)){if(!Array.isArray(r)||r.length>16||new Set(r.map(n=>n.version)).size!==r.length)throw new f("invalid_storage","Invalid installed version list");for(let n of r)this.validateRecord(t,n)}return e}validateRecord(e,t){if(!t||!nt(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${Te(e)}/${t.version}-${t.digest}`||typeof t.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(t.integrity)||typeof t.installedAt!="string")throw new f("invalid_storage","Invalid installed plugin record")}path(e){return Ie(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await dt(Ie(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(s=>!["schema","pluginId","next"].includes(s)))throw new f("invalid_storage","Invalid install journal");ut(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let n=e.versions[t.pluginId]?.find(s=>s.version===t.next.version);if(n&&n.digest!==t.next.digest)throw new f("invalid_storage","Conflicting installation journal");await Ui(Ie(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=Ie(this.root,"staging");await Le(r);for(let n of await nC(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await xw(Ie(r,n))).isSymbolicLink())throw new f("invalid_storage","Invalid abandoned staging directory");await Ui(Ie(r,n),{recursive:!0})}return e}async recoverCollection(e){let t=Ie(this.root,"gc-journal.json"),r=await dt(t);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new f("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");ut(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(o=>o.directory===s.directory));if(n.length&&n.length!==r.records.length)throw new f("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!n.length){await Le(Ie(this.root,"versions")),await Le(Ie(this.root,"versions",Te(r.pluginId)));for(let s of r.records)await Ui(this.path(s),{recursive:!0,force:!0})}await Ui(t)}async collect(e,t){return ut(e,this.catalog),Ue(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]??[],s=new Set(await t()),o=n.at(-1);o&&s.add(o.version);let l=n.filter(a=>!s.has(a.version));return await this.removeLocked(e,r,l),l.map(a=>a.version)})}async removeLocked(e,t,r){r.length&&(await Le(Ie(this.root,"versions")),await Le(Ie(this.root,"versions",Te(e))),await ye(Ie(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),t.versions[e]=(t.versions[e]??[]).filter(n=>!r.some(s=>s.directory===n.directory)),t.revision++,await ye(Ie(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return Ue(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,t){let r;try{r=new URL(e)}catch{throw new f("registry_denied","Invalid registry URL")}let n=new URL(t.registry);if(r.protocol!=="https:"||r.origin!==n.origin||r.username||r.password||r.hash||r.search)throw new f("registry_denied","Only the official registry origin is permitted");return r}async download(e,t,r,n="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(d){throw r?.aborted?r.reason:new f("registry_unreachable",d instanceof Error?d.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new f(o.status===404?`${n}_not_found`:"download_failed",`Registry ${n} request failed (${o.status})`);if(o.url&&new URL(o.url).origin!==e.origin)throw new f("registry_denied","Registry redirect is forbidden");let l=o.body.getReader(),a=[],c=0,p=()=>{l.cancel(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.throwIfAborted(),Number(o.headers.get("content-length"))>t)throw new f("download_too_large","Registry response exceeds budget");for(;;){let d=await l.read();if(d.done)break;if(c+=d.value.length,c>t)throw new f("download_too_large","Registry response exceeds budget");a.push(Buffer.from(d.value))}return s.throwIfAborted(),Buffer.concat(a)}catch(d){throw r?.aborted?r.reason:d instanceof f?d:new f("registry_unreachable",d instanceof Error?d.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await l.cancel().catch(()=>{}),l.releaseLock()}}async check(e,t,r,n){let s=ut(e,this.catalog);if(r&&!nt(r))throw new f("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),l,a=await this.download(o,8*1024*1024,n,"metadata");try{l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{throw new f("registry_invalid","Invalid registry metadata JSON")}return Iw(l,s,this.hostVersion,t,r)}async install(e,t,r){let n=ut(e,this.catalog);if(!eu(t,n,this.hostVersion))throw new f("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(t.dist.tarball,n),vo,r);return this.installArchive(e,s,t.dist.integrity,t.version,r)}async installArchive(e,t,r,n,s){let o=ut(e,this.catalog);if(!nt(n))throw new f("invalid_version","Choose an exact stable version");if(t.length>vo)throw new f("download_too_large","Package archive exceeds budget");return pC(t,r),Ue(this.root,async()=>{let l=await this.recoverLocked();s?.throwIfAborted();let a=await tu(Ie(this.root,"staging","stage-"));try{await zd(t,a),s?.throwIfAborted();let c=await mr(a,e);if(c.version!==n||!Di(c.manifest)||!Xr(this.hostVersion,c.manifest.hostRange)||!o.requiredCapabilities.every(p=>c.manifest.capabilities.includes(p)))throw new f("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,l,a,c,r,s)}finally{await Ui(a,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,r,n,s,o){let l=t.versions[e]?.find(d=>d.version===n.version);if(l&&l.digest!==n.digest)throw new f("version_replaced","An installed immutable version cannot be replaced with different content");let a={version:n.version,digest:n.digest,integrity:s,directory:`${Te(e)}/${n.version}-${n.digest}`,installedAt:new Date().toISOString()};if(await Le(Ie(this.root,"versions",Te(e))),!l&&(t.versions[e]?.length??0)>=16)throw new f("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await ye(Ie(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let c=this.path(a),p=!1;try{await xw(c),p=!0}catch(d){if(!Ci(d))throw d}if(p){if((await mr(c,e)).digest!==n.digest)throw new f("resource_changed","Installed package content was modified")}else await oC(r,c);return o?.throwIfAborted(),l||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await ye(Ie(this.root,"installed.json"),t)),await Ui(Ie(this.root,"install-journal.json")),{...n,root:await aC(c)}}async installDevArchive(e,t,r){ut(e,this.catalog);let n=await sC(t),s="sha512-"+iu("sha512").update(n).digest("base64"),o=await tu(Ie(cC(),"pi-dev-archive-"));try{await zd(n,o);let l=(await mr(o,e)).version;return await this.installArchive(e,n,s,l,r)}finally{await Ui(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,r){let n=ut(e,this.catalog);return Ue(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let o=await tu(Ie(this.root,"staging","stage-"));try{let{contentHash:l,packageJson:a}=await fw(t,o);r?.throwIfAborted();let c=Ie(this.root,"dev-sources.json"),p=await qe(c)??{},d=p[e],g=s.versions[e]??[],b=d?.contentHash===l?g.find(B=>B.version===d.version):void 0;if(b){let B=await mr(this.path(b),e);if(B.digest!==b.digest)throw new f("resource_changed","Installed package integrity changed");return B}let v=typeof a.version=="string"?nt(a.version):null;if(!v)throw new f("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let y=Math.max(-1,...g.map(B=>nt(B.version)).filter(B=>B&&B.major===v.major&&B.minor===v.minor).map(B=>B.patch)),S=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),y+1),T=`${v.major}.${v.minor}.${S}`;await lC(Ie(o,"package.json"),JSON.stringify({...a,version:T},null,2),{flag:"wx",mode:384});let I=await mr(o,e);if(!Xr(this.hostVersion,I.manifest.hostRange))throw new f("incompatible_plugin",`Package hostRange ${I.manifest.hostRange} does not include host ${this.hostVersion}`);let x=n.requiredCapabilities.filter(B=>!I.manifest.capabilities.includes(B));if(x.length)throw new f("incompatible_plugin",`Package lacks required capabilities: ${x.join(", ")}`);let P="sha512-"+iu("sha512").update(l).digest("base64"),U=await this.commitStaged(e,s,o,I,P,r);return p[e]={contentHash:l,version:T},await ye(c,p),U}finally{await Ui(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let r=ut(e,this.catalog);return Ue(this.root,async()=>{let n=await this.recoverLocked(),s=n.versions[e]?.find(l=>l.version===t);if(!s)throw new f("not_installed","Plugin version is not installed");let o=await mr(this.path(s),e);if(o.digest!==s.digest)throw new f("resource_changed","Installed package integrity changed");if(!Xr(this.hostVersion,o.manifest.hostRange)||!r.requiredCapabilities.every(l=>o.manifest.capabilities.includes(l)))throw new f("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){ut(e,this.catalog),await Ue(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,r,s)})}};import{lstat as wo,mkdir as dC,open as Aw,realpath as Ow,readdir as ru,link as uC,rename as mC,unlink as br,copyFile as gC,rm as bC}from"node:fs/promises";import{dirname as hC,isAbsolute as Rw,join as de,relative as Nw,resolve as yC,sep as nu,win32 as fC}from"node:path";import{randomUUID as su}from"node:crypto";var ds=192*1024*1024,U9=512*1024,Pw=i=>typeof i=="string"&&/^[a-f0-9-]{36}$/.test(i);function _C(i){if(!i||typeof i!="object"||Array.isArray(i))throw new f("invalid_input","Expected object input");return i}function Cw(i){if(typeof i!="string"||!/^[\w.-]{1,160}$/.test(i)||i==="."||i==="..")throw new f("invalid_input","Invalid state key");return i}function us(i){if(i&&(!Pw(i.stateRef)||typeof i.version!="string"||!Number.isSafeInteger(i.generation)||i.generation<1||!Number.isSafeInteger(i.schema)||i.schema<1||typeof i.enabled!="boolean"||typeof i.operationId!="string"))throw new f("invalid_storage","Invalid active plugin record");return i}var hr=class{root;pluginId;legacy;checkpoint;files;constructor(e,t,r,n,s=Kd){this.root=de(e,Te(t)),this.pluginId=t,this.legacy=r,this.checkpoint=n,this.files=s}rule(e){let t=typeof e=="string"?this.files.find(r=>e.toLowerCase().endsWith(r.extension)):void 0;if(!t)throw new f("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return t}active(){return qe(de(this.root,"active.json")).then(us)}async recover(){return Ue(this.root,async()=>{let e=await this.active(),t=await dt(de(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(o=>!["version","before","next"].includes(o))||Object.hasOwn(t,"version")&&t.version!==1)throw new f("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");us(t.next),us(t.before);let r=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,l)=>o===null||l===null?o===l:["version","generation","stateRef","schema","enabled","operationId"].every(a=>o[a]===l[a]))(e,r==="committed"?t.next:t.before))throw new f("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await ye(de(this.root,"previous.json"),s),r==="committed"){let o=await dt(de(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(l=>["version","stateRef"].includes(l))&&await br(de(this.root,"fork.json"))}return await br(de(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,t){return Ue(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new f("stale_generation","Plugin activation changed concurrently");let n=await dt(de(this.root,"fork.json"));if(n&&(n.version!==1||n.stateRef!==t.stateRef||Object.keys(n).some(o=>!["version","stateRef"].includes(o))))throw new f("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=us({...t,generation:e+1,operationId:su()});await Le(de(this.root,"states")),await Le(de(this.root,"states",s.stateRef)),await ye(de(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await ye(de(this.root,"active.json"),s)}catch(o){if((await this.active())?.operationId!==s.operationId)throw o}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await ye(de(this.root,"previous.json"),r),await br(de(this.root,"transition.json")),await br(de(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return Ue(this.root,async()=>{let t=await this.assertGeneration(e,!1),r=su(),n=de(this.root,"states",r);if(await dt(de(this.root,"fork.json")))throw new f("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await ye(de(this.root,"fork.json"),{version:1,stateRef:r}),await Le(n);let s=de(this.root,"states",t.stateRef);for(let o of await ru(s)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new f("invalid_storage","Unexpected state file");if(!await Ce(de(s,o),ds))throw new f("invalid_storage","Missing state file");await gC(de(s,o),de(n,o))}return await this.checkpoint?.("forked"),r})}async collect(e){return Ue(this.root,async()=>{for(let c of["transition.json","fork.json"])if(await Ce(de(this.root,c),2*1024*1024))throw new f("gc_recovery_required",`GC refused: unresolved ${c}; stop all owners and inspect recovery references`);let t=await this.active(),r=us(await dt(de(this.root,"previous.json")));if(!t&&await Ce(de(this.root,"active.json"),2*1024*1024))throw new f("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let n=[t,r].filter(c=>!!c),s=de(this.root,"states");await Le(s);let o=await ru(s),l=new Set(n.map(c=>c.stateRef));for(let c of o){if(!Pw(c))throw new f("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=de(s,c),d=await wo(p);if(!d.isDirectory()||d.isSymbolicLink())throw new f("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let g of await ru(p)){let b=await wo(de(p,g));if(!/^[a-f0-9]{64}\.json$/.test(g)||!b.isFile()||b.isSymbolicLink()||b.nlink!==1)throw new f("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!l.has(c)){let v=await qe(de(p,g),ds);if(!v)throw new f("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(v,"committed")){let y=v;if(Object.keys(y).some(S=>!["requestId","inputHash","nextHash","committed"].includes(S))||y.committed!==!0||!/^[a-f0-9]{64}$/.test(y.inputHash)||!/^[a-f0-9]{64}$/.test(y.nextHash)||typeof y.requestId!="string")throw new f("gc_recovery_required",`GC refused: unresolved file intent in states/${c}; reconcile the workspace save before cleanup`)}else{if(Object.keys(v).some(y=>!["revision","schema","value","requestId","inputHash"].includes(y)))throw new f("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(v)}}}}for(let c of l)if(!o.includes(c))throw new f("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let a=await e(n);for(let c of o)l.has(c)||await bC(de(s,c),{recursive:!0,force:!0});return a})}async assertGeneration(e,t=!0){let r=await this.active();if(!r||r.generation!==e||t&&!r.enabled)throw new f("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new f("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,r,n="session"){if(n!=="session"&&n!=="workspace")throw new f("invalid_input","Invalid state scope");let s=n==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return de(this.root,"states",e.stateRef,`${Te(s+":state:"+r)}.json`)}async call(e,t,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new f("invalid_lease","Invalid invocation lease");this.scopeKey(e);let n=_C(r);return Ue(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await qe(this.statePath(s,e,Cw(n.key),n.scope),ds);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(s,e,Cw(n.key),n.scope);if(!Number.isSafeInteger(n.expectedRevision)||n.expectedRevision<0||n.schema!==s.schema||!Object.hasOwn(n,"value"))throw new f("invalid_input","Invalid state revision or schema");if(JSON.stringify(n.value)===void 0)throw new f("invalid_input","State value must be JSON serializable");let l=JSON.stringify(n);if(Buffer.byteLength(l)>ds)throw new f("state_too_large","Plugin state exceeds limit");let a=await qe(o,ds);a&&this.validateState(a);let c=Te(l);if(a?.requestId===e.requestId&&a.inputHash===c)return{revision:a.revision,schema:a.schema,value:a.value};if((a?.revision??0)!==n.expectedRevision)throw new f("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 ye(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let o=this.rule(n.path),{target:l}=await this.fileTarget(e.scope.cwd,n.path),a=n.maxBytes===void 0?o.maxBytes:n.maxBytes;if(!Number.isSafeInteger(a)||a<=0||a>o.maxBytes)throw new f("invalid_input","Invalid workspace read limit");if(n.encoding!==void 0&&n.encoding!==(o.binary?"base64":"utf-8"))throw new f("invalid_input","Encoding does not match the reviewed file rule");let c=await Ce(l,a);return c?o.binary?{base64:c.toString("base64"),bytes:c.length,hash:Te(c)}:{text:new TextDecoder("utf-8",{fatal:!0}).decode(c),hash:Te(c)}:null}case"workspace.commit":return this.commitFile(s,e,n);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new f("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new f("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,r=!1){let n=this.rule(t);if(typeof t!="string"||t.length>4096||t.includes("\\")||t.includes("\0")||Rw(t)||fC.isAbsolute(t))throw new f("invalid_path",`Use a workspace-relative ${n.extension} path`);let s=await Ow(e),o=yC(s,t),l=Nw(s,o);if(!l||l===".."||l.startsWith(`..${nu}`)||Rw(l))throw new f("invalid_path","Workspace path escapes root");let a=s,c=l.split(nu);for(let d=0;d<c.length;d++){a=de(a,c[d]);let g;try{g=await wo(a)}catch(b){if(!Ci(b))throw b;if(d<c.length-1){if(!r||!n.createDirectory||Nw(s,a)!==n.createDirectory)throw new f("invalid_path","Workspace directory does not exist");try{await dC(a,{mode:448})}catch(v){if(v.code!=="EEXIST")throw v}g=await wo(a)}}if(g&&(g.isSymbolicLink()||(d<c.length-1?!g.isDirectory():!g.isFile()||g.nlink!==1)))throw new f("invalid_path","Workspace path contains a link or non-regular file")}let p=await Ow(hC(o));if(p!==s&&!p.startsWith(s+nu))throw new f("invalid_path","Workspace directory changed");return{target:o,parent:p}}async commitFile(e,t,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 f("invalid_input","Invalid file content or expected hash");let{target:o,parent:l}=await this.fileTarget(t.scope.cwd,r.path,!0),a=de(this.root,"states",e.stateRef,`${Te(this.scopeKey(t)+":file:"+t.requestId+":"+String(r.path))}.json`),c=Te(JSON.stringify(r)),p=Te(s),d=await qe(a);if(d&&(d.requestId!==t.requestId||d.inputHash!==c||d.nextHash!==p))throw new f("duplicate_request","Request ID was reused with different content");let g;try{g=await Aw(`${o}.lock`,"wx",384)}catch(v){throw v.code==="EEXIST"?new f("file_busy","Workspace file is locked; original file preserved"):v}let b;try{await g.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let v=await Ce(o,n.maxBytes),y=v?Te(v):null;if(d&&y===p)return{hash:p};if(d?.committed||y!==r.expectedHash)throw new f("file_conflict","Workspace file already exists or changed externally");await ye(a,{requestId:t.requestId,inputHash:c,nextHash:p,committed:!1}),b=de(l,`.plugin-${su()}.tmp`);let S=await Aw(b,"wx",384);try{await S.writeFile(s),await S.sync()}finally{await S.close()}if((await this.fileTarget(t.scope.cwd,r.path)).parent!==l)throw new f("file_conflict","Workspace directory changed during save");let I=await Ce(o,n.maxBytes);if((I?Te(I):null)!==r.expectedHash)throw new f("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),r.expectedHash===null){try{await uC(b,o)}catch(x){throw x.code==="EEXIST"?new f("file_conflict","Workspace file was created concurrently"):x}await br(b),b=void 0}else await mC(b,o),b=void 0;return await ye(a,{requestId:t.requestId,inputHash:c,nextHash:p,committed:!0}),{hash:p}}finally{b&&await br(b).catch(()=>{}),await g.close(),await br(`${o}.lock`)}}};import{randomUUID as EC}from"node:crypto";import{fork as vC}from"node:child_process";import{randomUUID as kC}from"node:crypto";import{join as wC}from"node:path";import{EventEmitter as SC}from"node:events";var Dw=192*1024*1024,ms=class i{child;pending=new Map;events=new SC;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,r,n){this.package=e,this.generation=t,this.broker=n;let s={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(s[o]=process.env[o]);this.child=vC(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new f("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,t,r,n,s=1e4){let o=new i(e,t,r,n);try{await o.request("initialize",{entry:wC(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},s);let l=await o.request("describe",void 0,s);if(!l||!Array.isArray(l.tools)||l.tools.length>128)throw new f("invalid_tools","Invalid hosted tool catalog");let a=new Set;for(let c of l.tools){if(!c||typeof c.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(c.name)||a.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 f("invalid_tools","Invalid or duplicate tool descriptor");a.add(c.name)}return o.tools=structuredClone(l.tools),await o.request("health",void 0,s),o}catch(l){throw await o.dispose(),l}}fail(e){this.stopped=!0;for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{return}if(t>Dw){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 f(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let n=this.pending.get(r.invocationId);try{if(!n?.invocation||n.expired)throw new f("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:Ne(s)})}}}request(e,t,r=3e4,n){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new f("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new f("worker_busy","Too many plugin requests"));let s=n?.requestId??kC();if(this.pending.has(s))return Promise.reject(new f("duplicate_request","An identical request is still running"));let o={type:"request",id:s,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>Dw?Promise.reject(new f("message_too_large","Plugin request exceeds limit")):new Promise((l,a)=>{let c=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),a(new f("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:l,reject:a,timer:c,invocation:n,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(c),this.pending.delete(s),a(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,t=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new f("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,t,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(t=>{let r=()=>{clearTimeout(n),this.events.off("idle",r),t(!0)},n=setTimeout(()=>{this.events.off("idle",r),t(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new f("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let t=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",t),this.child.kill("SIGTERM")})}}}};var TC={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},So=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,r=TC,n){this.broker=e,this.workerEntry=t,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 t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await Id(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,r)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new f("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,r):this.broker.call(e,t,r);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new f("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},t)}flushAction(e,t){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new f("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},t)}replace(e,t=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new f("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let r;try{if(r=(await this.broker.recover()).active,r&&r.schema!==e.manifest.dataSchemaVersion)throw new f("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(c){throw this.worker||await this.releaseOwnership?.(),c}let n=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let o=null,l=!1,a=!1;try{if(o=await ms.start(e,n+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(t))throw new f("drain_pending","Plugin calls are still running; switch deferred without killing them");if(a=!0,await this.hooks.freeze(),s&&!await s.waitForIdle(t))throw new f("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new f("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(o.tools)),this.phaseValue="switching";let c=r?await this.broker.forkState(n):EC(),p=await this.broker.activate(n,{version:e.version,stateRef:c,schema:e.manifest.dataSchemaVersion,enabled:!0});l=!0,this.worker=o,o=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 l||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",a&&await this.hooks.resume().catch(()=>{})),c}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,t=!1){return this.serialize(async()=>{let r=this.worker,n=this.phaseValue,s=await this.broker.active(),o=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(s))throw await this.releaseOwnership?.(),this.phaseValue="failed",new f("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await ms.start(r.package,r.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(a){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),a}}};this.phaseValue="draining";try{let a=async c=>{try{await c()}catch(p){if(!t)throw p}};await a(async()=>{if(r&&!await r.waitForIdle(e))throw new f("drain_pending","Plugin work is still draining; current host retained")}),await a(()=>this.hooks.freeze()),await a(async()=>{if(r&&!await r.waitForIdle(e))throw new f("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(a){try{await o(),this.phaseValue=n,await this.hooks.resume()}catch(c){throw this.phaseValue="failed",c}throw a}let l=!1;return()=>this.serialize(async()=>{l||(await o(),this.phaseValue=n,await this.hooks.resume(),l=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,r;try{r=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!r){if(t)throw this.phaseValue="failed",new f("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!t&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let n=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(t&&!await t.waitForIdle(e))throw new f("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new f("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=n,s&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new f("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new f("drain_pending","Host checkpoint synchronization is still running");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(n){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),n}})}};import{readFile as Mw}from"node:fs/promises";var Eo=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 Zr({root:wt(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new fo(e.capabilities):void 0;this.scheduler=new _o({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:xC(),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 hr(wt(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 So(n,e.workerEntry,{validateCandidate:o=>s.validateCandidate?.(o),canSwitch:()=>s.canSwitch(),freeze:()=>s.freeze(),resume:()=>s.resume(),committed:async o=>{if(o.enabled){let l=await this.installer.load(r.id,o.version);this.packages.set(r.id,l),this.assetTokens.set(r.id,IC(24).toString("base64url"));try{this.scheduler.start(r.id,Qr(l.manifest).schedules)}catch(a){this.scheduler.stop(r.id),this.errors.set(r.id,Ne(a))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await s.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return!t&&!r?null:async n=>(await this.collectSettled(e).catch(()=>{}),t?this.installer.installDevDirectory(e,t,n):this.installer.installDevArchive(e,r,n))}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){ut(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new f("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new f("manager_closed","Plugin manager is shutting down"));let r=(this.operations.get(e)??Promise.resolve()).then(t,t);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),n=>{this.errors.set(e,Ne(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,r=!1){return this.options.lifecycle?this.options.lifecycle(e,t,r):t()}async policies(){let e=await qe(wt(this.options.root,"policies","policies.json"));if(!e){if(await Ce(wt(this.options.root,"policies","policies.json"),2*1024*1024))throw new f("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[t,r]of Object.entries(e))if(this.installer.catalog.some(n=>n.id===t)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new f("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await qe(wt(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await Ue(wt(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await ye(wt(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,t){return this.recordCheck(e,{status:"up-to-date",version:t,message:"Developer source installed"})}async check(e,t,r,n){try{let s=await this.installer.check(e,t,r,n),o=!t||Lt(s.version,t)>0;return o?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:s.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:Ne(s).code,message:Ne(s).message}),s}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new f("invalid_input","Invalid plugin update policy");await Ue(wt(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await ye(wt(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return Ue(oo(this.options.root),async()=>{let e=await Od(this.options.root);if(!e)return{intent:e,admitted:!1};if(!Rd(e))return e.phase==="required-action"&&await co(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await Ad(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Ad(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Mw(this.options.workerEntry)).equals(await Mw(wt(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(t){return await co(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${Ne(t).message}; data retained`}),{intent:e,admitted:!1}}return await co(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 Ue(wt(this.options.root,"policies"),async()=>{let t=await this.policies();await ye(wt(this.options.root,"policies","policies.json"),t)});let{admitted:e}=await this.settleHostPair();await this.installer.inventory();for(let t of this.installer.catalog){let r=this.supervisor(t.id),n=await r.broker.active();if(n?.enabled)try{let s=await this.compatiblePackage(t.id,n.version);await this.lifecycle(t.id,()=>r.replace(s)),this.packages.set(t.id,s),e||await this.collectSettled(t.id)}catch(s){let o=Ne(s),l=["runtime_owned","storage_busy"].includes(o.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(t.id,{...o,message:`Plugin unavailable: startup failed (${o.code}): ${o.message}; data retained. ${l}`})}}}async compatiblePackage(e,t){try{return await this.installer.load(e,t)}catch(r){if(Ne(r).code!=="incompatible_plugin")throw r;let n=((await this.installer.inventory()).versions[e]??[]).map(s=>s.version).filter(s=>s!==t).sort((s,o)=>Lt(o,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(),t=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let o=this.supervisor(s.id),l=await o.broker.active(),a=this.packages.get(s.id),c=(e.versions[s.id]??[]).map(p=>p.version).sort((p,d)=>Lt(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:l?.version??null,enabled:l?.enabled??!1,phase:o.phase,generation:o.generation,pendingVersion:o.pendingVersion,updatePolicy:t[s.id]?.updatePolicy??"notify",pinnedVersion:t[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...a&&o.phase==="active"?{digest:a.digest,document:a.manifest.frontend.document.slice(2),controller:a.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(s.id)}/${this.assetTokens.get(s.id)}/${a.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,r,n){return this.serialize(e,async()=>{let s=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],l=o.map(c=>c.version).sort((c,p)=>Lt(p,c))[0],a=await(async()=>{switch(t){case"check":return this.isDevPlugin(e)?{version:l??null,dev:!0}:{version:(await this.check(e,l,void 0,n)).version};case"install":{let c=this.devSource(e);if(c){let g=await c(n);return await this.recordDevSync(e,g.version),{installed:!0,version:g.version}}let p=await this.check(e,l,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??l;if(!c)throw new f("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(!l)throw new f("not_installed","Only installed plugins can be updated");let c=this.devSource(e);if(c){let v=await c(n),y=await s.broker.active();if(await this.recordDevSync(e,v.version),!y?.enabled)return{installed:!0,enabled:!1,version:v.version};if(y.version===v.version&&!s.pendingVersion)return{unchanged:!0,version:v.version};let S=await this.lifecycle(e,()=>s.replace(v));return S.pending||this.packages.set(e,v),S}let p=await this.check(e,l,r,n),d=await s.broker.active();if(p.version===l&&(!d?.enabled||d.version===l)&&!s.pendingVersion)return{unchanged:!0,version:l};let g=p.version===l?await this.installer.load(e,l):await this.installer.install(e,p,n);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:g.version,message:"Selected compatible release installed; activation may wait for editors"}),!d?.enabled)return{installed:!0,enabled:!1,version:g.version};let b=await this.lifecycle(e,()=>s.replace(g));return b.pending||this.packages.set(e,g),b}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(c=>c.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new f("invalid_operation","Unknown plugin management operation")}})().catch(async c=>{if(["install","update"].includes(t)){this.available.delete(e);let p=Ne(c);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw c});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),a})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async r=>this.installer.collect(e,async()=>{let n=(await this.policies())[e];return[...r.map(s=>s.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...n?.pinnedVersion?[n.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,r){let n=this.supervisor(e);return t!==n.generation?Promise.reject(new f("stale_generation","Reconnect the plugin view before editing",{status:409})):n.invoke(r,this.options.invokeTimeoutMs?.(e))}flush(e,t,r){let n=this.supervisor(e);return t!==n.generation?Promise.reject(new f("stale_generation","Flush generation changed",{status:409})):n.flushAction(r)}async asset(e,t,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 hw(n,r,t)}finally{let o=s.get(n.version)-1;o?s.set(n.version,o):s.delete(n.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let r;try{r=decodeURIComponent(t[1])}catch{return null}let n=this.assetTokens.get(r),s=Buffer.from(t[2]);if(!n||s.length!==Buffer.byteLength(n)||!AC(s,Buffer.from(n)))return null;let o=await this.asset(r,t[3],t[4]);return o?{...o,pluginId:r}:null}servedManifest(e){return this.packages.get(e)?.manifest??null}async reconcileHostUpgrade(){if(Nk(await Od(this.options.root)))return!1;let e=await this.installer.inventory(),t=await this.policies(),r=!0;for(let n of this.installer.catalog){let s=e.versions[n.id];if(s?.length)try{let o=await this.supervisor(n.id).broker.active(),l=o?.enabled?o.version:s.map(c=>c.version).sort((c,p)=>Lt(p,c))[0];try{await this.installer.load(n.id,l);continue}catch(c){if(Ne(c).code!=="incompatible_plugin")throw c}let a=await this.manage(n.id,"update");a&&typeof a=="object"&&"pending"in a&&a.pending&&(r=!1)}catch(o){r=!1;let l=Ne(o);this.errors.set(n.id,l),await this.recordCheck(n.id,{status:"failed",code:l.code,message:l.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}async prefetchForHost(e,t){let r=new Zr({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 o=(n.versions[s.id]??[]).map(c=>c.version).sort((c,p)=>Lt(p,c)),l=await this.supervisor(s.id).broker.active();if(!o.length||this.isDevPlugin(s.id))continue;let a=!1;for(let c of new Set([...l?.enabled?[l.version]:[],...o]))try{await r.load(s.id,c),a=!0;break}catch{}if(!a)try{let c=await r.check(s.id,o[0],void 0,t),p=await r.install(s.id,c,t);await this.recordCheck(s.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(c){t?.throwIfAborted();let p=Ne(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 t=new Zr({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),n=[];for(let s of this.installer.catalog){let o=r.versions[s.id],l=await this.supervisor(s.id).broker.active();if(!l?.enabled)continue;if(!o?.length){n.push({pluginId:s.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let a=[l.version,...o.map(d=>d.version).sort((d,g)=>Lt(g,d))],c=!1,p="";for(let d of new Set(a))try{await t.load(s.id,d),c=!0;break}catch(g){p||=Ne(g).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[t,r]of this.supervisors)e.push(await this.lifecycle(t,()=>r.suspendForRestart(),!0));this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(t){throw await Promise.allSettled(e.reverse().map(r=>r())),this.closing=!1,t}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let t=[],r=async()=>{let n=await Promise.allSettled(t.map(o=>o()));this.closing=!1;let s=n.find(o=>o.status==="rejected");if(s?.status==="rejected")throw s.reason};try{for(let n of this.supervisors.values())t.push(await n.suspendForRestart(void 0,e));return r}catch(n){throw await r(),n}}};import{randomUUID as OC}from"node:crypto";var oe=i=>Object.assign(new Error(i),{status:409,code:"view_barrier"}),gs=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;staleMs;constructor(e,t,r=2e4,n=15e3,s=12e4){this.pluginId=e,this.generation=t,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(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&r.scope.ownerId===t.ownerId&&r.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||t.ownerId!==r.scope.ownerId||t.workspaceId!==r.scope.workspaceId||t.sessionId!==r.identity.sessionId)throw oe("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw oe("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,t,r=++this.sequence){return e.commands.push({id:r,type:t,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw oe("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw oe("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw oe("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 oe("Invalid registration capability");let o=e.viewToken??OC();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw oe("View initialization was cancelled; register a new document identity");let l=this.views.get(o);if(l){if(!this.sameScope(l,e,t)||l.kind!==e.kind)throw oe("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.identity.mountId===e.mountId))throw oe("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw oe("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,t))throw oe("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,t)||n&&!this.sameScope(n,e,t))throw oe("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 o=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:o}}}if(r&&this.sameScope(r,e,t)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,t)||n&&!this.sameScope(n,e,t))throw oe("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 oe("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,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw oe("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 oe("Explicit per-view discard confirmation required");if(this.switching)throw oe("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,t))throw oe("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw oe("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw oe("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw oe("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(oe("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw oe("Invalid acknowledgement");let o=r.commands.find(l=>l.id===e.commandId);if(!o)throw oe("Unknown command acknowledgement");r.commands=r.commands.filter(l=>l.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(oe(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw oe("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw oe("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw oe("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw oe("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw oe("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 oe("Invalid poll cursor");if(r.waiter)throw oe("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw oe("Invalid poll mode");return!e.immediate&&!r.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let l=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(l),r.waiter=void 0,o()}r.waiter=a}),{viewToken:r.token,commands:r.commands.filter(o=>o.id>e.after)}}default:throw oe("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw oe("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(n=>n.activeActions||n.kind!=="controller"&&!n.frozen&&(n.busy||!this.immediate&&["editor","workspace"].includes(n.kind))),r=oe(`Close editors before updating; old version retained. Pending views: ${t.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((t,r)=>{let n=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>n(),reject:s=>n(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));n(oe(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||n()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw oe("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(oe("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(oe("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var Lw={"image/png":i=>i.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),"image/jpeg":i=>i[0]===255&&i[1]===216,"image/webp":i=>i.subarray(0,4).toString("latin1")==="RIFF"&&i.subarray(8,12).toString("latin1")==="WEBP"};function qw(i){let e=i;if(!e||typeof e!="object"||e.$hosted!=="tool-result"||!Array.isArray(e.content))return{content:[{type:"text",text:JSON.stringify(i)??"null"}],details:i};let t=[],r=0;for(let n of e.content.slice(0,16)){let s=n;if(s?.type==="text"&&typeof s.text=="string")t.push({type:"text",text:s.text.slice(0,262144)});else if(s?.type==="image"&&typeof s.data=="string"&&typeof s.mimeType=="string"&&Lw[s.mimeType]&&r<4){let o=/^[A-Za-z0-9+/]*={0,2}$/.test(s.data)?Buffer.from(s.data,"base64"):null;o&&o.length<=2097152&&Lw[s.mimeType](o)?(t.push({type:"image",data:s.data,mimeType:s.mimeType}),r++):t.push({type:"text",text:"[image omitted by host: invalid or too large]"})}}return t.some(n=>n.type==="text")||t.unshift({type:"text",text:"(no text)"}),{content:t,details:e.details??null}}import{randomUUID as RC}from"node:crypto";var NC="Ov23limJmKiuu8cOP83E";function au(i,e,t=process.env){let r=i?.secrets&&Object.hasOwn(i.secrets,e)?i.secrets[e]:void 0;if(r?.provider==="github")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||r.clientId||NC,scope:r.scope,createUrl:r.createUrl}}var CC="https://github.com/login/device/code",PC="https://github.com/login/oauth/access_token",DC=8,To=class{flows=new Map;fetcher;now;constructor(e=(r,n)=>fetch(r,{...n,signal:n.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let r;try{r=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(t).toString()})}catch{throw new f("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let n=await r.json().catch(()=>null);if(!n||typeof n!="object"||!r.ok&&!("error"in n))throw new f("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return n}async start(e,t,r){if(!r.clientId)throw new f("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[d,g]of this.flows)g.expiresAt<=this.now()&&this.flows.delete(d);if(this.flows.size>=DC)throw new f("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(CC,{client_id:r.clientId,scope:r.scope}),{device_code:s,user_code:o,verification_uri:l}=n,a=Number(n.expires_in),c=Math.max(Number(n.interval)||5,1);if(typeof s!="string"||typeof o!="string"||typeof l!="string"||!l.startsWith("https://github.com/")||!Number.isFinite(a))throw new f("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=RC();return this.flows.set(p,{pluginId:e,name:t,clientId:r.clientId,deviceCode:s,expiresAt:this.now()+a*1e3,interval:c,nextPoll:this.now()+c*1e3}),{deviceId:p,userCode:o,verificationUri:l,interval:c,expiresIn:a}}async poll(e){let t=this.flows.get(e);if(!t||t.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<t.nextPoll)return{status:"pending"};t.nextPoll=this.now()+t.interval*1e3;let r=await this.post(PC,{client_id:t.clientId,device_code:t.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:t.pluginId,name:t.name};switch(r.error){case"authorization_pending":return{status:"pending"};case"slow_down":return t.interval+=5,t.nextPoll=this.now()+t.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as ou,readFileSync as Uw,readdirSync as MC,statSync as LC}from"node:fs";import{lstat as qC,readdir as UC,writeFile as jC,mkdir as BC,rename as FC}from"node:fs/promises";import{delimiter as GC,dirname as HC,isAbsolute as WC,join as Bi,resolve as bs}from"node:path";var Io=i=>kt.some(e=>e.id===i),jw=()=>kt.map(i=>i.id).join(", "),ji="piWebappCatalog",zC="https://registry.npmjs.org";function VC(i,e){let t=i[ji];if(t===void 0)throw new f("invalid_catalog",`${e}: ${i.name} is not an official plugin (official: ${jw()}). Describe it in package.json "${ji}" with name, description and policy`);if(!t||typeof t!="object"||Array.isArray(t))throw new f("invalid_catalog",`${e}: ${ji} must be an object`);if("id"in t||"registry"in t)throw new f("invalid_catalog",`${e}: ${ji} must not set id or registry; the package name is the id`);return{...Xd({registry:zC,recommendedVersion:"0.0.0",requiredCapabilities:[...i.piWebapp.capabilities],...t,id:i.name},e,ji),official:!1}}function $C(i=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=new Map,t=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(i??"").split(/[;\n]/).map(s=>s.trim()).filter(Boolean)){let s=n.lastIndexOf("="),o=n.slice(0,s),l=n.slice(s+1),a=s<1?`entry "${n}" is not <id>=<path.tgz>`:Io(o)?l.endsWith(".tgz")?ou(bs(l))?null:`archive not found: ${bs(l)}`:`"${l}" is not a .tgz archive`:`"${o}" is not an official plugin (official: ${jw()}); develop other packages from a directory in PI_WEBAPP_HOSTED_DEV_ROOTS`;if(a){t.push({level:"error",source:r,...Io(o)?{pluginId:o}:{},message:a});continue}e.set(o,bs(l))}return{archives:e,notices:t}}var Bw=i=>Bi(i,"pi-web","hosted-dev.json"),Fw=i=>Bi(i,"pi-web","hosted-dev-status.json");function YC(i,e,t=process.cwd()){let r=[],n=[],s=(i.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(GC).map(l=>l.trim()).filter(Boolean);for(let l of s)r.push({path:bs(t,l),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=s.length>0;if(e&&ou(e)){o=!0;try{let l=JSON.parse(Uw(e,"utf8")),a=l&&typeof l=="object"?l.roots:void 0;if(!Array.isArray(a))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let c of a)typeof c!="string"||!WC(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:bs(c),source:e})}catch(l){n.push({level:"error",source:e,message:`cannot read dev configuration: ${l instanceof Error?l.message:String(l)}`})}}return{specs:r,notices:n,configured:o}}function KC(i){let e=[];try{e=MC(i,{withFileTypes:!0}).filter(t=>t.isDirectory()&&t.name!=="node_modules"&&ou(Bi(i,t.name,"package.json"))).map(t=>t.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 QC(i){let e=(n,s)=>({notice:{level:"error",source:i.source,...s?{pluginId:s}:{},message:`${i.path}: ${n}`}}),t;try{t=LC(i.path)}catch{return e("directory does not exist")}if(!t.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(Uw(Bi(i.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?KC(i.path):"package.json is not valid JSON")}if(typeof r.name!="string")return e("package.json has no name");if(!Di(r.piWebapp))return e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name);if(Io(r.name))return{pluginId:r.name};try{return{pluginId:r.name,entry:VC({name:r.name,piWebapp:r.piWebapp,[ji]:r[ji]},"package.json")}}catch(n){return e(Ne(n).message,r.name)}}var xo=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 t=$C(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let t=YC(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let o of t.specs){let l=QC(o);if(l.notice){r.push(l.notice);continue}let a=l.pluginId;if(n.has(a)){r.push({level:"error",pluginId:a,source:o.source,message:`${o.path}: plugin ${a} is already provided by ${n.get(a)}`});continue}if(this.archives.has(a)&&r.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${a}; the dev directory wins`}),!Io(a)&&!this.catalog.some(c=>c.id===a)){if(!e){r.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: ${a} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}let{policy:c,...p}=l.entry;this.catalog.push(p),this.policies.set(a,c)}else l.entry&&JSON.stringify(l.entry.policy)!==JSON.stringify(this.policies.get(a))&&r.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: the ${ji} policy changed; restart pi-webapp once (npm run stop && npm run start) to apply it. Code still reloads live.`});n.set(a,o.path),s.set(a,o.source)}for(let o of[...this.roots.keys()])n.has(o)||this.roots.delete(o);for(let[o,l]of n)this.roots.set(o,l);this.rootSource.clear();for(let[o,l]of s)this.rootSource.set(o,l);return this.fileNotices=t.notices,this.rootNotices=r,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Ao=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let t of this.options.sources.notices())this.log(`${t.level}: ${t.message}`);let e=()=>{this.current=this.tick().catch(t=>{this.running&&this.log(`poll failed: ${Ne(t).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let t=this.roots.get(e);t&&(t.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,t])=>({pluginId:e,root:t.root,state:t.state,...t.version?{version:t.version}:{},...t.message?{message:t.message}:{}}))}}log(e){(this.options.log??(t=>console.error(`pi-webapp [hosted-dev] ${t}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let t of[...this.roots.keys()])e.has(t)||this.roots.delete(t);for(let[t,r]of e){let n=this.roots.get(t);(!n||n.root!==r)&&(n={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,n));let s=await JC(r);if(s===null){this.set(t,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(t,n,s,!0);continue}await this.apply(t,n,s)}}await this.publish()}set(e,t,r,n={}){let s=t.state!==r||t.message!==n.message||t.version!==n.version;t.state=r,t.message=n.message,t.code=n.code,t.version=n.version??t.version,s&&(t.at=new Date().toISOString(),this.log(`${e}: ${r}${n.version?` ${n.version}`:""}${n.message?` \u2014 ${n.message}`:""}`))}async apply(e,t,r,n=!1){n||this.set(e,t,"switching");try{let o=(await(n?this.options.switcher.retry(e):this.options.switcher.update(e))).plugins.find(l=>l.pluginId===e);t.applied=r,t.retry=!!o?.installed&&!!o.pendingVersion,o?.installed?o.pendingVersion?this.set(e,t,"pending",{version:o.version,message:`Waiting for editors to close before switching to ${o.pendingVersion}`}):this.set(e,t,"synced",{version:o.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(s){let o=Ne(s),l=o.reason==="view_busy",a=l||["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(o.code);n?(t.applied=r,t.retry=a):a||(t.applied=r);let c=o.code==="not_installed";l?this.set(e,t,"pending",{message:"An open editor is saving; switching once it finishes"}):c?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:o.code,message:`${o.message} (${o.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let n=Object.fromEntries([...this.roots].map(([l,a])=>[l,{root:a.root,state:a.state,version:a.version,message:a.message,code:a.code,at:a.at}])),s=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(l=>l.id),plugins:n,notices:e.notices});if(s===this.lastStatus)return;this.lastStatus=s;let o=`${r}.${process.pid}.tmp`;try{await BC(HC(r),{recursive:!0}),await jC(o,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await FC(o,r)}catch{}}};async function JC(i){let e=[],t=async(r,n)=>{let s=await qC(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await t(Bi(i,"package.json"),"package.json");let r=async(n,s,o)=>{if(!(o>16||e.length>8192))for(let l of(await UC(n,{withFileTypes:!0})).sort((a,c)=>a.name.localeCompare(c.name)))l.isDirectory()?await r(Bi(n,l.name),`${s}/${l.name}`,o+1):await t(Bi(n,l.name),`${s}/${l.name}`)};if(await r(Bi(i,"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 ZC(i){try{return[...Qr(i).secrets]}catch{return[]}}var Oo=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new To;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??ko,e.dev?.enabled&&(this.devWatcher=new Ao({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let r=await this.inventory();return r.plugins.find(n=>n.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):r},retry:t=>this.manage({pluginId:t,operation:"retry",reopenEditors:!0})}})),this.adapter=new bo({policy:(t,r)=>{let n=e.policy?.(t,r);return{...n,enabled:!this.recovery.has(t)&&this.manager.tools.some(s=>s.pluginId===t)&&n?.enabled!==!1}},invoke:async(t,r,n)=>{n?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(l=>l.pluginId===t);if(!s)throw new f("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,s.generation,r);return qw(o)}}),this.manager=new Eo({...e,workspaceRules:t=>vw(this.trusted,t),invokeTimeoutMs:t=>kw(this.trusted,t),lifecycle:(t,r,n)=>this.lifecycle(t,r,n),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(Qd(this.trusted,t).tools).length)throw new f("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,r),this.adapter.validateChange(t,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async r=>{try{let n=r.enabled?this.manager.tools.find(s=>s.pluginId===t)?.descriptors:[];if(!n)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,n),r.enabled){let s=await this.manager.installer.load(t,r.version);this.documents.set(t,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,""),secrets:ZC(s.manifest)})}else this.documents.delete(t);this.adapter.change(t,n),await this.coordinator(t).committed(r),e.changed?.(),this.recovery.delete(t)}catch(n){throw this.recovery.set(t,n),await this.coordinator(t).committed(r).catch(()=>{}),n}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,r,n)=>{let s=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!s)throw new f("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(r))throw new f("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return n===null?await s.delete(t,r):await s.set(t,r,n),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let r=this.options.capabilities?.secrets;if(!r)throw new f("hosted_unavailable","Secrets are not available",{status:503});if(t.phase==="cancel")return this.deviceFlows.cancel(t.deviceId),{status:"cancelled"};if(t.phase==="start"){let s=this.documents.get(t.pluginId)?.secrets.includes(t.name)?au(this.trusted.get(t.pluginId),t.name):void 0;if(!s)throw new f("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(t.pluginId,t.name,s)}let n=await this.deviceFlows.poll(t.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:(t,r)=>{if(!this.options.approvals)throw new f("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,r),this.inventory()},action:(t,r)=>this.action(t,r?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new f("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}let r=t,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 t=>{let r=await this.manager.assetRequest(t);if(!r)return null;let n=this.trusted.get(r.pluginId)?.browser?.wasm===!0&&B0(this.manager.servedManifest(r.pluginId));return{bytes:r.bytes,mime:r.mime,csp:j0({wasm:n})}}}}verifyTools(e,t){let r=Qd(this.trusted,e);for(let n of t)if(!Object.hasOwn(r.tools,n.name)||r.tools[n.name]!==n.action||n.readonly!==r.readonlyActions.includes(n.action))throw new f("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new f("unknown_plugin","Hosted coordinator unavailable");return t}scope(e,t){let r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||t&&(r.cwd!==t.cwd||r.workspaceId!==t.workspaceId))throw new f("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let r=this.manager.tools.find(n=>n.pluginId===e);if(!r||r.generation!==t)throw new f("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,t=!1){let r=this.queue.then(async()=>{if(this.closing&&!t)throw new f("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,t,r=!1){let n=this.switches.then(async()=>{if(this.closing&&!r)throw new f("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await t();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new hr(lu(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new f("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{if(!r)for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=n.catch(()=>{}),n.catch(s=>{throw r&&this.adapter.thaw(),s})}async admit(e){let t,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(n=>{t=setTimeout(()=>n(!1),e),t.unref?.()})])}finally{clearTimeout(t)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??kt)try{let t=await new hr(lu(this.options.root,"data"),e.id).active();this.views.set(e.id,new gs(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new gs(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=lu(this.options.root,"host-version.json");(await qe(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await Le(this.options.root),await ye(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??kt)this.recovery.set(t.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,r=new Map;for(let n of e.plugins){let s=n.enabled?this.documents.get(n.id)?.secrets??[]:[];t&&s.length&&r.set(n.id,await Promise.all(s.map(async o=>{let l=au(this.trusted.get(n.id),o);return{name:o,configured:await t.has(n.id,o),...l?{signIn:l.clientId?"browser":"token-page",...l.createUrl?{createUrl:l.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??kt).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 f("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new f("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let t=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(t){if(this.downloads.has(e.pluginId))throw new f("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,t)}try{return await this.enqueue(async()=>{let r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new f("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let n=await this.manager.manage(e.pluginId,e.operation,e.version,t?.abort.signal);if(this.recovery.has(e.pluginId)||n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired)throw new f("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{t&&this.downloads.get(e.pluginId)===t&&this.downloads.delete(e.pluginId)}}async action(e,t=!1){let r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new f("action_denied","Action is not reviewed by this host",{status:403});let n=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:XC(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);throw new f("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new f("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...s,kind:"action"})}finally{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 t=await this.manager.suspendForRestart(e),r=!1,n=async()=>{if(!r)try{await t(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=n,n}catch(t){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),t}finally{for(let t of this.views.values())t.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as eP,readdir as tP,unlink as iP}from"node:fs/promises";import{join as en}from"node:path";import{randomUUID as rP}from"node:crypto";var cu="hosted-migration.json";function Gw(i,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:n}=t.scope,s=en(i,Te(JSON.stringify([r,n])));await Le(i),await Le(s);let o=en(s,"scope.lock"),l;try{l=await eP(o,"wx",384)}catch(a){throw a.code==="EEXIST"?new f("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):a}try{await l.writeFile(JSON.stringify({pid:process.pid,operationId:rP()}));let a=await qe(en(s,cu));if(a&&(a.version!==1||a.pluginId!==e))throw new f("invalid_storage","Legacy scope belongs to another migration");let c=await tP(s),p=[];for(let g of c){if(g==="scope.lock"||g==="focus.json"||g===cu||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(g))continue;if(!/^[\w-]{1,80}\.json$/.test(g))throw new f("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new f("invalid_storage","Too many legacy checkpoints");let b=await qe(en(s,g),3*512*1024);if(!b||b.version!==1||b.cwd!==r||b.sessionId!==n||!b.draft||g!==`${b.draft.id}.json`)throw new f("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(b.draft)}let d=await qe(en(s,"focus.json"),1024);if(d!==null&&(typeof d!="string"||!p.some(g=>g.id===d)))throw new f("invalid_storage","Invalid legacy focused drawing");return a||await ye(en(s,cu),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:d}}finally{await l.close(),await iP(o)}}}import{join as uP}from"node:path";import{randomUUID as nP}from"node:crypto";var sP=6e4,Ro=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:t,sessionId:r,title:n})=>({id:e,pluginId:t,sessionId:r,title:n}))}async authorize(e,t){let r=this.entries.get(t);if(r&&r.pluginId!==e)throw new f("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new f("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<sP?new f("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:nP(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new f("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,t){let r=[...this.entries.values()].find(n=>n.id===e&&n.status==="pending");if(!r)throw new f("unknown_approval","No such pending approval",{status:404});r.status=t?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as aP,readFile as oP,rename as lP,writeFile as cP}from"node:fs/promises";import{randomUUID as pP,createHash as dP}from"node:crypto";import{join as Hw}from"node:path";var No=class{dir;queue=Promise.resolve();constructor(e){this.dir=Hw(e,"secrets")}file=e=>Hw(this.dir,`${dP("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await oP(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!Ci(t))throw new f("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let t=this.queue.then(e,e);return this.queue=t.catch(()=>{}),t}async get(e,t){return(await this.read(e))[t]??null}has(e,t){return this.get(e,t).then(r=>r!==null)}set(e,t,r){return this.mutate(e,n=>{n[t]=r})}delete(e,t){return this.mutate(e,r=>{delete r[t]})}mutate(e,t){return this.serialize(async()=>{let r=await this.read(e);t(r),await aP(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${pP()}.tmp`;await cP(n,JSON.stringify(r),{mode:384}),await lP(n,this.file(e))})}};function Ww(i,e){let t=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:n,title:s,prompt:o}){let l=await i.createDetached(n,r,s);try{await i.sendDetached(l,o,!1)}catch(a){throw await i.releaseDetached(l),a}return{sessionId:l}},ownerOf:r=>i.detachedOwner(r),activeCount:r=>i.detachedCount(r),async send(r,n,s){let o=i.detachedOwner(r);if(s==="execute"&&(!o||!await e(o,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await i.sendDetached(r,n,s==="execute")},abort:r=>i.abortDetached(r),release:r=>i.releaseDetached(r),async events(r,n){let s=i.detachedEvents(r,n);return{events:s.events.map(t),next:s.next}}}}var mP="scheduler";function zw(i){let e=new Ro({describe:i.sessionTitle,changed:i.changed}),t=()=>{let n=i.sessions();if(!n)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return n},r={createDetached:(...n)=>t().createDetached(...n),detachedOwner:n=>i.sessions()?.detachedOwner(n)??null,detachedCount:n=>i.sessions()?.detachedCount(n)??0,sendDetached:(...n)=>t().sendDetached(...n),abortDetached:n=>t().abortDetached(n),releaseDetached:async n=>{e.forget(n),await t().releaseDetached(n)},detachedEvents:(...n)=>t().detachedEvents(...n)};return{approvals:e,capabilities:{secrets:new No(uP(i.root,"capability-secrets")),sessions:Ww(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=i.activeWorkspace();if(!n)return null;try{return i.trustedScope(n,mP)}catch{return null}}}}async function gP(){for(let i of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=Va(i),t=new Yt({env:i,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:dn,buildId:It,browser:Va({}).browser}}async function Vw(){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 i=new Yt({monitor:!1});try{if(await i.ready,!i.enabled)throw new Error("Sentry verification transport is disabled");let e=i.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await i.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:dn,buildId:It}}finally{await i.close()}}var hs=nn(hP(_P(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),EP=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),m=globalThis[EP]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new Ni(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:mi()}),He()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new dr,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};m.lifecycle??=new dr;m.tuiGeneration??=0;m.stopChanged??=null;m.tuiWaitController??=new AbortController;m.tuiStreaming??=null;m.tuiPrompts??=new Ni(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:mi()}),He()});m.tuiPromptSessionId??=null;m.tuiAgentError??=!1;var Yw=!1;function TP(i){return Yw||(Yw=!0,setTimeout(()=>{i.pruneReleases().catch(()=>{})},6e4).unref()),i}function Co(){return m.selected==="sdk"?m.workspaceSessions?.catalog??null:m.tuiCatalog}var IP=null;function xP(){return IP??=vP.create({refreshOnCreate:!1})}var Po=new Map;async function rn(){let i=await xP(),e=m.selected==="tui"?m.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Po.keys())t.has(r)||(i.unregisterProvider(r),Po.delete(r));for(let r of t){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),o=n??s;!o||Po.get(r)===o||(n?i.registerNativeProvider(n):s&&i.registerProvider(r,s),Po.set(r,o))}return await i.refresh({allowNetwork:!1}),i}function We(){return m.selected==="sdk"?m.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():mi()}function mi(){if(m.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...W0(m.current,m.current.sessionManager.getSessionName(),m.tuiCatalog?.ids()??[]),idle:m.current.isIdle()&&!m.tuiPrompts.sending,streaming:m.tuiStreaming,queuedPrompts:m.tuiPrompts.view(),hasPendingPrompts:m.current.hasPendingMessages?.()??!1,interactions:m.interactions?.pending(m.current.sessionManager.getSessionId())??[]}}async function bu(i,e,t,r,n){let s=st(i);Ri({...mi(),idle:s.isIdle()},e,n);let o=s.isIdle();o&&$r(()=>m.hosted?.adapter.assertAdmission(),r,(l,a)=>m.bridge?.reportError?.(l,a)),o&&(m.operation=r);try{let l=t.length?[{type:"text",text:e},...t]:e;if(m.replacementContext!==null&&m.replacementSessionId===i)await m.replacementContext.sendUserMessage(l,{expandPromptTemplates:!0,deliverAs:n});else{if(!m.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");m.pi.sendUserMessage(l,{expandPromptTemplates:!0,deliverAs:n})}m.current?.sessionManager.getSessionId()===i&&m.selected==="tui"&&m.bridge?.publish({type:"snapshot",session:mi()})}catch(l){throw o&&(m.operation=void 0),l}}function uu(){let i=m.current?.sessionManager.getSessionId(),e=m.tuiGeneration,t=()=>{if(!i||!m.current||m.tuiGeneration!==e||m.current.sessionManager.getSessionId()!==i||m.tuiAgentError)return!1;let r=mi();return!m.hosted?.adapter.isFrozen&&m.current.isIdle()&&!r.paused&&!r.interactions.length};m.tuiPrompts.schedule(t,(r,n,s)=>bu(i,r,n,s))}function Je(i){if(We().sessionId!==i)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function Xw(){let i=(m.workspaces?.list()??[]).map(p=>({...p})),e=m.activeWorkspaceId,t=We(),n=m.current?mi():null,s=await lr(t.cwd).catch(p=>(m.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=n?await lr(n.cwd).catch(p=>(m.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,l=await gu.listAll(),a=m.workspaceSessions?.retainedSessions()??[];n&&o&&a.push({sessionId:n.sessionId,cwd:o,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&&m.tuiPrompts.length===0&&!n.messages.some(p=>p.role==="user")});let c=(await Promise.all(i.map(async p=>{let g=(await zr(p.path,l).catch(b=>(b instanceof ts?p.available=!1:m.bridge?.reportError?.(b,{stage:"workspace_sessions"}),[]))).map(b=>({id:b.id,workspaceId:p.id,path:b.path,name:b.name||b.firstMessage?.slice(0,50)||"",modified:b.modified.toISOString(),idle:!0}));for(let b of a.filter(v=>v.cwd===p.path)){if(b.blank&&b.sessionId!==t.sessionId)continue;let v=g.findIndex(S=>S.id===b.sessionId),y={id:b.sessionId,workspaceId:p.id,path:b.path??g[v]?.path??null,name:b.name,modified:b.modified,idle:b.idle};v<0?g.unshift(y):g[v]=y}return p.path===s&&!g.some(b=>b.id===t.sessionId)&&g.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),g}))).flat();return{items:i,activeId:e,sessions:c}}var Kw=0;async function He(){if(!m.bridge)return;let i=++Kw;try{let e=await Xw();i===Kw&&m.bridge?.publish({type:"workspaces",value:e})}catch(e){m.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function mu(i,e=!1){let t=m.workspaces?.get(i);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Qt(t.path),!e&&m.current&&t.path===await lr(m.current.cwd)&&!m.workspaceSessions?.hasWorkspace(t.path))m.selected="tui",m.activeWorkspaceId=i,m.bridge?.publish({type:"stream",message:null}),m.bridge?.publish({type:"snapshot",session:We()});else{if(!m.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await m.workspaceSessions.reuseBlank(t.path))&&await m.workspaceSessions.open(t.path,e?"new":"continue"),m.selected="sdk",m.activeWorkspaceId=i,m.bridge?.publish({type:"snapshot",session:We()})}await He()}async function Qw(i,e,t){let r=m.workspaces?.get(i);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await Qt(r.path);if(m.workspaceSessions?.hasSession(n,e)||m.current?.sessionManager.getSessionId()===e&&await lr(m.current.cwd)===n)return r;if(!(await zr(n)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function st(i){let e=m.current;if(e===null||e.sessionManager.getSessionId()!==i)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function it(i){m.current=i,m.selected==="tui"&&m.bridge?.publish({type:"snapshot",session:We()})}function Zw(){if(m.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let i=m.selected==="sdk"?m.workspaceSessions?.path:m.current.cwd;if(!i)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=m.selected==="tui"?m.current.isProjectTrusted():m.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return kP.create(i,void 0,{projectTrusted:e})}async function eS(){let i=Zw(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),t=new Jw({cwd:We().cwd,agentDir:mt(),settingsManager:i}),r=Ek(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:i.isProjectTrusted(),global:e(i.getGlobalSettings()),project:e(i.getProjectSettings()),installed:r}}async function AP(i){Je(i.sessionId);let e=m.selected==="tui"?st(i.sessionId):null;if(e?!e.isIdle():!m.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=Zw();if(i.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=i.value.trim(),n=i.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(i.kind==="packages"){let s=new Jw({cwd:We().cwd,agentDir:mt(),settingsManager:t});i.action==="add"?await s.installAndPersist(r,{local:i.scope==="project"}):await s.removeAndPersist(r,{local:i.scope==="project"})}else if(i.kind==="extensions"){let s=n.extensions??[],o=i.action==="add"?[...new Set([...s,r])]:s.filter(l=>l!==r);i.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let s=n.skills??[],o=i.action==="add"?[...new Set([...s,r])]:s.filter(l=>l!==r);i.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),m.selected==="tui"?(m.commandContext&&await m.commandContext.reload(),m.current&&it(m.current)):(await m.workspaceSessions?.reload(),m.bridge?.publish({type:"plugins_changed"})),await eS()}function Do(i,e=Ed){if(m.hostedMode===!1||m.hostedMode===void 0&&m.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");m.hostedMode=!0;let t=(c,p)=>{let d=pu(c);return{cwd:d,sessionId:p,workspaceId:$w("sha256").update(d).digest("hex")}},r=tn(mt(),"pi-web","hosted"),n=new xo({configPath:Bw(mt())});m.hosted??=new Oo({root:r,...n.enabled?{dev:n,devStatusPath:Fw(mt())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...kt,...n.catalog],policies:new Map([...ko,...n.policies])}:{},...zw({root:r,sessions:()=>m.workspaceSessions,activeWorkspace:()=>m.workspaceSessions?.path??null,trustedScope:t,sessionTitle:c=>m.workspaceSessions?.retainedSessions().find(p=>p.sessionId===c)?.name,changed:()=>m.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(yP(nn(hs,"../../package.json"),"utf8")).version,packageRoot:nn(hs,"../.."),workerEntry:nn(hs,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${$w("sha256").update(mt()).digest("hex")}`,resolveSession:c=>{let p=m.current;if(p?.sessionManager.getSessionId()===c)return t(p.cwd,c);let d=m.workspaceSessions?.hostedScope(c);return d?t(d.cwd,c):null},legacy:()=>Gw(tn(mt(),"pi-web","diagrams")),changed:()=>m.bridge?.publish({type:"hosted_plugins_changed"})}),m.offHostedThaw?.(),m.offHostedThaw=m.hosted?.adapter.onThaw(uu),m.pi=i;let s=zm({async run(...c){if(!m.bridge)throw new Error("Open the pi-web workbench first; workspace terminals live there.");return m.bridge.runPluginTool(...c)},async ask(c,p){if(m.pi&&c.sessionId===m.current?.sessionManager.getSessionId())return eo(m.pi.events,c,p);if(!m.workspaceSessions)throw new Error("The Web workbench is not open");return m.workspaceSessions.requestInteraction(c,p)}});for(let c of s)i.registerTool(c);m.tools?.clear(),m.tools=new Vr({enabled:()=>!!m.telemetry?.enabled&&!!m.bridge,capture:(c,p)=>m.bridge?.reportError?.(c,p),breadcrumb:(c,p)=>m.bridge?.breadcrumb?.(c,p),anonymize:c=>m.telemetry?.session(c)??"unavailable"});let o=c=>({...m.operation,session:m.telemetry?.session(c.sessionManager.getSessionId()),piVersion:du,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});m.interactions?.dispose(),m.interactions=new Wr(i.events,c=>!!m.bridge&&c.sessionId===m.current?.sessionManager.getSessionId()&&is(m.tuiCatalog,c.pluginId),()=>{m.current&&m.selected==="tui"&&it(m.current)});let l=()=>{m.stopChanged?.(),m.stopChanged=i.events.on(to,()=>{m.selected==="tui"&&m.current&&it(m.current)})};l(),i.on("session_start",async(c,p)=>{if(m.tuiStreaming=null,m.tools?.clear(),m.operation=void 0,m.tuiWaitController.abort(),m.tuiWaitController=new AbortController,m.tuiGeneration++,l(),m.current=p,m.releaseHostedTui?.(),m.releaseHostedTui=m.hosted?.adapter.mountTui(i,t(p.cwd,p.sessionManager.getSessionId())),m.hosted&&!await m.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),m.tuiPromptSessionId!==p.sessionManager.getSessionId()&&(m.tuiPrompts=new Ni(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:mi()}),He()}),m.tuiPromptSessionId=p.sessionManager.getSessionId()),m.tuiAgentError=!1,m.bridge){let d=await pr.discover(p.cwd,p.isProjectTrusted?.()??!1);if(m.current!==p)return;m.tuiCatalog=d}m.replacementSessionId!==p.sessionManager.getSessionId()&&(m.replacementContext=null,m.replacementSessionId=null),it(p),m.bridge&&m.selected==="tui"&&m.bridge.publish({type:"plugins_changed"}),m.selected==="tui"&&m.workspaces&&m.workspaces.add(p.cwd).then(async d=>{m.selected!=="tui"||m.current?.sessionManager.getSessionId()!==p.sessionManager.getSessionId()||(m.activeWorkspaceId=d.id,await He())}).catch(d=>{m.bridge?.publish({type:"error",message:d instanceof Error?d.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:m.bridge.reportError?.(d,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&p.mode==="tui"&&!m.autoOpened&&(m.autoOpened=!0,a(p).catch(d=>{p.ui.notify(d instanceof Error?d.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),i.on("agent_start",(c,p)=>{m.tuiAgentError=!1,m.bridge?.breadcrumb?.("agent_start",o(p)),it(p),He()}),i.on("agent_end",(c,p)=>it(p)),i.on("agent_settled",(c,p)=>{m.bridge?.breadcrumb?.("agent_end",o(p)),m.tools?.clear(),m.operation=void 0,m.tuiStreaming=null,uu(),it(p),He()}),i.on("tool_execution_start",(c,p)=>{m.tools?.start(c,o(p))}),i.on("tool_execution_end",(c,p)=>{m.tools?.end(c,o(p))}),i.on("model_select",(c,p)=>it(p)),i.on("thinking_level_select",(c,p)=>it(p)),i.on("message_end",(c,p)=>{if(c.message.role==="assistant"&&c.message.stopReason==="error"){m.tuiAgentError=!0;let d=m.bridge?.reportError?.(new Error("Agent response failed"),{...m.operation,stage:"agent",code:"agent_failed",piVersion:du});m.selected==="tui"&&m.bridge?.publish({type:"error",message:c.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:d,inTranscript:!0,...m.operation})}c.message.role==="toolResult"&&m.tools?.message(c.message,o(p)),c.message.role==="assistant"&&(m.tuiStreaming=null),m.selected==="tui"&&c.message.role==="assistant"&&m.bridge?.publish({type:"stream",message:null}),it(p),He()}),i.on("session_info_changed",(c,p)=>it(p)),i.on("message_update",(c,p)=>{if(m.current=p,c.message.role!=="assistant"||(m.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(c.message.timestamp).toISOString(),blocks:or(c.message.content)},m.selected!=="tui"||m.bridge===null))return;let d=Date.now();d-m.lastStreamAt<60||(m.lastStreamAt=d,m.bridge.publish({type:"stream",message:m.tuiStreaming}))}),i.on("session_shutdown",async c=>{if(m.tuiStreaming=null,m.tools?.clear(),m.operation=void 0,m.tuiWaitController.abort(),m.tuiGeneration++,m.stopChanged?.(),m.stopChanged=null,m.interactions?.cancelAll(),m.releaseHostedTui?.(),m.releaseHostedTui=void 0,c.reason==="new"||c.reason==="resume"||c.reason==="fork"||c.reason==="reload"){m.current=null;return}await m.hosted?.shutdown(),m.hosted=void 0,m.offHostedThaw?.(),m.offHostedThaw=void 0,m.current=null;let p=m.bridge,d=m.telemetry;m.bridge=null,m.commandContext=null,m.replacementContext=null,m.replacementSessionId=null,m.pi=null;let g=m.workspaceSessions;m.workspaceSessions=null,await g?.dispose(),m.selected="tui",m.activeWorkspaceId=null,m.autoOpened=!1,m.tuiCatalog=null,m.stopPluginWatch?.(),m.stopPluginWatch=null,m.operation=void 0,m.telemetry=null,p?await p.close():await d?.close()});let a=async c=>{m.telemetry??=new Yt;try{m.current=c,m.commandContext="newSession"in c?c:null,m.pi=i,m.tuiCatalog=await pr.discover(c.cwd,c.isProjectTrusted?.()??!1),m.workspaces===null&&(m.workspaces=new Za(Y0(mt())),await m.workspaces.load());try{await m.workspaces.discover((await gu.listAll()).map(g=>g.cwd))}catch(g){c.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${g instanceof Error?g.message:String(g)}`,"warning")}let p=await m.workspaces.add(c.cwd);if(m.selected==="tui"&&(m.activeWorkspaceId=p.id),m.bridge&&(m.bridge.protocolVersion!==7||m.bridge.buildId!==It||typeof m.bridge.reportError!="function"||typeof m.bridge.runPluginTool!="function")){let g=m.bridge;if(m.workspaceSessions&&(m.workspaceSessions.telemetryVersion!==2||m.workspaceSessions.runtimeVersion!==4)&&m.workspaceSessions.session&&!m.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");m.bridge=null,await g.close(),await m.telemetry.close(),m.telemetry=new Yt}if(m.bridge===null){let g=m.workspaceSessions&&(m.workspaceSessions.telemetryVersion!==2||m.workspaceSessions.runtimeVersion!==4)?m.workspaceSessions:null,b=g?.session&&g.path?{path:g.path,sessionManager:g.session.sessionManager}:null;g&&(await g.dispose(),m.workspaceSessions=null),m.workspaceSessions??=new so(y=>{m.selected==="sdk"&&m.bridge?.publish(y)},()=>m.current?.model,y=>{try{return!!m.current&&pu(m.current.cwd)===y&&(m.current.isProjectTrusted?.()??!1)}catch{return!1}},(y,S)=>m.bridge?.reportError?.(y,S),{enabled:()=>!!m.telemetry?.enabled&&!!m.bridge,breadcrumb:(y,S)=>m.bridge?.breadcrumb?.(y,S),anonymize:y=>m.telemetry?.session(y)??"unavailable"},()=>{He()},s,{adapter:m.hosted.adapter,scope:t}),b&&await m.workspaceSessions.open(b.path,{sessionManager:b.sessionManager});let v={hosted:m.hosted?.handlers,selfUpdate:TP(new go({agentDir:mt(),packageRoot:nn(hs,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:y=>m.hosted.manager.hostUpdateWarnings(y),prefetchPlugins:(y,S)=>m.hosted.manager.prefetchForHost(y,S),beforeRestart:y=>m.hosted.prepareRestart(y)})),snapshot:We,busyGitWorkspaces:()=>{let y=(m.workspaceSessions?.retainedSessions()??[]).filter(S=>!S.idle).map(S=>S.cwd);if(m.current&&(!m.current.isIdle()||m.tuiPrompts.sending))try{y.push(pu(m.current.cwd))}catch{y.push(m.current.cwd)}return y},plugins:async()=>{let y=Co();return await y?.refreshAssets(),y?.view()??{plugins:[],errors:[]}},pluginAsset:async y=>Co()?.asset(y)??null,async invokePluginAction(y,S,T,I){if(Je(y),!Co()?.has(S))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let x=m.selected,P=m.tuiGeneration,U=m.workspaceSessions?.session,B={requestId:SP(),sessionId:y,pluginId:S,action:T,input:I},N=m.selected==="sdk"?await m.workspaceSessions.invokePluginAction(B):await io(m.pi.events,B,15e3,m.tuiWaitController.signal);if(Je(y),x!==m.selected||(x==="tui"?P!==m.tuiGeneration:U!==m.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return m.selected==="tui"&&m.current&&it(m.current),N},async resolvePluginInteraction(y,S,T,I){if(Je(y),!is(Co(),S))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");m.selected==="sdk"?m.workspaceSessions.resolveInteraction(y,S,T,I):m.interactions.resolve(y,S,T,I)},image(y,S,T){Je(y);let x=(m.selected==="sdk"?m.workspaceSessions?.session?.sessionManager.getBranch():m.current?.sessionManager.getBranch())?.find(U=>U.id===S);if(x?.type!=="message"||x.message.role!=="user"||!Array.isArray(x.message.content))return null;let P=x.message.content[T];return P?.type!=="image"?null:{data:Buffer.from(P.data,"base64"),mimeType:P.mimeType}},async workspaces(){return Xw()},async addWorkspace(y,S){let T=await m.workspaces.add(y,S);try{await mu(T.id,!0)}catch(I){throw await He(),I}},async selectWorkspace(y){await mu(y)},async newSessionInWorkspace(y){await mu(y,!0)},async removeWorkspace(y){if(y===m.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await m.workspaces.remove(y),await He()},async selectSession(y,S,T){let I=m.workspaces?.get(y);if(!I)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Qt(I.path),S===m.current?.sessionManager.getSessionId()&&I.path===await lr(m.current.cwd))m.selected="tui",m.activeWorkspaceId=y,m.bridge?.publish({type:"stream",message:null}),m.bridge?.publish({type:"snapshot",session:We()});else{if(m.selected==="sdk"&&m.workspaceSessions?.session?.sessionManager.getSessionId()===S&&m.workspaceSessions.path===I.path)return;if(m.workspaceSessions?.hasSession(I.path,S))await m.workspaceSessions.open(I.path,{sessionId:S});else{if(!(await zr(I.path)).some(P=>P.id===S&&P.path===T))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await m.workspaceSessions.open(I.path,{sessionFile:T})}m.selected="sdk",m.activeWorkspaceId=y,m.bridge?.publish({type:"snapshot",session:We()})}await He()},async renameSession(y,S,T,I){let x=I.replace(/\s+/g," ").trim();if(x.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await Qw(y,S,T),m.current?.sessionManager.getSessionId()===S&&m.pi?m.pi.setSessionName(x):m.workspaceSessions?.rename(S,x)||gu.open(T).appendSessionInfo(x),m.selected==="tui"&&m.current?.sessionManager.getSessionId()===S&&m.bridge?.publish({type:"snapshot",session:We()}),await He()},async deleteSession(y,S,T){let I=await Qw(y,S,T);if(m.current?.sessionManager.getSessionId()===S)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 x=await m.workspaceSessions?.discard(S)??null,P=x?.path??(T||null);P&&await Sk(P,mt()),x?.wasActive&&m.selected==="sdk"&&(await m.workspaceSessions.open(I.path,"new"),m.selected="sdk",m.activeWorkspaceId=y,m.bridge?.publish({type:"snapshot",session:We()})),await He()},async models(){if(m.selected==="sdk")return m.workspaceSessions?.models()??[];let y=m.current;if(!y)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let S=y.scopedModels?.map(T=>`${T.model.provider}/${T.model.id}`)??[];return y.modelRegistry.getAvailable().filter(T=>S.length===0||S.includes(`${T.provider}/${T.id}`)).map(T=>({provider:T.provider,id:T.id,name:T.name}))},async providers(){let y=await rn(),S=new Set((await y.listCredentials()).map(T=>T.providerId));return y.getProviders().map(T=>({id:T.id,name:T.name,configured:y.getProviderAuthStatus(T.id).configured,storedCredential:S.has(T.id),methods:[T.auth.apiKey?.login?"api_key":null,T.auth.oauth?"oauth":null].filter(I=>I!==null)}))},async providerModels(y){let S=await rn();return ug(tn(mt(),"models.json"),y,S)},async updateProviderModel(y,S,T){if(Je(y),m.selected==="tui"?!st(y).isIdle():!m.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let I=We().model;if(T.action==="remove"&&I===`${S}/${T.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(T.action==="save"&&T.originalId&&T.originalId!==T.model.id&&I===`${S}/${T.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let x=await rn();await mg(tn(mt(),"models.json"),S,T,x),await x.refresh({providers:[S],allowNetwork:!1}),await m.current?.modelRegistry.refresh({providers:[S],allowNetwork:!1}),await m.workspaceSessions?.session?.modelRuntime.refresh({providers:[S],allowNetwork:!1});let P=T.action==="save"?T.model.id:T.action==="base_url"&&I?.startsWith(`${S}/`)?I.slice(S.length+1):null;if(P&&I===`${S}/${P}`)if(m.selected==="sdk")try{await m.workspaceSessions.setModel(S,P)}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 U=st(y),B=U.modelRegistry.find(S,P);if(!B||!m.pi||!await m.pi.setModel(B))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");it(U)}},async logoutProvider(y,S){if(Je(y),m.selected==="tui"?!st(y).isIdle():!m.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let T=await rn();if(!(await T.listCredentials()).some(I=>I.providerId===S))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await T.logout(S),await m.current?.modelRegistry.refresh({providers:[S],allowNetwork:!1}),await m.workspaceSessions?.session?.modelRuntime.refresh({providers:[S],allowNetwork:!1})},async loginProvider(y,S,T){let I=await rn();await I.login(y,S,ag(y,S,T)),await I.refresh({providers:[y],allowNetwork:!1}),await m.current?.modelRegistry.refresh({providers:[y],allowNetwork:!1}),await m.workspaceSessions?.session?.modelRuntime.refresh({providers:[y],allowNetwork:!1})},async addCustomProvider(y,S){if(Je(y),m.selected==="tui"?!st(y).isIdle():!m.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let T=await rn();if(T.getProvider(S.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await og(tn(mt(),"models.json"),S),await T.refresh({allowNetwork:!1}),await m.current?.modelRegistry.refresh({allowNetwork:!1}),await m.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return m.selected==="tui"?(m.pi?.getCommands()??[]).filter(y=>y.name!=="web"&&y.name!=="web-dev-reload").map(y=>({name:y.name,description:y.description})):[]},async compact(y){if(Je(y),m.selected==="sdk"){let T=m.workspaceSessions?.session;if(!T||!T.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await T.compact(),m.bridge?.publish({type:"snapshot",session:We()});return}let S=st(y);if(!S.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");S.compact()},async setModel(y,S,T){if(Je(y),m.selected==="sdk"){await m.workspaceSessions.setModel(S,T);return}let I=st(y);if(!I.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let x=I.modelRegistry.find(S,T);if(!x||!I.modelRegistry.getAvailable().some(P=>P.provider===S&&P.id===T))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!m.pi||!await m.pi.setModel(x))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");it(I)},async setThinkingLevel(y,S){if(Je(y),!["off","minimal","low","medium","high","xhigh"].includes(S))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(m.selected==="sdk"){let x=m.workspaceSessions?.session;if(!x||!x.isIdle||!x.getAvailableThinkingLevels().includes(S))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");x.setThinkingLevel(S),m.bridge?.publish({type:"snapshot",session:We()});return}let I=st(y);if(!I.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!I.model||!wP(I.model).includes(S))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!m.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");m.pi.setThinkingLevel(S),it(I)},config:eS,updateConfig:AP,async send(y,S,T=[],I,x){if(Je(y),m.selected==="sdk"){await m.workspaceSessions.send(S,T,I,x);return}let P=st(y);if(Ri(mi(),S,x),x==="followUp"&&(!P.isIdle()||m.tuiPrompts.length>0)){m.tuiPrompts.enqueue(S,T,I),uu();return}if(P.isIdle()&&m.tuiPrompts.sending)throw new tt("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await bu(y,S,T,I,x)},async updateQueuedPrompt(y,S,T,I){if(Je(y),m.selected==="sdk"){await m.workspaceSessions.updateQueuedPrompt(S,T,I);return}if(I.kind==="steer"&&st(y).isIdle())throw new tt("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await m.tuiPrompts.update(S,T,I,(x,P,U)=>bu(y,x,P,U,"steer"))},async abort(y){if(Je(y),m.selected==="sdk")await m.workspaceSessions.stop();else{let S=st(y);if(S.isIdle()&&!m.tuiPrompts.sending)return;if(!m.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");m.tools?.cancel(),m.bridge?.breadcrumb?.("cancel",{...m.operation}),m.pi.appendEntry(Zn),S.abort()}},async resume(y,S){if(Je(y),m.selected==="sdk"){await m.workspaceSessions.resume(S);return}let T=st(y);if($r(()=>m.hosted?.adapter.assertAdmission(),S,(I,x)=>m.bridge?.reportError?.(I,x)),!T.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!T.model||!m.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!T.modelRegistry.hasConfiguredAuth(T.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");m.operation=S;try{m.pi.sendMessage(ro(We().messages),{triggerTurn:!0})}catch(I){throw m.operation=void 0,I}},async newSession(y){if(Je(y),m.selected==="sdk"){let I=m.workspaces?.get(m.activeWorkspaceId??"");if(!I)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await m.workspaceSessions.reuseBlank(I.path)||await m.workspaceSessions.open(I.path,"new"),await He();return}let S=st(y);if(!S.isIdle()||m.tuiPrompts.length>0||m.commandContext===null){await m.workspaceSessions.open(S.cwd,"new"),m.selected="sdk",m.bridge?.publish({type:"snapshot",session:We()}),await He();return}if((await m.commandContext.newSession({withSession:async I=>{m.commandContext=I,m.replacementContext=I,m.replacementSessionId=I.sessionManager.getSessionId(),m.current=I}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await He()}};v.addWorkspace=m.lifecycle.wrap(v.addWorkspace),v.selectWorkspace=m.lifecycle.wrap(v.selectWorkspace),v.newSessionInWorkspace=m.lifecycle.wrap(v.newSessionInWorkspace),v.removeWorkspace=m.lifecycle.wrap(v.removeWorkspace),v.selectSession=m.lifecycle.wrap(v.selectSession),v.renameSession=m.lifecycle.wrap(v.renameSession),v.deleteSession=m.lifecycle.wrap(v.deleteSession),v.newSession=m.lifecycle.wrap(v.newSession),v.updateConfig=m.lifecycle.wrap(v.updateConfig),m.bridge=await H0(v,hs,m.telemetry)}if(m.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let g=[],b=null;for(let v of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(bP).filter(Boolean))try{g.push(fP(tn(nn(v),"dist"),(y,S)=>{let T=String(S??"");["client.js","client.css"].includes(T)&&(b&&clearTimeout(b),b=setTimeout(()=>m.bridge?.publish({type:"plugins_changed"}),180))}))}catch(y){m.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${v}: ${String(y)}`})}m.stopPluginWatch=()=>{for(let v of g)v.close();b&&clearTimeout(b)}}let d=await e(m.bridge.url).catch(()=>!1);c.ui.notify(`pi-webapp: ${m.bridge.url}`,d?"info":"warning"),c.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(p){throw m.telemetry?.capture(p,{stage:"open_web",piVersion:du}),m.bridge||(await m.telemetry?.close(),m.telemetry=null),p}};i.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(c,p)=>a(p)}),i.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 m.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")}}}),i.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 m.lifecycle.run(async()=>{let d=m.workspaceSessions?.session;d&&(await d.waitForIdle(),await m.workspaceSessions.reload()),await p.reload()}))}})}var ZY=Do;export{ZY as default,gP as verifySentryDisabledRelease,Vw as verifySentryNodeRelease};
242
+ `)}`:void 0,i<3&&t.cause instanceof Error&&(n.cause=iv(t.cause,e,i+1)),Ui(n)}import{randomUUID as sv}from"node:crypto";import{randomUUID as GA}from"node:crypto";import{EnvHttpProxyAgent as WA,getGlobalDispatcher as D6,setGlobalDispatcher as L6}from"undici";var rv=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 $A(t,e){let i=rv(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 VA(t){let e=rv(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 WA(e)}function op({env:t=process.env,onFailure:e=()=>{},fetchRequest:i=globalThis.fetch,autoClose:r=!1}={}){let n,s=new Set,a=i===globalThis.fetch,o=(p,u)=>{try{e(p,u)}catch{}},l=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let m={requestId:GA(),phase:"headers",proxied:a&&$A(t,p)},g=r?void 0:n,h=!1,f=u?.signal??(p instanceof Request?p.signal:void 0),v=()=>S(),S=()=>{f?.removeEventListener("abort",v),!h&&r&&(h=!0,l(g).catch(()=>{}))},E;try{a?(g??=VA(t),s.add(g),r||(n=g),E=await i(p,{...u,dispatcher:g})):E=await i(p,u)}catch(P){throw o(P,m),S(),P}if(E.ok||o(void 0,{...m,status:E.status}),!E.body)return S(),E;let O=E.body.getReader();f?.addEventListener("abort",v,{once:!0}),f?.aborted&&S();let L=new ReadableStream({async pull(P){try{let G=await O.read();G.done?(P.close(),O.releaseLock(),S()):P.enqueue(G.value)}catch(G){o(G,{...m,phase:"body"}),P.error(G),O.releaseLock(),S()}},async cancel(P){try{await O.cancel(P)}finally{O.releaseLock(),S()}}}),C=new Response(L,{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 nv=(t,e)=>op({autoClose:!0}).fetch(t,e);var zA=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),KA=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 lp(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=KA(l.code);if(i.push({name:zA.has(l.name)?l.name:"Error",...p?{code:p}:{}}),n(l.cause,c+1),l instanceof AggregateError)for(let u of l.errors.slice(0,4))n(u,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:sv(),requestId:o(e.requestId)??sv(),...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 av({env:t=process.env,onDiagnostic:e=()=>{},fetchRequest:i=globalThis.fetch}={}){return op({env:t,fetchRequest:i,onFailure:(r,n)=>e(lp(r,{...n,stage:n.phase==="body"?"model_stream":"model_headers"}))})}function YA(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 QA=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function ov(t,e,i=()=>{}){let r=t.agent.streamFunction;t.agent.streamFunction=async(n,s,a)=>{if(!QA.has(n.api))return r(n,s,a);let o=i(),l=av({env:YA(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 lr(t,e,i){try{t()}catch(r){let n=lp(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 ix=["read","grep","find","ls"];var lv=200,oa=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Ri;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=vn.create(r);else if(i==="continue"){let o=(await ar(r))[0];s=o?vn.open(o.path):vn.create(r)}else s="sessionManager"in i?i.sessionManager:vn.open(i.sessionFile);if(await tx(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=hn(o);return l?[l]:[]});return{sessionId:i.sessionManager.getSessionId(),cwd:r,path:i.sessionManager.getSessionFile()??null,idle:i.isIdle&&!n.sending,name:ea(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=>hn(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 Oi.discover(e,this.isProjectTrusted(e)),o=XA(),l=await Z_(e,a.extensionRoots,this.isProjectTrusted(e)),c=new ZA({cwd:e,agentDir:ex(),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 u=c.getExtensions().errors;if(u.length)throw new Error(u.map(N=>`${N.path}: ${N.error}`).join("; "));let m=i.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:g}=await JA({cwd:e,sessionManager:i,model:m,resourceLoader:c,customTools:this.customTools}),h=new or({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(N,I)=>this.telemetry.breadcrumb(N,I),anonymize:N=>this.telemetry.anonymize(N)}),f={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:h,streaming:null,prompts:null,detached:n?{owner:n,events:[],seq:0,lastText:"",restoreTools:null}:void 0};f.prompts=s?.prompts??new Jt(()=>{let N=this.runtimes.get(i.getSessionId())??f;this.publishFor(N,{type:"snapshot",session:this.snapshotOf(N)}),!this.disposed&&!N.closing&&this.onSessionsChanged()}),p=f,ov(g,N=>{f.networkDiagnostic=N},()=>f.operation?.operationId);let v=N=>this.publishFor(f,N),S=f.detached,E=(N,I)=>{S&&(S.events.push({seq:++S.seq,type:N,...I===void 0?{}:{text:I}}),S.events.length>lv&&S.events.splice(0,S.events.length-lv))};f.interactions=new sr(o,N=>!f.closing&&N.sessionId===g.sessionManager.getSessionId()&&bn(a,N.pluginId),()=>v({type:"snapshot",session:this.snapshotOf(f)}));let O=0,L=o.on(ra,()=>v({type:"snapshot",session:this.snapshotOf(f)})),C=g.subscribe(N=>{if(S&&!f.closing&&(N.type==="message_end"&&N.message.role==="assistant"&&(N.message.stopReason==="error"?E("error",N.message.errorMessage??"Agent response failed"):S.lastText=N.message.content.flatMap(I=>I.type==="text"?[I.text]:[]).join(`
243
+ `)),N.type==="agent_settled"&&E("turn_end",S.lastText)),!this.disposed&&!f.closing){let I={...f.operation,session:this.telemetry.anonymize(g.sessionManager.getSessionId()),piVersion:aa,model:g.model?`${g.model.provider}/${g.model.id}`:null,thinkingLevel:g.thinkingLevel};if(N.type==="agent_start"&&(f.activityId++,this.telemetry.breadcrumb("agent_start",I)),N.type==="tool_execution_start"&&h.start(N,I),N.type==="tool_execution_end"&&h.end(N,I),N.type==="message_end"&&N.message.role==="assistant"&&N.message.stopReason==="error"){f.agentErrorReported=!0;let A=f.networkDiagnostic,D=this.reportError(new Error("Agent response failed"),{...f.operation,stage:"agent",code:"agent_failed",piVersion:aa,...A?{networkKind:A.kind,networkStage:A.stage,causeCodes:A.causes.flatMap(k=>k.code?[k.code]:[]).join(","),requestId:A.requestId}:{}})??A?.errorId;v({type:"error",message:N.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:D,inTranscript:!0,...f.operation})}N.type==="message_end"&&N.message.role==="toolResult"&&h.message(N.message,I),N.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",I),h.clear(),f.operation=void 0)}N.type==="message_update"&&N.message.role==="assistant"&&(f.streaming={id:"stream",role:"assistant",timestamp:new Date(N.message.timestamp).toISOString(),blocks:Ii(N.message.content)},Date.now()-O>=60&&(O=Date.now(),v({type:"stream",message:f.streaming}))),N.type==="agent_settled"&&this.scheduleQueued(f),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(N.type)&&((N.type==="message_end"&&N.message.role==="assistant"||N.type==="agent_settled")&&(f.streaming=null,v({type:"stream",message:null})),v({type:"snapshot",session:this.snapshotOf(f)}),!this.disposed&&!f.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(N.type)&&this.onSessionsChanged())});f.detach=()=>{L(),C()},f.releaseHosted=this.hosted?.adapter.attach(g);let P=[],G=!0;if(await g.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:N=>{G&&P.push(N.error),this.diagnostic(f,a.plugins.find(I=>N.extensionPath.startsWith(I.root+"/"))?.id??N.extensionPath,N.event??"runtime",N.error)}}),G=!1,P.length)throw new Error(P.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");f.detached&&(f.detached.restoreTools=g.getActiveToolNames(),g.setActiveToolsByName(ix)),this.runtimes.set(g.sessionManager.getSessionId(),f),p=null,f.detached?this.onSessionsChanged():this.activate(f)}catch(u){throw this.hosted?.adapter.releasePending(i.getSessionId()),p?await this.close(p,"quit"):(o.clear(),await l.release()),u}}async close(e,i){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await V_(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=hn(a);return o?[o]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:r,name:ea(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:nr(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:Jc(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 na(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")):ia(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(Qt(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 Ce("\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");lr(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),Qt({...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:aa});let l=!1,c,p,u=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:aa});this.publishFor(e,{type:"error",message:m instanceof Error?m.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:g,...n})}});try{await u}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&&!nr(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 Ce("\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(fn),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");lr(()=>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(!nr(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(!nr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=sa(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=vn.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{copyFile as rx,mkdir as nx,rename as sx,unlink as ax}from"node:fs/promises";import{basename as ox,join as cv}from"node:path";var lx=t=>cv(t,"pi-web","trash");async function pv(t,e){let i=lx(e);await nx(i,{recursive:!0});let r=cv(i,`${Date.now()}_${ox(t)}`);try{await sx(t,r)}catch(n){let s=n.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw n;await rx(t,r),await ax(t)}return r}import{basename as cp,dirname as cx}from"node:path";function dv(t,e){let i=r=>e[r].map(n=>({name:r==="skills"&&cp(n.path).toLowerCase()==="skill.md"?cp(cx(n.path)):cp(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 px}from"node:child_process";var dx=(t,e)=>new Promise((i,r)=>{px(t,[...e],{windowsHide:!0},n=>{n?r(n):i()})});async function pp(t,e=process.platform,i=process.env,r=dx){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 lO}from"node:child_process";import{randomUUID as xp}from"node:crypto";import{existsSync as Fv}from"node:fs";import{access as cO,mkdir as En,mkdtemp as pO,readFile as ri,realpath as dO,rename as Hv,rm as Gv,writeFile as Wv}from"node:fs/promises";import{join as pe}from"node:path";import{createHash as mp}from"node:crypto";import{readdir as _x,realpath as yv,rename as vx,stat as wx}from"node:fs/promises";import{join as ii}from"node:path";import{constants as dp}from"node:fs";import{DatabaseSync as ux}from"node:sqlite";import{lstat as gv,mkdir as mx,open as wn,rename as gx,unlink as fv}from"node:fs/promises";import{dirname as fx,join as uv,resolve as hx}from"node:path";import{randomUUID as yx}from"node:crypto";import{setTimeout as bx}from"node:timers/promises";async function ve(t){await mx(t,{recursive:!0,mode:448});let e=await gv(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 wn(t,dp.O_RDONLY|dp.O_NONBLOCK|(dp.O_NOFOLLOW??0))}catch(r){if(Xt(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 Ve(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}.${yx()}.tmp`,r=await wn(i,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await gx(i,t);let n;try{n=await wn(fx(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 fv(i).catch(()=>{})}}var hv='{"version":2,"mechanism":"sqlite-exclusive"}',mv=t=>t.toString("utf8")===hv,la=new Set;async function up(t,e,i=0){await ve(t);let r=uv(t,`${e}.lock`),n=uv(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 wn(n,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await o?.close()}let l=await gv(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 ux(n,{allowExtension:!1}),p=hx(n),u=Date.now()+i,m=!1;try{for(;;){if(!la.has(p))try{c.exec("BEGIN EXCLUSIVE"),la.add(p),m=!0;break}catch(f){if(f.errcode!==5)throw f}if(Date.now()>=u)throw new y(s,"Another host owns this plugin storage; wait for it to stop before retrying");await bx(10)}let h=await fe(r,4096);if(h===null){let f;try{f=await wn(r,"wx",384),await f.writeFile(hv),await f.sync()}catch(v){if(v.code!=="EEXIST")throw v}finally{await f?.close()}h=await fe(r,4096)}if(h===null||!mv(h))throw a()}catch(h){throw c.close(),m&&la.delete(p),h}let g=!1;return async()=>{if(g)return;let h=await fe(r,4096);if(h===null||!mv(h))throw new y("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await fv(r),c.close(),la.delete(p),g=!0}}async function Se(t,e,i=2e3){let r=await up(t,"transaction",i);try{return await e()}finally{await r()}}var ca=t=>ii(t,"host-pair"),Sx=t=>mp("sha256").update(JSON.stringify(t)).digest("hex"),kx=10*6e4;async function Ex(t){let e=mp("sha256"),i=0,r=0;async function n(s){let a=(await _x(ii(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(ii(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,mp("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function gp(t,e){let i=await yv(e),r=ii(e,"dist","hosted-worker.js");if(await yv(r)!==ii(i,"dist","hosted-worker.js"))throw new y("host_pair_required","Candidate worker must remain inside the staged host");let n=await fe(ii(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 Sx([n.toString("base64"),o.toString("base64"),await Ex(e)])}async function pa(t){await vx(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Tx=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 fp(t){let e=ii(ca(t),"intent.json"),i,r=!0;try{i=await Ve(e)}catch{i=null,r=!1}if(!r||i&&!Tx(i))return await pa(e),null;if(i){let{lifecyclePhase:n,...s}=i,a=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await wx(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 da(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(ii(ca(t),"intent.json"),n)}var hp=t=>t&&["selecting","selected","restart-requested"].includes(t.phase),bv=(t,e=Date.now())=>!!t&&!!hp(t)&&e-Date.parse(t.updatedAt??"")<kx;import{promisify as uO}from"node:util";import{realpathSync as wv,statSync as Ix}from"node:fs";import{basename as Ax,delimiter as xx,dirname as _v,join as yp,resolve as Ox}from"node:path";function vv(t){if(!t)return null;try{let e=wv(t);return Ax(e)==="npm-cli.js"&&Ix(e).isFile()?e:null}catch{return null}}function Rx({execPath:t=process.execPath,env:e=process.env}={}){let i=vv(e.npm_execpath);if(i)return i;let r=new Set([_v(t)]);try{r.add(_v(wv(t)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(xx).filter(Boolean))r.add(Ox(s));for(let s of r)for(let a of[yp(s,"node_modules","npm","bin","npm-cli.js"),yp(s,"..","lib","node_modules","npm","bin","npm-cli.js"),yp(s,"npm")]){let o=vv(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 Sv(t){return{file:process.execPath,args:[Rx(),...t]}}import{randomUUID as Nx}from"node:crypto";import{mkdir as Tv,readFile as Px,rename as _p,rm as Cx,unlink as j$,writeFile as Mx}from"node:fs/promises";import{isAbsolute as kv,join as Sn}from"node:path";var vp=1,Dx=1440*6e4,ua=t=>Sn(t,"pi-web","upgrade"),wp=t=>Sn(ua(t),"candidate.json"),Lx=t=>Sn(ua(t),"transaction.json"),Ev=t=>Sn(ua(t),"history"),Iv=/^[a-f0-9-]{36}$/i;async function Ux(t,e){let i=`${t}.${Nx()}.tmp`;try{await Mx(i,e,{mode:384}),await _p(i,t)}finally{await Cx(i,{force:!0})}}var qx=(t,e)=>Ux(t,JSON.stringify(e));async function bp(t,e){await _p(t,`${t}.${e}-${Date.now()}`).catch(i=>{if(i?.code!=="ENOENT")throw i})}async function Av(t,e,i=()=>!1){let r;try{r=JSON.parse(await Px(t,"utf8"))}catch(n){return n?.code==="ENOENT"||await bp(t,"invalid"),null}return e(r)?i(r)?(await bp(t,"expired"),null):r:(await bp(t,"invalid"),null)}function xv(t){if(!t||typeof t!="object"||t.schema!==vp||!Iv.test(t.id??""))return!1;try{St(t.version)}catch{return!1}return typeof t.launcher=="string"&&kv(t.launcher)&&typeof t.packageRoot=="string"&&kv(t.packageRoot)&&["stable","alpha"].includes(t.channel)&&typeof t.downgrade=="boolean"&&!Number.isNaN(Date.parse(t.createdAt??""))}async function ma(t,e=Date.now()){return Av(wp(t),xv,i=>e-Date.parse(i.createdAt)>Dx)}async function Ov(t,e){let i={schema:vp,createdAt:new Date().toISOString(),...e};if(!xv(i))throw new Error("Invalid upgrade candidate");return await Tv(ua(t),{recursive:!0,mode:448}),await qx(wp(t),i),i}async function Sp(t,e,i){let r=await ma(t);!r||e&&r.id!==e||(await Tv(Ev(t),{recursive:!0,mode:448}),await _p(wp(t),Sn(Ev(t),`${r.id}-candidate-${i}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var jx=["selected","committed","rolled-back"];function Bx(t){return!!t&&typeof t=="object"&&t.schema===vp&&Iv.test(t.id??"")&&jx.includes(t.phase)&&typeof t.version=="string"&&typeof t.from=="string"&&!Number.isNaN(Date.parse(t.updatedAt??""))}async function Rv(t){return Av(Lx(t),Bx)}import{readFile as Fx,rename as Hx,writeFile as Gx,unlink as Wx}from"node:fs/promises";import{join as $x}from"node:path";import{randomUUID as Vx}from"node:crypto";var kp=1,Nv=t=>$x(t,"pi-web","launcher-handoff.json");function Pv(t){return t?.protocol===kp&&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 Ep(t){try{let e=JSON.parse(await Fx(Nv(t),"utf8"));if(!Pv(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 zx(t,e){let i=`${t}.${Vx()}.tmp`;try{await Gx(i,JSON.stringify(e),{mode:384}),await Hx(i,t)}finally{await Wx(i).catch(()=>{})}}async function Cv(t,e){if(!Pv(e))throw new Error("Invalid launcher handoff receipt");await zx(Nv(t),e)}import{execFile as Kx}from"node:child_process";import{cp as Yx,readFile as Tp,realpath as Qx,rm as Jx}from"node:fs/promises";import{join as cr,sep as Xx}from"node:path";import{promisify as Zx}from"node:util";var Mv=Zx(Kx),Ip=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Ap(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 Ip.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 ga(t){return Promise.all(Ip.map(async e=>{let i=await rr(t,e),r=JSON.parse(await Tp(cr(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 Dv(t,e){let i=JSON.parse(await Tp(cr(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 ga(t):Ap(i.peerDependencies);if(JSON.stringify(await ga(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 rr(t,"node-pty"),s=await rr(e,"node-pty"),a=await Qx(cr(e,"../.."));if(n===s||!s.startsWith(a+Xx))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let o=async u=>JSON.parse(await Tp(cr(u,"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 Jx(s,{recursive:!0,force:!0}),await Yx(n,s,{recursive:!0});let l={...process.env};delete l.NODE_OPTIONS,delete l.NODE_PATH,delete l.ELECTRON_RUN_AS_NODE,await Mv(process.execPath,[cr(e,"desktop","check-pty.cjs")],{cwd:e,env:l,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await rr(e,Ip[0]),{stdout:p}=await Mv(process.execPath,[cr(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 Uv,readdir as qv,readFile as eO,realpath as Lv,rm as tO}from"node:fs/promises";import{join as kn,relative as iO,sep as jv}from"node:path";var rO=1440*6e4,nO=1024*1024,sO=4,aO=t=>t==="releases"||t==="history"||t.endsWith("-history");async function oO(t,e){let i=new Set,r=[...new Set(e.flatMap(a=>[a+jv,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 qv(a,{withFileTypes:!0}).catch(()=>[]);for(let c of l){let p=kn(a,c.name);if(c.isDirectory()){o<sO&&!aO(c.name)&&await s(p,o+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await Uv(p)).size>nO)continue;n(JSON.parse(await eO(p,"utf8")))}catch{}}};return await s(t,0),i}async function Bv(t){let e=kn(t.agentDir,"pi-web"),i;try{i=await Lv(kn(e,"releases"))}catch{return[]}let r=t.now??Date.now(),n=t.graceMs??rO,s=await oO(e,[kn(e,"releases"),i]);try{let o=iO(i,await Lv(t.packageRoot));o&&!o.startsWith("..")&&s.add(o.split(jv)[0])}catch{}let a=[];for(let o of await qv(i,{withFileTypes:!0}).catch(()=>[])){if(!o.isDirectory()||s.has(o.name))continue;let l=kn(i,o.name);try{if(r-(await Uv(l)).mtimeMs<n)continue;await tO(l,{recursive:!0,force:!0}),a.push(o.name)}catch{}}return a}var mO=uO(lO),pr=t=>["committed","cancelled","failed"].includes(t);function $v(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 gO(t,e){try{let i=Sv(t),{stdout:r}=await mO(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 fa=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??gO,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 ga(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Ap(s)},this.verifyPackage=e.verifyPackage??Dv,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"?kp: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&&!pr(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 ri(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 Ep(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 ri(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 Cv(this.agentDir,p),c=!0}catch(u){let m=await Ep(this.agentDir).catch(()=>null);if(c=m?.nonce===e&&m?.requestId===i&&["requested","draining","stopped"].includes(m.phase),!c)throw u}this.restartPending=!0}finally{!c&&l&&await l()}}async current(){let e=JSON.parse(await ri(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&&!pr(e.phase)?[]:Bv({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),i=await this.transaction();if(!i||pr(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 Rv(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 Sp(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 Ve(this.transactionPath)}catch{return await pa(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 pa(this.transactionPath),null):e:null}async record(e){if(await En(pe(this.agentDir,"pi-web"),{recursive:!0}),await Z(this.transactionPath,e),pr(e.phase)){let i=pe(this.agentDir,"pi-web","update-history");await En(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 ma(this.agentDir);i&&(!e||i.id===e.id)&&await Sp(this.agentDir,i.id,"cancelled"),e&&!pr(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 ri(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}.${xp()}.tmp`;try{await En(pe(this.agentDir,"pi-web"),{recursive:!0}),await Wv(i,JSON.stringify({channel:e}),{mode:384}),await Hv(i,this.preferencePath)}finally{this.savingPreference=!1,await Gv(i,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),i=await this.channel(),r=Fv(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&&!pr(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||!k_(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(!Qs(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");$e(l.alpha,c)>0&&(c=l.alpha)}if(n.latest=c,n.downgrade=$e(c,e)<0,n.available=i==="stable"?$e(c,e)!==0:$e(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&&$e(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(Fv(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 En(r,{recursive:!0});let n=await pO(pe(await dO(r),`${i.latest}-`)),s=pe(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),a={schema:1,id:xp(),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 ri(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 ri(pe(this.packageRoot,"package.json"),"utf8"));if(i.downgrade&&$v(c)!==$v(p))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let u=pe(l,"bin","pi-webapp.mjs");return await Promise.all([u,pe(l,"dist","extension.js"),pe(l,"web","dist","index.html")].map(m=>cO(m))),this.desktopManaged&&(await zc(this.agentDir,{version:i.latest,launcher:u,desktopProtocolVersion:Zt}),await this.verifyPackage(this.packageRoot,l)),await this.prefetchPlugins?.(i.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await Ov(this.agentDir,{id:a.id,version:i.latest,launcher:u,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:u},channel:i.channel??"stable"},{version:i.latest,launcher:u}}catch(o){await Gv(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 ma(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 ri(a,"utf8"))?.nonce!==this.launcherNonce){let c=pe(this.agentDir,"pi-web","restart-history");await En(c,{recursive:!0,mode:448}),await Hv(a,pe(c,`stale-${xp()}.json`))}}catch{}try{await Wv(a,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(l){try{let c=JSON.parse(await ri(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 Mw,randomUUID as EN}from"node:crypto";import{randomUUID as ZR}from"node:crypto";import{join as Kp}from"node:path";import{randomUUID as Kv}from"node:crypto";import{randomUUID as fO}from"node:crypto";function Vv(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_${fO().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 hO;function zv(){return hO??=yO().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function yO(){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=[],u=0,m=0,g=!1,h=!1;try{let f=(C,P,G)=>({name:C,label:C,description:"Inert host SDK contract check",exposure:P,parameters:{type:"object",properties:{}},execute:G}),v=()=>({content:[],details:void 0}),S=new e({cwd:l,agentDir:l,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[C=>{C.on("tool_call",P=>{if(P.toolName==="__contract_direct"&&(g=!!P.parentToolCallId),P.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let P of["hidden","model-only"])C.registerTool(f(`__contract_${P.replace("-","_")}`,P,async()=>(m++,v())));C.registerTool(f("__contract_protected","direct",async()=>(m++,v()))),C.registerTool(f("__contract_direct","direct",async()=>(u++,v()))),C.registerTool(f("__contract_driver","direct",async(P,G,N,I,A)=>{let D=await A.executeTool("__contract_hidden",{}),k=await A.executeTool("__contract_model_only",{}),b=await A.executeTool("__contract_direct",{}),q=await A.executeTool("__contract_protected",{});return(!D.isError||!k.isError)&&p.push("nested-tool-exposure"),(b.isError||u!==1)&&p.push("nested-tool-execution"),(!q.isError||m!==0)&&p.push("nested-tool-permission-guard"),g||p.push("nested-parent-identity"),h=!0,v()}))}]});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 O=0;c.agent.streamFunction=async C=>{let P=O++===0,G={role:"assistant",api:C.api,provider:C.provider,model:C.id,timestamp:Date.now(),content:P?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:P?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},N=r();return N.push({type:"start",partial:G}),N.push({type:"done",reason:P?"toolUse":"stop",message:G}),N.end(G),N};let L;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((C,P)=>{L=setTimeout(()=>P(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(L)}return h||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(l,{recursive:!0,force:!0})}}var ha=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??=zv().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=Vv(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,u,m)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:Kv(),scope:{...e.scope},kind:"tool",action:s.action,input:u},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:bO};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:Kv(),scope:i,kind:"action",action:r,input:n},s)}};async function bO(){throw new Error("Hosted tool unavailable")}import{randomBytes as AR,randomUUID as xR,timingSafeEqual as OR}from"node:crypto";import{join as Ze}from"node:path";var _O=30,Yv=/^[a-z][a-z0-9-]{0,63}$/,vO=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Tn=t=>{throw new y("invalid_package",t)},Op=(t,e)=>t===void 0?[]:!Array.isArray(t)||t.length>32?Tn(`Invalid ${e} declaration`):t;function dr(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")?Op(e.secrets,"secrets").map(o=>{let l=o?.name;return typeof l=="string"&&Yv.test(l)?l:Tn("Invalid secret name")}):[],n=e.network,s=i.has("network")?Op(n?.hosts,"network").map(o=>typeof o=="string"&&vO.test(o)?o:Tn("Network hosts must be exact lowercase DNS names")):[],a=i.has("scheduler")?Op(e.schedules,"schedules").map(o=>{let l=o;return!l||typeof l.id!="string"||!Yv.test(l.id)||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!Number.isSafeInteger(l.intervalSec)||l.intervalSec<_O||l.intervalSec>86400?Tn("Invalid schedule declaration"):{id:l.id,intervalSec:l.intervalSec,action:l.action}}):[];return new Set(a.map(o=>o.id)).size!==a.length&&Tn("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:a,sessions:i.has("sessions")}}import{lookup as wO}from"node:dns/promises";import{isIP as SO}from"node:net";var kO=new Set(["GET","POST","PATCH","PUT","DELETE"]),EO=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),TO=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),ya=(t,e)=>{throw new y("network_denied",t,{status:403,reason:e})};function IO(t){let e=t.toLowerCase().replace(/^::ffff:/,"");if(SO(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 Qv(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")&&ya("Only plain https on port 443 is allowed","scheme"),e.includes(a.hostname)||ya("Host is not declared by the plugin","host");let o=(s.method??"GET").toUpperCase();if(!kO.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,O]of Object.entries(s.headers??{})){if(typeof O!="string"||EO.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(O))throw new y("invalid_input",`Header not allowed: ${E.slice(0,64)}`);l[E]=O}let c=null;if(s.secret!==void 0){if(i.includes(s.secret)||ya("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 wO(E,{all:!0})).map(O=>O.address)))(a.hostname);(!p.length||p.some(IO))&&ya("Host resolves to a non-public address","address");let u=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(u)}),h=[],f=0;if(g.body)for await(let E of g.body){if(f+=E.byteLength,f>m)throw new y("response_too_large","Network response exceeds limit",{status:502});h.push(Buffer.from(E))}let v=Buffer.concat(h).toString("utf8"),S={};return g.headers.forEach((E,O)=>{TO.has(O.toLowerCase())&&(S[O.toLowerCase()]=E)}),c&&(v=v.split(c).join("[redacted]")),{status:g.status,headers:S,body:v}}var ba=(t,e,i)=>{if(typeof t!="string"||!t||t.length>e)throw new y("invalid_input",`Invalid ${i}`);return t};async function Jv(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:ba(a.title,200,"title"),prompt:ba(a.prompt,64*1024,"prompt"),mode:"plan"})}let o=ba(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,ba(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 AO=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),_a=class{options;constructor(e){this.options=e}handles(e){return AO.has(e)}async call(e,i,r,n,s){let a=dr(i);if(n==="network.fetch"){if(!a.networkHosts.length)throw new y("capability_denied","Plugin did not declare network access",{status:403});return Qv(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 Jv(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var va=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 Hp,timingSafeEqual as nR}from"node:crypto";import{lstat as gw,mkdtemp as Fp,readdir as sR,readFile as aR,realpath as oR,rename as lR,rm as ni,writeFile as cR}from"node:fs/promises";import{tmpdir as pR}from"node:os";import{join as ne}from"node:path";import{gunzipSync as MO}from"node:zlib";import{mkdir as DO,writeFile as LO}from"node:fs/promises";import{dirname as UO,join as qO}from"node:path";import{constants as Rp}from"node:fs";import{lstat as ew,open as xO,readdir as Xv,realpath as tw}from"node:fs/promises";import{createHash as OO}from"node:crypto";import{join as iw,relative as RO,resolve as NO,sep as PO}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},CO={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=>OO("sha256").update(t).digest("hex");function ie(t){throw new y("invalid_package",t)}async function Ni(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=iw(n,r[o]);let l=await ew(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 tw(n);(s!==NO(t,e)||RO(t,s).startsWith(`..${PO}`))&&ie("Resource escapes package root");let a=await xO(n,Rp.O_RDONLY|Rp.O_NONBLOCK|(Rp.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 Zv(t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return ie("Invalid package JSON")}}async function Pi(t,e){let i=await tw(t);(await ew(t)).isSymbolicLink()&&ie("Package root cannot be a symlink");let r=Zv(await Ni(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"),ei(r.piWebapp)||ie("Unsupported hosted manifest"),r.type!=="module"&&ie("Hosted package must declare ESM module type");for(let u of await Xv(i,{withFileTypes:!0}))u.name==="dist"&&u.isDirectory()||(!u.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(u.name))&&ie("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(u=>/^(?:preinstall|install|postinstall|prepare)$/.test(u))&&ie("Hosted packages cannot run install lifecycle scripts");for(let u of["dependencies","optionalDependencies"]){let m=r[u];m&&(typeof m!="object"||Object.keys(m).length>0)&&ie("Hosted packages must contain all runtime dependencies")}let n=r.piWebapp,s=Zv(await Ni(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 u of s.files){(!u||typeof u!="object")&&ie("Invalid resource entry");let m=u,g={...m,path:typeof m.path=="string"&&m.path.startsWith("./")?m.path.slice(2):m.path};(!xi(`./${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 h=g.path.split(".").at(-1);CO[h]?.includes(g.mime)||ie("Unsupported resource MIME");let f=h==="js"||h==="mjs"||h==="cjs"?de.js:h==="css"?de.css:["woff","woff2","ttf","otf"].includes(h)?de.font:h==="wasm"?de.wasm:de.other;(g.bytes>f||(o+=g.bytes)>de.total)&&ie("Resource budget exceeded");let v=await Ni(i,g.path,f);(v.length!==g.bytes||re(v)!==g.sha256)&&ie("Resource integrity mismatch"),a.set(g.path,Object.freeze({...g}))}for(let u of[n.backend.entry,n.frontend.document,n.frontend.controller])a.has(u.slice(2))||ie("Entrypoint is absent from resource manifest");let l=0;async function c(u,m=0){m>16&&ie("Package directory nesting limit exceeded");for(let g of await Xv(iw(i,u),{withFileTypes:!0})){++l>de.files*2&&ie("Too many package entries");let h=`${u}/${g.name}`;(g.isSymbolicLink()||!g.isDirectory()&&!g.isFile())&&ie("Invalid archive member"),g.isDirectory()?await c(h,m+1):h!==n.resourcesManifest.slice(2)&&!a.has(h)&&ie("Undeclared distribution asset")}}await c("dist");let p=re(JSON.stringify({id:r.name,version:r.version,manifest:n,resources:[...a.values()].sort((u,m)=>u.path.localeCompare(m.path))}));return{id:r.name,version:r.version,root:i,manifest:n,resources:a,digest:p}}async function rw(t,e,i){if(i!==t.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!xi(`./${r}`))return null;let n=t.resources.get(r);if(!n||r===t.manifest.backend.entry.slice(2))return null;let s=await Ni(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 wa=64*1024*1024,jO=de.total+de.files*2048,te=t=>{throw new y("invalid_archive",t)};function ur(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 nw(t){let e=ur(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 BO(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 FO(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=ur(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 HO(t){if(!t.length||t.length>wa)return te("Compressed archive exceeds budget");let e;try{e=MO(t,{maxOutputLength:jO})}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 u=e.subarray(n,n+512);if(n+=512,u.every(L=>L===0)){if(l||e.subarray(n).some(L=>L!==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 L=0;L<512;L++)m+=L>=148&&L<156?32:u[L];if(nw(u.subarray(148,156))!==m)return te("Invalid tar header checksum");let g=ur(u.subarray(257,263));if(g&&g!=="ustar"&&g!=="ustar ")return te("Unsupported tar format");let h=u[156],f=ur(u.subarray(345,500)),v=(f?f+"/":"")+ur(u.subarray(0,100)),S=nw(u.subarray(124,136));if(l&&(l.path!==void 0&&(v=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,h===120){if(l||S>8192)return te("Oversized or chained PAX header");l=FO(E);continue}if(l=null,h!==0&&h!==48&&h!==53)return te("Links and special archive members are forbidden");let O=h===53;if(O&&S!==0||ur(u.subarray(157,257)))return te("Invalid archive link or directory");if(v=BO(v),!v&&!O)return te("Invalid package root member");if(r.has(v))return te("Duplicate archive member");if(r.add(v),++s>de.files||(a+=S)>de.total)return te("Unpacked archive exceeds budget");i.push({path:v,data:E,directory:O})}if(!c||!r.has("package.json"))return te("Archive is incomplete or has no package.json");let p=new Set(i.filter(u=>!u.directory).map(u=>u.path));for(let u of i){let m=u.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 Np(t,e){let i=HO(t);for(let r of i){if(!r.path)continue;let n=qO(e,r.path);await DO(r.directory?n:UO(n),{recursive:!0,mode:448}),r.directory||await LO(n,r.data,{flag:"wx",mode:384})}}import{lstat as GO,mkdir as WO,readdir as $O,realpath as VO,writeFile as zO}from"node:fs/promises";import{dirname as KO,join as Pp}from"node:path";async function sw(t,e){let i=await VO(t),r=await Ni(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 h of await $O(Pp(i,m),{withFileTypes:!0})){let f=`${m}/${h.name}`;if(++a>de.files)throw new y("invalid_package","Too many package entries");if(h.isDirectory()){await l(f,g+1);continue}if(!h.isFile())throw new y("invalid_package",`Links and non-regular files are forbidden: ${f}`);let v=await Ni(i,f,de.js);if((o+=v.length)>de.total)throw new y("invalid_package","Resource budget exceeded");let S=Pp(e,f);await WO(KO(S),{recursive:!0,mode:448}),await zO(S,v,{flag:"wx",mode:384}),s.push([f,re(v)])}}let c;try{c=await GO(Pp(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,...u}=n;return s.sort((m,g)=>m[0].localeCompare(g[0])),{contentHash:re(JSON.stringify({package:u,files:s})),packageJson:n}}function Ue(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=Ue(t),r=Ue(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 aw(t){let e=Ue(t);if(e)return e;if(!Qs(t))return null;let[i,r]=t.split("-alpha."),n=Ue(i),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function Cp(t){return!!aw(t)}function mr(t,e){if(!Cp(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&&aw(l[2]);if(!l||!c)return!1;let p=l[2],u=$e(t,p);switch(l[1]??"="){case"=":a&&=u===0;break;case">=":a&&=u>=0;break;case"<=":a&&=u<=0;break;case">":a&&=u>0;break;case"<":a&&=u<0;break;case"~":a&&=u>=0&&$e(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&&=u>=0&&$e(t,`${m}-0`)<0;break}}}r.push(a)}return r.some(Boolean)}var Mp=64*1024*1024,Dp=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);function Lp(t,e){let i=t.get(e);if(!i)throw new y("unreviewed_plugin","No trusted tool policy for this package");return i}function ow(t,e){let i=t.get(e)?.workspace?.files??Dp;for(let r of i)if(!/^\.[a-z0-9]{1,16}$/.test(r.extension)||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0||r.maxBytes>Mp||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 lw(t,e){let i=t.get(e)?.runtime?.invokeTimeoutMs;return i===void 0?void 0:Math.min(Math.max(i,1e3),18e4)}var cw=["drawing","design"],YO=/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,QO=/^[a-z][a-z0-9.-]{0,79}$/,Up=/^[a-z][a-z0-9_]{0,63}$/,Ci=/^[a-z][a-z0-9_-]{0,63}$/,JO=/^[a-z][a-z0-9-]{0,63}$/,In=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 XO(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,Ci)},panels:t.strings(r.panels,`${i}.panels`,Ci,16),artifactTools:t.strings(r.artifactTools,`${i}.artifactTools`,Up,128),toolViews:t.strings(r.toolViews,`${i}.toolViews`,Up,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,Ci),title:t.string(s.title,`${i}.panelAlias.title`,64)}}}function ZO(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,Mp),...a.createDirectory!==void 0?{createDirectory:t.string(a.createDirectory,`${s}.createDirectory`,64,/^[A-Za-z0-9_-]{1,64}$/)}:{}}})}function eR(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,JO);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 tR(t,e,i="policy"){let r=new In(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,h]of Object.entries(s))r.string(g,`${i}.tools key`,64,Up),r.string(h,`${i}.tools.${g}`,64,Ci);let a=Object.keys(s),o=Object.values(s),l=r.strings(n.readonlyActions,`${i}.readonlyActions`,Ci),c=r.strings(n.actions,`${i}.actions`,Ci),p=r.strings(n.checkpointActions,`${i}.checkpointActions`,Ci);r.subset(l,o,`${i}.readonlyActions`,"tool actions"),r.subset(p,c,`${i}.checkpointActions`,"actions");let u=XO(r,n.contribution,`${i}.contribution`);r.subset(u.artifactTools,a,`${i}.contribution.artifactTools`,"tools"),r.subset(u.toolViews,a,`${i}.contribution.toolViews`,"tools");let m={tools:s,readonlyActions:l,actions:c,checkpointActions:p,contribution:u};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:ZO(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=eR(r,n.secrets,`${i}.secrets`)),m}var iR=["id","name","icon","description","registry","recommendedVersion","requiredCapabilities","reviewed","policy"];function qp(t,e,i="plugin"){let r=new In(e),n=r.object(t,i,iR,["id","name","description","registry","recommendedVersion","requiredCapabilities","policy"]),s=r.string(n.id,`${i}.id`,214,YO);n.icon!==void 0&&!cw.includes(n.icon)&&r.fail(`${i}.icon`,`must be one of ${cw.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 Ue(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`,QO),policy:tR(n.policy,e,`${i}.policy`)}}function pw(t,e){let i=new In(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)=>qp(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 jp(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))jp(e)}return t}var dw={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 uw=jp(pw(dw,"official-plugins.json")),Xe=Object.freeze(uw.map(({policy:t,...e})=>Object.freeze(e))),Sa=new Map(uw.map(t=>[t.id,t.policy]));function ze(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 Bp(t,e,i){let r=t.piWebapp;return t.name===e.id&&!!Ue(t.version)&&!t.deprecated&&ei(r)&&mr(i,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function mw(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&&Bp(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 dR(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=Hp("sha512").update(t).digest();if(r.length!==n.length||!nR(r,n))throw new y("integrity_mismatch","Downloaded package failed integrity verification")}var gr=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Cp(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??nv}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||!Ue(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 Ve(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");ze(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 ni(ne(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=ne(this.root,"staging");await ve(r);for(let n of await sR(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await gw(ne(r,n))).isSymbolicLink())throw new y("invalid_storage","Invalid abandoned staging directory");await ni(ne(r,n),{recursive:!0})}return e}async recoverCollection(e){let i=ne(this.root,"gc-journal.json"),r=await Ve(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");ze(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 ni(this.path(s),{recursive:!0,force:!0})}await ni(i)}async collect(e,i){return ze(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(u){throw r?.aborted?r.reason:new y("registry_unreachable",u instanceof Error?u.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 u=await o.read();if(u.done)break;if(c+=u.value.length,c>i)throw new y("download_too_large","Registry response exceeds budget");l.push(Buffer.from(u.value))}return s.throwIfAborted(),Buffer.concat(l)}catch(u){throw r?.aborted?r.reason:u instanceof y?u:new y("registry_unreachable",u instanceof Error?u.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await o.cancel().catch(()=>{}),o.releaseLock()}}async check(e,i,r,n){let s=ze(e,this.catalog);if(r&&!Ue(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 mw(o,s,this.hostVersion,i,r)}async install(e,i,r){let n=ze(e,this.catalog);if(!Bp(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),wa,r);return this.installArchive(e,s,i.dist.integrity,i.version,r)}async installArchive(e,i,r,n,s){let a=ze(e,this.catalog);if(!Ue(n))throw new y("invalid_version","Choose an exact stable version");if(i.length>wa)throw new y("download_too_large","Package archive exceeds budget");return dR(i,r),Se(this.root,async()=>{let o=await this.recoverLocked();s?.throwIfAborted();let l=await Fp(ne(this.root,"staging","stage-"));try{await Np(i,l),s?.throwIfAborted();let c=await Pi(l,e);if(c.version!==n||!ei(c.manifest)||!mr(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 ni(l,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,i,r,n,s,a){let o=i.versions[e]?.find(u=>u.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 gw(c),p=!0}catch(u){if(!Xt(u))throw u}if(p){if((await Pi(c,e)).digest!==n.digest)throw new y("resource_changed","Installed package content was modified")}else await lR(r,c);return a?.throwIfAborted(),o||(i.versions[e]=[...i.versions[e]??[],l],i.revision++,await Z(ne(this.root,"installed.json"),i)),await ni(ne(this.root,"install-journal.json")),{...n,root:await oR(c)}}async installDevArchive(e,i,r){ze(e,this.catalog);let n=await aR(i),s="sha512-"+Hp("sha512").update(n).digest("base64"),a=await Fp(ne(pR(),"pi-dev-archive-"));try{await Np(n,a);let o=(await Pi(a,e)).version;return await this.installArchive(e,n,s,o,r)}finally{await ni(a,{recursive:!0,force:!0})}}async installDevDirectory(e,i,r){let n=ze(e,this.catalog);return Se(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let a=await Fp(ne(this.root,"staging","stage-"));try{let{contentHash:o,packageJson:l}=await sw(i,a);r?.throwIfAborted();let c=ne(this.root,"dev-sources.json"),p=await we(c)??{},u=p[e],m=s.versions[e]??[],g=u?.contentHash===o?m.find(P=>P.version===u.version):void 0;if(g){let P=await Pi(this.path(g),e);if(P.digest!==g.digest)throw new y("resource_changed","Installed package integrity changed");return P}let h=typeof l.version=="string"?Ue(l.version):null;if(!h)throw new y("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let f=Math.max(-1,...m.map(P=>Ue(P.version)).filter(P=>P&&P.major===h.major&&P.minor===h.minor).map(P=>P.patch)),v=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),f+1),S=`${h.major}.${h.minor}.${v}`;await cR(ne(a,"package.json"),JSON.stringify({...l,version:S},null,2),{flag:"wx",mode:384});let E=await Pi(a,e);if(!mr(this.hostVersion,E.manifest.hostRange))throw new y("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let O=n.requiredCapabilities.filter(P=>!E.manifest.capabilities.includes(P));if(O.length)throw new y("incompatible_plugin",`Package lacks required capabilities: ${O.join(", ")}`);let L="sha512-"+Hp("sha512").update(o).digest("base64"),C=await this.commitStaged(e,s,a,E,L,r);return p[e]={contentHash:o,version:S},await Z(c,p),C}finally{await ni(a,{recursive:!0,force:!0})}},1e4)}async load(e,i){let r=ze(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 Pi(this.path(s),e);if(a.digest!==s.digest)throw new y("resource_changed","Installed package integrity changed");if(!mr(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){ze(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 ka,mkdir as uR,open as fw,realpath as hw,readdir as Gp,link as mR,rename as gR,unlink as Mi,copyFile as fR,rm as hR}from"node:fs/promises";import{dirname as yR,isAbsolute as yw,join as J,relative as bw,resolve as bR,sep as Wp,win32 as _R}from"node:path";import{randomUUID as $p}from"node:crypto";var An=192*1024*1024,Bz=512*1024,vw=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function vR(t){if(!t||typeof t!="object"||Array.isArray(t))throw new y("invalid_input","Expected object input");return t}function _w(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new y("invalid_input","Invalid state key");return t}function xn(t){if(t&&(!vw(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 Di=class{root;pluginId;legacy;checkpoint;files;constructor(e,i,r,n,s=Dp){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(xn)}async recover(){return Se(this.root,async()=>{let e=await this.active(),i=await Ve(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");xn(i.next),xn(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 Ve(J(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(o=>["version","stateRef"].includes(o))&&await Mi(J(this.root,"fork.json"))}return await Mi(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 Ve(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=xn({...i,generation:e+1,operationId:$p()});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 Mi(J(this.root,"transition.json")),await Mi(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=$p(),n=J(this.root,"states",r);if(await Ve(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 Gp(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new y("invalid_storage","Unexpected state file");if(!await fe(J(s,a),An))throw new y("invalid_storage","Missing state file");await fR(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=xn(await Ve(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 Gp(s),o=new Set(n.map(c=>c.stateRef));for(let c of a){if(!vw(c))throw new y("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=J(s,c),u=await ka(p);if(!u.isDirectory()||u.isSymbolicLink())throw new y("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await Gp(p)){let g=await ka(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 h=await we(J(p,m),An);if(!h)throw new y("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let f=h;if(Object.keys(f).some(v=>!["requestId","inputHash","nextHash","committed"].includes(v))||f.committed!==!0||!/^[a-f0-9]{64}$/.test(f.inputHash)||!/^[a-f0-9]{64}$/.test(f.nextHash)||typeof f.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(h).some(f=>!["revision","schema","value","requestId","inputHash"].includes(f)))throw new y("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}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 hR(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=vR(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,_w(n.key),n.scope),An);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,_w(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)>An)throw new y("state_too_large","Plugin state exceeds limit");let l=await we(a,An);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")||yw(i)||_R.isAbsolute(i))throw new y("invalid_path",`Use a workspace-relative ${n.extension} path`);let s=await hw(e),a=bR(s,i),o=bw(s,a);if(!o||o===".."||o.startsWith(`..${Wp}`)||yw(o))throw new y("invalid_path","Workspace path escapes root");let l=s,c=o.split(Wp);for(let u=0;u<c.length;u++){l=J(l,c[u]);let m;try{m=await ka(l)}catch(g){if(!Xt(g))throw g;if(u<c.length-1){if(!r||!n.createDirectory||bw(s,l)!==n.createDirectory)throw new y("invalid_path","Workspace directory does not exist");try{await uR(l,{mode:448})}catch(h){if(h.code!=="EEXIST")throw h}m=await ka(l)}}if(m&&(m.isSymbolicLink()||(u<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 hw(yR(a));if(p!==s&&!p.startsWith(s+Wp))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),u=await we(l);if(u&&(u.requestId!==i.requestId||u.inputHash!==c||u.nextHash!==p))throw new y("duplicate_request","Request ID was reused with different content");let m;try{m=await fw(`${a}.lock`,"wx",384)}catch(h){throw h.code==="EEXIST"?new y("file_busy","Workspace file is locked; original file preserved"):h}let g;try{await m.writeFile(JSON.stringify({pid:process.pid,requestId:i.requestId}));let h=await fe(a,n.maxBytes),f=h?re(h):null;if(u&&f===p)return{hash:p};if(u?.committed||f!==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-${$p()}.tmp`);let v=await fw(g,"wx",384);try{await v.writeFile(s),await v.sync()}finally{await v.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 mR(g,a)}catch(O){throw O.code==="EEXIST"?new y("file_conflict","Workspace file was created concurrently"):O}await Mi(g),g=void 0}else await gR(g,a),g=void 0;return await Z(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!0}),{hash:p}}finally{g&&await Mi(g).catch(()=>{}),await m.close(),await Mi(`${a}.lock`)}}};import{randomUUID as TR}from"node:crypto";import{fork as wR}from"node:child_process";import{randomUUID as SR}from"node:crypto";import{join as kR}from"node:path";import{EventEmitter as ER}from"node:events";var ww=192*1024*1024,On=class t{child;pending=new Map;events=new ER;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=wR(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:kR(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>ww){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??SR();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))>ww?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 IR={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ea=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,i,r=IR,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 up(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 On.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):TR(),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 u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await s?.dispose(),{pending:!1,active:p,...u?{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 On.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 Sw}from"node:fs/promises";var Ta=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 gr({root:Ze(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let i=e.capabilities?new _a(e.capabilities):void 0;this.scheduler=new va({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:xR(),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 Di(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 Ea(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,AR(24).toString("base64url"));try{this.scheduler.start(r.id,dr(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){ze(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(ca(this.options.root),async()=>{let e=await fp(this.options.root);if(!e)return{intent:e,admitted:!1};if(!hp(e))return e.phase==="required-action"&&await da(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await gp(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await gp(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Sw(this.options.workerEntry)).equals(await Sw(Ze(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(i){return await da(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 da(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,u)=>ft(u,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),u=await this.installer.install(e,p,n);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:u.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:u.version}}case"enable":{let c=r??o;if(!c)throw new y("not_installed","Install the plugin first");let p=await this.installer.load(e,c),u=await this.lifecycle(e,()=>s.replace(p));return u.pending||this.packages.set(e,p),u}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 h=await c(n),f=await s.broker.active();if(await this.recordDevSync(e,h.version),!f?.enabled)return{installed:!0,enabled:!1,version:h.version};if(f.version===h.version&&!s.pendingVersion)return{unchanged:!0,version:h.version};let v=await this.lifecycle(e,()=>s.replace(h));return v.pending||this.packages.set(e,h),v}let p=await this.check(e,o,r,n),u=await s.broker.active();if(p.version===o&&(!u?.enabled||u.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"}),!u?.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 rw(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)||!OR(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(bv(await fp(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 gr({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 gr({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(u=>u.version).sort((u,m)=>ft(m,u))],c=!1,p="";for(let u of new Set(l))try{await i.load(s.id,u),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 RR}from"node:crypto";var z=t=>Object.assign(new Error(t),{status:409,code:"view_barrier"}),Rn=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 z("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw z("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 z("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw z("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw z("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 z("Invalid registration capability");let a=e.viewToken??RR();if(this.cancelledRegistrations.has(a)||this.recoveries.has(a))throw z("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 z("Duplicate view capability");return{viewToken:a,commands:[]}}if([...this.views.values()].some(l=>l.scope.ownerId===i.ownerId&&l.identity.mountId===e.mountId))throw z("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 z("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 z("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw z("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 z("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 z("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 z("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 z("Explicit per-view discard confirmation required");if(this.switching)throw z("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 z("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw z("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw z("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw z("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(z("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw z("Invalid acknowledgement");let a=r.commands.find(o=>o.id===e.commandId);if(!a)throw z("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(z(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw z("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw z("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw z("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw z("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw z("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 z("Invalid poll cursor");if(r.waiter)throw z("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw z("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 z("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw z("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=z(`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(z(`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 z("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(z("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(z("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var kw={"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 Ew(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"&&kw[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&&kw[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 NR}from"node:crypto";var PR="Ov23limJmKiuu8cOP83E";function Vp(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||PR,scope:r.scope,createUrl:r.createUrl}}var CR="https://github.com/login/device/code",MR="https://github.com/login/oauth/access_token",DR=8,Ia=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[u,m]of this.flows)m.expiresAt<=this.now()&&this.flows.delete(u);if(this.flows.size>=DR)throw new y("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(CR,{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=NR();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(MR,{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 zp,readFileSync as Tw,readdirSync as LR,statSync as UR}from"node:fs";import{lstat as qR,readdir as jR,writeFile as BR,mkdir as FR,rename as HR}from"node:fs/promises";import{delimiter as GR,dirname as WR,isAbsolute as $R,join as ai,resolve as Nn}from"node:path";var Aa=t=>Xe.some(e=>e.id===t),Iw=()=>Xe.map(t=>t.id).join(", "),si="piWebappCatalog",VR="https://registry.npmjs.org";function zR(t,e){let i=t[si];if(i===void 0)throw new y("invalid_catalog",`${e}: ${t.name} is not an official plugin (official: ${Iw()}). Describe it in package.json "${si}" with name, description and policy`);if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_catalog",`${e}: ${si} must be an object`);if("id"in i||"registry"in i)throw new y("invalid_catalog",`${e}: ${si} must not set id or registry; the package name is the id`);return{...qp({registry:VR,recommendedVersion:"0.0.0",requiredCapabilities:[...t.piWebapp.capabilities],...i,id:t.name},e,si),official:!1}}function KR(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>`:Aa(a)?o.endsWith(".tgz")?zp(Nn(o))?null:`archive not found: ${Nn(o)}`:`"${o}" is not a .tgz archive`:`"${a}" is not an official plugin (official: ${Iw()}); develop other packages from a directory in PI_WEBAPP_HOSTED_DEV_ROOTS`;if(l){i.push({level:"error",source:r,...Aa(a)?{pluginId:a}:{},message:l});continue}e.set(a,Nn(o))}return{archives:e,notices:i}}var Aw=t=>ai(t,"pi-web","hosted-dev.json"),xw=t=>ai(t,"pi-web","hosted-dev-status.json");function YR(t,e,i=process.cwd()){let r=[],n=[],s=(t.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(GR).map(o=>o.trim()).filter(Boolean);for(let o of s)r.push({path:Nn(i,o),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let a=s.length>0;if(e&&zp(e)){a=!0;try{let o=JSON.parse(Tw(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"||!$R(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:Nn(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 QR(t){let e=[];try{e=LR(t,{withFileTypes:!0}).filter(i=>i.isDirectory()&&i.name!=="node_modules"&&zp(ai(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 JR(t){let e=(n,s)=>({notice:{level:"error",source:t.source,...s?{pluginId:s}:{},message:`${t.path}: ${n}`}}),i;try{i=UR(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(Tw(ai(t.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?QR(t.path):"package.json is not valid JSON")}if(typeof r.name!="string")return e("package.json has no name");if(!ei(r.piWebapp))return e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name);if(Aa(r.name))return{pluginId:r.name};try{return{pluginId:r.name,entry:zR({name:r.name,piWebapp:r.piWebapp,[si]:r[si]},"package.json")}}catch(n){return e(me(n).message,r.name)}}var xa=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=KR(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=YR(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let a of i.specs){let o=JR(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`}),!Aa(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 ${si} 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]}},Oa=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 XR(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 FR(WR(r),{recursive:!0}),await BR(a,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await HR(a,r)}catch{}}};async function XR(t){let e=[],i=async(r,n)=>{let s=await qR(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await i(ai(t,"package.json"),"package.json");let r=async(n,s,a)=>{if(!(a>16||e.length>8192))for(let o of(await jR(n,{withFileTypes:!0})).sort((l,c)=>l.name.localeCompare(c.name)))o.isDirectory()?await r(ai(n,o.name),`${s}/${o.name}`,a+1):await i(ai(n,o.name),`${s}/${o.name}`)};if(await r(ai(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 eN(t){try{return[...dr(t).secrets]}catch{return[]}}var Ra=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ia;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Sa,e.dev?.enabled&&(this.devWatcher=new Oa({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 ha({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 Ew(a)}}),this.manager=new Ta({...e,workspaceRules:i=>ow(this.trusted,i),invokeTimeoutMs:i=>lw(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(Lp(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:eN(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)?Vp(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&&A_(this.manager.servedManifest(r.pluginId));return{bytes:r.bytes,mime:r.mime,csp:I_({wasm:n})}}}}verifyTools(e,i){let r=Lp(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 Di(Kp(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 Di(Kp(this.options.root,"data"),e.id).active();this.views.set(e.id,new Rn(e.id,i?.generation??0))}catch(i){this.recovery.set(e.id,i),this.views.set(e.id,new Rn(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Kp(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=Vp(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:ZR(),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 tN,readdir as iN,unlink as rN}from"node:fs/promises";import{join as fr}from"node:path";import{randomUUID as nN}from"node:crypto";var Yp="hosted-migration.json";function Ow(t,e="@chengzhiyi/pi-excalidraw"){return async i=>{let{cwd:r,sessionId:n}=i.scope,s=fr(t,re(JSON.stringify([r,n])));await ve(t),await ve(s);let a=fr(s,"scope.lock"),o;try{o=await tN(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:nN()}));let l=await we(fr(s,Yp));if(l&&(l.version!==1||l.pluginId!==e))throw new y("invalid_storage","Legacy scope belongs to another migration");let c=await iN(s),p=[];for(let m of c){if(m==="scope.lock"||m==="focus.json"||m===Yp||/^[\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(fr(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 u=await we(fr(s,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(m=>m.id===u)))throw new y("invalid_storage","Invalid legacy focused drawing");return l||await Z(fr(s,Yp),{version:1,pluginId:e,operationId:i.requestId}),{drafts:p,focused:u}}finally{await o.close(),await rN(a)}}}import{join as mN}from"node:path";import{randomUUID as sN}from"node:crypto";var aN=6e4,Na=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<aN?new y("execute_denied","The user denied execution",{status:403}):(this.entries.set(i,{id:sN(),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 oN,readFile as lN,rename as cN,writeFile as pN}from"node:fs/promises";import{randomUUID as dN,createHash as uN}from"node:crypto";import{join as Rw}from"node:path";var Pa=class{dir;queue=Promise.resolve();constructor(e){this.dir=Rw(e,"secrets")}file=e=>Rw(this.dir,`${uN("sha256").update(e).digest("hex")}.json`);async read(e){try{let i=JSON.parse(await lN(this.file(e),"utf8"));if(i&&typeof i=="object"&&!Array.isArray(i))return i}catch(i){if(!Xt(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 oN(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${dN()}.tmp`;await pN(n,JSON.stringify(r),{mode:384}),await cN(n,this.file(e))})}};function Nw(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 gN="scheduler";function Pw(t){let e=new Na({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 Pa(mN(t.root,"capability-secrets")),sessions:Nw(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=t.activeWorkspace();if(!n)return null;try{return t.trustedScope(n,gN)}catch{return null}}}}async function fN(){for(let t of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=Ks(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:Tr,buildId:it,browser:Ks({}).browser}}async function Cw(){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:Tr,buildId:it}}finally{await t.close()}}var Pn=br(yN(vN(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),TN=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[TN]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new Jt(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:qt()}),Ee()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Ri,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Ri;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new Jt(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:qt()}),Ee()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;var Dw=!1;function IN(t){return Dw||(Dw=!0,setTimeout(()=>{t.pruneReleases().catch(()=>{})},6e4).unref()),t}function Ca(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var AN=null;function xN(){return AN??=wN.create({refreshOnCreate:!1})}var Ma=new Map;async function yr(){let t=await xN(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,i=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Ma.keys())i.has(r)||(t.unregisterProvider(r),Ma.delete(r));for(let r of i){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),a=n??s;!a||Ma.get(r)===a||(n?t.registerNativeProvider(n):s&&t.registerProvider(r,s),Ma.set(r,a))}return await t.refresh({allowNetwork:!1}),t}function Te(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():qt()}function qt(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...N_(d.current,d.current.sessionManager.getSessionName(),d.tuiCatalog?.ids()??[]),idle:d.current.isIdle()&&!d.tuiPrompts.sending,streaming:d.tuiStreaming,queuedPrompts:d.tuiPrompts.view(),hasPendingPrompts:d.current.hasPendingMessages?.()??!1,interactions:d.interactions?.pending(d.current.sessionManager.getSessionId())??[]}}async function td(t,e,i,r,n){let s=qe(t);Qt({...qt(),idle:s.isIdle()},e,n);let a=s.isIdle();a&&lr(()=>d.hosted?.adapter.assertAdmission(),r,(o,l)=>d.bridge?.reportError?.(o,l)),a&&(d.operation=r);try{let o=i.length?[{type:"text",text:e},...i]:e;if(d.replacementContext!==null&&d.replacementSessionId===t)await d.replacementContext.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n})}d.current?.sessionManager.getSessionId()===t&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:qt()})}catch(o){throw a&&(d.operation=void 0),o}}function Xp(){let t=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,i=()=>{if(!t||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==t||d.tuiAgentError)return!1;let r=qt();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!r.paused&&!r.interactions.length};d.tuiPrompts.schedule(i,(r,n,s)=>td(t,r,n,s))}function Ne(t){if(Te().sessionId!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function jw(){let t=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,i=Te(),n=d.current?qt():null,s=await Ai(i.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),a=n?await Ai(n.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,o=await ed.listAll(),l=d.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&&d.tuiPrompts.length===0&&!n.messages.some(p=>p.role==="user")});let c=(await Promise.all(t.map(async p=>{let m=(await ar(p.path,o).catch(g=>(g instanceof yn?p.available=!1:d.bridge?.reportError?.(g,{stage:"workspace_sessions"}),[]))).map(g=>({id:g.id,workspaceId:p.id,path:g.path,name:g.name||g.firstMessage?.slice(0,50)||"",modified:g.modified.toISOString(),idle:!0}));for(let g of l.filter(h=>h.cwd===p.path)){if(g.blank&&g.sessionId!==i.sessionId)continue;let h=m.findIndex(v=>v.id===g.sessionId),f={id:g.sessionId,workspaceId:p.id,path:g.path??m[h]?.path??null,name:g.name,modified:g.modified,idle:g.idle};h<0?m.unshift(f):m[h]=f}return p.path===s&&!m.some(g=>g.id===i.sessionId)&&m.unshift({id:i.sessionId,workspaceId:p.id,path:null,name:i.name,modified:new Date().toISOString(),idle:i.idle}),m}))).flat();return{items:t,activeId:e,sessions:c}}var Lw=0;async function Ee(){if(!d.bridge)return;let t=++Lw;try{let e=await jw();t===Lw&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function Zp(t,e=!1){let i=d.workspaces?.get(t);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await kt(i.path),!e&&d.current&&i.path===await Ai(d.current.cwd)&&!d.workspaceSessions?.hasWorkspace(i.path))d.selected="tui",d.activeWorkspaceId=t,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:Te()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await d.workspaceSessions.reuseBlank(i.path))&&await d.workspaceSessions.open(i.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=t,d.bridge?.publish({type:"snapshot",session:Te()})}await Ee()}async function Uw(t,e,i){let r=d.workspaces?.get(t);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await kt(r.path);if(d.workspaceSessions?.hasSession(n,e)||d.current?.sessionManager.getSessionId()===e&&await Ai(d.current.cwd)===n)return r;if(!(await ar(n)).some(a=>a.id===e&&a.path===i))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function qe(t){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function Me(t){d.current=t,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:Te()})}function Bw(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let t=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!t)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return SN.create(t,void 0,{projectTrusted:e})}async function Fw(){let t=Bw(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),i=new qw({cwd:Te().cwd,agentDir:Ke(),settingsManager:t}),r=dv(i.listConfiguredPackages(),await i.resolve(async()=>"skip"));return{projectTrusted:t.isProjectTrusted(),global:e(t.getGlobalSettings()),project:e(t.getProjectSettings()),installed:r}}async function ON(t){Ne(t.sessionId);let e=d.selected==="tui"?qe(t.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=Bw();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 qw({cwd:Te().cwd,agentDir:Ke(),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(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&Me(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await Fw()}function Da(t,e=pp){if(d.hostedMode===!1||d.hostedMode===void 0&&d.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");d.hostedMode=!0;let i=(c,p)=>{let u=Qp(c);return{cwd:u,sessionId:p,workspaceId:Mw("sha256").update(u).digest("hex")}},r=hr(Ke(),"pi-web","hosted"),n=new xa({configPath:Aw(Ke())});d.hosted??=new Ra({root:r,...n.enabled?{dev:n,devStatusPath:xw(Ke())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...Xe,...n.catalog],policies:new Map([...Sa,...n.policies])}:{},...Pw({root:r,sessions:()=>d.workspaceSessions,activeWorkspace:()=>d.workspaceSessions?.path??null,trustedScope:i,sessionTitle:c=>d.workspaceSessions?.retainedSessions().find(p=>p.sessionId===c)?.name,changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(bN(br(Pn,"../../package.json"),"utf8")).version,packageRoot:br(Pn,"../.."),workerEntry:br(Pn,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${Mw("sha256").update(Ke()).digest("hex")}`,resolveSession:c=>{let p=d.current;if(p?.sessionManager.getSessionId()===c)return i(p.cwd,c);let u=d.workspaceSessions?.hostedScope(c);return u?i(u.cwd,c):null},legacy:()=>Ow(hr(Ke(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Xp),d.pi=t;let s=fu({async run(...c){if(!d.bridge)throw new Error("Open the pi-web workbench first; workspace terminals live there.");return d.bridge.runPluginTool(...c)},async ask(c,p){if(d.pi&&c.sessionId===d.current?.sessionManager.getSessionId())return ia(d.pi.events,c,p);if(!d.workspaceSessions)throw new Error("The Web workbench is not open");return d.workspaceSessions.requestInteraction(c,p)}});for(let c of s)t.registerTool(c);d.tools?.clear(),d.tools=new or({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(c,p)=>d.bridge?.reportError?.(c,p),breadcrumb:(c,p)=>d.bridge?.breadcrumb?.(c,p),anonymize:c=>d.telemetry?.session(c)??"unavailable"});let a=c=>({...d.operation,session:d.telemetry?.session(c.sessionManager.getSessionId()),piVersion:Jp,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});d.interactions?.dispose(),d.interactions=new sr(t.events,c=>!!d.bridge&&c.sessionId===d.current?.sessionManager.getSessionId()&&bn(d.tuiCatalog,c.pluginId),()=>{d.current&&d.selected==="tui"&&Me(d.current)});let o=()=>{d.stopChanged?.(),d.stopChanged=t.events.on(ra,()=>{d.selected==="tui"&&d.current&&Me(d.current)})};o(),t.on("session_start",async(c,p)=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiWaitController=new AbortController,d.tuiGeneration++,o(),d.current=p,d.releaseHostedTui?.(),d.releaseHostedTui=d.hosted?.adapter.mountTui(t,i(p.cwd,p.sessionManager.getSessionId())),d.hosted&&!await d.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),d.tuiPromptSessionId!==p.sessionManager.getSessionId()&&(d.tuiPrompts=new Jt(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:qt()}),Ee()}),d.tuiPromptSessionId=p.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let u=await Oi.discover(p.cwd,p.isProjectTrusted?.()??!1);if(d.current!==p)return;d.tuiCatalog=u}d.replacementSessionId!==p.sessionManager.getSessionId()&&(d.replacementContext=null,d.replacementSessionId=null),Me(p),d.bridge&&d.selected==="tui"&&d.bridge.publish({type:"plugins_changed"}),d.selected==="tui"&&d.workspaces&&d.workspaces.add(p.cwd).then(async u=>{d.selected!=="tui"||d.current?.sessionManager.getSessionId()!==p.sessionManager.getSessionId()||(d.activeWorkspaceId=u.id,await Ee())}).catch(u=>{d.bridge?.publish({type:"error",message:u instanceof Error?u.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:d.bridge.reportError?.(u,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&p.mode==="tui"&&!d.autoOpened&&(d.autoOpened=!0,l(p).catch(u=>{p.ui.notify(u instanceof Error?u.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),t.on("agent_start",(c,p)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",a(p)),Me(p),Ee()}),t.on("agent_end",(c,p)=>Me(p)),t.on("agent_settled",(c,p)=>{d.bridge?.breadcrumb?.("agent_end",a(p)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Xp(),Me(p),Ee()}),t.on("tool_execution_start",(c,p)=>{d.tools?.start(c,a(p))}),t.on("tool_execution_end",(c,p)=>{d.tools?.end(c,a(p))}),t.on("model_select",(c,p)=>Me(p)),t.on("thinking_level_select",(c,p)=>Me(p)),t.on("message_end",(c,p)=>{if(c.message.role==="assistant"&&c.message.stopReason==="error"){d.tuiAgentError=!0;let u=d.bridge?.reportError?.(new Error("Agent response failed"),{...d.operation,stage:"agent",code:"agent_failed",piVersion:Jp});d.selected==="tui"&&d.bridge?.publish({type:"error",message:c.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:u,inTranscript:!0,...d.operation})}c.message.role==="toolResult"&&d.tools?.message(c.message,a(p)),c.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&c.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),Me(p),Ee()}),t.on("session_info_changed",(c,p)=>Me(p)),t.on("message_update",(c,p)=>{if(d.current=p,c.message.role!=="assistant"||(d.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(c.message.timestamp).toISOString(),blocks:Ii(c.message.content)},d.selected!=="tui"||d.bridge===null))return;let u=Date.now();u-d.lastStreamAt<60||(d.lastStreamAt=u,d.bridge.publish({type:"stream",message:d.tuiStreaming}))}),t.on("session_shutdown",async c=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiGeneration++,d.stopChanged?.(),d.stopChanged=null,d.interactions?.cancelAll(),d.releaseHostedTui?.(),d.releaseHostedTui=void 0,c.reason==="new"||c.reason==="resume"||c.reason==="fork"||c.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let p=d.bridge,u=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let m=d.workspaceSessions;d.workspaceSessions=null,await m?.dispose(),d.selected="tui",d.activeWorkspaceId=null,d.autoOpened=!1,d.tuiCatalog=null,d.stopPluginWatch?.(),d.stopPluginWatch=null,d.operation=void 0,d.telemetry=null,p?await p.close():await u?.close()});let l=async c=>{d.telemetry??=new wt;try{d.current=c,d.commandContext="newSession"in c?c:null,d.pi=t,d.tuiCatalog=await Oi.discover(c.cwd,c.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new ta(D_(Ke())),await d.workspaces.load());try{await d.workspaces.discover((await ed.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 d.workspaces.add(c.cwd);if(d.selected==="tui"&&(d.activeWorkspaceId=p.id),d.bridge&&(d.bridge.protocolVersion!==7||d.bridge.buildId!==it||typeof d.bridge.reportError!="function"||typeof d.bridge.runPluginTool!="function")){let m=d.bridge;if(d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)&&d.workspaceSessions.session&&!d.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");d.bridge=null,await m.close(),await d.telemetry.close(),d.telemetry=new wt}if(d.bridge===null){let m=d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)?d.workspaceSessions:null,g=m?.session&&m.path?{path:m.path,sessionManager:m.session.sessionManager}:null;m&&(await m.dispose(),d.workspaceSessions=null),d.workspaceSessions??=new oa(f=>{d.selected==="sdk"&&d.bridge?.publish(f)},()=>d.current?.model,f=>{try{return!!d.current&&Qp(d.current.cwd)===f&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(f,v)=>d.bridge?.reportError?.(f,v),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(f,v)=>d.bridge?.breadcrumb?.(f,v),anonymize:f=>d.telemetry?.session(f)??"unavailable"},()=>{Ee()},s,{adapter:d.hosted.adapter,scope:i}),g&&await d.workspaceSessions.open(g.path,{sessionManager:g.sessionManager});let h={hosted:d.hosted?.handlers,selfUpdate:IN(new fa({agentDir:Ke(),packageRoot:br(Pn,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:f=>d.hosted.manager.hostUpdateWarnings(f),prefetchPlugins:(f,v)=>d.hosted.manager.prefetchForHost(f,v),beforeRestart:f=>d.hosted.prepareRestart(f)})),snapshot:Te,busyGitWorkspaces:()=>{let f=(d.workspaceSessions?.retainedSessions()??[]).filter(v=>!v.idle).map(v=>v.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{f.push(Qp(d.current.cwd))}catch{f.push(d.current.cwd)}return f},plugins:async()=>{let f=Ca();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Ca()?.asset(f)??null,async invokePluginAction(f,v,S,E){if(Ne(f),!Ca()?.has(v))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let O=d.selected,L=d.tuiGeneration,C=d.workspaceSessions?.session,P={requestId:EN(),sessionId:f,pluginId:v,action:S,input:E},G=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(P):await na(d.pi.events,P,15e3,d.tuiWaitController.signal);if(Ne(f),O!==d.selected||(O==="tui"?L!==d.tuiGeneration:C!==d.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return d.selected==="tui"&&d.current&&Me(d.current),G},async resolvePluginInteraction(f,v,S,E){if(Ne(f),!bn(Ca(),v))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(f,v,S,E):d.interactions.resolve(f,v,S,E)},image(f,v,S){Ne(f);let O=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(C=>C.id===v);if(O?.type!=="message"||O.message.role!=="user"||!Array.isArray(O.message.content))return null;let L=O.message.content[S];return L?.type!=="image"?null:{data:Buffer.from(L.data,"base64"),mimeType:L.mimeType}},async workspaces(){return jw()},async addWorkspace(f,v){let S=await d.workspaces.add(f,v);try{await Zp(S.id,!0)}catch(E){throw await Ee(),E}},async selectWorkspace(f){await Zp(f)},async newSessionInWorkspace(f){await Zp(f,!0)},async removeWorkspace(f){if(f===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(f),await Ee()},async selectSession(f,v,S){let E=d.workspaces?.get(f);if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await kt(E.path),v===d.current?.sessionManager.getSessionId()&&E.path===await Ai(d.current.cwd))d.selected="tui",d.activeWorkspaceId=f,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:Te()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===v&&d.workspaceSessions.path===E.path)return;if(d.workspaceSessions?.hasSession(E.path,v))await d.workspaceSessions.open(E.path,{sessionId:v});else{if(!(await ar(E.path)).some(L=>L.id===v&&L.path===S))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(E.path,{sessionFile:S})}d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:Te()})}await Ee()},async renameSession(f,v,S,E){let O=E.replace(/\s+/g," ").trim();if(O.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await Uw(f,v,S),d.current?.sessionManager.getSessionId()===v&&d.pi?d.pi.setSessionName(O):d.workspaceSessions?.rename(v,O)||ed.open(S).appendSessionInfo(O),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===v&&d.bridge?.publish({type:"snapshot",session:Te()}),await Ee()},async deleteSession(f,v,S){let E=await Uw(f,v,S);if(d.current?.sessionManager.getSessionId()===v)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 O=await d.workspaceSessions?.discard(v)??null,L=O?.path??(S||null);L&&await pv(L,Ke()),O?.wasActive&&d.selected==="sdk"&&(await d.workspaceSessions.open(E.path,"new"),d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:Te()})),await Ee()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let f=d.current;if(!f)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let v=f.scopedModels?.map(S=>`${S.model.provider}/${S.model.id}`)??[];return f.modelRegistry.getAvailable().filter(S=>v.length===0||v.includes(`${S.provider}/${S.id}`)).map(S=>({provider:S.provider,id:S.id,name:S.name}))},async providers(){let f=await yr(),v=new Set((await f.listCredentials()).map(S=>S.providerId));return f.getProviders().map(S=>({id:S.id,name:S.name,configured:f.getProviderAuthStatus(S.id).configured,storedCredential:v.has(S.id),methods:[S.auth.apiKey?.login?"api_key":null,S.auth.oauth?"oauth":null].filter(E=>E!==null)}))},async providerModels(f){let v=await yr();return Lu(hr(Ke(),"models.json"),f,v)},async updateProviderModel(f,v,S){if(Ne(f),d.selected==="tui"?!qe(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=Te().model;if(S.action==="remove"&&E===`${v}/${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===`${v}/${S.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let O=await yr();await Uu(hr(Ke(),"models.json"),v,S,O),await O.refresh({providers:[v],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[v],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[v],allowNetwork:!1});let L=S.action==="save"?S.model.id:S.action==="base_url"&&E?.startsWith(`${v}/`)?E.slice(v.length+1):null;if(L&&E===`${v}/${L}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(v,L)}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=qe(f),P=C.modelRegistry.find(v,L);if(!P||!d.pi||!await d.pi.setModel(P))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");Me(C)}},async logoutProvider(f,v){if(Ne(f),d.selected==="tui"?!qe(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await yr();if(!(await S.listCredentials()).some(E=>E.providerId===v))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await S.logout(v),await d.current?.modelRegistry.refresh({providers:[v],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[v],allowNetwork:!1})},async loginProvider(f,v,S){let E=await yr();await E.login(f,v,Ru(f,v,S)),await E.refresh({providers:[f],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[f],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[f],allowNetwork:!1})},async addCustomProvider(f,v){if(Ne(f),d.selected==="tui"?!qe(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await yr();if(S.getProvider(v.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await Nu(hr(Ke(),"models.json"),v),await S.refresh({allowNetwork:!1}),await d.current?.modelRegistry.refresh({allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return d.selected==="tui"?(d.pi?.getCommands()??[]).filter(f=>f.name!=="web"&&f.name!=="web-dev-reload").map(f=>({name:f.name,description:f.description})):[]},async compact(f){if(Ne(f),d.selected==="sdk"){let S=d.workspaceSessions?.session;if(!S||!S.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await S.compact(),d.bridge?.publish({type:"snapshot",session:Te()});return}let v=qe(f);if(!v.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");v.compact()},async setModel(f,v,S){if(Ne(f),d.selected==="sdk"){await d.workspaceSessions.setModel(v,S);return}let E=qe(f);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let O=E.modelRegistry.find(v,S);if(!O||!E.modelRegistry.getAvailable().some(L=>L.provider===v&&L.id===S))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(O))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");Me(E)},async setThinkingLevel(f,v){if(Ne(f),!["off","minimal","low","medium","high","xhigh"].includes(v))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(d.selected==="sdk"){let O=d.workspaceSessions?.session;if(!O||!O.isIdle||!O.getAvailableThinkingLevels().includes(v))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");O.setThinkingLevel(v),d.bridge?.publish({type:"snapshot",session:Te()});return}let E=qe(f);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!E.model||!kN(E.model).includes(v))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.setThinkingLevel(v),Me(E)},config:Fw,updateConfig:ON,async send(f,v,S=[],E,O){if(Ne(f),d.selected==="sdk"){await d.workspaceSessions.send(v,S,E,O);return}let L=qe(f);if(Qt(qt(),v,O),O==="followUp"&&(!L.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(v,S,E),Xp();return}if(L.isIdle()&&d.tuiPrompts.sending)throw new Ce("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await td(f,v,S,E,O)},async updateQueuedPrompt(f,v,S,E){if(Ne(f),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(v,S,E);return}if(E.kind==="steer"&&qe(f).isIdle())throw new Ce("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(v,S,E,(O,L,C)=>td(f,O,L,C,"steer"))},async abort(f){if(Ne(f),d.selected==="sdk")await d.workspaceSessions.stop();else{let v=qe(f);if(v.isIdle()&&!d.tuiPrompts.sending)return;if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.tools?.cancel(),d.bridge?.breadcrumb?.("cancel",{...d.operation}),d.pi.appendEntry(fn),v.abort()}},async resume(f,v){if(Ne(f),d.selected==="sdk"){await d.workspaceSessions.resume(v);return}let S=qe(f);if(lr(()=>d.hosted?.adapter.assertAdmission(),v,(E,O)=>d.bridge?.reportError?.(E,O)),!S.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!S.model||!d.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");d.operation=v;try{d.pi.sendMessage(sa(Te().messages),{triggerTurn:!0})}catch(E){throw d.operation=void 0,E}},async newSession(f){if(Ne(f),d.selected==="sdk"){let E=d.workspaces?.get(d.activeWorkspaceId??"");if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(E.path)||await d.workspaceSessions.open(E.path,"new"),await Ee();return}let v=qe(f);if(!v.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(v.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:Te()}),await Ee();return}if((await d.commandContext.newSession({withSession:async E=>{d.commandContext=E,d.replacementContext=E,d.replacementSessionId=E.sessionManager.getSessionId(),d.current=E}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await Ee()}};h.addWorkspace=d.lifecycle.wrap(h.addWorkspace),h.selectWorkspace=d.lifecycle.wrap(h.selectWorkspace),h.newSessionInWorkspace=d.lifecycle.wrap(h.newSessionInWorkspace),h.removeWorkspace=d.lifecycle.wrap(h.removeWorkspace),h.selectSession=d.lifecycle.wrap(h.selectSession),h.renameSession=d.lifecycle.wrap(h.renameSession),h.deleteSession=d.lifecycle.wrap(h.deleteSession),h.newSession=d.lifecycle.wrap(h.newSession),h.updateConfig=d.lifecycle.wrap(h.updateConfig);try{d.bridge=await R_(h,Pn,d.telemetry)}catch(f){throw process.env.PI_WEBAPP_LAUNCHER_NONCE&&c.ui.notify(`pi-webapp-start-error: ${f instanceof Error?f.message:String(f)}`,"error"),f}}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let m=[],g=null;for(let h of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(hN).filter(Boolean))try{m.push(_N(hr(br(h),"dist"),(f,v)=>{let S=String(v??"");["client.js","client.css"].includes(S)&&(g&&clearTimeout(g),g=setTimeout(()=>d.bridge?.publish({type:"plugins_changed"}),180))}))}catch(f){d.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${h}: ${String(f)}`})}d.stopPluginWatch=()=>{for(let h of m)h.close();g&&clearTimeout(g)}}let u=await e(d.bridge.url).catch(()=>!1);c.ui.notify(`pi-webapp: ${d.bridge.url}`,u?"info":"warning"),c.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(p){throw d.telemetry?.capture(p,{stage:"open_web",piVersion:Jp}),d.bridge||(await d.telemetry?.close(),d.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 d.hosted?.shutdown(),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!0})}`,"info")}catch(u){console.error("pi-webapp: plugin shutdown refused the stop request:",u),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id: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 d.lifecycle.run(async()=>{let u=d.workspaceSessions?.session;u&&(await u.waitForIdle(),await d.workspaceSessions.reload()),await p.reload()}))}})}var t9=Da;export{t9 as default,fN as verifySentryDisabledRelease,Cw as verifySentryNodeRelease};
247
244
 
248
- //# debugId=9a5d0e7f-86cd-4bf7-a0ea-ce2309714b70
245
+ //# debugId=33824641-b63b-4649-a41f-6147985ab046