pi-webapp 0.1.54 → 0.1.55-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/extension.js +45 -45
  2. package/dist/hosted-recovery.js +3 -3
  3. package/dist/hosted-worker.js +2 -2
  4. package/package.json +2 -2
  5. package/web/dist/.vite/manifest.json +33 -33
  6. package/web/dist/assets/{MarkdownText-BR3sZaZW.js → MarkdownText-DF8BJV5i.js} +4 -4
  7. package/web/dist/assets/{app-CIG4uCO_.js → app-DwYC983k.js} +5 -5
  8. package/web/dist/assets/app.js +4 -4
  9. package/web/dist/assets/{code-editor-DRhkxaPw.js → code-editor-Njczr4Aq.js} +4 -4
  10. package/web/dist/assets/{dist-DWz4CJ7C.js → dist-B-bd7VCM.js} +2 -2
  11. package/web/dist/assets/{dist-nzUHJQnN.js → dist-B88A-0-q.js} +2 -2
  12. package/web/dist/assets/{dist-BXybcvYc.js → dist-BFaxoH5a.js} +2 -2
  13. package/web/dist/assets/{dist-Y1DWSB9X.js → dist-BSEV8UWP.js} +2 -2
  14. package/web/dist/assets/{dist-Lm5CcSgz.js → dist-BpfysUin.js} +2 -2
  15. package/web/dist/assets/{dist-CptaM7dm.js → dist-CLXF6v7a.js} +2 -2
  16. package/web/dist/assets/{dist-grdAiCLK.js → dist-CjWP7qLx.js} +2 -2
  17. package/web/dist/assets/{dist-CR92-SCE.js → dist-D2xI7N8L.js} +2 -2
  18. package/web/dist/assets/{dist-Dn8-zPdn.js → dist-DEGJW0Al.js} +2 -2
  19. package/web/dist/assets/{dist-Cig4tBp-.js → dist-l9rzcKKN.js} +2 -2
  20. package/web/dist/assets/{dist-DA9IZ4Cz.js → dist-xLBkmO57.js} +2 -2
  21. package/web/dist/assets/{graphql-XC5R1YoG.js → graphql-a_9GNzod.js} +2 -2
  22. package/web/dist/assets/{http-B2nL4bWC.js → http-DokH81pJ.js} +2 -2
  23. package/web/dist/assets/{php-Dx_jy0Md.js → php-BYAot5gz.js} +2 -2
  24. package/web/dist/assets/{plugin-B-DZzALa.js → plugin-AWio_je_.js} +2 -2
  25. package/web/dist/assets/{plugin-BryeYIz4.js → plugin-BGIBdp5R.js} +3 -3
  26. package/web/dist/assets/{plugin-D6n_U0kQ.js → plugin-BZPaYR4m.js} +2 -2
  27. package/web/dist/assets/{rst-B6Xh1ZOn.js → rst-CUsouaiW.js} +2 -2
  28. package/web/dist/assets/{ruby-Dl0_EnL3.js → ruby-eGmSFUio.js} +2 -2
  29. package/web/dist/assets/{svelte-CTPza2jZ.js → svelte-CEoWEKJ2.js} +2 -2
  30. package/web/dist/assets/{vue-UGI_ota8.js → vue-SlhNqE3a.js} +2 -2
package/dist/extension.js CHANGED
@@ -1,11 +1,11 @@
1
- var Ok=Object.defineProperty;var k=(i,e,t)=>()=>{if(t)throw t[0];try{return i&&(e=i(i=0)),e}catch(r){throw t=[r],r}};var vu=(i,e)=>{for(var t in e)Ok(i,t,{get:e[t],enumerable:!0})};var tg,Qo,ig,rg,Jo,ng,sg,ag,og,lg,cg,Xo,pg,dg,ug,mg,gg,fg,hg,fr=k(()=>{tg="sentry.environment",Qo="sentry.exclusive_time",ig="sentry.op",rg="sentry.origin",Jo="sentry.profile_id",ng="sentry.release",sg="sentry.sdk.integrations",ag="sentry.sdk.name",og="sentry.sdk.version",lg="sentry.segment.id",cg="sentry.segment.name",Xo="sentry.segment.name.source",pg="sentry.status.message",dg="sentry.trace_lifecycle",ug="url.path",mg="user.email",gg="user.id",fg="user.ip_address",hg="user.name"});var Q,Ve=k(()=>{Q=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var pe,xt=k(()=>{pe=globalThis});var ht,Ps=k(()=>{ht="11.10.0"});function Ce(){return lt(pe),pe}function lt(i){let e=i.__SENTRY__=i.__SENTRY__||{};return e.version=e.version||ht,e[ht]=e[ht]||{}}function yt(i,e,t=pe){let r=t.__SENTRY__=t.__SENTRY__||{},n=r[ht]=r[ht]||{};return n[i]||(n[i]=e())}var bt=k(()=>{Ps();xt()});function At(i){if(!("console"in pe))return i();let e=pe.console,t={},r=Object.keys(Zo);r.forEach(n=>{let s=Zo[n];t[n]=e[n],e[n]=s});try{return i()}finally{r.forEach(n=>{e[n]=t[n]})}}function LE(){tl().enabled=!0}function UE(){tl().enabled=!1}function yg(){return tl().enabled}function qE(...i){el("log",...i)}function jE(...i){el("warn",...i)}function BE(...i){el("error",...i)}function el(i,...e){Q&&yg()&&At(()=>{pe.console[i](`${ME}[${i}]:`,...e)})}function tl(){return Q?yt("loggerSettings",()=>({enabled:!1})):{enabled:!1}}var ME,Zo,z,$e=k(()=>{bt();Ve();xt();ME="Sentry Logger ",Zo={};z={enable:LE,disable:UE,isEnabled:yg,log:qE,warn:jE,error:BE}});function rl(...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=bg.test(a)?a.replace(bg,"$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(Cs(e).function||"")&&e.pop(),e.reverse(),_g.test(Cs(e).function||"")&&(e.pop(),_g.test(Cs(e).function||"")&&e.pop()),e.slice(0,50).map(t=>({...t,filename:t.filename||Cs(e).filename,function:t.function||"?"}))}function Cs(i){return i[i.length-1]||{}}function nl(i){try{return!i||typeof i!="function"?il:i.name||il}catch{return il}}function wg(i){let e=i?.startsWith("file://")?i.slice(7):i;return e?.match(/\/[A-Z]:/)&&(e=e.slice(1)),e}var bg,_g,il,Ds=k(()=>{bg=/\(error: (.*)\)/,_g=/captureMessage|captureException/;il="<anonymous>"});function Ot(i){switch(kg.call(i)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Ig(i,Error)}}function Ms(i,e){return kg.call(i)===`[object ${e}]`}function Sg(i){return Ms(i,"ErrorEvent")}function cn(i){return Ms(i,"String")}function pn(i){return typeof i=="object"&&i!==null&&"__sentry_template_string__"in i&&"__sentry_template_values__"in i}function ti(i){return i===null||pn(i)||typeof i!="object"&&typeof i!="function"}function hr(i){return Ms(i,"Object")}function dn(i){return typeof i=="object"&&i!==null}function Eg(i){return typeof Event<"u"&&Ig(i,Event)}function Tg(i){return Ms(i,"RegExp")}function ii(i){return!!(i?.then&&typeof i.then=="function")}function Ig(i,e){try{return i instanceof e}catch{return!1}}var kg,it=k(()=>{kg=Object.prototype.toString});function Ls(i,e,t){try{Object.defineProperty(i,e,{value:t,writable:!0,configurable:!0})}catch{Q&&z.log(`Failed to add non-enumerable property "${String(e)}" to object`,i)}}function sl(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 dn(i)?Object.fromEntries(Object.entries(i)):{}}function Ag(i){let e=Object.keys(sl(i));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}var un=k(()=>{Ve();$e();it()});function gi(i){if(yr!==void 0)return yr?yr(i):i();let e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),t=pe;return e in t&&typeof t[e]=="function"?(yr=t[e],yr(i)):(yr=null,i())}function _t(){return gi(()=>Math.random())}function ze(){return gi(()=>Date.now())}var yr,Rt=k(()=>{xt()});function Og(i){return!!i[FE]}function Rg(i){let e=i[HE];return typeof e=="number"?e:void 0}var FE,HE,Ng=k(()=>{FE=Symbol.for("sentry.skipNormalization"),HE=Symbol.for("sentry.overrideNormalizationDepth")});function Nt(i,e=100,t=1/0){try{return al("",i,e,t)}catch(r){return{ERROR:`**non-serializable** (${r})`}}}function ol(i,e=3,t=100*1024){let r=Nt(i,e);return $E(r)>t?ol(i,e-1,t):r}function al(i,e,t=1/0,r=1/0,n=zE()){let[s,o]=n;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;let l=GE(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 al("",v,c-1,r,n)}catch{}let d=Array.isArray(e)?[]:{},g=0,f=sl(e);for(let v in f){if(!Object.prototype.hasOwnProperty.call(f,v))continue;if(g>=r){d[v]="[MaxProperties ~]";break}let y=f[v];d[v]=al(v,y,c-1,r,n),g++}return o(e),d}function GE(i,e){try{if(Pg){let r=Pg(e);if(r)return r}return typeof global<"u"&&e===global?"[Global]":typeof e=="number"&&!Number.isFinite(e)?`[${e}]`:typeof e=="function"?`[Function: ${nl(e)}]`:typeof e=="symbol"?`[${String(e)}]`:typeof e=="bigint"?`[BigInt: ${String(e)}]`:`[object ${WE(e)}]`}catch(t){return`**non-serializable** (${t})`}}function WE(i){let e=Object.getPrototypeOf(i);return e?.constructor?e.constructor.name:"null prototype"}function VE(i){return~-encodeURI(i).split(/%..|./).length}function $E(i){return VE(JSON.stringify(i))}function zE(){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 Pg,Us=k(()=>{Ng();un();Ds()});function mn(i,e=0){return typeof i!="string"||e===0||i.length<=e?i:`${i.slice(0,e)}...`}function gn(i,e,t=!1){return cn(i)?Tg(e)?e.test(i):cn(e)?t?i===e:i.includes(e):typeof e=="function"?e(i):!1:!1}var qs=k(()=>{it()});function KE(){let i=pe;return i.crypto||i.msCrypto}function YE(){return _t()*16}function Me(i=KE()){try{if(i?.randomUUID)return gi(()=>i.randomUUID()).replace(/-/g,"")}catch{}return ll||(ll="10000000100040008000"+1e11),ll.replace(/[018]/g,e=>(e^(YE()&15)>>e/4).toString(16))}function QE(i){return i.exception?.values?.[0]}function pl(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 js(i,e){let t=QE(i);t&&Dg(t,e)}function Cg(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 cl(i){return parseInt(i||"",10)}function dl(i){let e=i.match(JE)||[],t=cl(e[1]),r=cl(e[2]),n=cl(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 Bs(i){if(Mg(i))return!0;try{Ls(i,"__sentry_captured__",!0)}catch{}return!1}function Mg(i){try{return i.__sentry_captured__}catch{}}var ll,JE,ri=k(()=>{un();Rt();xt();JE=/^(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 Hi(){return ze()/Ug}function eT(){let{performance:i}=pe;if(!i?.now||!i.timeOrigin)return i?.now&&(br=[{from:0,origin:ze()-gi(()=>i.now())}]),Hi;let e=i.timeOrigin;br=[{from:0,origin:e}];let t=!0,r=0;return()=>gi(()=>{let n=i.now(),s=Date.now();return Math.abs(e+n-s)>XE&&(e=s-n,t?br=[{from:0,origin:e}]:(br.push({from:r,origin:e}),br.length>ZE&&br.splice(1,1))),t=!1,r=n,(e+n)/Ug})}function Fs(){return(Lg??(Lg=eT()))()}var Ug,XE,ZE,br,Lg,_r=k(()=>{Rt();xt();Ug=1e3,XE=1e3,ZE=100;br=[]});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||Fs(),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 ul=k(()=>{ri();_r()});function fi(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]=fi(r[n],e[n],t-1));return r}var Hs=k(()=>{});function Gi(){return Me()}function hn(){return Me().substring(16)}var yn=k(()=>{ri()});var tT,Je,vr=k(()=>{Ve();ul();$e();it();un();Hs();ri();yn();Rt();qs();_r();tT=100,Je=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={},Ls(this,"refs",{}),this._propagationContext={traceId:Gi(),sampleRand:_t()}}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():hr(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:tT;if(r<=0)return this;let n={timestamp:Hi(),...e,message:e.message?mn(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=fi(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&&z.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&&z.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&&z.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 Wi(){return yt("defaultCurrentScope",()=>new Je)}function Vi(){return yt("defaultIsolationScope",()=>new Je)}var ml=k(()=>{bt();vr()});var gl,qg=k(()=>{gl="__SENTRY_SUPPRESS_TRACING__"});var jg,Bg,Fg,iT,Hg=k(()=>{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:iT(i,r)},iT=(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 wr(){let i=Ce(),e=lt(i);return e.stack=e.stack||new fl(Wi(),Vi())}function Wg(i){return wr().withScope(i)}function rT(i,e){let t=wr();return t.withScope(()=>(t.getStackTop().scope=i,e(i)))}function Gg(i){return wr().withScope(()=>i(wr().getIsolationScope()))}function Vg(){return{suppressTracing:nT,withIsolationScope:Gg,withScope:Wg,withSetScope:rT,withSetIsolationScope:(i,e)=>Gg(e),getCurrentScope:()=>wr().getScope(),getIsolationScope:()=>wr().getIsolationScope()}}function nT(i){return Wg(e=>{e.setSDKProcessingMetadata({[gl]:!0});let t=i();return e.setSDKProcessingMetadata({[gl]:void 0}),t})}var fl,$g=k(()=>{ml();vr();qg();Hg();it();bt();fl=class{constructor(e,t){let r;e?r=e:r=new Je;let n;t?n=t:n=new Je,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 ii(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 bn(i){let e=Ce(),t=lt(e);t.acs=i}function Pt(i){let e=lt(i);return e.acs?e.acs:Vg()}var Gs=k(()=>{bt();$g()});function sT(i){return typeof i=="object"&&i!=null&&!Array.isArray(i)&&Object.keys(i).includes("value")}function aT(i,e){let{value:t,unit:r}=sT(i)?i:{value:i,unit:void 0},n=oT(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 hl(i,e=!1){let t={};for(let[r,n]of Object.entries(i??{})){let s=aT(n,e);s&&(t[r]=s)}return t}function yl(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+=zg(n[0])*n.length:ti(n)?e+=zg(n):e+=100}return e}function zg(i){return typeof i=="string"?i.length*2:typeof i=="boolean"?4:typeof i=="number"?8:0}function oT(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 bl=k(()=>{it()});function Ws(){return lt(Ce()).externalPropagationContextProvider?.()}function ni(){let i=Ce();return Pt(i).getCurrentScope()}function $i(){let i=Ce();return Pt(i).getIsolationScope()}function _l(){return yt("globalScope",()=>new Je)}function Vs(...i){let e=Ce(),t=Pt(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 ni().getClient()}function zi(i){let e=Ws();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||hn()};return n&&(o.parent_span_id=n),o}var Ct=k(()=>{Gs();bt();vr();yn()});var Kg,Yg,Qg,vl=k(()=>{Kg="sentry.sample_rate",Yg="sentry.previous_trace_sample_rate",Qg="sentry.custom_span_name"});var Jg,Xg=k(()=>{Jg=["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 Zg(i){return i!=="ok"&&Jg.includes(i)}var wl,kl,ef=k(()=>{Xg();wl=0,kl=1});function kr(i){try{let e=pe.WeakRef;if(typeof e=="function")return new e(i)}catch{}return i}function Ki(i){if(i){if(typeof i=="object"&&"deref"in i&&typeof i.deref=="function")try{return i.deref()}catch{return}return i}}var $s=k(()=>{xt()});function hi(i){let e=i;return{scope:e[lT],isolationScope:Ki(e[cT])}}var lT,cT,zs=k(()=>{$s();lT="_sentryScope",cT="_sentryIsolationScope"});function _n(i){let e=rf(i);if(!e)return;let t=Object.entries(e).reduce((r,[n,s])=>{if(n.startsWith(Sl)){let o=n.slice(Sl.length);r[o]=s}return r},{});if(Object.keys(t).length>0)return t}function rf(i){if(!(!i||!cn(i)&&!Array.isArray(i)))return Array.isArray(i)?i.reduce((e,t)=>{let r=tf(t);return Object.entries(r).forEach(([n,s])=>{e[n]=s}),e},{}):tf(i)}function tf(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 Sl,El=k(()=>{it();Sl="sentry-"});function uT(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 mT(i){let e=dT.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 nf({host:s,pass:n,path:a,projectId:c,port:o,protocol:t,publicKey:r})}function nf(i){return{protocol:i.protocol,publicKey:i.publicKey||"",pass:i.pass||"",host:i.host,port:i.port||"",path:i.path||"",projectId:i.projectId}}function gT(i){if(!Q)return!0;let{port:e,projectId:t,protocol:r}=i;return["protocol","publicKey","host","projectId"].find(o=>i[o]?!1:(z.error(`Invalid Sentry Dsn: ${o} missing`),!0))?!1:t.match(/^\d+$/)?uT(r)?e&&isNaN(parseInt(e,10))?(z.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(z.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(z.error(`Invalid Sentry Dsn: Invalid projectId ${t}`),!1)}function fT(i){return i.match(pT)?.[1]}function sf(i){let e=i.getOptions(),{host:t}=i.getDsn()||{},r;return e.orgId?r=String(e.orgId):t&&(r=fT(t)),r}function vn(i){let e=typeof i=="string"?mT(i):nf(i);if(!(!e||!gT(e)))return e}var pT,dT,Ht=k(()=>{Ve();$e();pT=/^o(\d+)\./,dT=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/});function af(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 of=k(()=>{});function wn(i){return!!i.parentSpanId||!!i.dsc}var hT,lf=k(()=>{hT=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$")});function Ks(i,e){e?i.refs[Tl]=kr(e):delete i.refs[Tl]}function cf(i){return Ki(i.refs[Tl])}var Tl,Il=k(()=>{$s();Tl="span"});function Qs(i){let{spanId:e,traceId:t,isRemote:r}=i.spanContext(),n=r?e:Sr(i).parent_span_id,s=hi(i).scope,o=r?s?.getPropagationContext().propagationSpanId||hn():e;return{parent_span_id:n,span_id:o,trace_id:t}}function yT(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===xl,attributes:s,...n}))}function bT(i){if(i?.length)return i.map(({context:{spanId:e,traceId:t,traceFlags:r},attributes:n})=>({span_id:e,trace_id:t,sampled:r===xl,attributes:n}))}function Ys(i){return typeof i=="number"?pf(i):Array.isArray(i)?i[0]+i[1]/1e9:i instanceof Date?pf(i.getTime()):Fs()}function pf(i){return i>9999999999?i/1e3:i}function Sr(i){if(gf(i))return i.getStaticSpanJSON();let{spanId:e,traceId:t}=i.spanContext();if(mf(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:uf(i),start_timestamp:Ys(n),timestamp:Ys(o)||void 0,status:_T(l),op:r[ig],origin:r[rg],links:yT(a)}}return{span_id:e,trace_id:t,start_timestamp:0,status:"ok",data:{}}}function Al(i){if(gf(i))return i.getSpanJSON();let{spanId:e,traceId:t}=i.spanContext();if(mf(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:uf(i),start_timestamp:Ys(n),end_timestamp:Ys(o)||void 0,is_segment:df(i),status:ff(l),attributes:vT(r,l),links:bT(a)}}return{span_id:e,trace_id:t,start_timestamp:0,name:"",status:"ok",is_segment:df(i),attributes:{}}}function uf(i){return"parentSpanId"in i?i.parentSpanId:"parentSpanContext"in i?i.parentSpanContext?.spanId:void 0}function Js(i){return{...i,end_timestamp:i.end_timestamp??i.start_timestamp,attributes:hl(i.attributes),links:i.links?.map(e=>({...e,attributes:hl(e.attributes)}))}}function mf(i){let e=i;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function gf(i){return typeof i.getSpanJSON=="function"}function Xs(i){let{traceFlags:e}=i.spanContext();return e===xl}function _T(i){return!i||i.code===wl||i.code===kl?"ok":i.message&&Zg(i.message)?i.message:"internal_error"}function ff(i){return!i||i.code===kl||i.code===wl||i.message==="cancelled"?"ok":"error"}function vT(i,e){let t=ff(e)==="error"?e?.message:void 0;return{...t&&{[pg]:t},...i}}function ea(i){return i[wT]||i}function df(i){return i===ea(i)}function kn(i){let e=Ce(),t=Pt(e);return t.getActiveSpan?t.getActiveSpan(i):cf(i||ni())}var xl,wT,Zs,yi=k(()=>{Gs();bl();bt();Ct();fr();ef();zs();yn();_r();Il();xl=1;wT="_sentryRootSpan",Zs=ea});function Ol(i){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;let e=i||Ft()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}var hf=k(()=>{Ct()});function yf(i){z.log(`Ignoring span ${i.op} - ${i.description} because it matches \`ignoreSpans\`.`)}function Rl(i,e){if(!e?.length)return!1;for(let t of e){if(ST(t)){if(i.description&&gn(i.description,t))return Q&&yf(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&&gn(i.description,t.name):!0,s=t.op?i.op&&gn(i.op,t.op):!0,o=t.attributes?Object.entries(t.attributes).every(([l,a])=>kT(i.attributes?.[l],a)):!0;if(n&&s&&o)return Q&&yf(i),!0}return!1}function kT(i,e){return typeof i=="string"&&(typeof e=="string"||e instanceof RegExp)?gn(i,e):Array.isArray(i)&&Array.isArray(e)?i.length===e.length&&i.every((t,r)=>t===e[r]):i===e}function bf(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 ST(i){return typeof i=="string"||i instanceof RegExp}var _f=k(()=>{Ve();$e();qs()});function wf(i,e){let t={};return e.forEach(r=>{r?.beforeSetup&&r.beforeSetup(i)}),e.forEach(r=>{r&&Pl(i,r,t)}),t}function Nl(i,e){for(let t of e)t?.afterAllSetup&&t.afterAllSetup(i)}function Pl(i,e,t){if(t[e.name]){Q&&z.log(`Integration skipped because it was already installed: ${e.name}`);return}if(t[e.name]=e,!vf.includes(e.name)&&typeof e.setupOnce=="function"&&(e.setupOnce(),vf.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&&z.log(`Integration installed: ${e.name}`)}var vf,kf=k(()=>{Ve();$e();vf=[]});var bi,Sn=k(()=>{bi="production"});function Sf(i){return!!i&&i[ET]===!0}var ET,Ef=k(()=>{ET=Symbol.for("sentry.nonRecordingSpan")});function Cl(i,e){let t=e.getOptions(),{publicKey:r}=e.getDsn()||{},n={environment:t.environment||bi,release:t.release,public_key:r,trace_id:i,org_id:sf(e)};return e.emit("createDsc",n),n}function Er(i,e){if(Ws())return;let t=e.getPropagationContext();return t.dsc||Cl(t.traceId,i)}function si(i){let e=Ft();if(!e)return{};let t=Zs(i),r=Sr(t),n=r.data,s=t.spanContext().traceState,o=s?.get("sentry.sample_rate")??n[Kg]??n[Yg];function l(S){return(typeof o=="number"||typeof o=="string")&&(S.sample_rate=`${o}`),S}let a=t[TT];if(a)return l(a);let c=Sf(t),p=c&&t.dropReason==="ignored";if(c&&(!Ol(e.getOptions())||p)){let S=hi(t).scope,T=S&&Er(e,S);if(T){let A={...T};return p&&(A.sampled="false"),l(A)}}let d=s?.get("sentry.dsc"),g=d&&_n(d);if(g)return l(g);let f=Cl(i.spanContext().traceId,e),v=n[Xo],y=r.description;return v!=="url"&&y&&(f.transaction=y),Ol()&&(f.sampled=String(Xs(t)),f.sample_rand=s?.get("sentry.sample_rand")??hi(t).scope?.getPropagationContext().sampleRand.toString()),l(f),e.emit("createDsc",f,t),f}var TT,Tr=k(()=>{Sn();Ct();fr();vl();El();Ht();hf();yi();Ef();zs();TT="_frozenDsc"});function xf(i,e){let{fingerprint:t,breadcrumbs:r,sdkProcessingMetadata:n}=e;IT(i,e),OT(i,t),xT(i,r),AT(i,n)}function If(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:f,transactionName:v}=e;En(i,"extra",t),En(i,"tags",r),En(i,"attributes",n),En(i,"user",s),En(i,"contexts",o),i.sdkProcessingMetadata=fi(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,...f}}function En(i,e,t){i[e]=fi(i[e],t,1)}function ta(i,e){let t=_l().getScopeData();return i&&If(t,i.getScopeData()),e&&If(t,e.getScopeData()),t}function IT(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 xT(i,e){let t=[...i.breadcrumbs||[],...e];i.breadcrumbs=t.length?t:void 0}function AT(i,e){i.sdkProcessingMetadata={...i.sdkProcessingMetadata,...e}}function Af(i,e){i.contexts={trace:Qs(e),...i.contexts},i.sdkProcessingMetadata={dynamicSamplingContext:si(e),...i.sdkProcessingMetadata};let t=Zs(e),r=Sr(t).description;r&&!i.transaction&&i.type==="transaction"&&(i.transaction=r)}function OT(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 Dl=k(()=>{Ct();Tr();Hs();yi()});function Yi(i,e,t){let r;try{r=e()}catch(n){return Of(i,n,t)}return ii(r)?r.then(void 0,n=>Of(i,n,t)):r}function Of(i,e,t){return Q&&z.error(i,e),t(e)}var ia=k(()=>{Ve();$e();it()});function Tn(i){return!!i&&typeof i=="function"&&"_static"in i&&!!i._static}function In(i,e){return Yi(Q?"The `beforeSendSpan` callback threw an error, sending the span unmodified:":"",()=>e(i),()=>i)||i}var Ml=k(()=>{Ve();ia()});function Rf(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 Js(e)}var Nf=k(()=>{yi()});function Pf(i){let e={},{response:t,profile:r,cloud_resource:n,culture:s,state:o}=i;if(t&&(t.status_code!=null&&(e["http.response.status_code"]=t.status_code),t.body_size!=null&&(e["http.response.body.size"]=t.body_size)),r&&(r.profile_id&&(e["sentry.profile_id"]=r.profile_id),r.profiler_id&&(e["sentry.profiler_id"]=r.profiler_id)),n)for(let[c,p]of Object.entries(n))p!=null&&(e[c]=p);s&&(s.locale&&(e["culture.locale"]=s.locale),s.timezone&&(e["culture.timezone"]=s.timezone)),o?.state&&typeof o.state.type=="string"&&(e["state.type"]=o.state.type);let l=i.angular;if(l){let c=l.version;(typeof c=="string"||typeof c=="number")&&(e["angular.version"]=c)}let a=i.react;if(a){let c=a.version;(typeof c=="string"||typeof c=="number")&&(e["react.version"]=c)}return e}var Cf=k(()=>{});function Df(i,e){let t=Al(i);t.attributes&&delete t.attributes[Qg];let r=ea(i),n=Al(r),{isolationScope:s,scope:o}=hi(i),l=ta(s,o);CT(t,n,e,l),e.emit("preprocessSpan",t),t.is_segment&&(RT(t,l),NT(t,e),e.emit("processSegmentSpan",t)),e.emit("processSpan",t);let{beforeSendSpan:a,traceLifecycle:c}=e.getOptions(),p=c!=="static"&&a&&!Tn(a)?In(t,a):t;return{...Js(p),_segmentSpan:r}}function RT(i,e){let t=Pf(e.contexts);Ll(i,t)}function Ll(i,e){let t=i.attributes??(i.attributes={});Object.entries(e).forEach(([r,n])=>{n!=null&&!(r in t)&&(t[r]=n)})}function NT(i,e){let t=e.getIntegrationNames();t.length&&Ll(i,{[sg]:t})}function PT(i,e,t,r=!0){let n=e.getSdkMetadata(),{release:s,environment:o}=e.getOptions();return{[dg]:"stream",[cg]:i.name,[lg]:i.span_id,[ag]:n?.sdk?.name,[og]:n?.sdk?.version,[ng]:s,[tg]:o||bi,[gg]:t.user?.id,[mg]:t.user?.email,[fg]:t.user?.ip_address,[hg]:t.user?.username,...r?t.attributes:void 0}}function CT(i,e,t,r){Ll(i,PT(e,t,r))}var Mf=k(()=>{vl();Dl();yi();zs();Ml();Cf();Sn();fr()});function ra(i){return i.getOptions().traceLifecycle==="stream"}var Ul=k(()=>{});function _i(i){return typeof i=="object"&&typeof i.unref=="function"&&i.unref(),i}var xn=k(()=>{});function Xe(i,e=[]){return[i,e]}function jl(i,e){let[t,r]=i;return[t,[...r,e]]}function na(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 Lf(i,e){return na(i,(t,r)=>e.includes(r))}function ql(i){let e=lt(pe);return e.encodePolyfill?e.encodePolyfill(i):new TextEncoder().encode(i)}function Uf(i){let[e,t]=i,r=JSON.stringify(e);function n(s){typeof r=="string"?r=typeof s=="string"?r+s:[ql(r),s]:r.push(typeof s=="string"?ql(s):s)}for(let s of t){let[o,l]=s;if(n(`
1
+ var Uk=Object.defineProperty;var k=(i,e,t)=>()=>{if(t)throw t[0];try{return i&&(e=i(i=0)),e}catch(r){throw t=[r],r}};var wu=(i,e)=>{for(var t in e)Uk(i,t,{get:e[t],enumerable:!0})};var ig,Qo,rg,ng,Jo,sg,ag,og,lg,cg,pg,Xo,dg,ug,mg,gg,fg,hg,yg,fr=k(()=>{ig="sentry.environment",Qo="sentry.exclusive_time",rg="sentry.op",ng="sentry.origin",Jo="sentry.profile_id",sg="sentry.release",ag="sentry.sdk.integrations",og="sentry.sdk.name",lg="sentry.sdk.version",cg="sentry.segment.id",pg="sentry.segment.name",Xo="sentry.segment.name.source",dg="sentry.status.message",ug="sentry.trace_lifecycle",mg="url.path",gg="user.email",fg="user.id",hg="user.ip_address",yg="user.name"});var Q,$e=k(()=>{Q=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});var pe,xt=k(()=>{pe=globalThis});var ht,Ns=k(()=>{ht="11.10.0"});function Ce(){return lt(pe),pe}function lt(i){let e=i.__SENTRY__=i.__SENTRY__||{};return e.version=e.version||ht,e[ht]=e[ht]||{}}function yt(i,e,t=pe){let r=t.__SENTRY__=t.__SENTRY__||{},n=r[ht]=r[ht]||{};return n[i]||(n[i]=e())}var bt=k(()=>{Ns();xt()});function At(i){if(!("console"in pe))return i();let e=pe.console,t={},r=Object.keys(Zo);r.forEach(n=>{let s=Zo[n];t[n]=e[n],e[n]=s});try{return i()}finally{r.forEach(n=>{e[n]=t[n]})}}function WE(){tl().enabled=!0}function $E(){tl().enabled=!1}function bg(){return tl().enabled}function VE(...i){el("log",...i)}function zE(...i){el("warn",...i)}function KE(...i){el("error",...i)}function el(i,...e){Q&&bg()&&At(()=>{pe.console[i](`${GE}[${i}]:`,...e)})}function tl(){return Q?yt("loggerSettings",()=>({enabled:!1})):{enabled:!1}}var GE,Zo,z,Ve=k(()=>{bt();$e();xt();GE="Sentry Logger ",Zo={};z={enable:WE,disable:$E,isEnabled:bg,log:VE,warn:zE,error:KE}});function rl(...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=_g.test(a)?a.replace(_g,"$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 wg(s.slice(n))}}function wg(i){if(!i.length)return[];let e=Array.from(i);return/sentryWrapped/.test(Ps(e).function||"")&&e.pop(),e.reverse(),vg.test(Ps(e).function||"")&&(e.pop(),vg.test(Ps(e).function||"")&&e.pop()),e.slice(0,50).map(t=>({...t,filename:t.filename||Ps(e).filename,function:t.function||"?"}))}function Ps(i){return i[i.length-1]||{}}function nl(i){try{return!i||typeof i!="function"?il:i.name||il}catch{return il}}function kg(i){let e=i?.startsWith("file://")?i.slice(7):i;return e?.match(/\/[A-Z]:/)&&(e=e.slice(1)),e}var _g,vg,il,Cs=k(()=>{_g=/\(error: (.*)\)/,vg=/captureMessage|captureException/;il="<anonymous>"});function Ot(i){switch(Sg.call(i)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return xg(i,Error)}}function Ds(i,e){return Sg.call(i)===`[object ${e}]`}function Eg(i){return Ds(i,"ErrorEvent")}function cn(i){return Ds(i,"String")}function pn(i){return typeof i=="object"&&i!==null&&"__sentry_template_string__"in i&&"__sentry_template_values__"in i}function ti(i){return i===null||pn(i)||typeof i!="object"&&typeof i!="function"}function hr(i){return Ds(i,"Object")}function dn(i){return typeof i=="object"&&i!==null}function Tg(i){return typeof Event<"u"&&xg(i,Event)}function Ig(i){return Ds(i,"RegExp")}function ii(i){return!!(i?.then&&typeof i.then=="function")}function xg(i,e){try{return i instanceof e}catch{return!1}}var Sg,it=k(()=>{Sg=Object.prototype.toString});function Ms(i,e,t){try{Object.defineProperty(i,e,{value:t,writable:!0,configurable:!0})}catch{Q&&z.log(`Failed to add non-enumerable property "${String(e)}" to object`,i)}}function sl(i){if(Ot(i))return{message:i.message,name:i.name,stack:i.stack,...Ag(i)};if(Tg(i)){let{type:e,target:t,currentTarget:r,detail:n}=i;return{type:e,target:t,currentTarget:r,...n?{detail:n}:{},...Ag(i)}}return i}function Ag(i){return dn(i)?Object.fromEntries(Object.entries(i)):{}}function Og(i){let e=Object.keys(sl(i));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}var un=k(()=>{$e();Ve();it()});function gi(i){if(yr!==void 0)return yr?yr(i):i();let e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),t=pe;return e in t&&typeof t[e]=="function"?(yr=t[e],yr(i)):(yr=null,i())}function _t(){return gi(()=>Math.random())}function ze(){return gi(()=>Date.now())}var yr,Rt=k(()=>{xt()});function Rg(i){return!!i[YE]}function Ng(i){let e=i[QE];return typeof e=="number"?e:void 0}var YE,QE,Pg=k(()=>{YE=Symbol.for("sentry.skipNormalization"),QE=Symbol.for("sentry.overrideNormalizationDepth")});function Nt(i,e=100,t=1/0){try{return al("",i,e,t)}catch(r){return{ERROR:`**non-serializable** (${r})`}}}function ol(i,e=3,t=100*1024){let r=Nt(i,e);return eT(r)>t?ol(i,e-1,t):r}function al(i,e,t=1/0,r=1/0,n=tT()){let[s,o]=n;if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;let l=JE(i,e);if(!l.startsWith("[object "))return l;if(Rg(e))return e;let a=Ng(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 _=p.toJSON();return al("",_,c-1,r,n)}catch{}let d=Array.isArray(e)?[]:{},g=0,f=sl(e);for(let _ in f){if(!Object.prototype.hasOwnProperty.call(f,_))continue;if(g>=r){d[_]="[MaxProperties ~]";break}let y=f[_];d[_]=al(_,y,c-1,r,n),g++}return o(e),d}function JE(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: ${nl(e)}]`:typeof e=="symbol"?`[${String(e)}]`:typeof e=="bigint"?`[BigInt: ${String(e)}]`:`[object ${XE(e)}]`}catch(t){return`**non-serializable** (${t})`}}function XE(i){let e=Object.getPrototypeOf(i);return e?.constructor?e.constructor.name:"null prototype"}function ZE(i){return~-encodeURI(i).split(/%..|./).length}function eT(i){return ZE(JSON.stringify(i))}function tT(){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,Ls=k(()=>{Pg();un();Cs()});function mn(i,e=0){return typeof i!="string"||e===0||i.length<=e?i:`${i.slice(0,e)}...`}function gn(i,e,t=!1){return cn(i)?Ig(e)?e.test(i):cn(e)?t?i===e:i.includes(e):typeof e=="function"?e(i):!1:!1}var Us=k(()=>{it()});function iT(){let i=pe;return i.crypto||i.msCrypto}function rT(){return _t()*16}function Me(i=iT()){try{if(i?.randomUUID)return gi(()=>i.randomUUID()).replace(/-/g,"")}catch{}return ll||(ll="10000000100040008000"+1e11),ll.replace(/[018]/g,e=>(e^(rT()&15)>>e/4).toString(16))}function nT(i){return i.exception?.values?.[0]}function pl(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 qs(i,e){let t=nT(i);t&&Mg(t,e)}function Dg(i,e){let t=i.exception?.values,r=t?.find(n=>n.mechanism?.exception_id===0)??t?.[0];r&&Mg(r,e)}function Mg(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 cl(i){return parseInt(i||"",10)}function dl(i){let e=i.match(sT)||[],t=cl(e[1]),r=cl(e[2]),n=cl(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 js(i){if(Lg(i))return!0;try{Ms(i,"__sentry_captured__",!0)}catch{}return!1}function Lg(i){try{return i.__sentry_captured__}catch{}}var ll,sT,ri=k(()=>{un();Rt();xt();sT=/^(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 Hi(){return ze()/qg}function lT(){let{performance:i}=pe;if(!i?.now||!i.timeOrigin)return i?.now&&(br=[{from:0,origin:ze()-gi(()=>i.now())}]),Hi;let e=i.timeOrigin;br=[{from:0,origin:e}];let t=!0,r=0;return()=>gi(()=>{let n=i.now(),s=Date.now();return Math.abs(e+n-s)>aT&&(e=s-n,t?br=[{from:0,origin:e}]:(br.push({from:r,origin:e}),br.length>oT&&br.splice(1,1))),t=!1,r=n,(e+n)/qg})}function Fs(){return(Ug??(Ug=lT()))()}var qg,aT,oT,br,Ug,_r=k(()=>{Rt();xt();qg=1e3,aT=1e3,oT=100;br=[]});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||Fs(),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 ul=k(()=>{ri();_r()});function fi(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]=fi(r[n],e[n],t-1));return r}var Bs=k(()=>{});function Gi(){return Me()}function hn(){return Me().substring(16)}var yn=k(()=>{ri()});var cT,Je,vr=k(()=>{$e();ul();Ve();it();un();Bs();ri();yn();Rt();Us();_r();cT=100,Je=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={},Ms(this,"refs",{}),this._propagationContext={traceId:Gi(),sampleRand:_t()}}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():hr(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:cT;if(r<=0)return this;let n={timestamp:Hi(),...e,message:e.message?mn(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=fi(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&&z.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&&z.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&&z.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 Wi(){return yt("defaultCurrentScope",()=>new Je)}function $i(){return yt("defaultIsolationScope",()=>new Je)}var ml=k(()=>{bt();vr()});var gl,jg=k(()=>{gl="__SENTRY_SUPPRESS_TRACING__"});var Fg,Bg,Hg,pT,Gg=k(()=>{Fg=i=>i instanceof Promise&&!i[Bg],Bg=Symbol("chained PromiseLike"),Hg=(i,e,t)=>{let r=i.then(n=>(e(n),n),n=>{throw t(n),n});return Fg(r)&&Fg(i)?r:pT(i,r)},pT=(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 wr(){let i=Ce(),e=lt(i);return e.stack=e.stack||new fl(Wi(),$i())}function $g(i){return wr().withScope(i)}function dT(i,e){let t=wr();return t.withScope(()=>(t.getStackTop().scope=i,e(i)))}function Wg(i){return wr().withScope(()=>i(wr().getIsolationScope()))}function Vg(){return{suppressTracing:uT,withIsolationScope:Wg,withScope:$g,withSetScope:dT,withSetIsolationScope:(i,e)=>Wg(e),getCurrentScope:()=>wr().getScope(),getIsolationScope:()=>wr().getIsolationScope()}}function uT(i){return $g(e=>{e.setSDKProcessingMetadata({[gl]:!0});let t=i();return e.setSDKProcessingMetadata({[gl]:void 0}),t})}var fl,zg=k(()=>{ml();vr();jg();Gg();it();bt();fl=class{constructor(e,t){let r;e?r=e:r=new Je;let n;t?n=t:n=new Je,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 ii(r)?Hg(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 bn(i){let e=Ce(),t=lt(e);t.acs=i}function Pt(i){let e=lt(i);return e.acs?e.acs:Vg()}var Hs=k(()=>{bt();zg()});function mT(i){return typeof i=="object"&&i!=null&&!Array.isArray(i)&&Object.keys(i).includes("value")}function gT(i,e){let{value:t,unit:r}=mT(i)?i:{value:i,unit:void 0},n=fT(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 hl(i,e=!1){let t={};for(let[r,n]of Object.entries(i??{})){let s=gT(n,e);s&&(t[r]=s)}return t}function yl(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+=Kg(n[0])*n.length:ti(n)?e+=Kg(n):e+=100}return e}function Kg(i){return typeof i=="string"?i.length*2:typeof i=="boolean"?4:typeof i=="number"?8:0}function fT(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 bl=k(()=>{it()});function Gs(){return lt(Ce()).externalPropagationContextProvider?.()}function ni(){let i=Ce();return Pt(i).getCurrentScope()}function Vi(){let i=Ce();return Pt(i).getIsolationScope()}function _l(){return yt("globalScope",()=>new Je)}function Ws(...i){let e=Ce(),t=Pt(e);if(i.length===2){let[r,n]=i;return r?t.withSetScope(r,n):t.withScope(n)}return t.withScope(i[0])}function Bt(){return ni().getClient()}function zi(i){let e=Gs();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||hn()};return n&&(o.parent_span_id=n),o}var Ct=k(()=>{Hs();bt();vr();yn()});var Yg,Qg,Jg,vl=k(()=>{Yg="sentry.sample_rate",Qg="sentry.previous_trace_sample_rate",Jg="sentry.custom_span_name"});var Xg,Zg=k(()=>{Xg=["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 ef(i){return i!=="ok"&&Xg.includes(i)}var wl,kl,tf=k(()=>{Zg();wl=0,kl=1});function kr(i){try{let e=pe.WeakRef;if(typeof e=="function")return new e(i)}catch{}return i}function Ki(i){if(i){if(typeof i=="object"&&"deref"in i&&typeof i.deref=="function")try{return i.deref()}catch{return}return i}}var $s=k(()=>{xt()});function hi(i){let e=i;return{scope:e[hT],isolationScope:Ki(e[yT])}}var hT,yT,Vs=k(()=>{$s();hT="_sentryScope",yT="_sentryIsolationScope"});function _n(i){let e=nf(i);if(!e)return;let t=Object.entries(e).reduce((r,[n,s])=>{if(n.startsWith(Sl)){let o=n.slice(Sl.length);r[o]=s}return r},{});if(Object.keys(t).length>0)return t}function nf(i){if(!(!i||!cn(i)&&!Array.isArray(i)))return Array.isArray(i)?i.reduce((e,t)=>{let r=rf(t);return Object.entries(r).forEach(([n,s])=>{e[n]=s}),e},{}):rf(i)}function rf(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 Sl,El=k(()=>{it();Sl="sentry-"});function vT(i){return i==="http"||i==="https"}function Fe(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 wT(i){let e=_T.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 sf({host:s,pass:n,path:a,projectId:c,port:o,protocol:t,publicKey:r})}function sf(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:(z.error(`Invalid Sentry Dsn: ${o} missing`),!0))?!1:t.match(/^\d+$/)?vT(r)?e&&isNaN(parseInt(e,10))?(z.error(`Invalid Sentry Dsn: Invalid port ${e}`),!1):!0:(z.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(z.error(`Invalid Sentry Dsn: Invalid projectId ${t}`),!1)}function ST(i){return i.match(bT)?.[1]}function af(i){let e=i.getOptions(),{host:t}=i.getDsn()||{},r;return e.orgId?r=String(e.orgId):t&&(r=ST(t)),r}function vn(i){let e=typeof i=="string"?wT(i):sf(i);if(!(!e||!kT(e)))return e}var bT,_T,Ht=k(()=>{$e();Ve();bT=/^o(\d+)\./,_T=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/});function of(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 lf=k(()=>{});function wn(i){return!!i.parentSpanId||!!i.dsc}var ET,cf=k(()=>{ET=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$")});function zs(i,e){e?i.refs[Tl]=kr(e):delete i.refs[Tl]}function pf(i){return Ki(i.refs[Tl])}var Tl,Il=k(()=>{$s();Tl="span"});function Ys(i){let{spanId:e,traceId:t,isRemote:r}=i.spanContext(),n=r?e:Sr(i).parent_span_id,s=hi(i).scope,o=r?s?.getPropagationContext().propagationSpanId||hn():e;return{parent_span_id:n,span_id:o,trace_id:t}}function TT(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===xl,attributes:s,...n}))}function IT(i){if(i?.length)return i.map(({context:{spanId:e,traceId:t,traceFlags:r},attributes:n})=>({span_id:e,trace_id:t,sampled:r===xl,attributes:n}))}function Ks(i){return typeof i=="number"?df(i):Array.isArray(i)?i[0]+i[1]/1e9:i instanceof Date?df(i.getTime()):Fs()}function df(i){return i>9999999999?i/1e3:i}function Sr(i){if(ff(i))return i.getStaticSpanJSON();let{spanId:e,traceId:t}=i.spanContext();if(gf(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:mf(i),start_timestamp:Ks(n),timestamp:Ks(o)||void 0,status:xT(l),op:r[rg],origin:r[ng],links:TT(a)}}return{span_id:e,trace_id:t,start_timestamp:0,status:"ok",data:{}}}function Al(i){if(ff(i))return i.getSpanJSON();let{spanId:e,traceId:t}=i.spanContext();if(gf(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:mf(i),start_timestamp:Ks(n),end_timestamp:Ks(o)||void 0,is_segment:uf(i),status:hf(l),attributes:AT(r,l),links:IT(a)}}return{span_id:e,trace_id:t,start_timestamp:0,name:"",status:"ok",is_segment:uf(i),attributes:{}}}function mf(i){return"parentSpanId"in i?i.parentSpanId:"parentSpanContext"in i?i.parentSpanContext?.spanId:void 0}function Qs(i){return{...i,end_timestamp:i.end_timestamp??i.start_timestamp,attributes:hl(i.attributes),links:i.links?.map(e=>({...e,attributes:hl(e.attributes)}))}}function gf(i){let e=i;return!!e.attributes&&!!e.startTime&&!!e.name&&!!e.endTime&&!!e.status}function ff(i){return typeof i.getSpanJSON=="function"}function Js(i){let{traceFlags:e}=i.spanContext();return e===xl}function xT(i){return!i||i.code===wl||i.code===kl?"ok":i.message&&ef(i.message)?i.message:"internal_error"}function hf(i){return!i||i.code===kl||i.code===wl||i.message==="cancelled"?"ok":"error"}function AT(i,e){let t=hf(e)==="error"?e?.message:void 0;return{...t&&{[dg]:t},...i}}function Zs(i){return i[OT]||i}function uf(i){return i===Zs(i)}function kn(i){let e=Ce(),t=Pt(e);return t.getActiveSpan?t.getActiveSpan(i):pf(i||ni())}var xl,OT,Xs,yi=k(()=>{Hs();bl();bt();Ct();fr();tf();Vs();yn();_r();Il();xl=1;OT="_sentryRootSpan",Xs=Zs});function Ol(i){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;let e=i||Bt()?.getOptions();return!!e&&(e.tracesSampleRate!=null||!!e.tracesSampler)}var yf=k(()=>{Ct()});function bf(i){z.log(`Ignoring span ${i.op} - ${i.description} because it matches \`ignoreSpans\`.`)}function Rl(i,e){if(!e?.length)return!1;for(let t of e){if(NT(t)){if(i.description&&gn(i.description,t))return Q&&bf(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&&gn(i.description,t.name):!0,s=t.op?i.op&&gn(i.op,t.op):!0,o=t.attributes?Object.entries(t.attributes).every(([l,a])=>RT(i.attributes?.[l],a)):!0;if(n&&s&&o)return Q&&bf(i),!0}return!1}function RT(i,e){return typeof i=="string"&&(typeof e=="string"||e instanceof RegExp)?gn(i,e):Array.isArray(i)&&Array.isArray(e)?i.length===e.length&&i.every((t,r)=>t===e[r]):i===e}function _f(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 NT(i){return typeof i=="string"||i instanceof RegExp}var vf=k(()=>{$e();Ve();Us()});function kf(i,e){let t={};return e.forEach(r=>{r?.beforeSetup&&r.beforeSetup(i)}),e.forEach(r=>{r&&Pl(i,r,t)}),t}function Nl(i,e){for(let t of e)t?.afterAllSetup&&t.afterAllSetup(i)}function Pl(i,e,t){if(t[e.name]){Q&&z.log(`Integration skipped because it was already installed: ${e.name}`);return}if(t[e.name]=e,!wf.includes(e.name)&&typeof e.setupOnce=="function"&&(e.setupOnce(),wf.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&&z.log(`Integration installed: ${e.name}`)}var wf,Sf=k(()=>{$e();Ve();wf=[]});var bi,Sn=k(()=>{bi="production"});function Ef(i){return!!i&&i[PT]===!0}var PT,Tf=k(()=>{PT=Symbol.for("sentry.nonRecordingSpan")});function Cl(i,e){let t=e.getOptions(),{publicKey:r}=e.getDsn()||{},n={environment:t.environment||bi,release:t.release,public_key:r,trace_id:i,org_id:af(e)};return e.emit("createDsc",n),n}function Er(i,e){if(Gs())return;let t=e.getPropagationContext();return t.dsc||Cl(t.traceId,i)}function si(i){let e=Bt();if(!e)return{};let t=Xs(i),r=Sr(t),n=r.data,s=t.spanContext().traceState,o=s?.get("sentry.sample_rate")??n[Yg]??n[Qg];function l(S){return(typeof o=="number"||typeof o=="string")&&(S.sample_rate=`${o}`),S}let a=t[CT];if(a)return l(a);let c=Ef(t),p=c&&t.dropReason==="ignored";if(c&&(!Ol(e.getOptions())||p)){let S=hi(t).scope,T=S&&Er(e,S);if(T){let A={...T};return p&&(A.sampled="false"),l(A)}}let d=s?.get("sentry.dsc"),g=d&&_n(d);if(g)return l(g);let f=Cl(i.spanContext().traceId,e),_=n[Xo],y=r.description;return _!=="url"&&y&&(f.transaction=y),Ol()&&(f.sampled=String(Js(t)),f.sample_rand=s?.get("sentry.sample_rand")??hi(t).scope?.getPropagationContext().sampleRand.toString()),l(f),e.emit("createDsc",f,t),f}var CT,Tr=k(()=>{Sn();Ct();fr();vl();El();Ht();yf();yi();Tf();Vs();CT="_frozenDsc"});function Af(i,e){let{fingerprint:t,breadcrumbs:r,sdkProcessingMetadata:n}=e;DT(i,e),UT(i,t),MT(i,r),LT(i,n)}function xf(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:f,transactionName:_}=e;En(i,"extra",t),En(i,"tags",r),En(i,"attributes",n),En(i,"user",s),En(i,"contexts",o),i.sdkProcessingMetadata=fi(i.sdkProcessingMetadata,a,2),l&&(i.level=l),_&&(i.transactionName=_),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,...f}}function En(i,e,t){i[e]=fi(i[e],t,1)}function ea(i,e){let t=_l().getScopeData();return i&&xf(t,i.getScopeData()),e&&xf(t,e.getScopeData()),t}function DT(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 MT(i,e){let t=[...i.breadcrumbs||[],...e];i.breadcrumbs=t.length?t:void 0}function LT(i,e){i.sdkProcessingMetadata={...i.sdkProcessingMetadata,...e}}function Of(i,e){i.contexts={trace:Ys(e),...i.contexts},i.sdkProcessingMetadata={dynamicSamplingContext:si(e),...i.sdkProcessingMetadata};let t=Xs(e),r=Sr(t).description;r&&!i.transaction&&i.type==="transaction"&&(i.transaction=r)}function UT(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 Dl=k(()=>{Ct();Tr();Bs();yi()});function Yi(i,e,t){let r;try{r=e()}catch(n){return Rf(i,n,t)}return ii(r)?r.then(void 0,n=>Rf(i,n,t)):r}function Rf(i,e,t){return Q&&z.error(i,e),t(e)}var ta=k(()=>{$e();Ve();it()});function Tn(i){return!!i&&typeof i=="function"&&"_static"in i&&!!i._static}function In(i,e){return Yi(Q?"The `beforeSendSpan` callback threw an error, sending the span unmodified:":"",()=>e(i),()=>i)||i}var Ml=k(()=>{$e();ta()});function Nf(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 Qs(e)}var Pf=k(()=>{yi()});function Cf(i){let e={},{response:t,profile:r,cloud_resource:n,culture:s,state:o}=i;if(t&&(t.status_code!=null&&(e["http.response.status_code"]=t.status_code),t.body_size!=null&&(e["http.response.body.size"]=t.body_size)),r&&(r.profile_id&&(e["sentry.profile_id"]=r.profile_id),r.profiler_id&&(e["sentry.profiler_id"]=r.profiler_id)),n)for(let[c,p]of Object.entries(n))p!=null&&(e[c]=p);s&&(s.locale&&(e["culture.locale"]=s.locale),s.timezone&&(e["culture.timezone"]=s.timezone)),o?.state&&typeof o.state.type=="string"&&(e["state.type"]=o.state.type);let l=i.angular;if(l){let c=l.version;(typeof c=="string"||typeof c=="number")&&(e["angular.version"]=c)}let a=i.react;if(a){let c=a.version;(typeof c=="string"||typeof c=="number")&&(e["react.version"]=c)}return e}var Df=k(()=>{});function Mf(i,e){let t=Al(i);t.attributes&&delete t.attributes[Jg];let r=Zs(i),n=Al(r),{isolationScope:s,scope:o}=hi(i),l=ea(s,o);BT(t,n,e,l),e.emit("preprocessSpan",t),t.is_segment&&(qT(t,l),jT(t,e),e.emit("processSegmentSpan",t)),e.emit("processSpan",t);let{beforeSendSpan:a,traceLifecycle:c}=e.getOptions(),p=c!=="static"&&a&&!Tn(a)?In(t,a):t;return{...Qs(p),_segmentSpan:r}}function qT(i,e){let t=Cf(e.contexts);Ll(i,t)}function Ll(i,e){let t=i.attributes??(i.attributes={});Object.entries(e).forEach(([r,n])=>{n!=null&&!(r in t)&&(t[r]=n)})}function jT(i,e){let t=e.getIntegrationNames();t.length&&Ll(i,{[ag]:t})}function FT(i,e,t,r=!0){let n=e.getSdkMetadata(),{release:s,environment:o}=e.getOptions();return{[ug]:"stream",[pg]:i.name,[cg]:i.span_id,[og]:n?.sdk?.name,[lg]:n?.sdk?.version,[sg]:s,[ig]:o||bi,[fg]:t.user?.id,[gg]:t.user?.email,[hg]:t.user?.ip_address,[yg]:t.user?.username,...r?t.attributes:void 0}}function BT(i,e,t,r){Ll(i,FT(e,t,r))}var Lf=k(()=>{vl();Dl();yi();Vs();Ml();Df();Sn();fr()});function ia(i){return i.getOptions().traceLifecycle==="stream"}var Ul=k(()=>{});function _i(i){return typeof i=="object"&&typeof i.unref=="function"&&i.unref(),i}var xn=k(()=>{});function Xe(i,e=[]){return[i,e]}function jl(i,e){let[t,r]=i;return[t,[...r,e]]}function ra(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 Uf(i,e){return ra(i,(t,r)=>e.includes(r))}function ql(i){let e=lt(pe);return e.encodePolyfill?e.encodePolyfill(i):new TextEncoder().encode(i)}function qf(i){let[e,t]=i,r=JSON.stringify(e);function n(s){typeof r=="string"?r=typeof s=="string"?r+s:[ql(r),s]:r.push(typeof s=="string"?ql(s):s)}for(let s of t){let[o,l]=s;if(n(`
3
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:DT(r)}function DT(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 qf(i){let e=typeof i.data=="string"?ql(i.data):i.data;return[{type:"attachment",length:e.length,filename:i.filename,content_type:i.contentType,attachment_type:i.attachmentType},e]}function MT(i){return i in jf}function Bl(i){return MT(i)?jf[i]:i}function An(i){if(!i?.sdk)return;let{name:e,version:t}=i.sdk;return{name:e,version:t}}function Bf(i,e,t,r){let n=i.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:i.event_id,sent_at:new Date(ze()).toISOString(),...e&&{sdk:e},...!!t&&r&&{dsn:Be(r)},...n&&{trace:n}}}function On(i){return i==="replay_event"?"replay":i||"error"}var jf,Gt=k(()=>{bt();Ht();Us();Rt();xt();jf={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 Ff(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}var Hf=k(()=>{});function Gf(){return!Ff()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}var Wf=k(()=>{Hf()});function Ir(){return typeof window<"u"&&(!Gf()||LT())}function LT(){return pe.process?.type==="renderer"}var sa=k(()=>{Wf();xt()});function Vf(i,e,t){let r=t.getOptions(),n=t.getDsn(),s=r.tunnel,o=An(r._metadata),l={sent_at:new Date(ze()).toISOString(),...UT(e)&&{trace:e},...o&&{sdk:o},...!!s&&n&&{dsn:Be(n)}};return Xe(l,[Fl(i,t)])}function Fl(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:Ir()?{infer_ip:t,infer_user_agent:t}:void 0,items:i}]}function UT(i){return!!i.trace_id&&!!i.public_key}var Hl=k(()=>{Ht();Gt();sa();Rt()});function $f(i){let e=156;if(e+=i.name.length*2,e+=yl(i.attributes),i.links&&i.links.length>0){let r=i.links[0]?.attributes,n=100+(r?yl(r):0);e+=n*i.links.length}return e}var zf=k(()=>{bl()});var Kf,qT,aa,Yf=k(()=>{Ve();$e();xn();Tr();Hl();zf();Kf=1e3,qT=5e6,aa=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<=Kf?r:Kf,this._flushInterval=n&&n>0?n:5e3,this._maxTraceWeight=s&&s>0?s:qT,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:_i(setTimeout(()=>{this.flush(t)},this._flushInterval))},this._traceBuckets.set(t,r)),r.spans.add(e),r.size+=$f(e),(r.spans.size>=this._maxSpanLimit||r.size>=this._maxTraceWeight)&&this.flush(t)}drain(){this._traceBuckets.size&&(Q&&z.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&&z.warn("No segment span reference found on span JSON, cannot compute DSC"),this._removeTrace(e);return}let s=si(n),o=r.map(a=>{let{_segmentSpan:c,...p}=a;return p}),l=Vf(o,s,this._client);Q&&z.log(`Sending span envelope for trace ${e} with ${o.length} spans`),this._client.sendEnvelope(l).then(null,a=>{Q&&z.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 oa,Qf,Jf=k(()=>{Ve();Mf();Ul();Yf();$e();yi();xn();oa="SpanStreaming",Qf=(i={})=>{let e=i.flushOnSegmentEnd??!0;return{name:oa,setup(t){if(!ra(t)){Q&&z.log(`[${oa}] \`traceLifecycle\` is "static", skipping setup.`);return}let r=new aa(t);t.on("afterSpanEnd",n=>{Xs(n)&&r.add(Df(n,t))}),t.on("flushTraceSpans",n=>{r.flush(n)}),e&&t.on("afterSegmentSpanEnd",n=>{let s=n.spanContext().traceId;_i(setTimeout(()=>{r.flush(s)},500))})}}}});function BT(i){return ti(i)?void 0:i}function Xf(i,e,t){let r=BT(e.originalException),n=r&&jT.get(r);if(!n)return;let s=i.contexts?.trace;(s?.trace_id??(t&&zi(t).trace_id))===n.trace_id&&(i.contexts={...i.contexts,trace:{...s,...n}})}var jT,Zf=k(()=>{Ct();it();jT=new WeakMap});function eh(i){lt(Ce()).segmentSpanCaptureStrategy=i}function th(){return lt(Ce()).segmentSpanCaptureStrategy}var ih=k(()=>{bt()});function rh(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 nh=k(()=>{});function Gl(i){if(th()||eh(FT),ca.has(i))return;let e=new Set,t=rh(()=>{let r=[...e];e.clear();for(let n of r)n()},1,{maxWait:100});i.on("flush",()=>{t.flush()}),ca.set(i,r=>{e.add(r),t()})}var la,sh,ah,ca,FT,oh=k(()=>{nh();ih();la=new WeakSet,sh=i=>la.has(i),ah=i=>{la.add(i)},ca=new WeakMap;FT={onSegmentSpanEnded(i,e){let t=e.getClient(),r=t&&ca.get(t);if(!r){let n=i();n&&t?.captureEvent(n);return}r(()=>{let n=i({isSpanAlreadyCaptured:sh,onSpanCaptured:ah});n&&t.captureEvent(n)})},onChildSpanEnded(i,e,t,r){if(la.has(i)||!la.has(e))return;let n=r.getClient(),s=n&&ca.get(n),o=()=>{let l=t({isSpanAlreadyCaptured:sh,onSpanCaptured:ah});l?.contexts?.trace?.data&&(l.contexts.trace.data["sentry.parent_span_already_sent"]=!0),l&&n?.captureEvent(l)};s?s(o):o()}}});function HT(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 lh(i,e,t,r){let n=An(t),s={sent_at:new Date(ze()).toISOString(),...n&&{sdk:n},...!!r&&e&&{dsn:Be(e)}},o="aggregates"in i?[{type:"sessions"},i]:[{type:"session"},i.toJSON()];return Xe(s,[o])}function ch(i,e,t,r){let n=An(t),s=i.type&&i.type!=="replay_event"?i.type:"event";HT(i,t?.sdk);let o=Bf(i,n,r,e);return delete i.sdkProcessingMetadata,Xe(o,[[{type:s},i]])}var ph=k(()=>{Ht();Gt();Rt()});function ai(i){return new pa(e=>{e(i)})}function xr(i){return new pa((e,t)=>{t(i)})}var Wl,dh,uh,pa,Ar=k(()=>{it();Wl=0,dh=1,uh=2;pa=class i{constructor(e){this._state=Wl,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===Wl)return;let e=this._handlers.slice();this._handlers=[],e.forEach(t=>{t[0]||(this._state===dh&&t[1](this._value),this._state===uh&&t[2](this._value),t[0]=!0)})}_runExecutor(e){let t=(s,o)=>{if(this._state===Wl){if(ii(o)){o.then(r,n);return}this._state=s,this._value=o,this._executeHandlers()}},r=s=>{t(dh,s)},n=s=>{t(uh,s)};try{e(r,n)}catch(s){n(s)}}}});function mh(i,e,t,r=0,n){try{let s=Vl(e,t,i,r,n);return ii(s)?s:ai(s)}catch(s){return xr(s)}}function Vl(i,e,t,r,n){let s=t[r];if(!i||!s)return i;let o=`Event processor "${s.id||"?"}"`,l=!1,a=Yi(Q?`${o} threw an error, dropping event:`:"",()=>s({...i},e),()=>(l=!0,null));return Q&&a===null&&z.log(`${o} dropped event`),ii(a)?a.then(c=>c?Vl(c,e,t,r+1,n):(n?.(l?"callback_error":"event_processor"),null)):a?Vl(a,e,t,r+1,n):(n?.(l?"callback_error":"event_processor"),null)}var gh=k(()=>{Ve();$e();it();ia();Ar()});function yh(i){let e=pe._sentryDebugIds,t=pe._debugIds;if(!e&&!t)return{};let r=e?Object.keys(e):[],n=t?Object.keys(t):[];if(vi&&r.length===fh&&n.length===hh)return vi;fh=r.length,hh=n.length,vi={},Qi||(Qi={});let s=(o,l)=>{for(let a of o){let c=l[a],p=Qi?.[a];if(p&&vi&&c)vi[p[0]]=c,Qi&&(Qi[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&&vi&&Qi){vi[v]=c,Qi[a]=[v,c];break}}}}};return e&&s(r,e),t&&s(n,t),vi}var Qi,fh,hh,vi,bh=k(()=>{xt()});function Rn(i){return i.data?.__sentry__===!0}function _h(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 $l=k(()=>{});function vh(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||Hi()},c=t.integrations||i.integrations.map(x=>x.name);GT(a,i),$T(a,c),n&&n.emit("applyFrameMetadata",e),e.type===void 0&&WT(a,i.stackParser);let p=KT(r,t.captureContext);t.mechanism&&Cg(a,t.mechanism);let d=n?n.getEventProcessors():[],g=ta(s,p),f=[...t.attachments||[],...g.attachments];f.length&&(t.attachments=f),xf(a,g);let v=kn(p);v&&Af(a,v),Xf(a,t,p);let y=[...d,...g.eventProcessors],S=e.type==="transaction",T=e.spans?.length||0;return(Rn(t)?ai(a):mh(y,a,t,0,x=>{n&&(n.recordDroppedEvent(x,On(e.type)),S&&n.recordDroppedEvent(x,"span",1+T))})).then(x=>{if(!x)return null;if(S&&n){let C=T-(x.spans?.length||0);C>0&&n.recordDroppedEvent("event_processor","span",C)}return VT(x),typeof o=="number"&&o>0?zT(x,o,l):x})}function GT(i,e){let{environment:t,release:r,dist:n,maxValueLength:s}=e;i.environment=i.environment||t||bi,!i.release&&r&&(i.release=r),!i.dist&&n&&(i.dist=n);let o=i.request;o?.url&&s&&(o.url=mn(o.url,s)),s&&i.exception?.values?.forEach(l=>{l.value&&(l.value=mn(l.value,s))})}function WT(i,e){let t=yh(e);i.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.filename&&(n.debug_id=t[n.filename])})})}function VT(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 $T(i,e){e.length>0&&(i.sdk=i.sdk||{},i.sdk.integrations=[...i.sdk.integrations||[],...e])}function zT(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 KT(i,e){if(!e)return i;let t=i?i.clone():new Je;return t.update(e),t}var wh=k(()=>{Sn();gh();vr();bh();Gt();Zf();$l();ri();Us();Dl();yi();qs();Ar();_r()});function QT(i){let e=i.protocol?`${i.protocol}:`:"",t=i.port?`:${i.port}`:"";return`${e}//${i.host}${t}${i.path?`/${i.path}`:""}/api/`}function JT(i){return`${QT(i)}${i.projectId}/envelope/`}function XT(i,e){let t={sentry_version:YT};return i.publicKey&&(t.sentry_key=i.publicKey),e&&(t.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(t).toString()}function kh(i,e,t){return e||`${JT(i)}?${XT(i,t)}`}var YT,Sh=k(()=>{YT="7"});function Eh(i,e){return e?Vs(e,()=>{let t=kn(),r=t?Qs(t):zi(e);return[t?si(t):Er(i,e),r]}):[void 0,void 0]}var Th=k(()=>{Ct();Tr();yi()});function ZT(i,e){let t=e?"auto":"never";return[{type:"log",item_count:i.length,content_type:"application/vnd.sentry.items.log+json"},{version:2,...Ir()&&{ingest_settings:{infer_ip:t,infer_user_agent:t}},items:i}]}function Ih(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)),Xe(s,[ZT(i,n)])}var xh=k(()=>{Ht();Gt();sa()});function Ah(i,e){let t=e??eI(i)??[];if(t.length===0)return;let r=i.getOptions(),n=Ih(t,r._metadata,r.tunnel,i.getDsn(),i.getDataCollectionOptions().userInfo);Oh().set(i,[]),i.emit("flushLogs"),i.sendEnvelope(n)}function eI(i){return Oh().get(i)}function Oh(){return yt("clientToLogBufferMap",()=>new WeakMap)}var Rh=k(()=>{bt();xh()});function tI(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,...Ir()&&{ingest_settings:{infer_ip:t,infer_user_agent:t}},items:i}]}function Nh(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)),Xe(s,[tI(i,n)])}var Ph=k(()=>{Ht();Gt();sa()});function Ch(i,e){let t=e??iI(i)??[];if(t.length===0)return;let r=i.getOptions(),n=Nh(t,r._metadata,r.tunnel,i.getDsn(),i.getDataCollectionOptions().userInfo);Dh().set(i,[]),i.emit("flushMetrics"),i.sendEnvelope(n)}function iI(i){return Dh().get(i)}function Dh(){return yt("clientToMetricBufferMap",()=>new WeakMap)}var Mh=k(()=>{bt();Ph()});function Lh(i,e){if(i.type!=="transaction"||!i.spans?.length||!i.sdkProcessingMetadata?.hasGenAiSpans||ra(e))return;let t=[],r=[];for(let n of i.spans)n.op?.startsWith("gen_ai.")?t.push(Rf(n)):r.push(n);if(t.length!==0)return i.spans=r,Fl(t,e)}var Uh=k(()=>{Hl();Ul();Nf()});function Or(i=100){let e=new Set;function t(){return e.size<i}function r(o){e.delete(o)}function n(o){if(!t())return xr(Nn);let l=o();return e.add(l),l.then(()=>r(l),()=>r(l)),l}function s(o){if(!e.size)return ai(!0);let l=Promise.allSettled(Array.from(e)).then(()=>!0);if(!o)return l;let a=[l,new Promise(c=>_i(setTimeout(()=>c(!1),o)))];return Promise.race(a)}return{get $(){return Array.from(e)},add:n,drain:s}}var Nn,da=k(()=>{Ar();xn();Nn=Symbol.for("SentryBufferFullError")});function nI(i,e=ze()){let t=parseInt(`${i}`,10);if(!isNaN(t))return t*1e3;let r=Date.parse(`${i}`);return isNaN(r)?rI:r-e}function sI(i,e){return i[e]||i.all||0}function qh(i,e,t=ze()){return sI(i,e)>t}function jh(i,{statusCode:e,headers:t},r=ze()){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 f of c.split(";"))f==="metric_bucket"?(!p||p.split(";").includes("custom"))&&(n[f]=r+g):n[f]=r+g}else o?n.all=r+nI(o,r):e===429&&(n.all=r+60*1e3);return n}var rI,Bh=k(()=>{Rt();rI=60*1e3});function zl(i,e,t=Or(i.bufferSize||Pn)){let r={},n=l=>t.drain(l);function s(l,[a,c],p){let d=Bl(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(na(l,(g,f)=>{qh(r,Bl(f))?s("ratelimit_backoff",g,f):a.push(g)}),a.length===0)return Promise.resolve({});let c=Xe(l[0],a),p=g=>{if(Lf(c,["client_report"])){Q&&z.warn(`Dropping client report. Will not send outcomes (reason: ${g}).`);return}na(c,(f,v)=>{s(g,f,v)})},d=()=>e({body:Uf(c)}).then(g=>g.statusCode===413?(Q&&z.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)&&z.warn(`Sentry responded with status code ${g.statusCode} to sent event.`),r=jh(r,g),g),g=>{throw p("network_error"),Q&&z.error("Encountered error running transport request:",g),g});return t.add(d).then(g=>g,g=>{if(g===Nn)return Q&&z.error("Skipped sending event because buffer is full."),p("queue_overflow"),Promise.resolve({});throw g})}return{send:o,flush:n}}var Pn,ua=k(()=>{Ve();$e();Gt();da();Bh();Pn=64});function Fh(i,e,t){let r=[{type:"client_report"},{timestamp:t||Hi(),discarded_events:i}];return Xe(e?{dsn:e}:{},[r])}var Hh=k(()=>{Gt();_r()});function Gh(i){let{trace_id:e,parent_span_id:t,span_id:r,status:n,origin:s,data:o,op:l}=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,profile_id:o?.[Jo],exclusive_time:o?.[Qo],measurements:i.measurements,is_segment:!0}}function Wh(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,data:{...i.data,...i.profile_id&&{[Jo]:i.profile_id},...i.exclusive_time&&{[Qo]:i.exclusive_time}}}},measurements:i.measurements}}var Vh=k(()=>{fr()});function $h(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 zh=k(()=>{$e()});function aI(i){return typeof i=="boolean"||"allow"in i||"deny"in i}function oI(i){return i===void 0?{...Fe.httpHeaders}:aI(i)?{request:i,response:i}:{request:i.request??Fe.httpHeaders.request,response:i.response??Fe.httpHeaders.response}}function Kh(i){let e=i.dataCollection??{};return{userInfo:e.userInfo??Fe.userInfo,cookies:e.cookies??Fe.cookies,httpHeaders:oI(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,Yh=k(()=>{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 Xh(i){return{message:i,[ny]:!0}}function Kl(i){return{message:i,[sy]:!0}}function Zh(i){return Kl(`Discarding event because it's not included in the random sample (sampling rate = ${i})`)}function ey(i){return dn(i)&&ny in i}function ty(i){return dn(i)&&sy 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??lI;c>0&&(l=!0,o=_i(setTimeout(()=>{n(i)},c)))}}),i.on("flush",()=>{n(i)})}function pI(i,e,t,r,n){let{beforeSend:s,ignoreSpans:o,beforeSendTransaction:l}=i,a=Tn(i.beforeSendSpan)&&i.beforeSendSpan,c=e;if(Yl(c)&&s){let p=c;return Yi(Q?"The `beforeSend` callback threw an error, dropping the event:":"",()=>s(p,t),()=>(r("callback_error"),null))}if(ay(c)){if(a||o){let p=Gh(c);if(o?.length&&Rl({description:p.description,op:p.op,attributes:p.data},o))return r("ignored"),null;if(a){let d=In(p,a);c=fi(e,Wh(d))}if(c.spans){let d=[],g=c.spans;for(let f of g){if(o?.length&&Rl({description:f.description,op:f.op,attributes:f.data},o)){bf(g,f);continue}a?d.push(In(f,a)):d.push(f)}n(g.length-d.length),c.spans=d}}if(l)return Yi(Q?"The `beforeSendTransaction` callback threw an error, dropping the event:":"",()=>l(c,t),()=>(r("callback_error"),null))}return c}function Yl(i){return i.type===void 0}function ay(i){return i.type==="transaction"}function dI(i){let e=0;return i.name&&(e+=i.name.length*2),e+=8,e+oy(i.attributes)}function uI(i){let e=0;return i.message&&(e+=i.message.length*2),e+oy(i.attributes)}function oy(i){if(!i)return 0;let e=0;return Object.values(i).forEach(t=>{Array.isArray(t)?e+=t.length*ry(t[0]):ti(t)?e+=ry(t):e+=100}),e}function ry(i){return typeof i=="string"?i.length*2:typeof i=="number"?8:typeof i=="boolean"?4:0}var Qh,Jh,ny,sy,lI,cI,ma,ly=k(()=>{Sh();Sn();Ct();Ve();ph();kf();Rh();Mh();ul();Tr();Ml();Uh();ua();Hh();$e();Ht();Gt();$l();it();Hs();ri();of();wh();da();Rt();ia();_f();Ar();xn();Vh();zh();Yh();Qh="Not capturing exception because it's already been captured.",Jh="Discarded session because of missing or non-string release",ny=Symbol.for("SentryInternalError"),sy=Symbol.for("SentryDoNotSendEventError"),lI=5e3,cI=Symbol.for("SentryClosedClient");ma=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=Or(e.transportOptions?.bufferSize??Pn),this._dataCollection=Kh(e),this._unhandledSessionStatus="crashed",e.dsn?this._dsn=vn(e.dsn):Q&&z.warn("No DSN provided, client will not send events.");let{beforeSendSpan:t,traceLifecycle:r}=this._options;if(Q&&t&&Tn(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=kh(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",uI,Ah),iy(this,"afterCaptureMetric","flushMetrics",dI,Ch)}captureException(e,t,r){let n=Me();if(Bs(e))return Q&&z.log(Qh),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=pn(e)?e:String(e),l=ti(e),a=l?this.eventFromMessage(o,t,s):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&&Bs(t.originalException))return Q&&z.log(Qh),n;let s={event_id:n,...t},o=e.sdkProcessingMetadata||{},l=o.capturedSpanScope,a=o.capturedSpanIsolationScope,c=On(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,cI,{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(),$h(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),Pl(this,e,this._integrations),t||Nl(this,[e])}sendEvent(e,t={}){this.emit("beforeSendEvent",e,t);let r=Lh(e,this),n=ch(e,this._dsn,this._options._metadata,this._options.tunnel);if(!Rn(t))for(let s of t.attachments||[])n=jl(n,qf(s));r&&(n=jl(n,r)),this.sendEnvelope(n).then(s=>this.emit("afterSendEvent",e,s))}sendSession(e){let{release:t,environment:r=bi}=this._options;if("aggregates"in e){let s=e.attrs||{};if(!s.release&&!t){Q&&z.warn(Jh);return}s.release=s.release||t,s.environment=s.environment||r,e.attrs=s}else{if(!e.release&&!t){Q&&z.warn(Jh);return}e.release=e.release||t,e.environment=e.environment||r}this.emit("beforeSendSession",e);let n=lh(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&&z.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&&z.error("Error while sending envelope:",t),{}}return Q&&z.error("Transport disabled"),{}}registerCleanup(e){}dispose(){}_setupIntegrations(){let{integrations:e}=this._options;this._integrations=wf(this,e),Nl(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),vh(s,e,t,r,this,n).then(l=>{if(l===null)return l;this.emit("postprocessEvent",l,t),l.contexts={trace:{...l.contexts?.trace,...zi(r)},...l.contexts};let a=Er(this,r);return l.sdkProcessingMetadata={dynamicSamplingContext:a,...l.sdkProcessingMetadata},l})}_captureEvent(e,t={},r=ni(),n=$i()){return Q&&Yl(e)&&z.log(`Captured error event \`${_h(e)[0]||"<unknown>"}\``),this._processEvent(e,t,r,n).then(s=>s.event_id,s=>{Q&&(ty(s)?z.log(s.message):ey(s)?z.warn(s.message):z.warn(s))})}_processEvent(e,t,r,n){let s=this.getOptions(),{sampleRate:o}=s,l=ay(e),a=Yl(e),p=`before send for type \`${e.type||"error"}\``,d="before_send",g=0,f=typeof o>"u"?void 0:af(o),v=a&&typeof f=="number"&&_t()>f,y=On(e.type),S=0,T=r.getSession()||n.getSession();return v&&T?.status!=="ok"?(this.recordDroppedEvent("sample_rate","error"),xr(Zh(o))):this._prepareEvent(e,t,r,n).then(A=>{if(A===null)throw Kl("An event processor returned `null`, will not send event.");return S=A.spans?.length||0,Rn(t)?A:pI(s,A,t,x=>{d=x},x=>{g=x})}).then(A=>{if(g&&this.recordDroppedEvent("ignored","span",g),!hr(A)||A===null){if(this.recordDroppedEvent(d,y),l&&this.recordDroppedEvent(d,"span",1+S-g),A!==null)throw Xh(`${p} must return \`null\` or a valid event.`);let q=d==="ignored"?"Transaction matched `ignoreSpans`":`${p} ${d==="callback_error"?"threw an error":"returned `null`"}`;throw Kl(`${q}, will not send event.`)}if(a&&T&&this._updateSessionFromEvent(T,A),v)throw this.recordDroppedEvent("sample_rate","error"),Zh(o);if(l){let q=S-g-(A.spans?.length||0);q>0&&this.recordDroppedEvent("before_send","span",q)}let C=A.transaction_info;if(l&&C&&A.transaction!==e.transaction){let q="custom";A.transaction_info={...C,source:q}}return this.sendEvent(A,t),A}).then(null,A=>{throw ty(A)||ey(A)?A:(this.captureException(A,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:A}),Xh(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
5
- Reason: ${A}`))})}_process(e,t){this._numProcessing++,this._promiseBuffer.add(e).then(r=>(this._numProcessing--,r),r=>(this._numProcessing--,r===Nn&&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&&z.log("Flushing outcomes...");let e=this._clearOutcomes();if(e.length===0){Q&&z.log("No outcomes to send");return}if(!this._dsn){Q&&z.log("No dsn provided, will not send outcomes");return}Q&&z.log("Sending outcomes:",e);let t=Fh(e,this._options.tunnel&&Be(this._dsn));this.sendEnvelope(t)}}});function Ql(){mI.clear(),Q&&z.log("Cleared AI provider skip registrations")}var mI,cy=k(()=>{Ve();$e();mI=new Set});function py(i,e,t,r,n){let s={sent_at:new Date(ze()).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=gI(i);return Xe(s,[o])}function gI(i){return[{type:"check_in"},i]}var dy=k(()=>{Ht();Gt();Rt()});function Jl(i){return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var uy=k(()=>{});function my(i,e,t){let r=_I(e.allowedDsns,i.getDsn()),n={paths:bI(e,r),basePath:e.basePath,allowedDsns:r,forward:t};return fI.set(i,n),n}function gy(i){return i.getIntegrationByName?.(hI)?.forward}function yI(i){let e=i?vn(i):Ft()?.getDsn();return e?`/${vI(Be(e)).toString(36)}`:void 0}function bI(i,e){let t=i.path?.replace(/\/$/,"");if(t)return[t];let r=e.map(n=>yI(n));return[...new Set(r.filter(n=>!!n))]}function fy(i,e){if(!e.length)return[];let r=`${Jl(Xl(i.basePath))}(?:${e.map(Jl).join("|")})/?`;return[{attributes:{[ug]:new RegExp(`^${r}$`)}},{attributes:{"http.url":new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${r}(?:[?#].*)?$`)}}]}function Xl(i){let e=(i?.startsWith("./")?i.slice(1):i??"").replace(/\/$/,"");return!e||e.startsWith("/")?e:`/${e}`}function _I(i,e){let t=new Set;for(let r of[...(i??[]).map(n=>vn(n)),e])r&&t.add(Be(r));return[...t]}function vI(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 fI,hI,hy=k(()=>{Ct();fr();uy();Ht();fI=new WeakMap,hI="ServeTunnel"});function Zl(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:ht})),n.version=ht)}var yy=k(()=>{Ps()});function ec(i){return Array.from(new Set(i))}var by=k(()=>{});function _y(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=ga(i,e,r,s.originalException,t,n.exception.values,o,0))}function ga(i,e,t,r,n,s,o,l){if(s.length>=t+1)return s;let a=[...s];if(Ot(r[n])){tc(o,l,r);let c=i(e,r[n]),p=a.length;ic(c,n,p,l),a=ga(i,e,t,r[n],n,[c,...a],c,p)}return vy(r)&&r.errors.forEach((c,p)=>{if(Ot(c)){tc(o,l,r);let d=i(e,c),g=a.length;ic(d,`errors[${p}]`,g,l),a=ga(i,e,t,c,n,[d,...a],d,g)}}),wI(r)&&["error","suppressed"].forEach(c=>{let p=r[c];if(Ot(p)){tc(o,l,r);let d=i(e,p),g=a.length;ic(d,c,g,l),a=ga(i,e,t,p,n,[d,...a],d,g)}}),a}function vy(i){return Array.isArray(i.errors)}function wI(i){return"error"in i&&"suppressed"in i}function tc(i,e,t){i.mechanism={handled:!0,type:"auto.core.linked_errors",...vy(t)&&{is_exception_group:!0},...i.mechanism,exception_id:e}}function ic(i,e,t,r){i.mechanism={handled:!0,...i.mechanism,type:"chained",source:e,exception_id:t,parent_id:r}}var wy=k(()=>{it()});function ky(i,e){return i(e.stack||"",1)}function kI(i){return Ot(i)&&"__sentry_fetch_url_host__"in i&&typeof i.__sentry_fetch_url_host__=="string"}function SI(i){return kI(i)?`${i.message} (${i.__sentry_fetch_url_host__})`:i.message}function rc(i,e){let t={type:e.name||e.constructor.name,value:SI(e)},r=ky(i,e);return r.length&&(t.stacktrace={frames:r}),t}function EI(i){for(let e in i)if(Object.prototype.hasOwnProperty.call(i,e)){let t=i[e];if(Ot(t))return t}}function TI(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=II(i);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${e}`}function II(i){try{let e=Object.getPrototypeOf(i);return e?e.constructor.name:void 0}catch{}}function xI(i,e,t,r){if(Ot(t))return[t,void 0];if(e.synthetic=!0,hr(t)){let s=i?.getOptions().normalizeDepth,o={__serialized__:ol(t,s)},l=EI(t);if(l)return[l,o];let a=TI(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 Sy(i,e,t,r){let s=r?.data&&r.data.mechanism||{handled:!0,type:"generic"},[o,l]=xI(i,s,t,r),a={exception:{values:[rc(e,o)]}};return l&&(a.extra=l),pl(a,void 0,void 0),js(a,s),{...a,event_id:r?.event_id}}function Ey(i,e,t="info",r,n){let s={event_id:r?.event_id,level:t};if(n&&r?.syntheticException){let o=ky(i,r.syntheticException);o.length&&(s.exception={values:[{value:e,stacktrace:{frames:o}}]},js(s,{synthetic:!0}))}if(pn(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 nc=k(()=>{it();ri();Us();un()});var AI,OI,RI,NI,sc,Ty=k(()=>{wy();nc();AI="cause",OI=5,RI="LinkedErrors",NI=((i={})=>{let e=i.limit||OI,t=i.key||AI;return{name:RI,preprocessEvent(r,n,s){let o=s.getOptions();_y(rc,o.stackParser,t,e,r,n)}}}),sc=NI});function CI(i){let e=i.length>1024?`<truncated>${i.slice(-1024)}`:i,t=PI.exec(e);return t?t.slice(1):[]}function ac(i){let e=CI(i),t=e[0]||"",r=e[1];return!t&&!r?".":(r&&(r=r.slice(0,r.length-1)),t+r)}var PI,Iy=k(()=>{PI=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/});var Wt=k(()=>{oh();Tr();Ct();ml();Gs();bt();vr();ua();cy();Il();yy();by();$s();Ty();xt();$e();ri();Iy();Ds();lf();El();yn();Ps();Rt()});function Ay(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 Oy=k(()=>{});function Ny(i){let e=i?.getOptions(),t=e?._managedTunnel??oc?.tunnel,r=i&&(LI.get(i)??gy(i)??oc?.forward);if(!i||!e||!t||!r)return;let n=Xl(oc?.basePath),s=t.basePath===void 0&&!t.path&&n?{...t,basePath:n}:t;e._managedTunnel=s;let{paths:o}=my(i,s,r),l=Ry.get(i)??[],a=fy(s,o);e.ignoreSpans=[...(e.ignoreSpans??[]).filter(c=>!l.includes(c)),...a],Ry.set(i,a)}var oc,LI,Ry,Py=k(()=>{hy();LI=new WeakMap,Ry=new WeakMap});function Cy(i){let e=$i().getScopeData().sdkProcessingMetadata.requestSession;if(e){let t=i?.mechanism?.handled??!0;t&&e.status!=="crashed"?e.status="errored":t||(e.status="crashed")}}var Cn,Dy=k(()=>{dy();ly();Ct();Ve();Jf();ua();Oy();$e();nc();ri();da();Ar();Th();Py();Cn=class extends ma{constructor(e){Ay(e),(typeof __SENTRY_TRACING__>"u"||__SENTRY_TRACING__)&&e.traceLifecycle!=="static"&&!e.integrations.some(t=>t.name===oa)&&e.integrations.push(Qf()),super(e),this._disposeCallbacks=[],Ny(this),this._setUpMetricsProcessing()}eventFromException(e,t){let r=Sy(this,this._options.stackParser,e,t);return r.level="error",ai(r)}eventFromMessage(e,t="info",r){return ai(Ey(this._options.stackParser,e,t,r,this._options.attachStacktrace))}captureException(e,t,r){return Cy(t),super.captureException(e,t,r)}captureEvent(e,t,r){return!e.type&&e.exception?.values&&e.exception.values.length>0&&Cy(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&&z.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]=Eh(this,r);d&&(c.contexts={trace:d});let g=py(c,p,this.getSdkMetadata(),a,this.getDsn());return Q&&z.log("Sending checkin:",e.monitorSlug,e.status),this.sendEnvelope(g),n}registerCleanup(e){this._disposeCallbacks.push(e)}dispose(){Q&&z.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=Or(Pn)}_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={"server.address":this._options.serverName,...e.attributes})})}}});function Ly(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 Uy(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=wg(o[2]),f=o[5]==="native";!g&&o[5]&&!f&&(g=o[5]);let v=g?UI(g):void 0;return{filename:v??g,module:v&&i?.(v),function:c,lineno:My(o[3]),colno:My(o[4]),in_app:Ly(g||"",f)}}if(n.match(e))return{filename:n}}}function lc(i){return[90,Uy(i)]}function My(i){return parseInt(i||"",10)||void 0}function UI(i){try{return decodeURI(i)}catch{return}}var qy=k(()=>{Ds()});var cc=k(()=>{Dy();qy()});var wi,pc=k(()=>{wi="1.10.0"});function qI(i){let e=new Set([i]),t=new Set,r=i.match(jy);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(jy);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 jy,By,Fy=k(()=>{pc();jy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;By=qI(wi)});function BI(){return Object.defineProperty({},"version",{value:wi,enumerable:!0,writable:!1,configurable:!1})}function Rr(i,e,t,r=!1){var n;let s=ha[fa]=(n=ha[fa])!==null&&n!==void 0?n:BI();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${wi}`);return t.error(o.stack||o.message),!1}return s[i]=e,t.debug(`@opentelemetry/api: Registered a global for ${i} v${wi}.`),!0}function oi(i){let e=ha[fa];if(e!=null){if(e!==Hy){if(!e.version||!By(e.version))return;Hy=e}return e[i]}}function Nr(i,e){e.debug(`@opentelemetry/api: Unregistering a global for ${i} v${wi}.`);let t=ha[fa];t&&delete t[i]}var jI,fa,ha,Hy,Dn=k(()=>{pc();Fy();jI=wi.split(".")[0],fa=Symbol.for(`opentelemetry.js.api.${jI}`),ha=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function Mn(i,e,t){let r=oi("diag");if(r)return r[i](e,...t)}var Gy,Wy=k(()=>{Dn();Gy=class{constructor(i){this._namespace=i.namespace||"DiagComponentLogger"}debug(...i){return Mn("debug",this._namespace,i)}error(...i){return Mn("error",this._namespace,i)}info(...i){return Mn("info",this._namespace,i)}warn(...i){return Mn("warn",this._namespace,i)}verbose(...i){return Mn("verbose",this._namespace,i)}}});function Vy(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 $y=k(()=>{});var FI,Ji,dc=k(()=>{Dn();Wy();$y();FI="diag",Ji=class zy{static instance(){return this._instance||(this._instance=new zy),this._instance}constructor(){function e(n){return function(...s){let o=oi("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=oi("diag"),c=Vy((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 Rr("diag",c,t,!0)};t.setLogger=r,t.disable=()=>{Nr(FI,t)},t.createComponentLogger=n=>new Gy(n),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}});function li(i){return Symbol.for(i)}var Ln,ya=k(()=>{Ln=new class uc{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 uc(t._currentContext);return s._currentContext.set(r,n),s},t.deleteValue=r=>{let n=new uc(t._currentContext);return n._currentContext.delete(r),n}}}});var mc,Ky=k(()=>{mc=(function(i){return i[i.NONE=0]="NONE",i[i.SAMPLED=1]="SAMPLED",i})({})});var HI,GI,Yy,Qy=k(()=>{HI="0000000000000000",GI="00000000000000000000000000000000",Yy={traceId:GI,spanId:HI,traceFlags:0}});var ki,ba=k(()=>{Qy();ki=class{constructor(i=Yy){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 Jy(i,e){if(typeof i!="string"||i.length!==e)return!1;let t=0;for(let r=0;r<i.length;r+=4)t+=(_a[i.charCodeAt(r)]|0)+(_a[i.charCodeAt(r+1)]|0)+(_a[i.charCodeAt(r+2)]|0)+(_a[i.charCodeAt(r+3)]|0);return t===e}function Xy(i){return Jy(i,32)&&i!=="00000000000000000000000000000000"}function Zy(i){return Jy(i,16)&&i!=="0000000000000000"}function Xi(i){return Xy(i.traceId)&&Zy(i.spanId)}function eb(i){return new ki(i)}var _a,va=k(()=>{ba();_a=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 tb,ib=k(()=>{ya();tb=class{active(){return Ln}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 gc,WI,VI,Pr,wa=k(()=>{Dn();dc();ib();gc="context",WI=new tb,VI=Object.freeze({dispose:()=>{}}),Pr=class rb{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new rb),this._instance}setGlobalContextManager(e){return Rr(gc,e,Ji.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,Ji.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.")),VI)}_getContextManager(){return oi(gc)||WI}disable(){this._getContextManager().disable(),Nr(gc,Ji.instance())}}});function ka(i){return i.getValue(fc)||void 0}function nb(){return ka(Pr.getInstance().active())}function Un(i,e){return i.setValue(fc,e)}function sb(i){return i.deleteValue(fc)}function ab(i,e){return Un(i,new ki(e))}function Sa(i){var e;return(e=ka(i))===null||e===void 0?void 0:e.spanContext()}var fc,hc=k(()=>{ya();wa();ba();fc=li("OpenTelemetry Context Key SPAN")});function $I(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 yc,Ea,bc=k(()=>{wa();ba();hc();va();yc=Pr.getInstance(),Ea=class{startSpan(i,e,t=yc.active()){if(e?.root)return new ki;let r=t&&Sa(t);return $I(r)&&Xi(r)?new ki(r):new ki}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:yc.active(),c=this.startSpan(i,s,a),p=Un(a,c);return yc.with(p,l,void 0,c)}}});var zI,ob,lb=k(()=>{bc();zI=new Ea,ob=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):zI}}});var cb,pb=k(()=>{bc();cb=class{getTracer(i,e,t){return new Ea}}});var KI,_c,db=k(()=>{lb();pb();KI=new cb,_c=class{getTracer(i,e,t){var r;return(r=this.getDelegateTracer(i,e,t))!==null&&r!==void 0?r:new ob(this,i,e,t)}getDelegate(){var i;return(i=this._delegate)!==null&&i!==void 0?i:KI}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 Ke,ub=k(()=>{wa();Ke=Pr.getInstance()});var vc,mb,fb=k(()=>{Dn();dc();hc();va();db();vc="trace",mb=class gb{constructor(){this._proxyTracerProvider=new _c,this.wrapSpanContext=eb,this.isSpanContextValid=Xi,this.deleteSpan=sb,this.getSpan=ka,this.getActiveSpan=nb,this.getSpanContext=Sa,this.setSpan=Un,this.setSpanContext=ab}static getInstance(){return this._instance||(this._instance=new gb),this._instance}setGlobalTracerProvider(e){let t=Rr(vc,this._proxyTracerProvider,Ji.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return oi(vc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){Nr(vc,Ji.instance()),this._proxyTracerProvider=new _c}}});var Si,hb=k(()=>{fb();Si=mb.getInstance()});var Ta=k(()=>{ya();Ky();va();ub();hb()});import{AsyncLocalStorage as QI}from"node:async_hooks";function wc(){let e=Pt(Ce()).getTracingChannelBinding?.()?.asyncLocalStorage??new QI;function t(){let l=e.getStore();return l||{scope:Wi(),isolationScope:Vi()}}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 wn(a.getPropagationContext())||a.setPropagationContext({traceId:Gi(),sampleRand:_t()}),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 bn({withScope:r,withSetScope:n,withIsolationScope:s,withSetIsolationScope:o,getCurrentScope:()=>t().scope,getIsolationScope:()=>t().isolationScope,getTracingChannelBinding:()=>({asyncLocalStorage:e})}),e}var yb=k(()=>{Wt()});function K(i){return[...new Set(i.map(e=>e.module.name))]}var ce=k(()=>{});var kc,LB,bb=k(()=>{ce();kc=[{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"}}],LB=K(kc)});var Dt,Sc,jB,_b=k(()=>{ce();Dt={name:"amqplib",versionRange:">=0.5.5 <3"},Sc=[...["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"}}],jB=K(Sc)});var Ec,HB,vb=k(()=>{ce();Ec=[...["resources/messages/messages.js","resources/messages/messages.mjs"].map(i=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <1",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 <1",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 <1",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 <1",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 <1",filePath:i},functionQuery:{className:"SessionToolRunner"}}))],HB=K(Ec)});var Cr,wb,kb=k(()=>{Cr={name:"dataloader",versionRange:">=2.0.0 <3",filePath:"index.js"},wb=[{channelName:"construct",module:Cr,functionQuery:{functionName:"DataLoader",kind:"Sync"}},{channelName:"load",module:Cr,functionQuery:{expressionName:"load",kind:"Async"}},{channelName:"loadMany",module:Cr,functionQuery:{expressionName:"loadMany",kind:"Async"}},{channelName:"prime",module:Cr,functionQuery:{expressionName:"prime",kind:"Sync"}},{channelName:"clear",module:Cr,functionQuery:{expressionName:"clear",kind:"Sync"}},{channelName:"clearAll",module:Cr,functionQuery:{expressionName:"clearAll",kind:"Sync"}}]});var Tc,$B,Sb=k(()=>{ce();Tc=[{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"}}],$B=K(Tc)});var JI,XI,ZI,ex,tx,Ic,YB,Eb=k(()=>{ce();JI=">=3.0.0 <5",XI=/dist\/lite\/(index|common-[^/]+)\.node\.(cjs\.js|mjs)$/,ZI=[{functionName:"addDoc",channelName:"add-doc"},{functionName:"getDocs",channelName:"get-docs"},{functionName:"setDoc",channelName:"set-doc"},{functionName:"deleteDoc",channelName:"delete-doc"}],ex=">=6.0.0 <7",tx=[{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"}],Ic=[...ZI.map(({functionName:i,channelName:e})=>({channelName:e,module:{name:"@firebase/firestore",versionRange:JI,filePath:XI},functionQuery:{functionName:i,kind:"Auto"}})),...tx.map(({file:i,functionName:e,channelName:t})=>({channelName:t,module:{name:"firebase-functions",versionRange:ex,filePath:i},functionQuery:{functionName:e,kind:"Sync"}}))],YB=K(Ic)});var xc,XB,Tb=k(()=>{ce();xc=[{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"}}],XB=K(xc)});var Ac,Oc,tF,Ib=k(()=>{ce();Ac=["dist/node/index.js","dist/node/index.mjs","dist/node/index.cjs"],Oc=[...Ac.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"}}))),...Ac.map(i=>({channelName:"embed-content",module:{name:"@google/genai",versionRange:">=0.10.0 <3",filePath:i},functionQuery:{className:"Models",methodName:"embedContent",kind:"Auto"}})),...Ac.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"}})))],tF=K(Oc)});var Rc,nF,xb=k(()=>{ce();Rc=[...["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"}}))],nF=K(Rc)});function qn(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 Nc=k(()=>{});var Pc,cF,Ab=k(()=>{ce();Nc();Pc=qn({name:"groq-sdk",versionRange:">=0.3.0 <2"}),cF=K(Pc)});var Cc,uF,Ob=k(()=>{ce();Cc=[{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"}}],uF=K(Cc)});var ix,Dc,fF,Rb=k(()=>{ce();ix=[{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"}}],Dc=ix,fF=K(Dc)});function rt(i){return{channelName:"module-registration",module:i,astQuery:"Program",transform:rx}}var rx,Ei=k(()=>{rx="sentryModuleRegistration"});var Mc,vF,Nb=k(()=>{ce();Ei();Mc=[rt({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"}}],vF=K(Mc)});var Lc,SF,Pb=k(()=>{ce();Lc=[{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"}}],SF=K(Lc)});function ox(i,e){return{channelName:"query",module:{name:Cb,versionRange:e,filePath:i},functionQuery:{className:"Runner",methodName:"query",kind:"Async"}}}function lx(i,e,t){return{channelName:i,module:{name:Cb,versionRange:t,filePath:e},functionQuery:{className:"Client",methodName:i,kind:"Sync"}}}var Cb,nx,sx,ax,Db,Mb=k(()=>{Cb="knex",nx=[{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"}],sx=[{filePath:"lib/client.js",versionRange:">=0.10.0 <4"},{filePath:"src/client.js",versionRange:">=0.18.0 <0.19.0"}],ax=["queryBuilder","schemaBuilder","raw"];Db=[...nx.map(({filePath:i,versionRange:e})=>ox(i,e)),...sx.flatMap(({filePath:i,versionRange:e})=>ax.map(t=>lx(t,i,e)))]});var Uc,xF,Lb=k(()=>{ce();Uc=[{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"}}],xF=K(Uc)});var cx,qc,Ia,Ub,px,dx,jc,RF,NF,qb=k(()=>{ce();cx=["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"}}]}),qc="embedQuery",Ia="embedDocuments",Ub=[{name:"@langchain/openai",versionRange:">=0.1.0 <2.0.0",methods:[qc,Ia]},{name:"@langchain/google-genai",versionRange:">=0.1.0 <3.0.0",methods:[qc,Ia]},{name:"@langchain/mistralai",versionRange:">=0.1.0 <2.0.0",methods:[qc,Ia]},{name:"@langchain/google-common",versionRange:">=0.1.0 <3.0.0",methods:[Ia]}],px=Ub.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"}})))),dx=["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"}})),jc=[...cx,...px,...dx],RF=Ub.flatMap(({name:i,methods:e})=>e.map(t=>`orchestrion:${i}:${t}`)),NF=K(jc)});var jb,ux,mx,Bc,DF,Bb=k(()=>{ce();jb=i=>({name:"@langchain/langgraph",versionRange:">=0.0.0 <2.0.0",filePath:i}),ux=["dist/graph/state.cjs","dist/graph/state.js"].map(i=>({channelName:"stateGraphCompile",module:jb(i),functionQuery:{className:"StateGraph",methodName:"compile",kind:"Sync"}})),mx=["dist/prebuilt/react_agent_executor.cjs","dist/prebuilt/react_agent_executor.js"].map(i=>({channelName:"createReactAgent",module:jb(i),functionQuery:{functionName:"createReactAgent",kind:"Sync"}})),Bc=[...ux,...mx],DF=K(Bc)});var Fc,UF,Fb=k(()=>{ce();Fc=[{channelName:"load",module:{name:"lru-memoizer",versionRange:">=2.1.0 <4",filePath:"lib/async.js"},functionQuery:{functionName:"memoizedFunction",kind:"Callback"}}],UF=K(Fc)});var Hb,Gb=k(()=>{Ei();Hb=[rt({name:"@flue/runtime",versionRange:">=2.0.0 <3.0.0",filePath:"dist/index.mjs"})]});var gx,fx,hx,Hc,HF,Wb=k(()=>{ce();gx=[{channelName:"mastraConstructor",module:{name:"@mastra/core",versionRange:">=1.63.2 <2.0.0",filePath:/^dist\/(?:[\w.-]+\/)?mastra[\w.-]*\.(?:cjs|mjs|js)$/},functionQuery:{className:"Mastra"}}],fx=["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"}})),hx=[{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"}}],Hc=[...gx,...fx,...hx],HF=K(Hc)});var Vb,Gc,VF,$b=k(()=>{ce();Vb={name:"@earendil-works/pi-durable",versionRange:">=1.0.0 <2.0.0"},Gc=[{channelName:"harnessOpen",module:{...Vb,filePath:"dist/harness/harness.js"},functionQuery:{methodName:"open",kind:"Async"}},...[["bash","createBashTool"],["read","createReadTool"],["edit","createEditTool"],["write","createWriteTool"]].map(([i,e])=>({channelName:"codingTool",module:{...Vb,filePath:`dist/tools/${i}.js`},functionQuery:{functionName:e,kind:"Sync"}}))],VF=K(Gc)});var yx,bx,Wc,KF,zb=k(()=>{ce();yx=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/server",versionRange:">=2.0.0 <3",filePath:/^dist\/mcp-[\w-]+\.(?:cjs|mjs)$/},functionQuery:{className:"McpServer"}}],bx=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/sdk",versionRange:">=1.9.0 <2",filePath:/(?:^|\/)server\/mcp\.js$/},functionQuery:{className:"McpServer"}}],Wc=[...yx,...bx],KF=K(Wc)});var Vc,xa,Kb,$c,JF,Yb=k(()=>{ce();Vc={name:"@mistralai/mistralai",versionRange:">=2.0.0 <3"},xa={...Vc,filePath:"esm/sdk/chat.js"},Kb={...Vc,filePath:"esm/sdk/agents.js"},$c=[{channelName:"chat",module:xa,functionQuery:{className:"Chat",methodName:"complete",kind:"Auto"}},{channelName:"chat",module:xa,functionQuery:{className:"Chat",methodName:"parse",kind:"Auto"}},{channelName:"chat-stream",module:xa,functionQuery:{className:"Chat",methodName:"stream",kind:"Auto"}},{channelName:"chat-stream",module:xa,functionQuery:{className:"Chat",methodName:"parseStream",kind:"Auto"}},{channelName:"embeddings",module:{...Vc,filePath:"esm/sdk/embeddings.js"},functionQuery:{className:"Embeddings",methodName:"create",kind:"Auto"}},{channelName:"agents",module:Kb,functionQuery:{className:"Agents",methodName:"complete",kind:"Auto"}},{channelName:"agents-stream",module:Kb,functionQuery:{className:"Agents",methodName:"stream",kind:"Auto"}}],JF=K($c)});var Zi,zc,eH,Qb=k(()=>{ce();Zi={name:"mongodb"},zc=[{channelName:"command",module:{...Zi,versionRange:">=6.4.0 <8",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Async"}},{channelName:"command",module:{...Zi,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Callback"}},{channelName:"checkout",module:{...Zi,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:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/index.js"},functionQuery:{expressionName:i,kind:"Callback"}})),{channelName:"v3_command",module:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/command.js"},functionQuery:{functionName:"command",kind:"Callback"}},{channelName:"v3_query",module:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/query.js"},functionQuery:{functionName:"query",kind:"Callback"}},{channelName:"v3_get_more",module:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/get_more.js"},functionQuery:{functionName:"getMore",kind:"Callback"}}],eH=K(zc)});var Ti,Jb,Kc,nH,sH,Xb=k(()=>{ce();Ei();Ti={name:"mongoose",versionRange:">=5.9.7 <9.7.0"},Jb=["find","findOne","deleteOne","deleteMany","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace","remove","count","findOneAndRemove"],Kc=[rt({name:"mongoose",versionRange:">=9.7.0",filePath:"lib/query.js"}),{channelName:"query_exec",module:{...Ti,filePath:"lib/query.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"aggregate_exec",module:{...Ti,filePath:"lib/aggregate.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"model_save",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"save",kind:"Auto"}},{channelName:"model_insert_many",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"insertMany",kind:"Auto"}},{channelName:"model_bulk_write",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"bulkWrite",kind:"Auto"}},{channelName:"model_remove",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"remove",kind:"Auto"}},{channelName:"model_aggregate",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"aggregate",kind:"Sync"}},...Jb.map(i=>({channelName:`ctx_${i}`,module:{...Ti,filePath:"lib/query.js"},functionQuery:{expressionName:i,kind:"Sync"}}))],nH=K(Kc),sH=Jb.map(i=>`orchestrion:mongoose:ctx_${i}`)});var Yc,cH,Zb=k(()=>{ce();Ei();Yc=[rt({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"}}],cH=K(Yc)});var Qc,uH,e_=k(()=>{ce();Qc=[{channelName:"query",module:{name:"mysql",versionRange:">=2.0.0 <3",filePath:"lib/Connection.js"},functionQuery:{expressionName:"query",kind:"Auto"}}],uH=K(Qc)});var Jc,Xc,fH,t_=k(()=>{ce();Jc={name:"@neondatabase/serverless",versionRange:">=1.0.0 <2",filePath:/^index\.m?js$/},Xc=[{channelName:"query",module:Jc,astQuery:'ClassBody:has(MethodDefinition[key.name="_pulseQueryQueue"]) > MethodDefinition[key.name="query"] > FunctionExpression',functionQuery:{methodName:"query",kind:"Auto"}},{channelName:"http-query",module:Jc,astQuery:'FunctionDeclaration[async=true]:has(Literal[value="Neon-Connection-String"])',functionQuery:{kind:"Async"}},{channelName:"resolve-connection",module:Jc,astQuery:'FunctionDeclaration[async=true]:has(ReturnStatement > ObjectExpression > Property[key.name="resolvedURL"])',functionQuery:{kind:"Async"}}],fH=K(Xc)});var i_,r_=k(()=>{i_=[{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:"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 n_,s_=k(()=>{Ei();n_=[rt({name:"h3",versionRange:">=2.0.0-0",filePath:"dist/h3.mjs"})]});var Zc,wH,a_=k(()=>{ce();Zc=[...["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"}}))],wH=K(Zc)});var ep,EH,o_=k(()=>{ce();ep=[{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"}}],EH=K(ep)});var _x,tp,xH,l_=k(()=>{ce();_x=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"}}],tp=["src","cjs/src"].flatMap(_x),xH=K(tp)});function c_(i,e){return{channelName:i,module:{name:vx,versionRange:kx,filePath:wx},functionQuery:{className:"CollectionBase",methodName:i,kind:e}}}var vx,wx,kx,Sx,Ex,ip,RH,p_=k(()=>{ce();vx="@prisma/orm-family-sql",wx="dist/orm-client.mjs",kx=">=8.0.0-rc.15 <9",Sx=["aggregate","first","create","createAndCount","upsert","update","updateAndCount","delete","deleteAndCount"],Ex=["all","createAll","updateAll","deleteAll"];ip=[...Sx.map(i=>c_(i,"Async")),...Ex.map(i=>c_(i,"Sync"))],RH=K(ip)});var rp,DH,d_=k(()=>{ce();Ei();rp=[rt({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"}}],DH=K(rp)});var Tx,u_,m_=k(()=>{Tx=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"}}],u_=["dist","dist/esm"].flatMap(Tx)});var g_,f_=k(()=>{g_=[{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 Ix,xx,Ax,Ox,np,jH,h_=k(()=>{ce();Ix="tedious",xx="lib/connection.js",Ax=">=1.11.0 <21",Ox=["connect","execSql","execSqlBatch","callProcedure","execBulkLoad","prepare","execute"],np=Ox.map(i=>({channelName:i,module:{name:Ix,versionRange:Ax,filePath:xx},functionQuery:{className:"Connection",methodName:i,kind:"Sync"}})),jH=K(np)});var sp,GH,y_=k(()=>{ce();Nc();sp=[...qn({name:"together-ai",versionRange:">=0.6.0 <1"}),...qn({name:"together-ai",versionRange:">=1.0.0 <2"},{chat:"BaseCompletions",embeddings:"BaseEmbeddings"})],GH=K(sp)});var ap,$H,b_=k(()=>{ce();ap=["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"}})),$H=K(ap)});function er(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 op,QH,__=k(()=>{ce();Ei();op=[...["dist/index.js","dist/index.mjs"].map(i=>rt({name:"ai",versionRange:">=7.0.0",filePath:i})),...er(">=4.0.0 <7.0.0","generateText","generateText","Async"),...er(">=4.0.0 <7.0.0","streamText","streamText","Sync"),...er(">=4.0.0 <7.0.0","generateObject","generateObject","Async"),...er(">=4.0.0 <7.0.0","embed","embed","Async"),...er(">=4.0.0 <7.0.0","embedMany","embedMany","Async"),...er(">=5.0.0 <7.0.0","resolveLanguageModel","resolveLanguageModel","Sync"),...er(">=6.0.0 <7.0.0","executeToolCall","executeToolCall","Async")];QH=K(op)});function Rx(i=[]){return[...ec([...v_,...i].map(e=>e.module.name)),"@remix-run/node"]}var v_,jn,FG,w_=k(()=>{Wt();bb();_b();vb();kb();Sb();Eb();Tb();Ib();xb();Ab();Ob();Rb();Nb();Pb();Mb();Lb();qb();Bb();Fb();Gb();Wb();$b();zb();Yb();Qb();Xb();Zb();e_();t_();r_();s_();a_();o_();l_();p_();d_();m_();f_();h_();y_();b_();__();v_=[...Sc,...Ec,...kc,...wb,...Tc,...Ic,...xc,...Oc,...Rc,...Pc,...Cc,...Dc,...Mc,...Lc,...Db,...Uc,...jc,...Bc,...Fc,...Hb,...Hc,...Wc,...$c,...zc,...Kc,...Yc,...Qc,...Xc,...i_,...n_,...Zc,...ep,...Gc,...tp,...ip,...rp,...u_,...g_,...np,...sp,...ap,...op],jn=v_.filter(i=>!i.transform);FG=Rx()});var k_=k(()=>{yb()});var S_,E_=k(()=>{S_=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});import{posix as Nx,sep as Px}from"node:path";function T_(i){return i.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function I_(i=process.argv[1]?ac(process.argv[1]):process.cwd(),e=Px==="\\"){let t=e?T_(i):i;return r=>{if(!r)return;let n=e?T_(r):r,{dir:s,base:o,ext:l}=Nx.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 x_=k(()=>{Wt()});var lp,A_=k(()=>{Wt();cc();x_();lp=rl(lc(I_()))});import{AsyncLocalStorage as Cx}from"node:async_hooks";function N_(i){return i.getValue(fp)}function Mx(i,e){return i.setValue(fp,e)}function Lx(i,e){i.refs[R_]=kr(e)}function P_(i){return Ki(i.refs[R_])}function Ux(i,e){let t=i?Si.setSpan(Ke.active(),i):Si.deleteSpan(Ke.active());return Ke.with(t,()=>{let r=ni();return Ks(r,i??void 0),e(r)})}function qx(i){let e=i?jx(i):Si.getActiveSpan();return e&&Xi(e.spanContext())?e:void 0}function jx(i){let e=P_(i);return e?Si.getSpan(e):void 0}function Bx(i){let e=N_(i),t=e?.scope||ni(),r=e?.isolationScope||$i(),n=i.getValue(dp)===!0,s=i.getValue(up),o=i.getValue(mp),l=s||t.clone(),a=o||(n?r.clone():r),d=Mx(i,{scope:l,isolationScope:a}).deleteValue(dp).deleteValue(up).deleteValue(mp);return Lx(l,d),d}function Hx(i){if(typeof i!="object"||!i)return!1;let e=i;return typeof e.on=="function"&&typeof e.emit=="function"}function cp(i,e){let t=i[e];return typeof t=="function"?t:void 0}function pp(i,e,t){try{i[e]=t}catch{}}function C_(){let e=Pt(Ce()).getTracingChannelBinding?.()?.asyncLocalStorage??new Cx;function t(){let d=Ke.active(),g=N_(d);return g||{scope:Wi(),isolationScope:Vi()}}function r(d){let g=Ke.active();return Ke.with(g,()=>d(l()))}function n(d,g){let f=P_(d)||Ke.active();return Ke.with(f.setValue(up,d),()=>g(d))}function s(d){let g=Ke.active();return Ke.with(g.setValue(dp,!0),()=>{let f=l();return wn(f.getPropagationContext())||f.setPropagationContext({traceId:Gi(),sampleRand:_t()}),d(a())})}function o(d,g){let f=Ke.active();return Ke.with(f.setValue(mp,d),()=>g(a()))}function l(){return t().scope}function a(){return t().isolationScope}function c(){return{asyncLocalStorage:e}}bn({withScope:r,withSetScope:n,withSetIsolationScope:o,withIsolationScope:s,getCurrentScope:l,getIsolationScope:a,getActiveSpan:qx,withActiveSpan:Ux,getTracingChannelBinding:c});let p=new gp(e);return Ke.setGlobalContextManager(p),p.getAsyncLocalStorageLookup()}function Gx(i){let{traceFlags:e,traceState:t}=i,r=t?t.get(Dx)==="1":!1;if(e===mc.SAMPLED)return!0;if(r)return!1;let n=t?t.get(O_):void 0,s=n?_n(n):void 0;if(s?.sampled==="true")return!0;if(s?.sampled==="false")return!1}function D_(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=si(r),a=typeof l.sample_rand=="string"?Number(l.sample_rand):void 0,c=!!o?.get(O_),p=t.clone();p.setPropagationContext({traceId:s,parentSpanId:n,sampled:Gx(r.spanContext()),dsc:c?l:void 0,sampleRand:typeof a=="number"&&!Number.isNaN(a)?a:_t()}),Ks(p,void 0),e.scope=p,e.parentSpan=void 0})}var O_,Dx,fp,dp,up,mp,R_,g5,Fx,gp,M_=k(()=>{Wt();Ta();Ta();O_="sentry.dsc",Dx="sentry.sampled_not_recording",fp=li("sentry_scopes"),dp=li("sentry_fork_isolation_scope"),up=li("sentry_fork_set_scope"),mp=li("sentry_fork_set_isolation_scope"),R_="context";g5=li("OpenTelemetry SDK Context Key SUPPRESS_TRACING");Fx=["addListener","on","once","prependListener","prependOnceListener"],gp=class{constructor(e){this._kOtListeners=Symbol("OtListeners"),this._wrapped=!1,this._asyncLocalStorage=e}active(){return this._asyncLocalStorage.getStore()??Ln}with(e,t,r,...n){let s=Bx(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 Hx(t)?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:fp}}_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 Fx){let s=cp(t,n);s&&pp(t,n,this._patchAddListener(t,s,e))}for(let n of["removeListener","off"]){let s=cp(t,n);s&&pp(t,n,this._patchRemoveListener(t,s))}let r=cp(t,"removeAllListeners");return r&&pp(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 Dr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function L_(i){return i&&Object.prototype.hasOwnProperty.call(i,"default")&&Object.keys(i).length===1?i.default:i}var Bn=k(()=>{});function Wx(i,e){let[t]=j_(i,"");for(let r of $x(e))if(Vx(r,t))return!0;return!1}function Vx(i,e){for(let[t,r]of i)if(!Yx(e,r,t))return!1;return!0}function U_(i){return i==="latest"&&(i=">=0"),i.match(/^([^\d+]*)(\d.*)$/)||[null,"","*.*.*"]}function $x(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=U_(s),l=o[1]||"=";l.endsWith("v")&&(l=l.slice(0,-1));let[a,c]=j_(o[2],l);if(n+2<r.length&&r[n+1]==="-"){let p=U_(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?Mr(a,0):Mr(a,1)])}else if(c[0]==="^"){let p=a[0]!==0?0:a[1]!==0?1:2;t.push([">=",a]),t.push(["<",p===0?Mr(a,0):p===1?Mr(a,1):Mr(a,2)])}else t.push([c.replace("~","").replace("^",""),a])}return t.length&&e.push(t),e}function Mr(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 zx(i){return i==="x"||i==="X"||i==="*"||i==="latest"?-1:Number(i)}function Kx(i){return/^\d+$/.test(i)?Number(i):i}function Ii(i,e,t){return t===-1?i!=="<":i==="="?e===t:i===">"?e>t:i===">="?e>=t:i==="<"?e<t:i==="<="?e<=t:!1}function j_(i,e){i=i.split("+")[0];let[t,r]=i.split("-"),n=t.split(".").map(zx).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(Kx)),e]:[n.slice(0,3),e]}function Yx(i,e,t){if(!Ii("=",i[0],e[0]))return Ii(t,i[0],e[0]);if(!Ii("=",i[1],e[1]))return Ii(t,i[1],e[1]);if(!Ii("=",i[2],e[2])||i.length===3&&e.length===3)return Ii(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(Ii(t,i[r]||"",e[r]||""))return!0;return!1}var q_,B_=k(()=>{q_=Wx});function yp(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 _p(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)||V_(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 Qx(i){return(function(e){if(Array.isArray(e))return yp(e)})(i)||(function(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)})(i)||V_(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 Fn(i){return(Fn=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 V_(i,e){if(i){if(typeof i=="string")return yp(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)?yp(i,e):void 0}}function $_(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 He(i){if(i==null)return function(){return!0};if(hp!=null){var e=hp.get(i);return e!=null||(e=F_(i),hp.set(i,e)),e}return F_(i)}function F_(i){switch(i.type){case"wildcard":return function(){return!0};case"identifier":var e=i.value.toLowerCase();return function(N,w,h){var M=h&&h.nodeTypeKey||"type";return e===N[M].toLowerCase()};case"exactNode":return function(N,w){return w.length===0};case"field":var t=i.name.split(".");return function(N,w){return(function h(M,Z,re,ae){for(var P=Z,Se=ae;Se<re.length;++Se){if(P==null)return!1;var me=P[re[Se]];if(Array.isArray(me)){for(var be=0;be<me.length;++be)if(h(M,me[be],re,Se+1))return!0;return!1}P=me}return M===P})(N,w[t.length-1],t,0)};case"matches":var r=i.selectors.map(He);return function(N,w,h){for(var M=0;M<r.length;++M)if(r[M](N,w,h))return!0;return!1};case"compound":var n=i.selectors.map(He);return function(N,w,h){for(var M=0;M<n.length;++M)if(!n[M](N,w,h))return!1;return!0};case"not":var s=i.selectors.map(He);return function(N,w,h){for(var M=0;M<s.length;++M)if(s[M](N,w,h))return!1;return!0};case"has":var o=i.selectors.map(He);return function(N,w,h){var M=!1,Z=[];return Aa.traverse(N,{enter:function(re,ae){ae!=null&&Z.unshift(ae);for(var P=0;P<o.length;++P)if(o[P](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=He(i.left),a=He(i.right);return function(N,w,h){return!!(w.length>0&&a(N,w,h))&&l(w[0],w.slice(1),h)};case"descendant":var c=He(i.left),p=He(i.right);return function(N,w,h){if(p(N,w,h)){for(var M=0,Z=w.length;M<Z;++M)if(c(w[M],w.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 w=Mt(N,d);return typeof w=="string"&&i.value.value.test(w)};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===Fn(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 f="".concat(i.value.value);return function(N){return f!=="".concat(Mt(N,d))};case"type":return function(N){return i.value.value!==Fn(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=He(i.left),y=He(i.right);return function(N,w,h){return y(N,w,h)&&H_(N,v,w,"LEFT_SIDE",h)||i.left.subject&&v(N,w,h)&&H_(N,y,w,"RIGHT_SIDE",h)};case"adjacent":var S=He(i.left),T=He(i.right);return function(N,w,h){return T(N,w,h)&&G_(N,S,w,"LEFT_SIDE",h)||i.right.subject&&S(N,w,h)&&G_(N,T,w,"RIGHT_SIDE",h)};case"nth-child":var A=i.index.value,x=He(i.right);return function(N,w,h){return x(N,w,h)&&W_(N,w,A,h)};case"nth-last-child":var C=-i.index.value,q=He(i.right);return function(N,w,h){return q(N,w,h)&&W_(N,w,C,h)};case"class":var B=i.name.toLowerCase();return function(N,w,h){if(h&&h.matchClass)return h.matchClass(i.name,N,w);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"&&(w.length===0||w[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 vp(i,e){var t=e&&e.nodeTypeKey||"type",r=i[t];return e&&e.visitorKeys&&e.visitorKeys[r]?e.visitorKeys[r]:Aa.VisitorKeys[r]?Aa.VisitorKeys[r]:e&&typeof e.fallback=="function"?e.fallback(i):Object.keys(i).filter((function(n){return n!==t}))}function bp(i,e){var t=e&&e.nodeTypeKey||"type";return i!==null&&Fn(i)==="object"&&typeof i[t]=="string"}function H_(i,e,t,r,n){var s=_p(t,1)[0];if(!s)return!1;for(var o=vp(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(bp(a[g],n)&&e(a[g],t,n))return!0}}return!1}function G_(i,e,t,r,n){var s=_p(t,1)[0];if(!s)return!1;for(var o=vp(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&&bp(a[c-1],n)&&e(a[c-1],t,n)||r==="RIGHT_SIDE"&&c<a.length-1&&bp(a[c+1],n)&&e(a[c+1],t,n))return!0}}return!1}function W_(i,e,t,r){if(t===0)return!1;var n=_p(e,1)[0];if(!n)return!1;for(var s=vp(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 z_(i,e,t,r){if(e){var n=[],s=He(e),o=(function l(a,c){if(a==null||Fn(a)!="object")return[];c==null&&(c=a);for(var p=a.subject?[c]:[],d=Object.keys(a),g=0;g<d.length;++g){var f=d[g],v=a[f];p.push.apply(p,Qx(l(v,f==="left"?v:c)))}return p})(e).map(He);Aa.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 f=n.slice(d+1);o[c](n[d],f,r)&&t(n[d],a,f)}}else t(l,a,n)},leave:function(){n.shift()},keys:r&&r.visitorKeys,fallback:r&&r.fallback||"iteration"})}}function K_(i,e,t){var r=[];return z_(i,e,(function(n){r.push(n)}),t),r}function Y_(i){return Jx.parse(i)}function Vt(i,e,t){return K_(i,Y_(e),t)}var Aa,Jx,hp,wp=k(()=>{Aa=$_((function(i,e){(function t(r){var n,s,o,l,a,c;function p(x){var C,q,B={};for(C in x)x.hasOwnProperty(C)&&(q=x[C],B[C]=typeof q=="object"&&q!==null?p(q):q);return B}function d(x,C){this.parent=x,this.key=C}function g(x,C,q,B){this.node=x,this.path=C,this.wrap=q,this.ref=B}function f(){}function v(x){return x!=null&&typeof x=="object"&&typeof x.type=="string"}function y(x,C){return(x===n.ObjectExpression||x===n.ObjectPattern)&&C==="properties"}function S(x,C){for(var q=x.length-1;q>=0;--q)if(x[q].node===C)return!0;return!1}function T(x,C){return new f().traverse(x,C)}function A(x,C){var q;return q=(function(B,N){var w,h,M,Z;for(h=B.length,M=0;h;)N(B[Z=M+(w=h>>>1)])?h=w:(M=Z+1,h-=w+1);return M})(C,(function(B){return B.range[0]>x.range[0]})),x.extendedRange=[x.range[0],x.range[1]],q!==C.length&&(x.extendedRange[1]=C[q].range[0]),(q-=1)>=0&&(x.extendedRange[0]=C[q].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)},f.prototype.path=function(){var x,C,q,B,N;function w(h,M){if(Array.isArray(M))for(q=0,B=M.length;q<B;++q)h.push(M[q]);else h.push(M)}if(!this.__current.path)return null;for(N=[],x=2,C=this.__leavelist.length;x<C;++x)w(N,this.__leavelist[x].path);return w(N,this.__current.path),N},f.prototype.type=function(){return this.current().type||this.__current.wrap},f.prototype.parents=function(){var x,C,q;for(q=[],x=1,C=this.__leavelist.length;x<C;++x)q.push(this.__leavelist[x].node);return q},f.prototype.current=function(){return this.__current.node},f.prototype.__execute=function(x,C){var q,B;return B=void 0,q=this.__current,this.__current=C,this.__state=null,x&&(B=x.call(this,C.node,this.__leavelist[this.__leavelist.length-1].node)),this.__current=q,B},f.prototype.notify=function(x){this.__state=x},f.prototype.skip=function(){this.notify(a)},f.prototype.break=function(){this.notify(l)},f.prototype.remove=function(){this.notify(c)},f.prototype.__initialize=function(x,C){this.visitor=C,this.root=x,this.__worklist=[],this.__leavelist=[],this.__current=null,this.__state=null,this.__fallback=null,C.fallback==="iteration"?this.__fallback=Object.keys:typeof C.fallback=="function"&&(this.__fallback=C.fallback),this.__keys=o,C.keys&&(this.__keys=Object.assign(Object.create(this.__keys),C.keys))},f.prototype.traverse=function(x,C){var q,B,N,w,h,M,Z,re,ae,P,Se,me;for(this.__initialize(x,C),me={},q=this.__worklist,B=this.__leavelist,q.push(new g(x,null,null,null)),B.push(new g(null,null,null,null));q.length;)if((N=q.pop())!==me){if(N.node){if(M=this.__execute(C.enter,N),this.__state===l||M===l)return;if(q.push(me),B.push(N),this.__state===a||M===a)continue;if(h=(w=N.node).type||N.wrap,!(P=this.__keys[h])){if(!this.__fallback)throw new Error("Unknown node type "+h+".");P=this.__fallback(w)}for(re=P.length;(re-=1)>=0;)if(Se=w[Z=P[re]]){if(Array.isArray(Se)){for(ae=Se.length;(ae-=1)>=0;)if(Se[ae]&&!S(B,Se[ae])){if(y(h,P[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)}q.push(N)}}else if(v(Se)){if(S(B,Se))continue;q.push(new g(Se,Z,null,null))}}}}else if(N=B.pop(),M=this.__execute(C.leave,N),this.__state===l||M===l)return},f.prototype.replace=function(x,C){var q,B,N,w,h,M,Z,re,ae,P,Se,me,be;function _(D){var V,ie,ue,je;if(D.ref.remove()){for(ie=D.ref.key,je=D.ref.parent,V=q.length;V--;)if((ue=q[V]).ref&&ue.ref.parent===je){if(ue.ref.key<ie)break;--ue.ref.key}}}for(this.__initialize(x,C),Se={},q=this.__worklist,B=this.__leavelist,M=new g(x,null,null,new d(me={root:x},"root")),q.push(M),B.push(M);q.length;)if((M=q.pop())!==Se){if((h=this.__execute(C.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)&&(q.push(Se),B.push(M),this.__state!==a&&h!==a)){if(w=N.type||M.wrap,!(ae=this.__keys[w])){if(!this.__fallback)throw new Error("Unknown node type "+w+".");ae=this.__fallback(N)}for(Z=ae.length;(Z-=1)>=0;)if(P=N[be=ae[Z]])if(Array.isArray(P)){for(re=P.length;(re-=1)>=0;)if(P[re]){if(y(w,ae[Z]))M=new g(P[re],[be,re],"Property",new d(P,re));else{if(!v(P[re]))continue;M=new g(P[re],[be,re],null,new d(P,re))}q.push(M)}}else v(P)&&q.push(new g(P,be,null,new d(N,be)))}}else if(M=B.pop(),(h=this.__execute(C.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,C){return new f().replace(x,C)},r.attachComments=function(x,C,q){var B,N,w,h,M=[];if(!x.range)throw new Error("attachComments needs range information");if(!q.length){if(C.length){for(w=0,N=C.length;w<N;w+=1)(B=p(C[w])).extendedRange=[0,x.range[0]],M.push(B);x.leadingComments=M}return x}for(w=0,N=C.length;w<N;w+=1)M.push(A(p(C[w]),q));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=f,r.cloneEnvironment=function(){return t({})},r})(e)})),Jx=$_((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:mu},p=mu,d=_e(" ",!1),g=/^[^ [\],():#!=><~+.]/,f=jt([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),v=_e(">",!1),y=_e("~",!1),S=_e("+",!1),T=_e(",",!1),A=function(I,L){return[I].concat(L.map((function(j){return j[3]})))},x=_e("!",!1),C=_e("*",!1),q=_e("#",!1),B=_e("[",!1),N=_e("]",!1),w=/^[><!]/,h=jt([">","<","!"],!1,!1),M=_e("=",!1),Z=function(I){return(I||"")+"="},re=/^[><]/,ae=jt([">","<"],!1,!1),P=_e(".",!1),Se=function(I,L,j){return{type:"attribute",name:I,operator:L,value:j}},me=_e('"',!1),be=/^[^\\"]/,_=jt(["\\",'"'],!0,!1),D=_e("\\",!1),V={type:"any"},ie=function(I,L){return I+L},ue=function(I){return{type:"literal",value:(L=I.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),Ut=/^[^\\']/,mi=jt(["\\","'"],!0,!1),ge=/^[0-9]/,St=jt([["0","9"]],!1,!1),ms=_e("type(",!1),tn=/^[^ )]/,iu=jt([" ",")"],!0,!1),qi=_e(")",!1),ru=/^[imsu]/,nu=jt(["i","m","s","u"],!1,!1),su=_e("/",!1),au=/^[^\]\\]/,ou=jt(["]","\\"],!0,!1),lu=/^[^\/\\[]/,cu=jt(["/","\\","["],!0,!1),vk=_e(":not(",!1),wk=_e(":matches(",!1),pu=function(I){return{type:"matches",selectors:I}},kk=_e(":is(",!1),Sk=_e(":has(",!1),Ek=_e(":first-child",!1),Tk=_e(":last-child",!1),Ik=_e(":nth-child(",!1),xk=_e(":nth-last-child(",!1),Ak=_e(":",!1),u=0,gs=[{line:1,column:1}],qt=0,Ro=[],$={};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(I,L){return{type:"literal",text:I,ignoreCase:L}}function jt(I,L,j){return{type:"class",parts:I,inverted:L,ignoreCase:j}}function du(I){var L,j=gs[I];if(j)return j;for(L=I-1;!gs[L];)L--;for(j={line:(j=gs[L]).line,column:j.column};L<I;)t.charCodeAt(L)===10?(j.line++,j.column=1):j.column++,L++;return gs[I]=j,j}function uu(I,L){var j=du(I),E=du(L);return{start:{offset:I,line:j.line,column:j.column},end:{offset:L,line:E.line,column:E.column}}}function F(I){u<qt||(u>qt&&(qt=u,Ro=[]),Ro.push(I))}function mu(){var I,L,j,E,R=36*u+0,W=$[R];return W?(u=W.nextPos,W.result):(I=u,(L=le())!==a&&(j=fs())!==a&&le()!==a?I=L=(E=j).length===1?E[0]:{type:"matches",selectors:E}:(u=I,I=a),I===a&&(I=u,(L=le())!==a&&(L=void 0),I=L),$[R]={nextPos:u,result:I},I)}function le(){var I,L,j=36*u+1,E=$[j];if(E)return u=E.nextPos,E.result;for(I=[],t.charCodeAt(u)===32?(L=" ",u++):(L=a,F(d));L!==a;)I.push(L),t.charCodeAt(u)===32?(L=" ",u++):(L=a,F(d));return $[j]={nextPos:u,result:I},I}function Qt(){var I,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(f)),j!==a)for(;j!==a;)L.push(j),g.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,F(f));else L=a;return L!==a&&(L=L.join("")),I=L,$[E]={nextPos:u,result:I},I}function No(){var I,L,j,E=36*u+3,R=$[E];return R?(u=R.nextPos,R.result):(I=u,(L=le())!==a?(t.charCodeAt(u)===62?(j=">",u++):(j=a,F(v)),j!==a&&le()!==a?I=L="child":(u=I,I=a)):(u=I,I=a),I===a&&(I=u,(L=le())!==a?(t.charCodeAt(u)===126?(j="~",u++):(j=a,F(y)),j!==a&&le()!==a?I=L="sibling":(u=I,I=a)):(u=I,I=a),I===a&&(I=u,(L=le())!==a?(t.charCodeAt(u)===43?(j="+",u++):(j=a,F(S)),j!==a&&le()!==a?I=L="adjacent":(u=I,I=a)):(u=I,I=a),I===a&&(I=u,t.charCodeAt(u)===32?(L=" ",u++):(L=a,F(d)),L!==a&&(j=le())!==a?I=L="descendant":(u=I,I=a)))),$[E]={nextPos:u,result:I},I)}function fs(){var I,L,j,E,R,W,G,J,ee=36*u+5,te=$[ee];if(te)return u=te.nextPos,te.result;if(I=u,(L=hs())!==a){for(j=[],E=u,(R=le())!==a?(t.charCodeAt(u)===44?(W=",",u++):(W=a,F(T)),W!==a&&(G=le())!==a&&(J=hs())!==a?E=R=[R,W,G,J]:(u=E,E=a)):(u=E,E=a);E!==a;)j.push(E),E=u,(R=le())!==a?(t.charCodeAt(u)===44?(W=",",u++):(W=a,F(T)),W!==a&&(G=le())!==a&&(J=hs())!==a?E=R=[R,W,G,J]:(u=E,E=a)):(u=E,E=a);j!==a?I=L=A(L,j):(u=I,I=a)}else u=I,I=a;return $[ee]={nextPos:u,result:I},I}function Po(){var I,L,j,E,R,W=36*u+6,G=$[W];return G?(u=G.nextPos,G.result):(I=u,(L=No())===a&&(L=null),L!==a&&(j=hs())!==a?(R=j,I=L=(E=L)?{type:E,left:{type:"exactNode"},right:R}:R):(u=I,I=a),$[W]={nextPos:u,result:I},I)}function hs(){var I,L,j,E,R,W,G,J=36*u+7,ee=$[J];if(ee)return u=ee.nextPos,ee.result;if(I=u,(L=Co())!==a){for(j=[],E=u,(R=No())!==a&&(W=Co())!==a?E=R=[R,W]:(u=E,E=a);E!==a;)j.push(E),E=u,(R=No())!==a&&(W=Co())!==a?E=R=[R,W]:(u=E,E=a);j!==a?(G=L,I=L=j.reduce((function(te,Ae){return{type:Ae[0],left:te,right:Ae[1]}}),G)):(u=I,I=a)}else u=I,I=a;return $[J]={nextPos:u,result:I},I}function Co(){var I,L,j,E,R,W,G,J=36*u+8,ee=$[J];if(ee)return u=ee.nextPos,ee.result;if(I=u,t.charCodeAt(u)===33?(L="!",u++):(L=a,F(x)),L===a&&(L=null),L!==a){if(j=[],(E=gu())!==a)for(;E!==a;)j.push(E),E=gu();else j=a;j!==a?(R=L,G=(W=j).length===1?W[0]:{type:"compound",selectors:W},R&&(G.subject=!0),I=L=G):(u=I,I=a)}else u=I,I=a;return $[J]={nextPos:u,result:I},I}function gu(){var I,L=36*u+9,j=$[L];return j?(u=j.nextPos,j.result):((I=(function(){var E,R,W=36*u+10,G=$[W];return G?(u=G.nextPos,G.result):(t.charCodeAt(u)===42?(R="*",u++):(R=a,F(C)),R!==a&&(R={type:"wildcard",value:R}),E=R,$[W]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W,G=36*u+11,J=$[G];return J?(u=J.nextPos,J.result):(E=u,t.charCodeAt(u)===35?(R="#",u++):(R=a,F(q)),R===a&&(R=null),R!==a&&(W=Qt())!==a?E=R={type:"identifier",value:W}:(u=E,E=a),$[G]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W,G,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&&le()!==a&&(W=(function(){var te,Ae,mt,he,Et=36*u+16,Qe=$[Et];return Qe?(u=Qe.nextPos,Qe.result):(te=u,(Ae=Do())!==a&&le()!==a&&(mt=(function(){var H,Y,ne,U=36*u+14,se=$[U];return se?(u=se.nextPos,se.result):(H=u,t.charCodeAt(u)===33?(Y="!",u++):(Y=a,F(x)),Y===a&&(Y=null),Y!==a?(t.charCodeAt(u)===61?(ne="=",u++):(ne=a,F(M)),ne!==a?(Y=Z(Y),H=Y):(u=H,H=a)):(u=H,H=a),$[U]={nextPos:u,result:H},H)})())!==a&&le()!==a?((he=(function(){var H,Y,ne,U,se,we=36*u+20,gt=$[we];if(gt)return u=gt.nextPos,gt.result;if(H=u,t.substr(u,5)==="type("?(Y="type(",u+=5):(Y=a,F(ms)),Y!==a)if(le()!==a){if(ne=[],tn.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(iu)),U!==a)for(;U!==a;)ne.push(U),tn.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(iu));else ne=a;ne!==a&&(U=le())!==a?(t.charCodeAt(u)===41?(se=")",u++):(se=a,F(qi)),se!==a?(Y={type:"type",value:ne.join("")},H=Y):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;else u=H,H=a;return $[we]={nextPos:u,result:H},H})())===a&&(he=(function(){var H,Y,ne,U,se,we,gt=36*u+22,Bt=$[gt];if(Bt)return u=Bt.nextPos,Bt.result;if(H=u,t.charCodeAt(u)===47?(Y="/",u++):(Y=a,F(su)),Y!==a){if(ne=[],(U=fu())===a&&(U=ys())===a&&(U=hu()),U!==a)for(;U!==a;)ne.push(U),(U=fu())===a&&(U=ys())===a&&(U=hu());else ne=a;ne!==a?(t.charCodeAt(u)===47?(U="/",u++):(U=a,F(su)),U!==a?((se=(function(){var Jt,ji,_u=36*u+21,Mo=$[_u];if(Mo)return u=Mo.nextPos,Mo.result;if(Jt=[],ru.test(t.charAt(u))?(ji=t.charAt(u),u++):(ji=a,F(nu)),ji!==a)for(;ji!==a;)Jt.push(ji),ru.test(t.charAt(u))?(ji=t.charAt(u),u++):(ji=a,F(nu));else Jt=a;return $[_u]={nextPos:u,result:Jt},Jt})())===a&&(se=null),se!==a?(we=se,Y={type:"regexp",value:new RegExp(ne.join(""),we?we.join(""):"")},H=Y):(u=H,H=a)):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;return $[gt]={nextPos:u,result:H},H})()),he!==a?(Ae=Se(Ae,mt,he),te=Ae):(u=te,te=a)):(u=te,te=a),te===a&&(te=u,(Ae=Do())!==a&&le()!==a&&(mt=(function(){var H,Y,ne,U=36*u+13,se=$[U];return se?(u=se.nextPos,se.result):(H=u,w.test(t.charAt(u))?(Y=t.charAt(u),u++):(Y=a,F(h)),Y===a&&(Y=null),Y!==a?(t.charCodeAt(u)===61?(ne="=",u++):(ne=a,F(M)),ne!==a?(Y=Z(Y),H=Y):(u=H,H=a)):(u=H,H=a),H===a&&(re.test(t.charAt(u))?(H=t.charAt(u),u++):(H=a,F(ae))),$[U]={nextPos:u,result:H},H)})())!==a&&le()!==a?((he=(function(){var H,Y,ne,U,se,we,gt=36*u+17,Bt=$[gt];if(Bt)return u=Bt.nextPos,Bt.result;if(H=u,t.charCodeAt(u)===34?(Y='"',u++):(Y=a,F(me)),Y!==a){for(ne=[],be.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(_)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,F(V)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));U!==a;)ne.push(U),be.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(_)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,F(V)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));ne!==a?(t.charCodeAt(u)===34?(U='"',u++):(U=a,F(me)),U!==a?(Y=ue(ne),H=Y):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;if(H===a)if(H=u,t.charCodeAt(u)===39?(Y="'",u++):(Y=a,F(je)),Y!==a){for(ne=[],Ut.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(mi)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,F(V)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));U!==a;)ne.push(U),Ut.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(mi)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,F(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,F(V)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));ne!==a?(t.charCodeAt(u)===39?(U="'",u++):(U=a,F(je)),U!==a?(Y=ue(ne),H=Y):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;return $[gt]={nextPos:u,result:H},H})())===a&&(he=(function(){var H,Y,ne,U,se,we,gt,Bt=36*u+18,Jt=$[Bt];if(Jt)return u=Jt.nextPos,Jt.result;for(H=u,Y=u,ne=[],ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(St));U!==a;)ne.push(U),ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(St));if(ne!==a?(t.charCodeAt(u)===46?(U=".",u++):(U=a,F(P)),U!==a?Y=ne=[ne,U]:(u=Y,Y=a)):(u=Y,Y=a),Y===a&&(Y=null),Y!==a){if(ne=[],ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(St)),U!==a)for(;U!==a;)ne.push(U),ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,F(St));else ne=a;ne!==a?(we=ne,gt=(se=Y)?[].concat.apply([],se).join(""):"",Y={type:"literal",value:parseFloat(gt+we.join(""))},H=Y):(u=H,H=a)}else u=H,H=a;return $[Bt]={nextPos:u,result:H},H})())===a&&(he=(function(){var H,Y,ne=36*u+19,U=$[ne];return U?(u=U.nextPos,U.result):((Y=Qt())!==a&&(Y={type:"literal",value:Y}),H=Y,$[ne]={nextPos:u,result:H},H)})()),he!==a?(Ae=Se(Ae,mt,he),te=Ae):(u=te,te=a)):(u=te,te=a),te===a&&(te=u,(Ae=Do())!==a&&(Ae={type:"attribute",name:Ae}),te=Ae)),$[Et]={nextPos:u,result:te},te)})())!==a&&le()!==a?(t.charCodeAt(u)===93?(G="]",u++):(G=a,F(N)),G!==a?E=R=W:(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W,G,J,ee,te,Ae,mt=36*u+26,he=$[mt];if(he)return u=he.nextPos,he.result;if(E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,F(P)),R!==a)if((W=Qt())!==a){for(G=[],J=u,t.charCodeAt(u)===46?(ee=".",u++):(ee=a,F(P)),ee!==a&&(te=Qt())!==a?J=ee=[ee,te]:(u=J,J=a);J!==a;)G.push(J),J=u,t.charCodeAt(u)===46?(ee=".",u++):(ee=a,F(P)),ee!==a&&(te=Qt())!==a?J=ee=[ee,te]:(u=J,J=a);G!==a?(Ae=W,R={type:"field",name:G.reduce((function(Et,Qe){return Et+Qe[0]+Qe[1]}),Ae)},E=R):(u=E,E=a)}else u=E,E=a;else u=E,E=a;return $[mt]={nextPos:u,result:E},E})())===a&&(I=(function(){var E,R,W,G,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(vk)),R!==a&&le()!==a&&(W=fs())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,F(qi)),G!==a?E=R={type:"not",selectors:W}:(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W,G,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(wk)),R!==a&&le()!==a&&(W=fs())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,F(qi)),G!==a?(R=pu(W),E=R):(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W,G,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(kk)),R!==a&&le()!==a&&(W=fs())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,F(qi)),G!==a?(R=pu(W),E=R):(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W,G,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(Sk)),R!==a&&le()!==a&&(W=(function(){var te,Ae,mt,he,Et,Qe,H,Y,ne=36*u+4,U=$[ne];if(U)return u=U.nextPos,U.result;if(te=u,(Ae=Po())!==a){for(mt=[],he=u,(Et=le())!==a?(t.charCodeAt(u)===44?(Qe=",",u++):(Qe=a,F(T)),Qe!==a&&(H=le())!==a&&(Y=Po())!==a?he=Et=[Et,Qe,H,Y]:(u=he,he=a)):(u=he,he=a);he!==a;)mt.push(he),he=u,(Et=le())!==a?(t.charCodeAt(u)===44?(Qe=",",u++):(Qe=a,F(T)),Qe!==a&&(H=le())!==a&&(Y=Po())!==a?he=Et=[Et,Qe,H,Y]:(u=he,he=a)):(u=he,he=a);mt!==a?te=Ae=A(Ae,mt):(u=te,te=a)}else u=te,te=a;return $[ne]={nextPos:u,result:te},te})())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,F(qi)),G!==a?E=R={type:"has",selectors:W}:(u=E,E=a)):(u=E,E=a),$[J]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W=36*u+31,G=$[W];return G?(u=G.nextPos,G.result):(t.substr(u,12)===":first-child"?(R=":first-child",u+=12):(R=a,F(Ek)),R!==a&&(R=yu(1)),E=R,$[W]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W=36*u+32,G=$[W];return G?(u=G.nextPos,G.result):(t.substr(u,11)===":last-child"?(R=":last-child",u+=11):(R=a,F(Tk)),R!==a&&(R=bu(1)),E=R,$[W]={nextPos:u,result:E},E)})())===a&&(I=(function(){var E,R,W,G,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(Ik)),R!==a)if(le()!==a){if(W=[],ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,F(St)),G!==a)for(;G!==a;)W.push(G),ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,F(St));else W=a;W!==a&&(G=le())!==a?(t.charCodeAt(u)===41?(J=")",u++):(J=a,F(qi)),J!==a?(R=yu(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&&(I=(function(){var E,R,W,G,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(xk)),R!==a)if(le()!==a){if(W=[],ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,F(St)),G!==a)for(;G!==a;)W.push(G),ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,F(St));else W=a;W!==a&&(G=le())!==a?(t.charCodeAt(u)===41?(J=")",u++):(J=a,F(qi)),J!==a?(R=bu(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&&(I=(function(){var E,R,W,G=36*u+35,J=$[G];return J?(u=J.nextPos,J.result):(E=u,t.charCodeAt(u)===58?(R=":",u++):(R=a,F(Ak)),R!==a&&(W=Qt())!==a?E=R={type:"class",name:W}:(u=E,E=a),$[G]={nextPos:u,result:E},E)})()),$[L]={nextPos:u,result:I},I)}function Do(){var I,L,j,E,R,W,G,J,ee=36*u+15,te=$[ee];if(te)return u=te.nextPos,te.result;if(I=u,(L=Qt())!==a){for(j=[],E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,F(P)),R!==a&&(W=Qt())!==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(P)),R!==a&&(W=Qt())!==a?E=R=[R,W]:(u=E,E=a);j!==a?(G=L,J=j,I=L=[].concat.apply([G],J).join("")):(u=I,I=a)}else u=I,I=a;return $[ee]={nextPos:u,result:I},I}function fu(){var I,L,j,E,R=36*u+23,W=$[R];if(W)return u=W.nextPos,W.result;if(I=u,t.charCodeAt(u)===91?(L="[",u++):(L=a,F(B)),L!==a){if(j=[],au.test(t.charAt(u))?(E=t.charAt(u),u++):(E=a,F(ou)),E===a&&(E=ys()),E!==a)for(;E!==a;)j.push(E),au.test(t.charAt(u))?(E=t.charAt(u),u++):(E=a,F(ou)),E===a&&(E=ys());else j=a;j!==a?(t.charCodeAt(u)===93?(E="]",u++):(E=a,F(N)),E!==a?I=L="["+j.join("")+"]":(u=I,I=a)):(u=I,I=a)}else u=I,I=a;return $[R]={nextPos:u,result:I},I}function ys(){var I,L,j,E=36*u+24,R=$[E];return R?(u=R.nextPos,R.result):(I=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?I=L="\\"+j:(u=I,I=a)):(u=I,I=a),$[E]={nextPos:u,result:I},I)}function hu(){var I,L,j,E=36*u+25,R=$[E];if(R)return u=R.nextPos,R.result;if(L=[],lu.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,F(cu)),j!==a)for(;j!==a;)L.push(j),lu.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,F(cu));else L=a;return L!==a&&(L=L.join("")),I=L,$[E]={nextPos:u,result:I},I}function yu(I){return{type:"nth-child",index:{type:"literal",value:I}}}function bu(I){return{type:"nth-last-child",index:{type:"literal",value:I}}}if((n=p())!==a&&u===t.length)return n;throw n!==a&&u<t.length&&F({type:"end"}),s=Ro,o=qt<t.length?t.charAt(qt):null,l=qt<t.length?uu(qt,qt+1):uu(qt,qt),new e(e.buildMessage(s,o),s,o,l)}}})())}));hp=typeof WeakMap=="function"?new WeakMap:null;Vt.parse=Y_,Vt.match=K_,Vt.traverse=z_,Vt.matches=function(i,e,t,r){return!e||!!i&&(t||(t=[]),He(e)(i,t,r))},Vt.query=Vt});var Oa,kp=k(()=>{Oa={}});var Q_,J_=k(()=>{Q_={}});function Zx(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 Ra(i,e,t,r){let n=r[r.length-1];e.type==="ClassDeclaration"||e.type==="ClassExpression"?sA(i,e,n):nA(i,e,n)}function eA(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 tA(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 iA(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=>eA(s,e)))return!0;r=tA(n)}return!1}function rA(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 nA(i,e,t){if(iA(e,ci(i.channelName)))return;i.transforms.tracingChannelDeclaration(i,t);let{functionQuery:{methodName:r,privateMethodName:n,functionName:s,expressionName:o,propertyName:l}}=i,c=r==="constructor"||!r&&!n&&!s&&!o&&!l?"ArrowFunctionExpression":e.type,p=e.params;e.body=ev(i,{type:c,params:p,body:e.body,async:e.async,expression:!1,generator:e.generator},t),e.params=Zx(p),e.generator=!1,e.async=!1,tv(i,e)}function sA(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=`${ci(s)}$${o}`;if(a&&rA(a,c))return;i.transforms.tracingChannelDeclaration(i,t),a||(a=Ze(e.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],l.body.unshift(a));let p=Ze(`
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:HT(r)}function HT(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 jf(i){let e=typeof i.data=="string"?ql(i.data):i.data;return[{type:"attachment",length:e.length,filename:i.filename,content_type:i.contentType,attachment_type:i.attachmentType},e]}function GT(i){return i in Ff}function Fl(i){return GT(i)?Ff[i]:i}function An(i){if(!i?.sdk)return;let{name:e,version:t}=i.sdk;return{name:e,version:t}}function Bf(i,e,t,r){let n=i.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:i.event_id,sent_at:new Date(ze()).toISOString(),...e&&{sdk:e},...!!t&&r&&{dsn:Fe(r)},...n&&{trace:n}}}function On(i){return i==="replay_event"?"replay":i||"error"}var Ff,Gt=k(()=>{bt();Ht();Ls();Rt();xt();Ff={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 Hf(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}var Gf=k(()=>{});function Wf(){return!Hf()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}var $f=k(()=>{Gf()});function Ir(){return typeof window<"u"&&(!Wf()||WT())}function WT(){return pe.process?.type==="renderer"}var na=k(()=>{$f();xt()});function Vf(i,e,t){let r=t.getOptions(),n=t.getDsn(),s=r.tunnel,o=An(r._metadata),l={sent_at:new Date(ze()).toISOString(),...$T(e)&&{trace:e},...o&&{sdk:o},...!!s&&n&&{dsn:Fe(n)}};return Xe(l,[Bl(i,t)])}function Bl(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:Ir()?{infer_ip:t,infer_user_agent:t}:void 0,items:i}]}function $T(i){return!!i.trace_id&&!!i.public_key}var Hl=k(()=>{Ht();Gt();na();Rt()});function zf(i){let e=156;if(e+=i.name.length*2,e+=yl(i.attributes),i.links&&i.links.length>0){let r=i.links[0]?.attributes,n=100+(r?yl(r):0);e+=n*i.links.length}return e}var Kf=k(()=>{bl()});var Yf,VT,sa,Qf=k(()=>{$e();Ve();xn();Tr();Hl();Kf();Yf=1e3,VT=5e6,sa=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<=Yf?r:Yf,this._flushInterval=n&&n>0?n:5e3,this._maxTraceWeight=s&&s>0?s:VT,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:_i(setTimeout(()=>{this.flush(t)},this._flushInterval))},this._traceBuckets.set(t,r)),r.spans.add(e),r.size+=zf(e),(r.spans.size>=this._maxSpanLimit||r.size>=this._maxTraceWeight)&&this.flush(t)}drain(){this._traceBuckets.size&&(Q&&z.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&&z.warn("No segment span reference found on span JSON, cannot compute DSC"),this._removeTrace(e);return}let s=si(n),o=r.map(a=>{let{_segmentSpan:c,...p}=a;return p}),l=Vf(o,s,this._client);Q&&z.log(`Sending span envelope for trace ${e} with ${o.length} spans`),this._client.sendEnvelope(l).then(null,a=>{Q&&z.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 aa,Jf,Xf=k(()=>{$e();Lf();Ul();Qf();Ve();yi();xn();aa="SpanStreaming",Jf=(i={})=>{let e=i.flushOnSegmentEnd??!0;return{name:aa,setup(t){if(!ia(t)){Q&&z.log(`[${aa}] \`traceLifecycle\` is "static", skipping setup.`);return}let r=new sa(t);t.on("afterSpanEnd",n=>{Js(n)&&r.add(Mf(n,t))}),t.on("flushTraceSpans",n=>{r.flush(n)}),e&&t.on("afterSegmentSpanEnd",n=>{let s=n.spanContext().traceId;_i(setTimeout(()=>{r.flush(s)},500))})}}}});function KT(i){return ti(i)?void 0:i}function Zf(i,e,t){let r=KT(e.originalException),n=r&&zT.get(r);if(!n)return;let s=i.contexts?.trace;(s?.trace_id??(t&&zi(t).trace_id))===n.trace_id&&(i.contexts={...i.contexts,trace:{...s,...n}})}var zT,eh=k(()=>{Ct();it();zT=new WeakMap});function th(i){lt(Ce()).segmentSpanCaptureStrategy=i}function ih(){return lt(Ce()).segmentSpanCaptureStrategy}var rh=k(()=>{bt()});function nh(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 sh=k(()=>{});function Gl(i){if(ih()||th(YT),la.has(i))return;let e=new Set,t=nh(()=>{let r=[...e];e.clear();for(let n of r)n()},1,{maxWait:100});i.on("flush",()=>{t.flush()}),la.set(i,r=>{e.add(r),t()})}var oa,ah,oh,la,YT,lh=k(()=>{sh();rh();oa=new WeakSet,ah=i=>oa.has(i),oh=i=>{oa.add(i)},la=new WeakMap;YT={onSegmentSpanEnded(i,e){let t=e.getClient(),r=t&&la.get(t);if(!r){let n=i();n&&t?.captureEvent(n);return}r(()=>{let n=i({isSpanAlreadyCaptured:ah,onSpanCaptured:oh});n&&t.captureEvent(n)})},onChildSpanEnded(i,e,t,r){if(oa.has(i)||!oa.has(e))return;let n=r.getClient(),s=n&&la.get(n),o=()=>{let l=t({isSpanAlreadyCaptured:ah,onSpanCaptured:oh});l?.contexts?.trace?.data&&(l.contexts.trace.data["sentry.parent_span_already_sent"]=!0),l&&n?.captureEvent(l)};s?s(o):o()}}});function QT(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=An(t),s={sent_at:new Date(ze()).toISOString(),...n&&{sdk:n},...!!r&&e&&{dsn:Fe(e)}},o="aggregates"in i?[{type:"sessions"},i]:[{type:"session"},i.toJSON()];return Xe(s,[o])}function ph(i,e,t,r){let n=An(t),s=i.type&&i.type!=="replay_event"?i.type:"event";QT(i,t?.sdk);let o=Bf(i,n,r,e);return delete i.sdkProcessingMetadata,Xe(o,[[{type:s},i]])}var dh=k(()=>{Ht();Gt();Rt()});function ai(i){return new ca(e=>{e(i)})}function xr(i){return new ca((e,t)=>{t(i)})}var Wl,uh,mh,ca,Ar=k(()=>{it();Wl=0,uh=1,mh=2;ca=class i{constructor(e){this._state=Wl,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===Wl)return;let e=this._handlers.slice();this._handlers=[],e.forEach(t=>{t[0]||(this._state===uh&&t[1](this._value),this._state===mh&&t[2](this._value),t[0]=!0)})}_runExecutor(e){let t=(s,o)=>{if(this._state===Wl){if(ii(o)){o.then(r,n);return}this._state=s,this._value=o,this._executeHandlers()}},r=s=>{t(uh,s)},n=s=>{t(mh,s)};try{e(r,n)}catch(s){n(s)}}}});function gh(i,e,t,r=0,n){try{let s=$l(e,t,i,r,n);return ii(s)?s:ai(s)}catch(s){return xr(s)}}function $l(i,e,t,r,n){let s=t[r];if(!i||!s)return i;let o=`Event processor "${s.id||"?"}"`,l=!1,a=Yi(Q?`${o} threw an error, dropping event:`:"",()=>s({...i},e),()=>(l=!0,null));return Q&&a===null&&z.log(`${o} dropped event`),ii(a)?a.then(c=>c?$l(c,e,t,r+1,n):(n?.(l?"callback_error":"event_processor"),null)):a?$l(a,e,t,r+1,n):(n?.(l?"callback_error":"event_processor"),null)}var fh=k(()=>{$e();Ve();it();ta();Ar()});function bh(i){let e=pe._sentryDebugIds,t=pe._debugIds;if(!e&&!t)return{};let r=e?Object.keys(e):[],n=t?Object.keys(t):[];if(vi&&r.length===hh&&n.length===yh)return vi;hh=r.length,yh=n.length,vi={},Qi||(Qi={});let s=(o,l)=>{for(let a of o){let c=l[a],p=Qi?.[a];if(p&&vi&&c)vi[p[0]]=c,Qi&&(Qi[a]=[p[0],c]);else if(c){let d=i(a);for(let g=d.length-1;g>=0;g--){let _=d[g]?.filename;if(_&&vi&&Qi){vi[_]=c,Qi[a]=[_,c];break}}}}};return e&&s(r,e),t&&s(n,t),vi}var Qi,hh,yh,vi,_h=k(()=>{xt()});function Rn(i){return i.data?.__sentry__===!0}function vh(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 Vl=k(()=>{});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||Hi()},c=t.integrations||i.integrations.map(I=>I.name);JT(a,i),eI(a,c),n&&n.emit("applyFrameMetadata",e),e.type===void 0&&XT(a,i.stackParser);let p=iI(r,t.captureContext);t.mechanism&&Dg(a,t.mechanism);let d=n?n.getEventProcessors():[],g=ea(s,p),f=[...t.attachments||[],...g.attachments];f.length&&(t.attachments=f),Af(a,g);let _=kn(p);_&&Of(a,_),Zf(a,t,p);let y=[...d,...g.eventProcessors],S=e.type==="transaction",T=e.spans?.length||0;return(Rn(t)?ai(a):gh(y,a,t,0,I=>{n&&(n.recordDroppedEvent(I,On(e.type)),S&&n.recordDroppedEvent(I,"span",1+T))})).then(I=>{if(!I)return null;if(S&&n){let C=T-(I.spans?.length||0);C>0&&n.recordDroppedEvent("event_processor","span",C)}return ZT(I),typeof o=="number"&&o>0?tI(I,o,l):I})}function JT(i,e){let{environment:t,release:r,dist:n,maxValueLength:s}=e;i.environment=i.environment||t||bi,!i.release&&r&&(i.release=r),!i.dist&&n&&(i.dist=n);let o=i.request;o?.url&&s&&(o.url=mn(o.url,s)),s&&i.exception?.values?.forEach(l=>{l.value&&(l.value=mn(l.value,s))})}function XT(i,e){let t=bh(e);i.exception?.values?.forEach(r=>{r.stacktrace?.frames?.forEach(n=>{n.filename&&(n.debug_id=t[n.filename])})})}function ZT(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 eI(i,e){e.length>0&&(i.sdk=i.sdk||{},i.sdk.integrations=[...i.sdk.integrations||[],...e])}function tI(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 iI(i,e){if(!e)return i;let t=i?i.clone():new Je;return t.update(e),t}var kh=k(()=>{Sn();fh();vr();_h();Gt();eh();Vl();ri();Ls();Dl();yi();Us();Ar();_r()});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 sI(i){return`${nI(i)}${i.projectId}/envelope/`}function aI(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 Sh(i,e,t){return e||`${sI(i)}?${aI(i,t)}`}var rI,Eh=k(()=>{rI="7"});function Th(i,e){return e?Ws(e,()=>{let t=kn(),r=t?Ys(t):zi(e);return[t?si(t):Er(i,e),r]}):[void 0,void 0]}var Ih=k(()=>{Ct();Tr();yi()});function oI(i,e){let t=e?"auto":"never";return[{type:"log",item_count:i.length,content_type:"application/vnd.sentry.items.log+json"},{version:2,...Ir()&&{ingest_settings:{infer_ip:t,infer_user_agent:t}},items:i}]}function xh(i,e,t,r,n){let s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),t&&r&&(s.dsn=Fe(r)),Xe(s,[oI(i,n)])}var Ah=k(()=>{Ht();Gt();na()});function Oh(i,e){let t=e??lI(i)??[];if(t.length===0)return;let r=i.getOptions(),n=xh(t,r._metadata,r.tunnel,i.getDsn(),i.getDataCollectionOptions().userInfo);Rh().set(i,[]),i.emit("flushLogs"),i.sendEnvelope(n)}function lI(i){return Rh().get(i)}function Rh(){return yt("clientToLogBufferMap",()=>new WeakMap)}var Nh=k(()=>{bt();Ah()});function cI(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,...Ir()&&{ingest_settings:{infer_ip:t,infer_user_agent:t}},items:i}]}function Ph(i,e,t,r,n){let s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),t&&r&&(s.dsn=Fe(r)),Xe(s,[cI(i,n)])}var Ch=k(()=>{Ht();Gt();na()});function Dh(i,e){let t=e??pI(i)??[];if(t.length===0)return;let r=i.getOptions(),n=Ph(t,r._metadata,r.tunnel,i.getDsn(),i.getDataCollectionOptions().userInfo);Mh().set(i,[]),i.emit("flushMetrics"),i.sendEnvelope(n)}function pI(i){return Mh().get(i)}function Mh(){return yt("clientToMetricBufferMap",()=>new WeakMap)}var Lh=k(()=>{bt();Ch()});function Uh(i,e){if(i.type!=="transaction"||!i.spans?.length||!i.sdkProcessingMetadata?.hasGenAiSpans||ia(e))return;let t=[],r=[];for(let n of i.spans)n.op?.startsWith("gen_ai.")?t.push(Nf(n)):r.push(n);if(t.length!==0)return i.spans=r,Bl(t,e)}var qh=k(()=>{Hl();Ul();Pf()});function Or(i=100){let e=new Set;function t(){return e.size<i}function r(o){e.delete(o)}function n(o){if(!t())return xr(Nn);let l=o();return e.add(l),l.then(()=>r(l),()=>r(l)),l}function s(o){if(!e.size)return ai(!0);let l=Promise.allSettled(Array.from(e)).then(()=>!0);if(!o)return l;let a=[l,new Promise(c=>_i(setTimeout(()=>c(!1),o)))];return Promise.race(a)}return{get $(){return Array.from(e)},add:n,drain:s}}var Nn,pa=k(()=>{Ar();xn();Nn=Symbol.for("SentryBufferFullError")});function uI(i,e=ze()){let t=parseInt(`${i}`,10);if(!isNaN(t))return t*1e3;let r=Date.parse(`${i}`);return isNaN(r)?dI:r-e}function mI(i,e){return i[e]||i.all||0}function jh(i,e,t=ze()){return mI(i,e)>t}function Fh(i,{statusCode:e,headers:t},r=ze()){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 f of c.split(";"))f==="metric_bucket"?(!p||p.split(";").includes("custom"))&&(n[f]=r+g):n[f]=r+g}else o?n.all=r+uI(o,r):e===429&&(n.all=r+60*1e3);return n}var dI,Bh=k(()=>{Rt();dI=60*1e3});function zl(i,e,t=Or(i.bufferSize||Pn)){let r={},n=l=>t.drain(l);function s(l,[a,c],p){let d=Fl(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(ra(l,(g,f)=>{jh(r,Fl(f))?s("ratelimit_backoff",g,f):a.push(g)}),a.length===0)return Promise.resolve({});let c=Xe(l[0],a),p=g=>{if(Uf(c,["client_report"])){Q&&z.warn(`Dropping client report. Will not send outcomes (reason: ${g}).`);return}ra(c,(f,_)=>{s(g,f,_)})},d=()=>e({body:qf(c)}).then(g=>g.statusCode===413?(Q&&z.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)&&z.warn(`Sentry responded with status code ${g.statusCode} to sent event.`),r=Fh(r,g),g),g=>{throw p("network_error"),Q&&z.error("Encountered error running transport request:",g),g});return t.add(d).then(g=>g,g=>{if(g===Nn)return Q&&z.error("Skipped sending event because buffer is full."),p("queue_overflow"),Promise.resolve({});throw g})}return{send:o,flush:n}}var Pn,da=k(()=>{$e();Ve();Gt();pa();Bh();Pn=64});function Hh(i,e,t){let r=[{type:"client_report"},{timestamp:t||Hi(),discarded_events:i}];return Xe(e?{dsn:e}:{},[r])}var Gh=k(()=>{Gt();_r()});function Wh(i){let{trace_id:e,parent_span_id:t,span_id:r,status:n,origin:s,data:o,op:l}=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,profile_id:o?.[Jo],exclusive_time:o?.[Qo],measurements:i.measurements,is_segment:!0}}function $h(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,data:{...i.data,...i.profile_id&&{[Jo]:i.profile_id},...i.exclusive_time&&{[Qo]:i.exclusive_time}}}},measurements:i.measurements}}var Vh=k(()=>{fr()});function zh(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 Kh=k(()=>{Ve()});function gI(i){return typeof i=="boolean"||"allow"in i||"deny"in i}function fI(i){return i===void 0?{...Be.httpHeaders}:gI(i)?{request:i,response:i}:{request:i.request??Be.httpHeaders.request,response:i.response??Be.httpHeaders.response}}function Yh(i){let e=i.dataCollection??{};return{userInfo:e.userInfo??Be.userInfo,cookies:e.cookies??Be.cookies,httpHeaders:fI(e.httpHeaders),httpBodies:e.httpBodies??Be.httpBodies,urlQueryParams:e.urlQueryParams??Be.urlQueryParams,graphQL:{document:e.graphQL?.document??Be.graphQL.document,variables:e.graphQL?.variables??Be.graphQL.variables},genAI:{inputs:e.genAI?.inputs??Be.genAI.inputs,outputs:e.genAI?.outputs??Be.genAI.outputs},mcp:{inputs:e.mcp?.inputs??Be.mcp.inputs,outputs:e.mcp?.outputs??Be.mcp.outputs},databaseQueryData:e.databaseQueryData??Be.databaseQueryData,queues:e.queues??Be.queues,stackFrameVariables:e.stackFrameVariables??Be.stackFrameVariables,frameContextLines:e.frameContextLines??Be.frameContextLines}}var Be,Qh=k(()=>{Be={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 Zh(i){return{message:i,[sy]:!0}}function Kl(i){return{message:i,[ay]:!0}}function ey(i){return Kl(`Discarding event because it's not included in the random sample (sampling rate = ${i})`)}function ty(i){return dn(i)&&sy in i}function iy(i){return dn(i)&&ay in i}function ry(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=_i(setTimeout(()=>{n(i)},c)))}}),i.on("flush",()=>{n(i)})}function bI(i,e,t,r,n){let{beforeSend:s,ignoreSpans:o,beforeSendTransaction:l}=i,a=Tn(i.beforeSendSpan)&&i.beforeSendSpan,c=e;if(Yl(c)&&s){let p=c;return Yi(Q?"The `beforeSend` callback threw an error, dropping the event:":"",()=>s(p,t),()=>(r("callback_error"),null))}if(oy(c)){if(a||o){let p=Wh(c);if(o?.length&&Rl({description:p.description,op:p.op,attributes:p.data},o))return r("ignored"),null;if(a){let d=In(p,a);c=fi(e,$h(d))}if(c.spans){let d=[],g=c.spans;for(let f of g){if(o?.length&&Rl({description:f.description,op:f.op,attributes:f.data},o)){_f(g,f);continue}a?d.push(In(f,a)):d.push(f)}n(g.length-d.length),c.spans=d}}if(l)return Yi(Q?"The `beforeSendTransaction` callback threw an error, dropping the event:":"",()=>l(c,t),()=>(r("callback_error"),null))}return c}function Yl(i){return i.type===void 0}function oy(i){return i.type==="transaction"}function _I(i){let e=0;return i.name&&(e+=i.name.length*2),e+=8,e+ly(i.attributes)}function vI(i){let e=0;return i.message&&(e+=i.message.length*2),e+ly(i.attributes)}function ly(i){if(!i)return 0;let e=0;return Object.values(i).forEach(t=>{Array.isArray(t)?e+=t.length*ny(t[0]):ti(t)?e+=ny(t):e+=100}),e}function ny(i){return typeof i=="string"?i.length*2:typeof i=="number"?8:typeof i=="boolean"?4:0}var Jh,Xh,sy,ay,hI,yI,ua,cy=k(()=>{Eh();Sn();Ct();$e();dh();Sf();Nh();Lh();ul();Tr();Ml();qh();da();Gh();Ve();Ht();Gt();Vl();it();Bs();ri();lf();kh();pa();Rt();ta();vf();Ar();xn();Vh();Kh();Qh();Jh="Not capturing exception because it's already been captured.",Xh="Discarded session because of missing or non-string release",sy=Symbol.for("SentryInternalError"),ay=Symbol.for("SentryDoNotSendEventError"),hI=5e3,yI=Symbol.for("SentryClosedClient");ua=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=Or(e.transportOptions?.bufferSize??Pn),this._dataCollection=Yh(e),this._unhandledSessionStatus="crashed",e.dsn?this._dsn=vn(e.dsn):Q&&z.warn("No DSN provided, client will not send events.");let{beforeSendSpan:t,traceLifecycle:r}=this._options;if(Q&&t&&Tn(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=Sh(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})}ry(this,"afterCaptureLog","flushLogs",vI,Oh),ry(this,"afterCaptureMetric","flushMetrics",_I,Dh)}captureException(e,t,r){let n=Me();if(js(e))return Q&&z.log(Jh),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=pn(e)?e:String(e),l=ti(e),a=l?this.eventFromMessage(o,t,s):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&&js(t.originalException))return Q&&z.log(Jh),n;let s={event_id:n,...t},o=e.sdkProcessingMetadata||{},l=o.capturedSpanScope,a=o.capturedSpanIsolationScope,c=On(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,yI,{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(),zh(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),Pl(this,e,this._integrations),t||Nl(this,[e])}sendEvent(e,t={}){this.emit("beforeSendEvent",e,t);let r=Uh(e,this),n=ph(e,this._dsn,this._options._metadata,this._options.tunnel);if(!Rn(t))for(let s of t.attachments||[])n=jl(n,jf(s));r&&(n=jl(n,r)),this.sendEnvelope(n).then(s=>this.emit("afterSendEvent",e,s))}sendSession(e){let{release:t,environment:r=bi}=this._options;if("aggregates"in e){let s=e.attrs||{};if(!s.release&&!t){Q&&z.warn(Xh);return}s.release=s.release||t,s.environment=s.environment||r,e.attrs=s}else{if(!e.release&&!t){Q&&z.warn(Xh);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&&z.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&&z.error("Error while sending envelope:",t),{}}return Q&&z.error("Transport disabled"),{}}registerCleanup(e){}dispose(){}_setupIntegrations(){let{integrations:e}=this._options;this._integrations=kf(this,e),Nl(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,...zi(r)},...l.contexts};let a=Er(this,r);return l.sdkProcessingMetadata={dynamicSamplingContext:a,...l.sdkProcessingMetadata},l})}_captureEvent(e,t={},r=ni(),n=Vi()){return Q&&Yl(e)&&z.log(`Captured error event \`${vh(e)[0]||"<unknown>"}\``),this._processEvent(e,t,r,n).then(s=>s.event_id,s=>{Q&&(iy(s)?z.log(s.message):ty(s)?z.warn(s.message):z.warn(s))})}_processEvent(e,t,r,n){let s=this.getOptions(),{sampleRate:o}=s,l=oy(e),a=Yl(e),p=`before send for type \`${e.type||"error"}\``,d="before_send",g=0,f=typeof o>"u"?void 0:of(o),_=a&&typeof f=="number"&&_t()>f,y=On(e.type),S=0,T=r.getSession()||n.getSession();return _&&T?.status!=="ok"?(this.recordDroppedEvent("sample_rate","error"),xr(ey(o))):this._prepareEvent(e,t,r,n).then(A=>{if(A===null)throw Kl("An event processor returned `null`, will not send event.");return S=A.spans?.length||0,Rn(t)?A:bI(s,A,t,I=>{d=I},I=>{g=I})}).then(A=>{if(g&&this.recordDroppedEvent("ignored","span",g),!hr(A)||A===null){if(this.recordDroppedEvent(d,y),l&&this.recordDroppedEvent(d,"span",1+S-g),A!==null)throw Zh(`${p} must return \`null\` or a valid event.`);let q=d==="ignored"?"Transaction matched `ignoreSpans`":`${p} ${d==="callback_error"?"threw an error":"returned `null`"}`;throw Kl(`${q}, will not send event.`)}if(a&&T&&this._updateSessionFromEvent(T,A),_)throw this.recordDroppedEvent("sample_rate","error"),ey(o);if(l){let q=S-g-(A.spans?.length||0);q>0&&this.recordDroppedEvent("before_send","span",q)}let C=A.transaction_info;if(l&&C&&A.transaction!==e.transaction){let q="custom";A.transaction_info={...C,source:q}}return this.sendEvent(A,t),A}).then(null,A=>{throw iy(A)||ty(A)?A:(this.captureException(A,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:A}),Zh(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
5
+ Reason: ${A}`))})}_process(e,t){this._numProcessing++,this._promiseBuffer.add(e).then(r=>(this._numProcessing--,r),r=>(this._numProcessing--,r===Nn&&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&&z.log("Flushing outcomes...");let e=this._clearOutcomes();if(e.length===0){Q&&z.log("No outcomes to send");return}if(!this._dsn){Q&&z.log("No dsn provided, will not send outcomes");return}Q&&z.log("Sending outcomes:",e);let t=Hh(e,this._options.tunnel&&Fe(this._dsn));this.sendEnvelope(t)}}});function Ql(){wI.clear(),Q&&z.log("Cleared AI provider skip registrations")}var wI,py=k(()=>{$e();Ve();wI=new Set});function dy(i,e,t,r,n){let s={sent_at:new Date(ze()).toISOString()};t?.sdk&&(s.sdk={name:t.sdk.name,version:t.sdk.version}),r&&n&&(s.dsn=Fe(n)),e&&(s.trace=e);let o=kI(i);return Xe(s,[o])}function kI(i){return[{type:"check_in"},i]}var uy=k(()=>{Ht();Gt();Rt()});function Jl(i){return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var my=k(()=>{});function gy(i,e,t){let r=xI(e.allowedDsns,i.getDsn()),n={paths:II(e,r),basePath:e.basePath,allowedDsns:r,forward:t};return SI.set(i,n),n}function fy(i){return i.getIntegrationByName?.(EI)?.forward}function TI(i){let e=i?vn(i):Bt()?.getDsn();return e?`/${AI(Fe(e)).toString(36)}`:void 0}function II(i,e){let t=i.path?.replace(/\/$/,"");if(t)return[t];let r=e.map(n=>TI(n));return[...new Set(r.filter(n=>!!n))]}function hy(i,e){if(!e.length)return[];let r=`${Jl(Xl(i.basePath))}(?:${e.map(Jl).join("|")})/?`;return[{attributes:{[mg]:new RegExp(`^${r}$`)}},{attributes:{"http.url":new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${r}(?:[?#].*)?$`)}}]}function Xl(i){let e=(i?.startsWith("./")?i.slice(1):i??"").replace(/\/$/,"");return!e||e.startsWith("/")?e:`/${e}`}function xI(i,e){let t=new Set;for(let r of[...(i??[]).map(n=>vn(n)),e])r&&t.add(Fe(r));return[...t]}function AI(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 SI,EI,yy=k(()=>{Ct();fr();my();Ht();SI=new WeakMap,EI="ServeTunnel"});function Zl(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:ht})),n.version=ht)}var by=k(()=>{Ns()});function ec(i){return Array.from(new Set(i))}var _y=k(()=>{});function vy(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=ma(i,e,r,s.originalException,t,n.exception.values,o,0))}function ma(i,e,t,r,n,s,o,l){if(s.length>=t+1)return s;let a=[...s];if(Ot(r[n])){tc(o,l,r);let c=i(e,r[n]),p=a.length;ic(c,n,p,l),a=ma(i,e,t,r[n],n,[c,...a],c,p)}return wy(r)&&r.errors.forEach((c,p)=>{if(Ot(c)){tc(o,l,r);let d=i(e,c),g=a.length;ic(d,`errors[${p}]`,g,l),a=ma(i,e,t,c,n,[d,...a],d,g)}}),OI(r)&&["error","suppressed"].forEach(c=>{let p=r[c];if(Ot(p)){tc(o,l,r);let d=i(e,p),g=a.length;ic(d,c,g,l),a=ma(i,e,t,p,n,[d,...a],d,g)}}),a}function wy(i){return Array.isArray(i.errors)}function OI(i){return"error"in i&&"suppressed"in i}function tc(i,e,t){i.mechanism={handled:!0,type:"auto.core.linked_errors",...wy(t)&&{is_exception_group:!0},...i.mechanism,exception_id:e}}function ic(i,e,t,r){i.mechanism={handled:!0,...i.mechanism,type:"chained",source:e,exception_id:t,parent_id:r}}var ky=k(()=>{it()});function Sy(i,e){return i(e.stack||"",1)}function RI(i){return Ot(i)&&"__sentry_fetch_url_host__"in i&&typeof i.__sentry_fetch_url_host__=="string"}function NI(i){return RI(i)?`${i.message} (${i.__sentry_fetch_url_host__})`:i.message}function rc(i,e){let t={type:e.name||e.constructor.name,value:NI(e)},r=Sy(i,e);return r.length&&(t.stacktrace={frames:r}),t}function PI(i){for(let e in i)if(Object.prototype.hasOwnProperty.call(i,e)){let t=i[e];if(Ot(t))return t}}function CI(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=Og(i);if(Eg(i))return`Event \`ErrorEvent\` captured as exception with message \`${i.message}\``;let t=DI(i);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${e}`}function DI(i){try{let e=Object.getPrototypeOf(i);return e?e.constructor.name:void 0}catch{}}function MI(i,e,t,r){if(Ot(t))return[t,void 0];if(e.synthetic=!0,hr(t)){let s=i?.getOptions().normalizeDepth,o={__serialized__:ol(t,s)},l=PI(t);if(l)return[l,o];let a=CI(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 Ey(i,e,t,r){let s=r?.data&&r.data.mechanism||{handled:!0,type:"generic"},[o,l]=MI(i,s,t,r),a={exception:{values:[rc(e,o)]}};return l&&(a.extra=l),pl(a,void 0,void 0),qs(a,s),{...a,event_id:r?.event_id}}function Ty(i,e,t="info",r,n){let s={event_id:r?.event_id,level:t};if(n&&r?.syntheticException){let o=Sy(i,r.syntheticException);o.length&&(s.exception={values:[{value:e,stacktrace:{frames:o}}]},qs(s,{synthetic:!0}))}if(pn(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 nc=k(()=>{it();ri();Ls();un()});var LI,UI,qI,jI,sc,Iy=k(()=>{ky();nc();LI="cause",UI=5,qI="LinkedErrors",jI=((i={})=>{let e=i.limit||UI,t=i.key||LI;return{name:qI,preprocessEvent(r,n,s){let o=s.getOptions();vy(rc,o.stackParser,t,e,r,n)}}}),sc=jI});function BI(i){let e=i.length>1024?`<truncated>${i.slice(-1024)}`:i,t=FI.exec(e);return t?t.slice(1):[]}function ac(i){let e=BI(i),t=e[0]||"",r=e[1];return!t&&!r?".":(r&&(r=r.slice(0,r.length-1)),t+r)}var FI,xy=k(()=>{FI=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/});var Wt=k(()=>{lh();Tr();Ct();ml();Hs();bt();vr();da();py();Il();by();_y();$s();Iy();xt();Ve();ri();xy();Cs();cf();El();yn();Ns();Rt()});function Oy(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 Ry=k(()=>{});function Py(i){let e=i?.getOptions(),t=e?._managedTunnel??oc?.tunnel,r=i&&(WI.get(i)??fy(i)??oc?.forward);if(!i||!e||!t||!r)return;let n=Xl(oc?.basePath),s=t.basePath===void 0&&!t.path&&n?{...t,basePath:n}:t;e._managedTunnel=s;let{paths:o}=gy(i,s,r),l=Ny.get(i)??[],a=hy(s,o);e.ignoreSpans=[...(e.ignoreSpans??[]).filter(c=>!l.includes(c)),...a],Ny.set(i,a)}var oc,WI,Ny,Cy=k(()=>{yy();WI=new WeakMap,Ny=new WeakMap});function Dy(i){let e=Vi().getScopeData().sdkProcessingMetadata.requestSession;if(e){let t=i?.mechanism?.handled??!0;t&&e.status!=="crashed"?e.status="errored":t||(e.status="crashed")}}var Cn,My=k(()=>{uy();cy();Ct();$e();Xf();da();Ry();Ve();nc();ri();pa();Ar();Ih();Cy();Cn=class extends ua{constructor(e){Oy(e),(typeof __SENTRY_TRACING__>"u"||__SENTRY_TRACING__)&&e.traceLifecycle!=="static"&&!e.integrations.some(t=>t.name===aa)&&e.integrations.push(Jf()),super(e),this._disposeCallbacks=[],Py(this),this._setUpMetricsProcessing()}eventFromException(e,t){let r=Ey(this,this._options.stackParser,e,t);return r.level="error",ai(r)}eventFromMessage(e,t="info",r){return ai(Ty(this._options.stackParser,e,t,r,this._options.attachStacktrace))}captureException(e,t,r){return Dy(t),super.captureException(e,t,r)}captureEvent(e,t,r){return!e.type&&e.exception?.values&&e.exception.values.length>0&&Dy(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&&z.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]=Th(this,r);d&&(c.contexts={trace:d});let g=dy(c,p,this.getSdkMetadata(),a,this.getDsn());return Q&&z.log("Sending checkin:",e.monitorSlug,e.status),this.sendEnvelope(g),n}registerCleanup(e){this._disposeCallbacks.push(e)}dispose(){Q&&z.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=Or(Pn)}_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={"server.address":this._options.serverName,...e.attributes})})}}});function Uy(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 qy(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]),f=o[5]==="native";!g&&o[5]&&!f&&(g=o[5]);let _=g?$I(g):void 0;return{filename:_??g,module:_&&i?.(_),function:c,lineno:Ly(o[3]),colno:Ly(o[4]),in_app:Uy(g||"",f)}}if(n.match(e))return{filename:n}}}function lc(i){return[90,qy(i)]}function Ly(i){return parseInt(i||"",10)||void 0}function $I(i){try{return decodeURI(i)}catch{return}}var jy=k(()=>{Cs()});var cc=k(()=>{My();jy()});var wi,pc=k(()=>{wi="1.10.0"});function VI(i){let e=new Set([i]),t=new Set,r=i.match(Fy);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(Fy);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 Fy,By,Hy=k(()=>{pc();Fy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;By=VI(wi)});function KI(){return Object.defineProperty({},"version",{value:wi,enumerable:!0,writable:!1,configurable:!1})}function Rr(i,e,t,r=!1){var n;let s=fa[ga]=(n=fa[ga])!==null&&n!==void 0?n:KI();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${wi}`);return t.error(o.stack||o.message),!1}return s[i]=e,t.debug(`@opentelemetry/api: Registered a global for ${i} v${wi}.`),!0}function oi(i){let e=fa[ga];if(e!=null){if(e!==Gy){if(!e.version||!By(e.version))return;Gy=e}return e[i]}}function Nr(i,e){e.debug(`@opentelemetry/api: Unregistering a global for ${i} v${wi}.`);let t=fa[ga];t&&delete t[i]}var zI,ga,fa,Gy,Dn=k(()=>{pc();Hy();zI=wi.split(".")[0],ga=Symbol.for(`opentelemetry.js.api.${zI}`),fa=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function Mn(i,e,t){let r=oi("diag");if(r)return r[i](e,...t)}var Wy,$y=k(()=>{Dn();Wy=class{constructor(i){this._namespace=i.namespace||"DiagComponentLogger"}debug(...i){return Mn("debug",this._namespace,i)}error(...i){return Mn("error",this._namespace,i)}info(...i){return Mn("info",this._namespace,i)}warn(...i){return Mn("warn",this._namespace,i)}verbose(...i){return Mn("verbose",this._namespace,i)}}});function Vy(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 zy=k(()=>{});var YI,Ji,dc=k(()=>{Dn();$y();zy();YI="diag",Ji=class Ky{static instance(){return this._instance||(this._instance=new Ky),this._instance}constructor(){function e(n){return function(...s){let o=oi("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=oi("diag"),c=Vy((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 Rr("diag",c,t,!0)};t.setLogger=r,t.disable=()=>{Nr(YI,t)},t.createComponentLogger=n=>new Wy(n),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}});function li(i){return Symbol.for(i)}var Ln,ha=k(()=>{Ln=new class uc{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 uc(t._currentContext);return s._currentContext.set(r,n),s},t.deleteValue=r=>{let n=new uc(t._currentContext);return n._currentContext.delete(r),n}}}});var mc,Yy=k(()=>{mc=(function(i){return i[i.NONE=0]="NONE",i[i.SAMPLED=1]="SAMPLED",i})({})});var QI,JI,Qy,Jy=k(()=>{QI="0000000000000000",JI="00000000000000000000000000000000",Qy={traceId:JI,spanId:QI,traceFlags:0}});var ki,ya=k(()=>{Jy();ki=class{constructor(i=Qy){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 Xy(i,e){if(typeof i!="string"||i.length!==e)return!1;let t=0;for(let r=0;r<i.length;r+=4)t+=(ba[i.charCodeAt(r)]|0)+(ba[i.charCodeAt(r+1)]|0)+(ba[i.charCodeAt(r+2)]|0)+(ba[i.charCodeAt(r+3)]|0);return t===e}function Zy(i){return Xy(i,32)&&i!=="00000000000000000000000000000000"}function eb(i){return Xy(i,16)&&i!=="0000000000000000"}function Xi(i){return Zy(i.traceId)&&eb(i.spanId)}function tb(i){return new ki(i)}var ba,_a=k(()=>{ya();ba=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 ib,rb=k(()=>{ha();ib=class{active(){return Ln}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 gc,XI,ZI,Pr,va=k(()=>{Dn();dc();rb();gc="context",XI=new ib,ZI=Object.freeze({dispose:()=>{}}),Pr=class nb{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new nb),this._instance}setGlobalContextManager(e){return Rr(gc,e,Ji.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,Ji.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.")),ZI)}_getContextManager(){return oi(gc)||XI}disable(){this._getContextManager().disable(),Nr(gc,Ji.instance())}}});function wa(i){return i.getValue(fc)||void 0}function sb(){return wa(Pr.getInstance().active())}function Un(i,e){return i.setValue(fc,e)}function ab(i){return i.deleteValue(fc)}function ob(i,e){return Un(i,new ki(e))}function ka(i){var e;return(e=wa(i))===null||e===void 0?void 0:e.spanContext()}var fc,hc=k(()=>{ha();va();ya();fc=li("OpenTelemetry Context Key SPAN")});function ex(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 yc,Sa,bc=k(()=>{va();ya();hc();_a();yc=Pr.getInstance(),Sa=class{startSpan(i,e,t=yc.active()){if(e?.root)return new ki;let r=t&&ka(t);return ex(r)&&Xi(r)?new ki(r):new ki}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:yc.active(),c=this.startSpan(i,s,a),p=Un(a,c);return yc.with(p,l,void 0,c)}}});var tx,lb,cb=k(()=>{bc();tx=new Sa,lb=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):tx}}});var pb,db=k(()=>{bc();pb=class{getTracer(i,e,t){return new Sa}}});var ix,_c,ub=k(()=>{cb();db();ix=new pb,_c=class{getTracer(i,e,t){var r;return(r=this.getDelegateTracer(i,e,t))!==null&&r!==void 0?r:new lb(this,i,e,t)}getDelegate(){var i;return(i=this._delegate)!==null&&i!==void 0?i:ix}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 Ke,mb=k(()=>{va();Ke=Pr.getInstance()});var vc,gb,hb=k(()=>{Dn();dc();hc();_a();ub();vc="trace",gb=class fb{constructor(){this._proxyTracerProvider=new _c,this.wrapSpanContext=tb,this.isSpanContextValid=Xi,this.deleteSpan=ab,this.getSpan=wa,this.getActiveSpan=sb,this.getSpanContext=ka,this.setSpan=Un,this.setSpanContext=ob}static getInstance(){return this._instance||(this._instance=new fb),this._instance}setGlobalTracerProvider(e){let t=Rr(vc,this._proxyTracerProvider,Ji.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return oi(vc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){Nr(vc,Ji.instance()),this._proxyTracerProvider=new _c}}});var Si,yb=k(()=>{hb();Si=gb.getInstance()});var Ea=k(()=>{ha();Yy();_a();mb();yb()});import{AsyncLocalStorage as nx}from"node:async_hooks";function wc(){let e=Pt(Ce()).getTracingChannelBinding?.()?.asyncLocalStorage??new nx;function t(){let l=e.getStore();return l||{scope:Wi(),isolationScope:$i()}}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 wn(a.getPropagationContext())||a.setPropagationContext({traceId:Gi(),sampleRand:_t()}),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 bn({withScope:r,withSetScope:n,withIsolationScope:s,withSetIsolationScope:o,getCurrentScope:()=>t().scope,getIsolationScope:()=>t().isolationScope,getTracingChannelBinding:()=>({asyncLocalStorage:e})}),e}var bb=k(()=>{Wt()});function K(i){return[...new Set(i.map(e=>e.module.name))]}var ce=k(()=>{});var kc,zB,_b=k(()=>{ce();kc=[{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"}}],zB=K(kc)});var Dt,Sc,QB,vb=k(()=>{ce();Dt={name:"amqplib",versionRange:">=0.5.5 <3"},Sc=[...["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"}}],QB=K(Sc)});var Ec,ZB,wb=k(()=>{ce();Ec=[...["resources/messages/messages.js","resources/messages/messages.mjs"].map(i=>({channelName:"chat",module:{name:"@anthropic-ai/sdk",versionRange:">=0.19.2 <1",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 <1",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 <1",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 <1",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 <1",filePath:i},functionQuery:{className:"SessionToolRunner"}}))],ZB=K(Ec)});var Cr,kb,Sb=k(()=>{Cr={name:"dataloader",versionRange:">=2.0.0 <3",filePath:"index.js"},kb=[{channelName:"construct",module:Cr,functionQuery:{functionName:"DataLoader",kind:"Sync"}},{channelName:"load",module:Cr,functionQuery:{expressionName:"load",kind:"Async"}},{channelName:"loadMany",module:Cr,functionQuery:{expressionName:"loadMany",kind:"Async"}},{channelName:"prime",module:Cr,functionQuery:{expressionName:"prime",kind:"Sync"}},{channelName:"clear",module:Cr,functionQuery:{expressionName:"clear",kind:"Sync"}},{channelName:"clearAll",module:Cr,functionQuery:{expressionName:"clearAll",kind:"Sync"}}]});var Tc,r3,Eb=k(()=>{ce();Tc=[{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"}}],r3=K(Tc)});var sx,ax,ox,lx,cx,Ic,a3,Tb=k(()=>{ce();sx=">=3.0.0 <5",ax=/dist\/lite\/(index|common-[^/]+)\.node\.(cjs\.js|mjs)$/,ox=[{functionName:"addDoc",channelName:"add-doc"},{functionName:"getDocs",channelName:"get-docs"},{functionName:"setDoc",channelName:"set-doc"},{functionName:"deleteDoc",channelName:"delete-doc"}],lx=">=6.0.0 <7",cx=[{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"}],Ic=[...ox.map(({functionName:i,channelName:e})=>({channelName:e,module:{name:"@firebase/firestore",versionRange:sx,filePath:ax},functionQuery:{functionName:i,kind:"Auto"}})),...cx.map(({file:i,functionName:e,channelName:t})=>({channelName:t,module:{name:"firebase-functions",versionRange:lx,filePath:i},functionQuery:{functionName:e,kind:"Sync"}}))],a3=K(Ic)});var xc,c3,Ib=k(()=>{ce();xc=[{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"}}],c3=K(xc)});var Ac,Oc,u3,xb=k(()=>{ce();Ac=["dist/node/index.js","dist/node/index.mjs","dist/node/index.cjs"],Oc=[...Ac.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"}}))),...Ac.map(i=>({channelName:"embed-content",module:{name:"@google/genai",versionRange:">=0.10.0 <3",filePath:i},functionQuery:{className:"Models",methodName:"embedContent",kind:"Auto"}})),...Ac.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"}})))],u3=K(Oc)});var Rc,f3,Ab=k(()=>{ce();Rc=[...["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"}}))],f3=K(Rc)});function qn(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 Nc=k(()=>{});var Pc,v3,Ob=k(()=>{ce();Nc();Pc=qn({name:"groq-sdk",versionRange:">=0.3.0 <2"}),v3=K(Pc)});var Cc,S3,Rb=k(()=>{ce();Cc=[{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"}}],S3=K(Cc)});var px,Dc,I3,Nb=k(()=>{ce();px=[{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"}}],Dc=px,I3=K(Dc)});function rt(i){return{channelName:"module-registration",module:i,astQuery:"Program",transform:dx}}var dx,Ei=k(()=>{dx="sentryModuleRegistration"});var Mc,N3,Pb=k(()=>{ce();Ei();Mc=[rt({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"}}],N3=K(Mc)});var Lc,D3,Cb=k(()=>{ce();Lc=[{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"}}],D3=K(Lc)});function fx(i,e){return{channelName:"query",module:{name:Db,versionRange:e,filePath:i},functionQuery:{className:"Runner",methodName:"query",kind:"Async"}}}function hx(i,e,t){return{channelName:i,module:{name:Db,versionRange:t,filePath:e},functionQuery:{className:"Client",methodName:i,kind:"Sync"}}}var Db,ux,mx,gx,Mb,Lb=k(()=>{Db="knex",ux=[{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"}],mx=[{filePath:"lib/client.js",versionRange:">=0.10.0 <4"},{filePath:"src/client.js",versionRange:">=0.18.0 <0.19.0"}],gx=["queryBuilder","schemaBuilder","raw"];Mb=[...ux.map(({filePath:i,versionRange:e})=>fx(i,e)),...mx.flatMap(({filePath:i,versionRange:e})=>gx.map(t=>hx(t,i,e)))]});var Uc,q3,Ub=k(()=>{ce();Uc=[{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"}}],q3=K(Uc)});var yx,qc,Ta,qb,bx,_x,jc,B3,H3,jb=k(()=>{ce();yx=["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"}}]}),qc="embedQuery",Ta="embedDocuments",qb=[{name:"@langchain/openai",versionRange:">=0.1.0 <2.0.0",methods:[qc,Ta]},{name:"@langchain/google-genai",versionRange:">=0.1.0 <3.0.0",methods:[qc,Ta]},{name:"@langchain/mistralai",versionRange:">=0.1.0 <2.0.0",methods:[qc,Ta]},{name:"@langchain/google-common",versionRange:">=0.1.0 <3.0.0",methods:[Ta]}],bx=qb.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"}})))),_x=["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"}})),jc=[...yx,...bx,..._x],B3=qb.flatMap(({name:i,methods:e})=>e.map(t=>`orchestrion:${i}:${t}`)),H3=K(jc)});var Fb,vx,wx,Fc,$3,Bb=k(()=>{ce();Fb=i=>({name:"@langchain/langgraph",versionRange:">=0.0.0 <2.0.0",filePath:i}),vx=["dist/graph/state.cjs","dist/graph/state.js"].map(i=>({channelName:"stateGraphCompile",module:Fb(i),functionQuery:{className:"StateGraph",methodName:"compile",kind:"Sync"}})),wx=["dist/prebuilt/react_agent_executor.cjs","dist/prebuilt/react_agent_executor.js"].map(i=>({channelName:"createReactAgent",module:Fb(i),functionQuery:{functionName:"createReactAgent",kind:"Sync"}})),Fc=[...vx,...wx],$3=K(Fc)});var Bc,K3,Hb=k(()=>{ce();Bc=[{channelName:"load",module:{name:"lru-memoizer",versionRange:">=2.1.0 <4",filePath:"lib/async.js"},functionQuery:{functionName:"memoizedFunction",kind:"Callback"}}],K3=K(Bc)});var Gb,Wb=k(()=>{Ei();Gb=[rt({name:"@flue/runtime",versionRange:">=2.0.0 <3.0.0",filePath:"dist/index.mjs"})]});var kx,Sx,Ex,Hc,Z3,$b=k(()=>{ce();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"}}],Sx=["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"}})),Ex=[{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"}}],Hc=[...kx,...Sx,...Ex],Z3=K(Hc)});var Vb,Gc,iH,zb=k(()=>{ce();Vb={name:"@earendil-works/pi-durable",versionRange:">=1.0.0 <2.0.0"},Gc=[{channelName:"harnessOpen",module:{...Vb,filePath:"dist/harness/harness.js"},functionQuery:{methodName:"open",kind:"Async"}},...[["bash","createBashTool"],["read","createReadTool"],["edit","createEditTool"],["write","createWriteTool"]].map(([i,e])=>({channelName:"codingTool",module:{...Vb,filePath:`dist/tools/${i}.js`},functionQuery:{functionName:e,kind:"Sync"}}))],iH=K(Gc)});var Tx,Ix,Wc,sH,Kb=k(()=>{ce();Tx=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/server",versionRange:">=2.0.0 <3",filePath:/^dist\/mcp-[\w-]+\.(?:cjs|mjs)$/},functionQuery:{className:"McpServer"}}],Ix=[{channelName:"mcpServerConstructor",module:{name:"@modelcontextprotocol/sdk",versionRange:">=1.9.0 <2",filePath:/(?:^|\/)server\/mcp\.js$/},functionQuery:{className:"McpServer"}}],Wc=[...Tx,...Ix],sH=K(Wc)});var $c,Ia,Yb,Vc,lH,Qb=k(()=>{ce();$c={name:"@mistralai/mistralai",versionRange:">=2.0.0 <3"},Ia={...$c,filePath:"esm/sdk/chat.js"},Yb={...$c,filePath:"esm/sdk/agents.js"},Vc=[{channelName:"chat",module:Ia,functionQuery:{className:"Chat",methodName:"complete",kind:"Auto"}},{channelName:"chat",module:Ia,functionQuery:{className:"Chat",methodName:"parse",kind:"Auto"}},{channelName:"chat-stream",module:Ia,functionQuery:{className:"Chat",methodName:"stream",kind:"Auto"}},{channelName:"chat-stream",module:Ia,functionQuery:{className:"Chat",methodName:"parseStream",kind:"Auto"}},{channelName:"embeddings",module:{...$c,filePath:"esm/sdk/embeddings.js"},functionQuery:{className:"Embeddings",methodName:"create",kind:"Auto"}},{channelName:"agents",module:Yb,functionQuery:{className:"Agents",methodName:"complete",kind:"Auto"}},{channelName:"agents-stream",module:Yb,functionQuery:{className:"Agents",methodName:"stream",kind:"Auto"}}],lH=K(Vc)});var Zi,zc,dH,Jb=k(()=>{ce();Zi={name:"mongodb"},zc=[{channelName:"command",module:{...Zi,versionRange:">=6.4.0 <8",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Async"}},{channelName:"command",module:{...Zi,versionRange:">=4.0.0 <6.4",filePath:"lib/cmap/connection.js"},functionQuery:{methodName:"command",kind:"Callback"}},{channelName:"checkout",module:{...Zi,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:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/index.js"},functionQuery:{expressionName:i,kind:"Callback"}})),{channelName:"v3_command",module:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/command.js"},functionQuery:{functionName:"command",kind:"Callback"}},{channelName:"v3_query",module:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/query.js"},functionQuery:{functionName:"query",kind:"Callback"}},{channelName:"v3_get_more",module:{...Zi,versionRange:">=3.3.0 <4",filePath:"lib/core/wireprotocol/get_more.js"},functionQuery:{functionName:"getMore",kind:"Callback"}}],dH=K(zc)});var Ti,Xb,Kc,fH,hH,Zb=k(()=>{ce();Ei();Ti={name:"mongoose",versionRange:">=5.9.7 <9.7.0"},Xb=["find","findOne","deleteOne","deleteMany","estimatedDocumentCount","countDocuments","distinct","where","$where","findOneAndUpdate","findOneAndDelete","findOneAndReplace","remove","count","findOneAndRemove"],Kc=[rt({name:"mongoose",versionRange:">=9.7.0",filePath:"lib/query.js"}),{channelName:"query_exec",module:{...Ti,filePath:"lib/query.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"aggregate_exec",module:{...Ti,filePath:"lib/aggregate.js"},functionQuery:{expressionName:"exec",kind:"Auto"}},{channelName:"model_save",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"save",kind:"Auto"}},{channelName:"model_insert_many",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"insertMany",kind:"Auto"}},{channelName:"model_bulk_write",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"bulkWrite",kind:"Auto"}},{channelName:"model_remove",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"remove",kind:"Auto"}},{channelName:"model_aggregate",module:{...Ti,filePath:"lib/model.js"},functionQuery:{expressionName:"aggregate",kind:"Sync"}},...Xb.map(i=>({channelName:`ctx_${i}`,module:{...Ti,filePath:"lib/query.js"},functionQuery:{expressionName:i,kind:"Sync"}}))],fH=K(Kc),hH=Xb.map(i=>`orchestrion:mongoose:ctx_${i}`)});var Yc,vH,e_=k(()=>{ce();Ei();Yc=[rt({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"}}],vH=K(Yc)});var Qc,SH,t_=k(()=>{ce();Qc=[{channelName:"query",module:{name:"mysql",versionRange:">=2.0.0 <3",filePath:"lib/Connection.js"},functionQuery:{expressionName:"query",kind:"Auto"}}],SH=K(Qc)});var Jc,Xc,IH,i_=k(()=>{ce();Jc={name:"@neondatabase/serverless",versionRange:">=1.0.0 <2",filePath:/^index\.m?js$/},Xc=[{channelName:"query",module:Jc,astQuery:'ClassBody:has(MethodDefinition[key.name="_pulseQueryQueue"]) > MethodDefinition[key.name="query"] > FunctionExpression',functionQuery:{methodName:"query",kind:"Auto"}},{channelName:"http-query",module:Jc,astQuery:'FunctionDeclaration[async=true]:has(Literal[value="Neon-Connection-String"])',functionQuery:{kind:"Async"}},{channelName:"resolve-connection",module:Jc,astQuery:'FunctionDeclaration[async=true]:has(ReturnStatement > ObjectExpression > Property[key.name="resolvedURL"])',functionQuery:{kind:"Async"}}],IH=K(Xc)});var r_,n_=k(()=>{r_=[{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:"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 s_,a_=k(()=>{Ei();s_=[rt({name:"h3",versionRange:">=2.0.0-0",filePath:"dist/h3.mjs"})]});var Zc,PH,o_=k(()=>{ce();Zc=[...["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"}}))],PH=K(Zc)});var ep,MH,l_=k(()=>{ce();ep=[{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"}}],MH=K(ep)});var xx,tp,qH,c_=k(()=>{ce();xx=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"}}],tp=["src","cjs/src"].flatMap(xx),qH=K(tp)});function p_(i,e){return{channelName:i,module:{name:Ax,versionRange:Rx,filePath:Ox},functionQuery:{className:"CollectionBase",methodName:i,kind:e}}}var Ax,Ox,Rx,Nx,Px,ip,BH,d_=k(()=>{ce();Ax="@prisma/orm-family-sql",Ox="dist/orm-client.mjs",Rx=">=8.0.0-rc.15 <9",Nx=["aggregate","first","create","createAndCount","upsert","update","updateAndCount","delete","deleteAndCount"],Px=["all","createAll","updateAll","deleteAll"];ip=[...Nx.map(i=>p_(i,"Async")),...Px.map(i=>p_(i,"Sync"))],BH=K(ip)});var rp,$H,u_=k(()=>{ce();Ei();rp=[rt({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"}}],$H=K(rp)});var Cx,m_,g_=k(()=>{Cx=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"}}],m_=["dist","dist/esm"].flatMap(Cx)});var f_,h_=k(()=>{f_=[{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 Dx,Mx,Lx,Ux,np,QH,y_=k(()=>{ce();Dx="tedious",Mx="lib/connection.js",Lx=">=1.11.0 <21",Ux=["connect","execSql","execSqlBatch","callProcedure","execBulkLoad","prepare","execute"],np=Ux.map(i=>({channelName:i,module:{name:Dx,versionRange:Lx,filePath:Mx},functionQuery:{className:"Connection",methodName:i,kind:"Sync"}})),QH=K(np)});var sp,eG,b_=k(()=>{ce();Nc();sp=[...qn({name:"together-ai",versionRange:">=0.6.0 <1"}),...qn({name:"together-ai",versionRange:">=1.0.0 <2"},{chat:"BaseCompletions",embeddings:"BaseEmbeddings"})],eG=K(sp)});var ap,rG,__=k(()=>{ce();ap=["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"}})),rG=K(ap)});function er(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 op,oG,v_=k(()=>{ce();Ei();op=[...["dist/index.js","dist/index.mjs"].map(i=>rt({name:"ai",versionRange:">=7.0.0",filePath:i})),...er(">=4.0.0 <7.0.0","generateText","generateText","Async"),...er(">=4.0.0 <7.0.0","streamText","streamText","Sync"),...er(">=4.0.0 <7.0.0","generateObject","generateObject","Async"),...er(">=4.0.0 <7.0.0","embed","embed","Async"),...er(">=4.0.0 <7.0.0","embedMany","embedMany","Async"),...er(">=5.0.0 <7.0.0","resolveLanguageModel","resolveLanguageModel","Sync"),...er(">=6.0.0 <7.0.0","executeToolCall","executeToolCall","Async")];oG=K(op)});function qx(i=[]){return[...ec([...w_,...i].map(e=>e.module.name)),"@remix-run/node"]}var w_,jn,XG,k_=k(()=>{Wt();_b();vb();wb();Sb();Eb();Tb();Ib();xb();Ab();Ob();Rb();Nb();Pb();Cb();Lb();Ub();jb();Bb();Hb();Wb();$b();zb();Kb();Qb();Jb();Zb();e_();t_();i_();n_();a_();o_();l_();c_();d_();u_();g_();h_();y_();b_();__();v_();w_=[...Sc,...Ec,...kc,...kb,...Tc,...Ic,...xc,...Oc,...Rc,...Pc,...Cc,...Dc,...Mc,...Lc,...Mb,...Uc,...jc,...Fc,...Bc,...Gb,...Hc,...Wc,...Vc,...zc,...Kc,...Yc,...Qc,...Xc,...r_,...s_,...Zc,...ep,...Gc,...tp,...ip,...rp,...m_,...f_,...np,...sp,...ap,...op],jn=w_.filter(i=>!i.transform);XG=qx()});var S_=k(()=>{bb()});var E_,T_=k(()=>{E_=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__});import{posix as jx,sep as Fx}from"node:path";function I_(i){return i.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function x_(i=process.argv[1]?ac(process.argv[1]):process.cwd(),e=Fx==="\\"){let t=e?I_(i):i;return r=>{if(!r)return;let n=e?I_(r):r,{dir:s,base:o,ext:l}=jx.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 A_=k(()=>{Wt()});var lp,O_=k(()=>{Wt();cc();A_();lp=rl(lc(x_()))});import{AsyncLocalStorage as Bx}from"node:async_hooks";function P_(i){return i.getValue(fp)}function Gx(i,e){return i.setValue(fp,e)}function Wx(i,e){i.refs[N_]=kr(e)}function C_(i){return Ki(i.refs[N_])}function $x(i,e){let t=i?Si.setSpan(Ke.active(),i):Si.deleteSpan(Ke.active());return Ke.with(t,()=>{let r=ni();return zs(r,i??void 0),e(r)})}function Vx(i){let e=i?zx(i):Si.getActiveSpan();return e&&Xi(e.spanContext())?e:void 0}function zx(i){let e=C_(i);return e?Si.getSpan(e):void 0}function Kx(i){let e=P_(i),t=e?.scope||ni(),r=e?.isolationScope||Vi(),n=i.getValue(dp)===!0,s=i.getValue(up),o=i.getValue(mp),l=s||t.clone(),a=o||(n?r.clone():r),d=Gx(i,{scope:l,isolationScope:a}).deleteValue(dp).deleteValue(up).deleteValue(mp);return Wx(l,d),d}function Qx(i){if(typeof i!="object"||!i)return!1;let e=i;return typeof e.on=="function"&&typeof e.emit=="function"}function cp(i,e){let t=i[e];return typeof t=="function"?t:void 0}function pp(i,e,t){try{i[e]=t}catch{}}function D_(){let e=Pt(Ce()).getTracingChannelBinding?.()?.asyncLocalStorage??new Bx;function t(){let d=Ke.active(),g=P_(d);return g||{scope:Wi(),isolationScope:$i()}}function r(d){let g=Ke.active();return Ke.with(g,()=>d(l()))}function n(d,g){let f=C_(d)||Ke.active();return Ke.with(f.setValue(up,d),()=>g(d))}function s(d){let g=Ke.active();return Ke.with(g.setValue(dp,!0),()=>{let f=l();return wn(f.getPropagationContext())||f.setPropagationContext({traceId:Gi(),sampleRand:_t()}),d(a())})}function o(d,g){let f=Ke.active();return Ke.with(f.setValue(mp,d),()=>g(a()))}function l(){return t().scope}function a(){return t().isolationScope}function c(){return{asyncLocalStorage:e}}bn({withScope:r,withSetScope:n,withSetIsolationScope:o,withIsolationScope:s,getCurrentScope:l,getIsolationScope:a,getActiveSpan:Vx,withActiveSpan:$x,getTracingChannelBinding:c});let p=new gp(e);return Ke.setGlobalContextManager(p),p.getAsyncLocalStorageLookup()}function Jx(i){let{traceFlags:e,traceState:t}=i,r=t?t.get(Hx)==="1":!1;if(e===mc.SAMPLED)return!0;if(r)return!1;let n=t?t.get(R_):void 0,s=n?_n(n):void 0;if(s?.sampled==="true")return!0;if(s?.sampled==="false")return!1}function M_(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=si(r),a=typeof l.sample_rand=="string"?Number(l.sample_rand):void 0,c=!!o?.get(R_),p=t.clone();p.setPropagationContext({traceId:s,parentSpanId:n,sampled:Jx(r.spanContext()),dsc:c?l:void 0,sampleRand:typeof a=="number"&&!Number.isNaN(a)?a:_t()}),zs(p,void 0),e.scope=p,e.parentSpan=void 0})}var R_,Hx,fp,dp,up,mp,N_,T5,Yx,gp,L_=k(()=>{Wt();Ea();Ea();R_="sentry.dsc",Hx="sentry.sampled_not_recording",fp=li("sentry_scopes"),dp=li("sentry_fork_isolation_scope"),up=li("sentry_fork_set_scope"),mp=li("sentry_fork_set_isolation_scope"),N_="context";T5=li("OpenTelemetry SDK Context Key SUPPRESS_TRACING");Yx=["addListener","on","once","prependListener","prependOnceListener"],gp=class{constructor(e){this._kOtListeners=Symbol("OtListeners"),this._wrapped=!1,this._asyncLocalStorage=e}active(){return this._asyncLocalStorage.getStore()??Ln}with(e,t,r,...n){let s=Kx(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 Qx(t)?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}getAsyncLocalStorageLookup(){return{asyncLocalStorage:this._asyncLocalStorage,contextSymbol:fp}}_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 Yx){let s=cp(t,n);s&&pp(t,n,this._patchAddListener(t,s,e))}for(let n of["removeListener","off"]){let s=cp(t,n);s&&pp(t,n,this._patchRemoveListener(t,s))}let r=cp(t,"removeAllListeners");return r&&pp(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 Dr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function U_(i){return i&&Object.prototype.hasOwnProperty.call(i,"default")&&Object.keys(i).length===1?i.default:i}var Fn=k(()=>{});function Xx(i,e){let[t]=F_(i,"");for(let r of eA(e))if(Zx(r,t))return!0;return!1}function Zx(i,e){for(let[t,r]of i)if(!rA(e,r,t))return!1;return!0}function q_(i){return i==="latest"&&(i=">=0"),i.match(/^([^\d+]*)(\d.*)$/)||[null,"","*.*.*"]}function eA(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=q_(s),l=o[1]||"=";l.endsWith("v")&&(l=l.slice(0,-1));let[a,c]=F_(o[2],l);if(n+2<r.length&&r[n+1]==="-"){let p=q_(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?Mr(a,0):Mr(a,1)])}else if(c[0]==="^"){let p=a[0]!==0?0:a[1]!==0?1:2;t.push([">=",a]),t.push(["<",p===0?Mr(a,0):p===1?Mr(a,1):Mr(a,2)])}else t.push([c.replace("~","").replace("^",""),a])}return t.length&&e.push(t),e}function Mr(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 tA(i){return i==="x"||i==="X"||i==="*"||i==="latest"?-1:Number(i)}function iA(i){return/^\d+$/.test(i)?Number(i):i}function Ii(i,e,t){return t===-1?i!=="<":i==="="?e===t:i===">"?e>t:i===">="?e>=t:i==="<"?e<t:i==="<="?e<=t:!1}function F_(i,e){i=i.split("+")[0];let[t,r]=i.split("-"),n=t.split(".").map(tA).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(iA)),e]:[n.slice(0,3),e]}function rA(i,e,t){if(!Ii("=",i[0],e[0]))return Ii(t,i[0],e[0]);if(!Ii("=",i[1],e[1]))return Ii(t,i[1],e[1]);if(!Ii("=",i[2],e[2])||i.length===3&&e.length===3)return Ii(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(Ii(t,i[r]||"",e[r]||""))return!0;return!1}var j_,B_=k(()=>{j_=Xx});function yp(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 _p(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)||V_(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 yp(e)})(i)||(function(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)})(i)||V_(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 Bn(i){return(Bn=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 V_(i,e){if(i){if(typeof i=="string")return yp(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)?yp(i,e):void 0}}function z_(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 He(i){if(i==null)return function(){return!0};if(hp!=null){var e=hp.get(i);return e!=null||(e=H_(i),hp.set(i,e)),e}return H_(i)}function H_(i){switch(i.type){case"wildcard":return function(){return!0};case"identifier":var e=i.value.toLowerCase();return function(N,w,h){var M=h&&h.nodeTypeKey||"type";return e===N[M].toLowerCase()};case"exactNode":return function(N,w){return w.length===0};case"field":var t=i.name.split(".");return function(N,w){return(function h(M,Z,re,ae){for(var P=Z,Se=ae;Se<re.length;++Se){if(P==null)return!1;var me=P[re[Se]];if(Array.isArray(me)){for(var be=0;be<me.length;++be)if(h(M,me[be],re,Se+1))return!0;return!1}P=me}return M===P})(N,w[t.length-1],t,0)};case"matches":var r=i.selectors.map(He);return function(N,w,h){for(var M=0;M<r.length;++M)if(r[M](N,w,h))return!0;return!1};case"compound":var n=i.selectors.map(He);return function(N,w,h){for(var M=0;M<n.length;++M)if(!n[M](N,w,h))return!1;return!0};case"not":var s=i.selectors.map(He);return function(N,w,h){for(var M=0;M<s.length;++M)if(s[M](N,w,h))return!1;return!0};case"has":var o=i.selectors.map(He);return function(N,w,h){var M=!1,Z=[];return xa.traverse(N,{enter:function(re,ae){ae!=null&&Z.unshift(ae);for(var P=0;P<o.length;++P)if(o[P](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=He(i.left),a=He(i.right);return function(N,w,h){return!!(w.length>0&&a(N,w,h))&&l(w[0],w.slice(1),h)};case"descendant":var c=He(i.left),p=He(i.right);return function(N,w,h){if(p(N,w,h)){for(var M=0,Z=w.length;M<Z;++M)if(c(w[M],w.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 w=Mt(N,d);return typeof w=="string"&&i.value.value.test(w)};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===Bn(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 f="".concat(i.value.value);return function(N){return f!=="".concat(Mt(N,d))};case"type":return function(N){return i.value.value!==Bn(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 _=He(i.left),y=He(i.right);return function(N,w,h){return y(N,w,h)&&G_(N,_,w,"LEFT_SIDE",h)||i.left.subject&&_(N,w,h)&&G_(N,y,w,"RIGHT_SIDE",h)};case"adjacent":var S=He(i.left),T=He(i.right);return function(N,w,h){return T(N,w,h)&&W_(N,S,w,"LEFT_SIDE",h)||i.right.subject&&S(N,w,h)&&W_(N,T,w,"RIGHT_SIDE",h)};case"nth-child":var A=i.index.value,I=He(i.right);return function(N,w,h){return I(N,w,h)&&$_(N,w,A,h)};case"nth-last-child":var C=-i.index.value,q=He(i.right);return function(N,w,h){return q(N,w,h)&&$_(N,w,C,h)};case"class":var F=i.name.toLowerCase();return function(N,w,h){if(h&&h.matchClass)return h.matchClass(i.name,N,w);if(h&&h.nodeTypeKey)return!1;switch(F){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"&&(w.length===0||w[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 vp(i,e){var t=e&&e.nodeTypeKey||"type",r=i[t];return e&&e.visitorKeys&&e.visitorKeys[r]?e.visitorKeys[r]:xa.VisitorKeys[r]?xa.VisitorKeys[r]:e&&typeof e.fallback=="function"?e.fallback(i):Object.keys(i).filter((function(n){return n!==t}))}function bp(i,e){var t=e&&e.nodeTypeKey||"type";return i!==null&&Bn(i)==="object"&&typeof i[t]=="string"}function G_(i,e,t,r,n){var s=_p(t,1)[0];if(!s)return!1;for(var o=vp(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(bp(a[g],n)&&e(a[g],t,n))return!0}}return!1}function W_(i,e,t,r,n){var s=_p(t,1)[0];if(!s)return!1;for(var o=vp(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&&bp(a[c-1],n)&&e(a[c-1],t,n)||r==="RIGHT_SIDE"&&c<a.length-1&&bp(a[c+1],n)&&e(a[c+1],t,n))return!0}}return!1}function $_(i,e,t,r){if(t===0)return!1;var n=_p(e,1)[0];if(!n)return!1;for(var s=vp(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 K_(i,e,t,r){if(e){var n=[],s=He(e),o=(function l(a,c){if(a==null||Bn(a)!="object")return[];c==null&&(c=a);for(var p=a.subject?[c]:[],d=Object.keys(a),g=0;g<d.length;++g){var f=d[g],_=a[f];p.push.apply(p,nA(l(_,f==="left"?_:c)))}return p})(e).map(He);xa.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 f=n.slice(d+1);o[c](n[d],f,r)&&t(n[d],a,f)}}else t(l,a,n)},leave:function(){n.shift()},keys:r&&r.visitorKeys,fallback:r&&r.fallback||"iteration"})}}function Y_(i,e,t){var r=[];return K_(i,e,(function(n){r.push(n)}),t),r}function Q_(i){return sA.parse(i)}function $t(i,e,t){return Y_(i,Q_(e),t)}var xa,sA,hp,wp=k(()=>{xa=z_((function(i,e){(function t(r){var n,s,o,l,a,c;function p(I){var C,q,F={};for(C in I)I.hasOwnProperty(C)&&(q=I[C],F[C]=typeof q=="object"&&q!==null?p(q):q);return F}function d(I,C){this.parent=I,this.key=C}function g(I,C,q,F){this.node=I,this.path=C,this.wrap=q,this.ref=F}function f(){}function _(I){return I!=null&&typeof I=="object"&&typeof I.type=="string"}function y(I,C){return(I===n.ObjectExpression||I===n.ObjectPattern)&&C==="properties"}function S(I,C){for(var q=I.length-1;q>=0;--q)if(I[q].node===C)return!0;return!1}function T(I,C){return new f().traverse(I,C)}function A(I,C){var q;return q=(function(F,N){var w,h,M,Z;for(h=F.length,M=0;h;)N(F[Z=M+(w=h>>>1)])?h=w:(M=Z+1,h-=w+1);return M})(C,(function(F){return F.range[0]>I.range[0]})),I.extendedRange=[I.range[0],I.range[1]],q!==C.length&&(I.extendedRange[1]=C[q].range[0]),(q-=1)>=0&&(I.extendedRange[0]=C[q].range[1]),I}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(I){this.parent[this.key]=I},d.prototype.remove=function(){return Array.isArray(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},f.prototype.path=function(){var I,C,q,F,N;function w(h,M){if(Array.isArray(M))for(q=0,F=M.length;q<F;++q)h.push(M[q]);else h.push(M)}if(!this.__current.path)return null;for(N=[],I=2,C=this.__leavelist.length;I<C;++I)w(N,this.__leavelist[I].path);return w(N,this.__current.path),N},f.prototype.type=function(){return this.current().type||this.__current.wrap},f.prototype.parents=function(){var I,C,q;for(q=[],I=1,C=this.__leavelist.length;I<C;++I)q.push(this.__leavelist[I].node);return q},f.prototype.current=function(){return this.__current.node},f.prototype.__execute=function(I,C){var q,F;return F=void 0,q=this.__current,this.__current=C,this.__state=null,I&&(F=I.call(this,C.node,this.__leavelist[this.__leavelist.length-1].node)),this.__current=q,F},f.prototype.notify=function(I){this.__state=I},f.prototype.skip=function(){this.notify(a)},f.prototype.break=function(){this.notify(l)},f.prototype.remove=function(){this.notify(c)},f.prototype.__initialize=function(I,C){this.visitor=C,this.root=I,this.__worklist=[],this.__leavelist=[],this.__current=null,this.__state=null,this.__fallback=null,C.fallback==="iteration"?this.__fallback=Object.keys:typeof C.fallback=="function"&&(this.__fallback=C.fallback),this.__keys=o,C.keys&&(this.__keys=Object.assign(Object.create(this.__keys),C.keys))},f.prototype.traverse=function(I,C){var q,F,N,w,h,M,Z,re,ae,P,Se,me;for(this.__initialize(I,C),me={},q=this.__worklist,F=this.__leavelist,q.push(new g(I,null,null,null)),F.push(new g(null,null,null,null));q.length;)if((N=q.pop())!==me){if(N.node){if(M=this.__execute(C.enter,N),this.__state===l||M===l)return;if(q.push(me),F.push(N),this.__state===a||M===a)continue;if(h=(w=N.node).type||N.wrap,!(P=this.__keys[h])){if(!this.__fallback)throw new Error("Unknown node type "+h+".");P=this.__fallback(w)}for(re=P.length;(re-=1)>=0;)if(Se=w[Z=P[re]]){if(Array.isArray(Se)){for(ae=Se.length;(ae-=1)>=0;)if(Se[ae]&&!S(F,Se[ae])){if(y(h,P[re]))N=new g(Se[ae],[Z,ae],"Property",null);else{if(!_(Se[ae]))continue;N=new g(Se[ae],[Z,ae],null,null)}q.push(N)}}else if(_(Se)){if(S(F,Se))continue;q.push(new g(Se,Z,null,null))}}}}else if(N=F.pop(),M=this.__execute(C.leave,N),this.__state===l||M===l)return},f.prototype.replace=function(I,C){var q,F,N,w,h,M,Z,re,ae,P,Se,me,be;function v(D){var $,ie,ue,je;if(D.ref.remove()){for(ie=D.ref.key,je=D.ref.parent,$=q.length;$--;)if((ue=q[$]).ref&&ue.ref.parent===je){if(ue.ref.key<ie)break;--ue.ref.key}}}for(this.__initialize(I,C),Se={},q=this.__worklist,F=this.__leavelist,M=new g(I,null,null,new d(me={root:I},"root")),q.push(M),F.push(M);q.length;)if((M=q.pop())!==Se){if((h=this.__execute(C.enter,M))!==void 0&&h!==l&&h!==a&&h!==c&&(M.ref.replace(h),M.node=h),this.__state!==c&&h!==c||(v(M),M.node=null),this.__state===l||h===l)return me.root;if((N=M.node)&&(q.push(Se),F.push(M),this.__state!==a&&h!==a)){if(w=N.type||M.wrap,!(ae=this.__keys[w])){if(!this.__fallback)throw new Error("Unknown node type "+w+".");ae=this.__fallback(N)}for(Z=ae.length;(Z-=1)>=0;)if(P=N[be=ae[Z]])if(Array.isArray(P)){for(re=P.length;(re-=1)>=0;)if(P[re]){if(y(w,ae[Z]))M=new g(P[re],[be,re],"Property",new d(P,re));else{if(!_(P[re]))continue;M=new g(P[re],[be,re],null,new d(P,re))}q.push(M)}}else _(P)&&q.push(new g(P,be,null,new d(N,be)))}}else if(M=F.pop(),(h=this.__execute(C.leave,M))!==void 0&&h!==l&&h!==a&&h!==c&&M.ref.replace(h),this.__state!==c&&h!==c||v(M),this.__state===l||h===l)return me.root;return me.root},r.Syntax=n,r.traverse=T,r.replace=function(I,C){return new f().replace(I,C)},r.attachComments=function(I,C,q){var F,N,w,h,M=[];if(!I.range)throw new Error("attachComments needs range information");if(!q.length){if(C.length){for(w=0,N=C.length;w<N;w+=1)(F=p(C[w])).extendedRange=[0,I.range[0]],M.push(F);I.leadingComments=M}return I}for(w=0,N=C.length;w<N;w+=1)M.push(A(p(C[w]),q));return h=0,T(I,{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(I,{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}}),I},r.VisitorKeys=o,r.VisitorOption=s,r.Controller=f,r.cloneEnvironment=function(){return t({})},r})(e)})),sA=z_((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:gu},p=gu,d=_e(" ",!1),g=/^[^ [\],():#!=><~+.]/,f=jt([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),_=_e(">",!1),y=_e("~",!1),S=_e("+",!1),T=_e(",",!1),A=function(x,L){return[x].concat(L.map((function(j){return j[3]})))},I=_e("!",!1),C=_e("*",!1),q=_e("#",!1),F=_e("[",!1),N=_e("]",!1),w=/^[><!]/,h=jt([">","<","!"],!1,!1),M=_e("=",!1),Z=function(x){return(x||"")+"="},re=/^[><]/,ae=jt([">","<"],!1,!1),P=_e(".",!1),Se=function(x,L,j){return{type:"attribute",name:x,operator:L,value:j}},me=_e('"',!1),be=/^[^\\"]/,v=jt(["\\",'"'],!0,!1),D=_e("\\",!1),$={type:"any"},ie=function(x,L){return x+L},ue=function(x){return{type:"literal",value:(L=x.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),Ut=/^[^\\']/,mi=jt(["\\","'"],!0,!1),ge=/^[0-9]/,St=jt([["0","9"]],!1,!1),us=_e("type(",!1),tn=/^[^ )]/,ru=jt([" ",")"],!0,!1),qi=_e(")",!1),nu=/^[imsu]/,su=jt(["i","m","s","u"],!1,!1),au=_e("/",!1),ou=/^[^\]\\]/,lu=jt(["]","\\"],!0,!1),cu=/^[^\/\\[]/,pu=jt(["/","\\","["],!0,!1),Ak=_e(":not(",!1),Ok=_e(":matches(",!1),du=function(x){return{type:"matches",selectors:x}},Rk=_e(":is(",!1),Nk=_e(":has(",!1),Pk=_e(":first-child",!1),Ck=_e(":last-child",!1),Dk=_e(":nth-child(",!1),Mk=_e(":nth-last-child(",!1),Lk=_e(":",!1),u=0,ms=[{line:1,column:1}],qt=0,Ro=[],V={};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(x,L){return{type:"literal",text:x,ignoreCase:L}}function jt(x,L,j){return{type:"class",parts:x,inverted:L,ignoreCase:j}}function uu(x){var L,j=ms[x];if(j)return j;for(L=x-1;!ms[L];)L--;for(j={line:(j=ms[L]).line,column:j.column};L<x;)t.charCodeAt(L)===10?(j.line++,j.column=1):j.column++,L++;return ms[x]=j,j}function mu(x,L){var j=uu(x),E=uu(L);return{start:{offset:x,line:j.line,column:j.column},end:{offset:L,line:E.line,column:E.column}}}function B(x){u<qt||(u>qt&&(qt=u,Ro=[]),Ro.push(x))}function gu(){var x,L,j,E,R=36*u+0,W=V[R];return W?(u=W.nextPos,W.result):(x=u,(L=le())!==a&&(j=gs())!==a&&le()!==a?x=L=(E=j).length===1?E[0]:{type:"matches",selectors:E}:(u=x,x=a),x===a&&(x=u,(L=le())!==a&&(L=void 0),x=L),V[R]={nextPos:u,result:x},x)}function le(){var x,L,j=36*u+1,E=V[j];if(E)return u=E.nextPos,E.result;for(x=[],t.charCodeAt(u)===32?(L=" ",u++):(L=a,B(d));L!==a;)x.push(L),t.charCodeAt(u)===32?(L=" ",u++):(L=a,B(d));return V[j]={nextPos:u,result:x},x}function Qt(){var x,L,j,E=36*u+2,R=V[E];if(R)return u=R.nextPos,R.result;if(L=[],g.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,B(f)),j!==a)for(;j!==a;)L.push(j),g.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,B(f));else L=a;return L!==a&&(L=L.join("")),x=L,V[E]={nextPos:u,result:x},x}function No(){var x,L,j,E=36*u+3,R=V[E];return R?(u=R.nextPos,R.result):(x=u,(L=le())!==a?(t.charCodeAt(u)===62?(j=">",u++):(j=a,B(_)),j!==a&&le()!==a?x=L="child":(u=x,x=a)):(u=x,x=a),x===a&&(x=u,(L=le())!==a?(t.charCodeAt(u)===126?(j="~",u++):(j=a,B(y)),j!==a&&le()!==a?x=L="sibling":(u=x,x=a)):(u=x,x=a),x===a&&(x=u,(L=le())!==a?(t.charCodeAt(u)===43?(j="+",u++):(j=a,B(S)),j!==a&&le()!==a?x=L="adjacent":(u=x,x=a)):(u=x,x=a),x===a&&(x=u,t.charCodeAt(u)===32?(L=" ",u++):(L=a,B(d)),L!==a&&(j=le())!==a?x=L="descendant":(u=x,x=a)))),V[E]={nextPos:u,result:x},x)}function gs(){var x,L,j,E,R,W,G,J,ee=36*u+5,te=V[ee];if(te)return u=te.nextPos,te.result;if(x=u,(L=fs())!==a){for(j=[],E=u,(R=le())!==a?(t.charCodeAt(u)===44?(W=",",u++):(W=a,B(T)),W!==a&&(G=le())!==a&&(J=fs())!==a?E=R=[R,W,G,J]:(u=E,E=a)):(u=E,E=a);E!==a;)j.push(E),E=u,(R=le())!==a?(t.charCodeAt(u)===44?(W=",",u++):(W=a,B(T)),W!==a&&(G=le())!==a&&(J=fs())!==a?E=R=[R,W,G,J]:(u=E,E=a)):(u=E,E=a);j!==a?x=L=A(L,j):(u=x,x=a)}else u=x,x=a;return V[ee]={nextPos:u,result:x},x}function Po(){var x,L,j,E,R,W=36*u+6,G=V[W];return G?(u=G.nextPos,G.result):(x=u,(L=No())===a&&(L=null),L!==a&&(j=fs())!==a?(R=j,x=L=(E=L)?{type:E,left:{type:"exactNode"},right:R}:R):(u=x,x=a),V[W]={nextPos:u,result:x},x)}function fs(){var x,L,j,E,R,W,G,J=36*u+7,ee=V[J];if(ee)return u=ee.nextPos,ee.result;if(x=u,(L=Co())!==a){for(j=[],E=u,(R=No())!==a&&(W=Co())!==a?E=R=[R,W]:(u=E,E=a);E!==a;)j.push(E),E=u,(R=No())!==a&&(W=Co())!==a?E=R=[R,W]:(u=E,E=a);j!==a?(G=L,x=L=j.reduce((function(te,Ae){return{type:Ae[0],left:te,right:Ae[1]}}),G)):(u=x,x=a)}else u=x,x=a;return V[J]={nextPos:u,result:x},x}function Co(){var x,L,j,E,R,W,G,J=36*u+8,ee=V[J];if(ee)return u=ee.nextPos,ee.result;if(x=u,t.charCodeAt(u)===33?(L="!",u++):(L=a,B(I)),L===a&&(L=null),L!==a){if(j=[],(E=fu())!==a)for(;E!==a;)j.push(E),E=fu();else j=a;j!==a?(R=L,G=(W=j).length===1?W[0]:{type:"compound",selectors:W},R&&(G.subject=!0),x=L=G):(u=x,x=a)}else u=x,x=a;return V[J]={nextPos:u,result:x},x}function fu(){var x,L=36*u+9,j=V[L];return j?(u=j.nextPos,j.result):((x=(function(){var E,R,W=36*u+10,G=V[W];return G?(u=G.nextPos,G.result):(t.charCodeAt(u)===42?(R="*",u++):(R=a,B(C)),R!==a&&(R={type:"wildcard",value:R}),E=R,V[W]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W,G=36*u+11,J=V[G];return J?(u=J.nextPos,J.result):(E=u,t.charCodeAt(u)===35?(R="#",u++):(R=a,B(q)),R===a&&(R=null),R!==a&&(W=Qt())!==a?E=R={type:"identifier",value:W}:(u=E,E=a),V[G]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W,G,J=36*u+12,ee=V[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.charCodeAt(u)===91?(R="[",u++):(R=a,B(F)),R!==a&&le()!==a&&(W=(function(){var te,Ae,mt,he,Et=36*u+16,Qe=V[Et];return Qe?(u=Qe.nextPos,Qe.result):(te=u,(Ae=Do())!==a&&le()!==a&&(mt=(function(){var H,Y,ne,U=36*u+14,se=V[U];return se?(u=se.nextPos,se.result):(H=u,t.charCodeAt(u)===33?(Y="!",u++):(Y=a,B(I)),Y===a&&(Y=null),Y!==a?(t.charCodeAt(u)===61?(ne="=",u++):(ne=a,B(M)),ne!==a?(Y=Z(Y),H=Y):(u=H,H=a)):(u=H,H=a),V[U]={nextPos:u,result:H},H)})())!==a&&le()!==a?((he=(function(){var H,Y,ne,U,se,we=36*u+20,gt=V[we];if(gt)return u=gt.nextPos,gt.result;if(H=u,t.substr(u,5)==="type("?(Y="type(",u+=5):(Y=a,B(us)),Y!==a)if(le()!==a){if(ne=[],tn.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(ru)),U!==a)for(;U!==a;)ne.push(U),tn.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(ru));else ne=a;ne!==a&&(U=le())!==a?(t.charCodeAt(u)===41?(se=")",u++):(se=a,B(qi)),se!==a?(Y={type:"type",value:ne.join("")},H=Y):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;else u=H,H=a;return V[we]={nextPos:u,result:H},H})())===a&&(he=(function(){var H,Y,ne,U,se,we,gt=36*u+22,Ft=V[gt];if(Ft)return u=Ft.nextPos,Ft.result;if(H=u,t.charCodeAt(u)===47?(Y="/",u++):(Y=a,B(au)),Y!==a){if(ne=[],(U=hu())===a&&(U=hs())===a&&(U=yu()),U!==a)for(;U!==a;)ne.push(U),(U=hu())===a&&(U=hs())===a&&(U=yu());else ne=a;ne!==a?(t.charCodeAt(u)===47?(U="/",u++):(U=a,B(au)),U!==a?((se=(function(){var Jt,ji,vu=36*u+21,Mo=V[vu];if(Mo)return u=Mo.nextPos,Mo.result;if(Jt=[],nu.test(t.charAt(u))?(ji=t.charAt(u),u++):(ji=a,B(su)),ji!==a)for(;ji!==a;)Jt.push(ji),nu.test(t.charAt(u))?(ji=t.charAt(u),u++):(ji=a,B(su));else Jt=a;return V[vu]={nextPos:u,result:Jt},Jt})())===a&&(se=null),se!==a?(we=se,Y={type:"regexp",value:new RegExp(ne.join(""),we?we.join(""):"")},H=Y):(u=H,H=a)):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;return V[gt]={nextPos:u,result:H},H})()),he!==a?(Ae=Se(Ae,mt,he),te=Ae):(u=te,te=a)):(u=te,te=a),te===a&&(te=u,(Ae=Do())!==a&&le()!==a&&(mt=(function(){var H,Y,ne,U=36*u+13,se=V[U];return se?(u=se.nextPos,se.result):(H=u,w.test(t.charAt(u))?(Y=t.charAt(u),u++):(Y=a,B(h)),Y===a&&(Y=null),Y!==a?(t.charCodeAt(u)===61?(ne="=",u++):(ne=a,B(M)),ne!==a?(Y=Z(Y),H=Y):(u=H,H=a)):(u=H,H=a),H===a&&(re.test(t.charAt(u))?(H=t.charAt(u),u++):(H=a,B(ae))),V[U]={nextPos:u,result:H},H)})())!==a&&le()!==a?((he=(function(){var H,Y,ne,U,se,we,gt=36*u+17,Ft=V[gt];if(Ft)return u=Ft.nextPos,Ft.result;if(H=u,t.charCodeAt(u)===34?(Y='"',u++):(Y=a,B(me)),Y!==a){for(ne=[],be.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(v)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,B(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,B($)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));U!==a;)ne.push(U),be.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(v)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,B(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,B($)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));ne!==a?(t.charCodeAt(u)===34?(U='"',u++):(U=a,B(me)),U!==a?(Y=ue(ne),H=Y):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;if(H===a)if(H=u,t.charCodeAt(u)===39?(Y="'",u++):(Y=a,B(je)),Y!==a){for(ne=[],Ut.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(mi)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,B(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,B($)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));U!==a;)ne.push(U),Ut.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(mi)),U===a&&(U=u,t.charCodeAt(u)===92?(se="\\",u++):(se=a,B(D)),se!==a?(t.length>u?(we=t.charAt(u),u++):(we=a,B($)),we!==a?(se=ie(se,we),U=se):(u=U,U=a)):(u=U,U=a));ne!==a?(t.charCodeAt(u)===39?(U="'",u++):(U=a,B(je)),U!==a?(Y=ue(ne),H=Y):(u=H,H=a)):(u=H,H=a)}else u=H,H=a;return V[gt]={nextPos:u,result:H},H})())===a&&(he=(function(){var H,Y,ne,U,se,we,gt,Ft=36*u+18,Jt=V[Ft];if(Jt)return u=Jt.nextPos,Jt.result;for(H=u,Y=u,ne=[],ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(St));U!==a;)ne.push(U),ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(St));if(ne!==a?(t.charCodeAt(u)===46?(U=".",u++):(U=a,B(P)),U!==a?Y=ne=[ne,U]:(u=Y,Y=a)):(u=Y,Y=a),Y===a&&(Y=null),Y!==a){if(ne=[],ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(St)),U!==a)for(;U!==a;)ne.push(U),ge.test(t.charAt(u))?(U=t.charAt(u),u++):(U=a,B(St));else ne=a;ne!==a?(we=ne,gt=(se=Y)?[].concat.apply([],se).join(""):"",Y={type:"literal",value:parseFloat(gt+we.join(""))},H=Y):(u=H,H=a)}else u=H,H=a;return V[Ft]={nextPos:u,result:H},H})())===a&&(he=(function(){var H,Y,ne=36*u+19,U=V[ne];return U?(u=U.nextPos,U.result):((Y=Qt())!==a&&(Y={type:"literal",value:Y}),H=Y,V[ne]={nextPos:u,result:H},H)})()),he!==a?(Ae=Se(Ae,mt,he),te=Ae):(u=te,te=a)):(u=te,te=a),te===a&&(te=u,(Ae=Do())!==a&&(Ae={type:"attribute",name:Ae}),te=Ae)),V[Et]={nextPos:u,result:te},te)})())!==a&&le()!==a?(t.charCodeAt(u)===93?(G="]",u++):(G=a,B(N)),G!==a?E=R=W:(u=E,E=a)):(u=E,E=a),V[J]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W,G,J,ee,te,Ae,mt=36*u+26,he=V[mt];if(he)return u=he.nextPos,he.result;if(E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,B(P)),R!==a)if((W=Qt())!==a){for(G=[],J=u,t.charCodeAt(u)===46?(ee=".",u++):(ee=a,B(P)),ee!==a&&(te=Qt())!==a?J=ee=[ee,te]:(u=J,J=a);J!==a;)G.push(J),J=u,t.charCodeAt(u)===46?(ee=".",u++):(ee=a,B(P)),ee!==a&&(te=Qt())!==a?J=ee=[ee,te]:(u=J,J=a);G!==a?(Ae=W,R={type:"field",name:G.reduce((function(Et,Qe){return Et+Qe[0]+Qe[1]}),Ae)},E=R):(u=E,E=a)}else u=E,E=a;else u=E,E=a;return V[mt]={nextPos:u,result:E},E})())===a&&(x=(function(){var E,R,W,G,J=36*u+27,ee=V[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,5)===":not("?(R=":not(",u+=5):(R=a,B(Ak)),R!==a&&le()!==a&&(W=gs())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,B(qi)),G!==a?E=R={type:"not",selectors:W}:(u=E,E=a)):(u=E,E=a),V[J]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W,G,J=36*u+28,ee=V[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,9)===":matches("?(R=":matches(",u+=9):(R=a,B(Ok)),R!==a&&le()!==a&&(W=gs())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,B(qi)),G!==a?(R=du(W),E=R):(u=E,E=a)):(u=E,E=a),V[J]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W,G,J=36*u+29,ee=V[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,4)===":is("?(R=":is(",u+=4):(R=a,B(Rk)),R!==a&&le()!==a&&(W=gs())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,B(qi)),G!==a?(R=du(W),E=R):(u=E,E=a)):(u=E,E=a),V[J]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W,G,J=36*u+30,ee=V[J];return ee?(u=ee.nextPos,ee.result):(E=u,t.substr(u,5)===":has("?(R=":has(",u+=5):(R=a,B(Nk)),R!==a&&le()!==a&&(W=(function(){var te,Ae,mt,he,Et,Qe,H,Y,ne=36*u+4,U=V[ne];if(U)return u=U.nextPos,U.result;if(te=u,(Ae=Po())!==a){for(mt=[],he=u,(Et=le())!==a?(t.charCodeAt(u)===44?(Qe=",",u++):(Qe=a,B(T)),Qe!==a&&(H=le())!==a&&(Y=Po())!==a?he=Et=[Et,Qe,H,Y]:(u=he,he=a)):(u=he,he=a);he!==a;)mt.push(he),he=u,(Et=le())!==a?(t.charCodeAt(u)===44?(Qe=",",u++):(Qe=a,B(T)),Qe!==a&&(H=le())!==a&&(Y=Po())!==a?he=Et=[Et,Qe,H,Y]:(u=he,he=a)):(u=he,he=a);mt!==a?te=Ae=A(Ae,mt):(u=te,te=a)}else u=te,te=a;return V[ne]={nextPos:u,result:te},te})())!==a&&le()!==a?(t.charCodeAt(u)===41?(G=")",u++):(G=a,B(qi)),G!==a?E=R={type:"has",selectors:W}:(u=E,E=a)):(u=E,E=a),V[J]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W=36*u+31,G=V[W];return G?(u=G.nextPos,G.result):(t.substr(u,12)===":first-child"?(R=":first-child",u+=12):(R=a,B(Pk)),R!==a&&(R=bu(1)),E=R,V[W]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W=36*u+32,G=V[W];return G?(u=G.nextPos,G.result):(t.substr(u,11)===":last-child"?(R=":last-child",u+=11):(R=a,B(Ck)),R!==a&&(R=_u(1)),E=R,V[W]={nextPos:u,result:E},E)})())===a&&(x=(function(){var E,R,W,G,J,ee=36*u+33,te=V[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,B(Dk)),R!==a)if(le()!==a){if(W=[],ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,B(St)),G!==a)for(;G!==a;)W.push(G),ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,B(St));else W=a;W!==a&&(G=le())!==a?(t.charCodeAt(u)===41?(J=")",u++):(J=a,B(qi)),J!==a?(R=bu(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 V[ee]={nextPos:u,result:E},E})())===a&&(x=(function(){var E,R,W,G,J,ee=36*u+34,te=V[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,B(Mk)),R!==a)if(le()!==a){if(W=[],ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,B(St)),G!==a)for(;G!==a;)W.push(G),ge.test(t.charAt(u))?(G=t.charAt(u),u++):(G=a,B(St));else W=a;W!==a&&(G=le())!==a?(t.charCodeAt(u)===41?(J=")",u++):(J=a,B(qi)),J!==a?(R=_u(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 V[ee]={nextPos:u,result:E},E})())===a&&(x=(function(){var E,R,W,G=36*u+35,J=V[G];return J?(u=J.nextPos,J.result):(E=u,t.charCodeAt(u)===58?(R=":",u++):(R=a,B(Lk)),R!==a&&(W=Qt())!==a?E=R={type:"class",name:W}:(u=E,E=a),V[G]={nextPos:u,result:E},E)})()),V[L]={nextPos:u,result:x},x)}function Do(){var x,L,j,E,R,W,G,J,ee=36*u+15,te=V[ee];if(te)return u=te.nextPos,te.result;if(x=u,(L=Qt())!==a){for(j=[],E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,B(P)),R!==a&&(W=Qt())!==a?E=R=[R,W]:(u=E,E=a);E!==a;)j.push(E),E=u,t.charCodeAt(u)===46?(R=".",u++):(R=a,B(P)),R!==a&&(W=Qt())!==a?E=R=[R,W]:(u=E,E=a);j!==a?(G=L,J=j,x=L=[].concat.apply([G],J).join("")):(u=x,x=a)}else u=x,x=a;return V[ee]={nextPos:u,result:x},x}function hu(){var x,L,j,E,R=36*u+23,W=V[R];if(W)return u=W.nextPos,W.result;if(x=u,t.charCodeAt(u)===91?(L="[",u++):(L=a,B(F)),L!==a){if(j=[],ou.test(t.charAt(u))?(E=t.charAt(u),u++):(E=a,B(lu)),E===a&&(E=hs()),E!==a)for(;E!==a;)j.push(E),ou.test(t.charAt(u))?(E=t.charAt(u),u++):(E=a,B(lu)),E===a&&(E=hs());else j=a;j!==a?(t.charCodeAt(u)===93?(E="]",u++):(E=a,B(N)),E!==a?x=L="["+j.join("")+"]":(u=x,x=a)):(u=x,x=a)}else u=x,x=a;return V[R]={nextPos:u,result:x},x}function hs(){var x,L,j,E=36*u+24,R=V[E];return R?(u=R.nextPos,R.result):(x=u,t.charCodeAt(u)===92?(L="\\",u++):(L=a,B(D)),L!==a?(t.length>u?(j=t.charAt(u),u++):(j=a,B($)),j!==a?x=L="\\"+j:(u=x,x=a)):(u=x,x=a),V[E]={nextPos:u,result:x},x)}function yu(){var x,L,j,E=36*u+25,R=V[E];if(R)return u=R.nextPos,R.result;if(L=[],cu.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,B(pu)),j!==a)for(;j!==a;)L.push(j),cu.test(t.charAt(u))?(j=t.charAt(u),u++):(j=a,B(pu));else L=a;return L!==a&&(L=L.join("")),x=L,V[E]={nextPos:u,result:x},x}function bu(x){return{type:"nth-child",index:{type:"literal",value:x}}}function _u(x){return{type:"nth-last-child",index:{type:"literal",value:x}}}if((n=p())!==a&&u===t.length)return n;throw n!==a&&u<t.length&&B({type:"end"}),s=Ro,o=qt<t.length?t.charAt(qt):null,l=qt<t.length?mu(qt,qt+1):mu(qt,qt),new e(e.buildMessage(s,o),s,o,l)}}})())}));hp=typeof WeakMap=="function"?new WeakMap:null;$t.parse=Q_,$t.match=Y_,$t.traverse=K_,$t.matches=function(i,e,t,r){return!e||!!i&&(t||(t=[]),He(e)(i,t,r))},$t.query=$t});var Aa,kp=k(()=>{Aa={}});var J_,X_=k(()=>{J_={}});function oA(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 Oa(i,e,t,r){let n=r[r.length-1];e.type==="ClassDeclaration"||e.type==="ClassExpression"?mA(i,e,n):uA(i,e,n)}function lA(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 cA(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 pA(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=>lA(s,e)))return!0;r=cA(n)}return!1}function dA(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 uA(i,e,t){if(pA(e,ci(i.channelName)))return;i.transforms.tracingChannelDeclaration(i,t);let{functionQuery:{methodName:r,privateMethodName:n,functionName:s,expressionName:o,propertyName:l}}=i,c=r==="constructor"||!r&&!n&&!s&&!o&&!l?"ArrowFunctionExpression":e.type,p=e.params;e.body=tv(i,{type:c,params:p,body:e.body,async:e.async,expression:!1,generator:e.generator},t),e.params=oA(p),e.generator=!1,e.async=!1,iv(i,e)}function mA(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=`${ci(s)}$${o}`;if(a&&dA(a,c))return;i.transforms.tracingChannelDeclaration(i,t),a||(a=Ze(e.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],l.body.unshift(a));let p=Ze(`
9
9
  const ${c} = this["${o}"]
10
10
  this["${o}"] = function () {}
11
11
  if (typeof ${c} === 'function') {
@@ -14,7 +14,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
14
14
  configurable: true
15
15
  })
16
16
  }
17
- `).body,d=p[1].expression.right;d.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],d.async=n==="tracePromise",d.body=ev(i,{type:"Identifier",name:c},t),tv(i,d),a.value.body.body.push(...p)}function ev(i,e,t){let{operator:r,moduleVersion:n}=i,{returnKind:s}=i.functionQuery,o=s?cA(i,s,t):"",l;r==="traceCallback"&&(l=iv(i,e,o)),r==="tracePromise"&&(l=rv(i,e,o)),r==="traceSync"&&(l=oA(i,e,o)),r==="traceAuto"&&(l=aA(i,e,o));let a=(e.params||[]).filter(d=>d.type!=="RestElement"&&d.type!=="AssignmentPattern").map((d,g)=>`__apm$arg${g}`).concat("...__apm$args").join(", "),c=l.body[0].body,p=Ze(e.type==="ArrowFunctionExpression"?`
17
+ `).body,d=p[1].expression.right;d.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],d.async=n==="tracePromise",d.body=tv(i,{type:"Identifier",name:c},t),iv(i,d),a.value.body.body.push(...p)}function tv(i,e,t){let{operator:r,moduleVersion:n}=i,{returnKind:s}=i.functionQuery,o=s?yA(i,s,t):"",l;r==="traceCallback"&&(l=rv(i,e,o)),r==="tracePromise"&&(l=nv(i,e,o)),r==="traceSync"&&(l=fA(i,e,o)),r==="traceAuto"&&(l=gA(i,e,o));let a=(e.params||[]).filter(d=>d.type!=="RestElement"&&d.type!=="AssignmentPattern").map((d,g)=>`__apm$arg${g}`).concat("...__apm$args").join(", "),c=l.body[0].body,p=Ze(e.type==="ArrowFunctionExpression"?`
18
18
  const __apm$arguments = [${a}];
19
19
  const __apm$ctx = {
20
20
  arguments: __apm$arguments,
@@ -35,13 +35,13 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
35
35
  const __apm$wrapped = () => {};
36
36
  return __apm$wrapped.apply(this, __apm$arguments);
37
37
  };
38
- `).body;return c.body.unshift(...p),Sp.query(c,"[id.name=__apm$wrapped]")[0].init=e,c}function tv(i,e){let t=new Set;Sp.traverse(e.body,Sp.parse("[object.type=Super]"),(r,n)=>{let{name:s}=r.property,o;if(n.callee){let{expression:l}=Ze(`__apm$super['${s}'].call(this)`).body[0];n.callee=o=l.callee,n.arguments.unshift(...l.arguments)}else n.expression=o=Ze(`__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=Ze(`
38
+ `).body;return c.body.unshift(...p),Sp.query(c,"[id.name=__apm$wrapped]")[0].init=e,c}function iv(i,e){let t=new Set;Sp.traverse(e.body,Sp.parse("[object.type=Super]"),(r,n)=>{let{name:s}=r.property,o;if(n.callee){let{expression:l}=Ze(`__apm$super['${s}'].call(this)`).body[0];n.callee=o=l.callee,n.arguments.unshift(...l.arguments)}else n.expression=o=Ze(`__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=Ze(`
39
39
  class Wrapper {
40
40
  wrapper () {
41
41
  __apm$super['${r}'] = super['${r}']
42
42
  }
43
43
  }
44
- `).body[0].body.body[0].value.body.body[0];e.body.body.unshift(n)}t.size>0&&e.body.body.unshift(Ze("const __apm$super = {}").body[0])}function aA(i,e,t=""){let r=iv(i,e,t),n=rv(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 iv(i,e,t=""){let{channelName:r,functionQuery:{callbackIndex:n=-1}}=i,s=ci(r);return Ze(`
44
+ `).body[0].body.body[0].value.body.body[0];e.body.body.unshift(n)}t.size>0&&e.body.body.unshift(Ze("const __apm$super = {}").body[0])}function gA(i,e,t=""){let r=rv(i,e,t),n=nv(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 rv(i,e,t=""){let{channelName:r,functionQuery:{callbackIndex:n=-1}}=i,s=ci(r);return Ze(`
45
45
  function wrapper () {
46
46
  const __apm$cb = Array.prototype.at.call(__apm$arguments, ${n});
47
47
 
@@ -85,7 +85,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
85
85
  }
86
86
  });
87
87
  }
88
- `)}function rv(i,e,t=""){let{channelName:r}=i,n=ci(r);return Ze(`
88
+ `)}function nv(i,e,t=""){let{channelName:r}=i,n=ci(r);return Ze(`
89
89
  function wrapper () {
90
90
  if (!tr_ch_apm_hasSubscribers(${n})) return __apm$traced();
91
91
 
@@ -146,7 +146,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
146
146
  }
147
147
  });
148
148
  }
149
- `)}function oA(i,e,t=""){let{channelName:r}=i,n=ci(r);return Ze(`
149
+ `)}function fA(i,e,t=""){let{channelName:r}=i,n=ci(r);return Ze(`
150
150
  function wrapper () {
151
151
  if (!tr_ch_apm_hasSubscribers(${n})) return __apm$traced();
152
152
 
@@ -165,7 +165,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
165
165
  return __apm$ctx.result;
166
166
  });
167
167
  }
168
- `)}function lA(i,e){let{channelName:t,module:{name:r}}=i,n=ci(t+":next");if(e.body.some(a=>a.declarations?.[0]?.id?.name===n))return;let s=ci(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,Ze(l).body[0])}function cA(i,e,t){let{channelName:r}=i,n=e==="Iterator"?"traceSync":"tracePromise",s=ci(r+":next");return lA(i,t),`
168
+ `)}function hA(i,e){let{channelName:t,module:{name:r}}=i,n=ci(t+":next");if(e.body.some(a=>a.declarations?.[0]?.id?.name===n))return;let s=ci(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,Ze(l).body[0])}function yA(i,e,t){let{channelName:r}=i,n=e==="Iterator"?"traceSync":"tracePromise",s=ci(r+":next");return hA(i,t),`
169
169
  const __apm$iter = __apm$ctx.result;
170
170
  if (__apm$iter != null && typeof __apm$iter.next === 'function') {
171
171
  const __apm$patchIter = function (method) {
@@ -183,66 +183,66 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
183
183
  __apm$patchIter('throw');
184
184
  __apm$patchIter('return');
185
185
  }
186
- `}var Sp,Ze,X_,Xx,ci,Z_,nv=k(()=>{wp();kp();Sp=Vt,{parse:Ze}=Oa,X_=i=>i.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",Xx=/[^\w]/g,ci=i=>`tr_ch_apm$${i.replace(Xx,"_")}`,Z_={tracingChannelImport({dcModule:i,moduleType:e},t){if(t.body.some(X_))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,Ze(s,r).body[0],Ze("const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc",r).body[0],Ze(`const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
186
+ `}var Sp,Ze,Z_,aA,ci,ev,sv=k(()=>{wp();kp();Sp=$t,{parse:Ze}=Aa,Z_=i=>i.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",aA=/[^\w]/g,ci=i=>`tr_ch_apm$${i.replace(aA,"_")}`,ev={tracingChannelImport({dcModule:i,moduleType:e},t){if(t.body.some(Z_))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,Ze(s,r).body[0],Ze("const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc",r).body[0],Ze(`const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
187
187
  || ch.end.hasSubscribers
188
188
  || ch.asyncStart.hasSubscribers
189
189
  || ch.asyncEnd.hasSubscribers
190
- || ch.error.hasSubscribers`,r).body[0])},tracingChannelDeclaration(i,e){let{channelName:t,module:{name:r}}=i,n=ci(t);if(e.body.some(l=>l.declarations?.[0]?.id?.name===n))return;i.transforms.tracingChannelImport(i,e);let s=e.body.findIndex(X_),o=`
190
+ || ch.error.hasSubscribers`,r).body[0])},tracingChannelDeclaration(i,e){let{channelName:t,module:{name:r}}=i,n=ci(t);if(e.body.some(l=>l.declarations?.[0]?.id?.name===n))return;i.transforms.tracingChannelImport(i,e);let s=e.body.findIndex(Z_),o=`
191
191
  const ${n} = tr_ch_apm_tracingChannel("orchestrion:${r}:${t}")
192
- `;e.body.splice(s+1,0,Ze(o).body[0])},traceCallback:Ra,tracePromise:Ra,traceSync:Ra,traceAuto:Ra}});var Ep,sv=k(()=>{Ep={}});var cv,Ap,$t,tr,Lr,Ur,Hn,Pa,Gn,qr,Ca,Da,xi,pv,dv,uv,Ip,mv,av,ov,pA,lv,Tp,Na,xp,gv,fv=k(()=>{wp();nv();J_();kp();sv();cv=i=>{throw TypeError(i)},Ap=(i,e,t)=>e.has(i)||cv("Cannot "+t),$t=(i,e,t)=>(Ap(i,e,"read from private field"),t?t.call(i):e.get(i)),tr=(i,e,t)=>e.has(i)?cv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Lr=(i,e,t,r)=>(Ap(i,e,"write to private field"),e.set(i,t),t),Ur=(i,e,t)=>(Ap(i,e,"access private method"),t),av=Vt,{parse:ov}=Oa,{generate:pA}=Q_,lv=Z_,xp=class{constructor(e,t,r,n,s,o={}){tr(this,xi),tr(this,Hn,null),tr(this,Pa,null),tr(this,Gn,null),tr(this,qr,[]),tr(this,Ca,null),tr(this,Da,{}),Lr(this,Hn,e),Lr(this,Pa,t),Lr(this,Gn,r),Lr(this,qr,n),Lr(this,Ca,s),Lr(this,Da,o)}free(){}get moduleName(){return $t(this,Hn)}get filePath(){return $t(this,Gn)}transform(e,t,r){if(Buffer.isBuffer(e)&&(e=e.toString()),!e)return{code:e};let n,s={},o=0,l={...lv,...$t(this,Da),defaults:{...lv}};for(let a of $t(this,qr)){let{astQuery:c,functionQuery:p={}}=a;if(!n){let v={loc:!0,ranges:!0,raw:!0,module:t==="esm"};try{n=ov(e,v)}catch{n=ov(e,{...v,module:!v.module})}t==="esm"&&(s=Ur(this,xi,uv).call(this,n))}let d=Ur(this,xi,Ip).call(this,p,s),g=c||Ur(this,xi,mv).call(this,d),f={...a,dcModule:$t(this,Ca),moduleType:t,moduleVersion:$t(this,Pa),functionQuery:d,transforms:l};f.operator=Ur(this,xi,dv).call(this,f),av.traverse(n,av.parse(g),(...v)=>{o++,Ur(this,xi,pv).call(this,f,...v)})}if(o===0&&$t(this,qr).length>0){let a=$t(this,qr).map(({astQuery:c,functionQuery:p={}})=>{if(c)return c;let d=Ur(this,xi,Ip).call(this,p,s),f=(S=>S.methodName||S.privateMethodName||S.functionName||S.expressionName||"constructor")(p),v=p.className||p.functionName||p.expressionName,y=d.className||d.functionName||d.expressionName;return v&&v!==y?`${v} (local name: ${y})`:f});throw new Error(`Failed to find injection points for: ${JSON.stringify(a)}`)}if(n){Tp??(Tp=Ep.SourceMapConsumer),Na??(Na=Ep.SourceMapGenerator);let a=`${$t(this,Hn)}/${$t(this,Gn)}`,c;if(r){let g=new Tp(r);g.file=a,c=Na.fromSourceMap(g)}else c=new Na({file:a});let p=pA(n,{sourceMap:c}),d=c.toString();return{code:p,map:d}}return{code:e}}};Hn=new WeakMap;Pa=new WeakMap;Gn=new WeakMap;qr=new WeakMap;Ca=new WeakMap;Da=new WeakMap;xi=new WeakSet;pv=function(i,...e){let t=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)};dv=function({transform:i,functionQuery:{kind:e}}){if(i)return i;switch(e){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}};uv=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};Ip=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};mv=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(", ")};gv={Transformer:xp}});var hv,yv,Ai,Ma,Op,La,Ua,ir,qa,dA,uA,Rp,bv,_v=k(()=>{B_();fv();hv=i=>{throw TypeError(i)},yv=(i,e,t)=>e.has(i)||hv("Cannot "+t),Ai=(i,e,t)=>(yv(i,e,"read from private field"),t?t.call(i):e.get(i)),Ma=(i,e,t)=>e.has(i)?hv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Op=(i,e,t,r)=>(yv(i,e,"write to private field"),e.set(i,t),t),dA=q_,{Transformer:uA}=gv,Rp=class{constructor(e,t){Ma(this,La,[]),Ma(this,Ua,null),Ma(this,ir,{}),Ma(this,qa,{}),Op(this,La,e),Op(this,Ua,t||"diagnostics_channel")}free(){Op(this,ir,{})}addTransform(e,t){Ai(this,qa)[e]=t}getTransformer(e,t,r){r=r.replace(/\\/g,"/");let n=`${e}/${r}@${t}`;if(Ai(this,ir)[n])return Ai(this,ir)[n];let s=Ai(this,La).filter(({module:o})=>o.name===e&&(typeof o.filePath=="string"?o.filePath===r:o.filePath.test(r))&&dA(t,o.versionRange));if(s.length!==0)return Ai(this,ir)[n]=new uA(e,t,r,s,Ai(this,Ua),Ai(this,qa)),Ai(this,ir)[n]}};La=new WeakMap;Ua=new WeakMap;ir=new WeakMap;qa=new WeakMap;bv={InstrumentationMatcher:Rp}});function gA(i,e){return new mA(i,e)}var mA,vv,wv=k(()=>{_v();({InstrumentationMatcher:mA}=bv);vv={create:gA}});var ja,Np=k(()=>{wv();ja=vv});import fA from"node:path";var Pp,Cp,kv,Dp=k(()=>{Bn();Pp=fA.sep,Cp=function(i){var e=i.split(Pp),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]+Pp;for(var c="",p=e.length-1,d=t+s;d<=p;d++)d===p?c+=e[d]:c+=e[d]+Pp;return{name:n,basedir:o,path:c}}},kv=Dr(Cp)});import hA from"node:fs";import yA from"node:path";function vA(i){if(Mp.has(i))return Mp.get(i);try{let e=_A(i,"package.json"),t=bA(e),{version:r}=JSON.parse(t);return Mp.set(i,r),r}catch{return process.version.slice(1)}}var bA,_A,Mp,Lp,Sv,Up=k(()=>{Bn();({readFileSync:bA}=hA),{join:_A}=yA,Mp=new Map;Lp=vA,Sv=Dr(Lp)});function wA(i){qp=i}function kA(i){qp&&qp(i)}var qp,pi,Ba=k(()=>{pi={setDiagnosticsHook:wA,emitDiagnostics:kA}});var Bp={};vu(Bp,{default:()=>jp});import{format as SA}from"node:util";function jp(i){return(...e)=>{z.isEnabled()&&z.log(`[${i}]`,SA(...e))}}var Fp=k(()=>{Wt()});var Ev,Tv=k(()=>{Fp();Bn();Ev=L_(Bp)});import EA from"node:module";import TA from"node:url";import IA from"node:os";import xA from"node:path";import AA from"node:fs";function PA(i,e){let t=IA,r=xA,n=AA,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);Fa("Dumping patched code to: %s",c),n.mkdirSync(a,{recursive:!0}),n.writeFileSync(c,i)}var OA,Hp,RA,Iv,NA,xv,Fa,Gp,CA,Wp,Av=k(()=>{Bn();Np();Dp();Up();Ba();Tv();({create:OA}=ja),Hp=EA,RA=Cp,{pathToFileURL:Iv}=TA,NA=Lp,{emitDiagnostics:xv}=pi,Fa=Ev("@apm-js-collab/tracing-hooks:module-patch"),Gp=class{constructor({instrumentations:e=[]}={}){this.packages=new Set(e.map(t=>t.module.name)),this.instrumentator=OA(e),this.compile=Hp.prototype._compile}patch(){let e=this;Hp.prototype._compile=function(...r){let[n,s]=r,o=RA(s);if(o&&e.packages.has(o.name)){Fa("found resolved module, checking if there is a transformer %s",s);let l=NA(o.basedir,o.name),a=e.instrumentator.getTransformer(o.name,l,o.path);if(a){Fa("transforming file %s",s);try{let c=a.transform(n,"cjs");r[0]=c?.code,xv({url:Iv(s).href,moduleName:a.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&PA(r[0],s)}catch(c){Fa("Error transforming module %s: %o",s,c),xv({url:Iv(s).href,moduleName:a.moduleName,error:c})}finally{a.free()}}}return e.compile.apply(this,r)}}unpatch(){Hp.prototype._compile=this.compile}};CA=Gp,Wp=Dr(CA)});import{fileURLToPath as Ov}from"node:url";import{dirname as Rv,join as DA}from"node:path";import{MessageChannel as MA}from"node:worker_threads";import{readFileSync as Nv}from"node:fs";function Dv(){let{port1:i,port2:e}=new MA;return i.on("message",pi.emitDiagnostics),i.unref(),e}function Mv(i={}){let e=i?.instrumentations||[];Cv=ja.create(e),Pv=new Set(e.map(t=>t.module.name)),Wn=new Map,zp=i?.diagnosticsPort?LA(i.diagnosticsPort):pi.emitDiagnostics}function LA(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){$p("failed to post diagnostics for %s: %o",e.url,t)}}}function UA(i){if(!i.url.startsWith("file:"))return i;let e=kv(Ov(i.url));if(e&&Pv.has(e.name)){let t=e.basedir,r=Sv(t),n=Cv.getTransformer(e.name,r,e.path);n&&Wn.set(i.url,n)}return i}function Lv(i,e,t){return UA(t(i,e))}function Kp(i,e,t){let r=t(i,e);if(Wn.has(i)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??i);r.source??=Nv(n)}return qA(i,r)}function qA(i,e){let t=e.source;if(t){let r=Wn.get(i);if(BA(i,e.format))return $p("skipping json module %s",i),r.free(),Wn.delete(i),e;try{let n=typeof t=="string"?t:Buffer.from(t).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":HA(i,n),o=r.transform(n,s);e.source=o?.code,e.shortCircuit=!0,zp({url:i,moduleName:r.moduleName})}catch(n){$p("Error transforming module %s: %o",i,n),zp({url:i,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function BA(i,e){return e==="json"||jA.test(i)}function HA(i,e){return GA(i)??(FA.test(e)?"esm":"cjs")}function GA(i){let e;try{e=Ov(i)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let t=Uv(Rv(e));return t==="module"?"esm":t==="commonjs"?"cjs":void 0}function Uv(i){if(Vp.has(i))return Vp.get(i);let e;try{e=JSON.parse(Nv(DA(i,"package.json"),"utf8")).type}catch{let t=Rv(i);t!==i&&(e=Uv(t))}return Vp.set(i,e),e}var $p,Wn,Pv,Cv,zp,jA,FA,Vp,y6,qv=k(()=>{Fp();Np();Dp();Up();Ba();$p=jp("@apm-js-collab/tracing-hooks:esm-hook"),Wn=null,Pv=null,Cv=null,zp=pi.emitDiagnostics;jA=/\.json([?#]|$)/;FA=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;Vp=new Map;y6=pi.setDiagnosticsHook});import{createHash as jv}from"node:crypto";import{existsSync as Hv,readFileSync as WA}from"node:fs";import*as VA from"node:module";import{join as Gv,dirname as Vn}from"node:path";import{pathToFileURL as Ha,fileURLToPath as Qp}from"node:url";function zA(i){if(i)return!0;let{major:e=0,minor:t=0}=dl(process.versions.node??"0.0.0");return e>25||e===25&&t>=1||e===24&&t>=13}function Wv(i){if(Yp.has(i))return Yp.get(i);let e,t=Gv(i,"package.json");if(Hv(t))try{e=JSON.parse(WA(t,"utf8")).type}catch{e=void 0}else Vn(i)!==i&&(e=Wv(Vn(i)));return Yp.set(i,e),e}function KA(i){if(i.endsWith(".json"))return"json";if(i.endsWith(".mjs")||i.startsWith("file:")&&i.endsWith(".js")&&Wv(Vn(Qp(i)))==="module")return"module"}function YA(i){return(e,t,r)=>i(e,t,(n,s)=>{let o=r(n,s);if(o&&o.format==null){let l=KA(n);l&&(o.format=l)}return o})}function Vv(i){At(()=>{console.warn(`[Sentry] ${i}`)})}function $v(i){Vv(`${i} See ${$A}`)}function QA(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(Fv.has(i))return;Fv.add(i),Vv(`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}Bv||(Bv=!0,$v(`\`@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 zv(){var i;let e=(i=pe).__SENTRY_ORCHESTRION__??(i.__SENTRY_ORCHESTRION__={});if(e.runtime||e.runtimeUnavailable)return;let t=globalThis,r=zA(!!t.Deno),n=VA;pi.setDiagnosticsHook(({url:s,moduleName:o,error:l})=>{var a;l?(l instanceof TypeError&&QA(o,l),z.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){Mv({instrumentations:jn});let s=new Map,o=t.Deno?YA(Kp):Kp;n.registerHooks({resolve:Lv,load:(p,d,g)=>{let f=o(p,d,g),v=f?.format??d.format;if((v==null||v==="commonjs")&&f?.shortCircuit===!0&&f?.source!=null&&p.startsWith("file:")){let y=jv("sha256").update(f.source).digest("hex");s.set(Ha(Qp(p)).href,y)}return f}});let l=n.Module.prototype,a=l._compile;new Wp({instrumentations:jn}).patch();let c=l._compile;l._compile=function(p,d,...g){let f=Ha(d).href,v=s.get(f);return s.delete(f),(v!==void 0&&v===jv("sha256").update(p).digest("hex")?a:c).call(this,p,d,...g)},z.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof n.register=="function"&&!t.Bun&&!t.Deno){let s=Dv(),o;o=import.meta.url;let l;l=Gv(Vn(Qp(import.meta.url)),"hook.js");let a=Hv(l);a||z.warn(`No orchestrion ESM hook at ${l}; falling back to the package specifier.`);let c=a?Ha(l).href:"@sentry/server-runtime-injection/hook";if(a){let p=`${Ha(Vn(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:jn,diagnosticsPort:s},transferList:[s]}),new Wp({instrumentations:jn}).patch(),z.log("Registered diagnostics-channel injection via Module.register()")}else{e.runtimeUnavailable=!0,z.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);$v(`Failed to register diagnostics-channel injection hooks (${o}), so channel-based integrations will not record spans.`),z.warn("Diagnostics-channel injection registration error:",s);return}e.runtime=e.runtime||[]}var $A,Yp,Bv,Fv,Kv=k(()=>{Wt();w_();Av();qv();Ba();$A="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";Yp=new Map;Bv=!1,Fv=new Set});import*as Yv from"node:os";import{threadId as JA,isMainThread as XA}from"worker_threads";var ZA,$n,Qv=k(()=>{Ta();Wt();cc();M_();Kv();k_();E_();ZA=6e4,$n=class extends Cn{constructor(e){let t=e.includeServerName===!1?void 0:e.serverName||global.process.env.SENTRY_NAME||Yv.hostname(),r={...e,platform:"node",runtime:e.runtime||{name:"node",version:global.process.version},serverName:t};Zl(r,"node"),z.log(`Initializing Sentry: process: ${process.pid}, thread: ${XA?"main":`worker-${JA}`}.`),super(r),this._onExitFlushListener=()=>{this.emit("flush")},t&&this.on("beforeCaptureLog",n=>{n.attributes={...n.attributes,"server.address":t}}),process.on("beforeExit",this._onExitFlushListener),Gl(this),D_(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&e.enableRuntimeChannelInjection!==!1&&zv()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=C_():this.asyncLocalStorageLookup={asyncLocalStorage:wc()},super.init()}get tracer(){if(this._tracer)return this._tracer;let e="@sentry/node",t=ht,r=Si.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(()=>{S_&&z.log("Flushing client reports based on interval."),this._flushOutcomes()},e.clientReportFlushInterval??ZA).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){Ql(),super._setupIntegrations()}}});var Jv=k(()=>{A_();Qv()});var Xv={};vu(Xv,{NodeClient:()=>$n,Scope:()=>Je,createTransport:()=>zl,defaultStackParser:()=>lp,linkedErrorsIntegration:()=>sc});var Zv=k(()=>{"use strict";Jv();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]="85b9f08e-ec7c-4ef5-8ddd-adbb8d36ec1a",i._sentryDebugIdIdentifier="sentry-dbid-85b9f08e-ec7c-4ef5-8ddd-adbb8d36ec1a")}catch{}})();import{delimiter as EP,dirname as TP,join as Xr,resolve as en}from"node:path";import{readFileSync as IP,realpathSync as Qd,watch as xP}from"node:fs";import{fileURLToPath as AP}from"node:url";import{DefaultPackageManager as hk,getAgentDir as ut,ModelRuntime as OP,SessionManager as eu,SettingsManager as RP,VERSION as Jd}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as NP}from"@earendil-works/pi-ai";import{randomBytes as pw,randomUUID as Zp,timingSafeEqual as pO}from"node:crypto";import{readFile as dO,readdir as uO}from"node:fs/promises";import{createServer as mO}from"node:http";import{join as ed}from"node:path";import{getAgentDir as gO}from"@earendil-works/pi-coding-agent";import{isAbsolute as sS,relative as aS}from"node:path";var st={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var wu={id:st.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 Rk}from"node:child_process";import{realpath as Nk}from"node:fs/promises";import{isAbsolute as ku,relative as Pk,sep as Ck,win32 as Dk}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=Rk("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 f=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",f==="outcome_unknown"?503:409,f));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 at(i){let e=await Nk(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=Pk(t,e).split(Ck).join("/");if(r===".."||r.startsWith("../")||ku(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 Bi(i){if(typeof i!="string"||!i||i.length>4096||i.includes("\0")||i.includes("\\")||ku(i)||Dk.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 zk}from"node:crypto";import{lstat as Bo,realpath as Lu}from"node:fs/promises";import{dirname as Mu,isAbsolute as Kk,relative as Yk,resolve as sn}from"node:path";import{lstat as Wk}from"node:fs/promises";import{resolve as Vk}from"node:path";import{createHash as Mk}from"node:crypto";import{constants as Xt}from"node:fs";import{open as Uo,opendir as Lk,realpath as Su,stat as bs}from"node:fs/promises";import{isAbsolute as Tu,relative as Uk,resolve as qk,sep as jk,win32 as Bk}from"node:path";var Fk=1e3,Hk={bytes:512*1024,lines:1e4},qo={bytes:5*1024*1024,lines:2e5},Iu=8*1024*1024,Gk=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Lo=i=>Mk("sha256").update(i).digest("hex"),fe=class extends Error{status;reason;constructor(e,t=400,r){super(e),this.name="WorkspaceFileError",this.status=t,this.reason=r}};function Eu(i,e){let t=Uk(i,e);return t!==".."&&!t.startsWith(`..${jk}`)&&!Tu(t)}async function rn(i,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||Tu(e)||Bk.isAbsolute(e))throw new fe("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Su(i),r=qk(t,e);if(!Eu(t,r))throw new fe("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await Su(r);if(!Eu(t,n))throw new fe("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function _s(i){try{return await i()}catch(e){if(e instanceof fe)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new fe("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new fe("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function xu(i,e){return _s(async()=>{let t=await rn(i,e),r=[],n=!1;for await(let s of await Lk(t)){if(s.name===".git")continue;if(r.length===Fk){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 bs(await rn(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")||Gk.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:r,truncated:n}})}function Au(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 nn(i,e,t=Hk){return _s(async()=>{let r=await rn(i,e);if(!(await bs(r)).isFile())throw new fe("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await Uo(r,Xt.O_RDONLY|Xt.O_NONBLOCK|(Xt.O_NOFOLLOW??0));try{let s=await n.stat();if(!s.isFile())throw new fe("\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=Au(l),c=a?Iu: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 fe("\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 f=1;for(let v=0;v<g.length-1;v++)if(g[v]===10&&++f>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:Lo(g)}}catch{return{...o,kind:"unsupported"}}}finally{await n.close()}})}async function Ou(i,e){return _s(async()=>{let t=await rn(i,e);if(!(await bs(t)).isFile())throw new fe("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Uo(t,Xt.O_RDONLY|Xt.O_NONBLOCK|(Xt.O_NOFOLLOW??0));try{let n=await r.stat();if(!n.isFile())throw new fe("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(n.size>Iu)throw new fe("\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 fe("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let l=s.subarray(0,o),a=Au(l);if(!a)throw new fe("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:l}}finally{await r.close()}})}async function Ru(i,e,t,r){if(typeof t!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new fe("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let n=Buffer.from(t,"utf8"),{bytes:s,lines:o}=qo;if(n.length>s)throw new fe(`\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 fe(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${o} \u884C`,413);return _s(async()=>{let a=await rn(i,e);if(!(await bs(a)).isFile())throw new fe("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await Uo(a,Xt.O_RDWR|Xt.O_NONBLOCK|(Xt.O_NOFOLLOW??0));try{let p=await c.stat();if(!p.isFile())throw new fe("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new fe("\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||Lo(d.subarray(0,g))!==r)throw new fe("\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 f=0;for(;f<n.length;)f+=(await c.write(n,f,n.length-f,f)).bytesWritten;return await c.sync(),{path:e,size:n.length,version:Lo(n)}}finally{await c.close()}})}var $k=1e3,Nu=512*1024,Pu=1e4;function Cu(i,e){return e.startsWith(i)&&e.slice(i.length)||void 0}async function mr(i){let e=await at(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=Cu(r,a.slice(d)),f=c==="2"?o[++l]:void 0;if(!g)continue;if(s.entries.length===$k){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=f===void 0?void 0:Cu(r,f);S&&(y.originalPath=S),s.entries.push(y)}return s}async function Du(i,e,t){if(Bi(e),!["staged","unstaged","untracked"].includes(t))throw new X("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await mr(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 Wk(Vk(i,e))).isFile())return{...n,kind:"unsupported"};let l=await nn(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(`
192
+ `;e.body.splice(s+1,0,Ze(o).body[0])},traceCallback:Oa,tracePromise:Oa,traceSync:Oa,traceAuto:Oa}});var Ep,av=k(()=>{Ep={}});var pv,Ap,Vt,tr,Lr,Ur,Hn,Na,Gn,qr,Pa,Ca,xi,dv,uv,mv,Ip,gv,ov,lv,bA,cv,Tp,Ra,xp,fv,hv=k(()=>{wp();sv();X_();kp();av();pv=i=>{throw TypeError(i)},Ap=(i,e,t)=>e.has(i)||pv("Cannot "+t),Vt=(i,e,t)=>(Ap(i,e,"read from private field"),t?t.call(i):e.get(i)),tr=(i,e,t)=>e.has(i)?pv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Lr=(i,e,t,r)=>(Ap(i,e,"write to private field"),e.set(i,t),t),Ur=(i,e,t)=>(Ap(i,e,"access private method"),t),ov=$t,{parse:lv}=Aa,{generate:bA}=J_,cv=ev,xp=class{constructor(e,t,r,n,s,o={}){tr(this,xi),tr(this,Hn,null),tr(this,Na,null),tr(this,Gn,null),tr(this,qr,[]),tr(this,Pa,null),tr(this,Ca,{}),Lr(this,Hn,e),Lr(this,Na,t),Lr(this,Gn,r),Lr(this,qr,n),Lr(this,Pa,s),Lr(this,Ca,o)}free(){}get moduleName(){return Vt(this,Hn)}get filePath(){return Vt(this,Gn)}transform(e,t,r){if(Buffer.isBuffer(e)&&(e=e.toString()),!e)return{code:e};let n,s={},o=0,l={...cv,...Vt(this,Ca),defaults:{...cv}};for(let a of Vt(this,qr)){let{astQuery:c,functionQuery:p={}}=a;if(!n){let _={loc:!0,ranges:!0,raw:!0,module:t==="esm"};try{n=lv(e,_)}catch{n=lv(e,{..._,module:!_.module})}t==="esm"&&(s=Ur(this,xi,mv).call(this,n))}let d=Ur(this,xi,Ip).call(this,p,s),g=c||Ur(this,xi,gv).call(this,d),f={...a,dcModule:Vt(this,Pa),moduleType:t,moduleVersion:Vt(this,Na),functionQuery:d,transforms:l};f.operator=Ur(this,xi,uv).call(this,f),ov.traverse(n,ov.parse(g),(..._)=>{o++,Ur(this,xi,dv).call(this,f,..._)})}if(o===0&&Vt(this,qr).length>0){let a=Vt(this,qr).map(({astQuery:c,functionQuery:p={}})=>{if(c)return c;let d=Ur(this,xi,Ip).call(this,p,s),f=(S=>S.methodName||S.privateMethodName||S.functionName||S.expressionName||"constructor")(p),_=p.className||p.functionName||p.expressionName,y=d.className||d.functionName||d.expressionName;return _&&_!==y?`${_} (local name: ${y})`:f});throw new Error(`Failed to find injection points for: ${JSON.stringify(a)}`)}if(n){Tp??(Tp=Ep.SourceMapConsumer),Ra??(Ra=Ep.SourceMapGenerator);let a=`${Vt(this,Hn)}/${Vt(this,Gn)}`,c;if(r){let g=new Tp(r);g.file=a,c=Ra.fromSourceMap(g)}else c=new Ra({file:a});let p=bA(n,{sourceMap:c}),d=c.toString();return{code:p,map:d}}return{code:e}}};Hn=new WeakMap;Na=new WeakMap;Gn=new WeakMap;qr=new WeakMap;Pa=new WeakMap;Ca=new WeakMap;xi=new WeakSet;dv=function(i,...e){let t=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)};uv=function({transform:i,functionQuery:{kind:e}}){if(i)return i;switch(e){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}};mv=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};Ip=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(", ")};fv={Transformer:xp}});var yv,bv,Ai,Da,Op,Ma,La,ir,Ua,_A,vA,Rp,_v,vv=k(()=>{B_();hv();yv=i=>{throw TypeError(i)},bv=(i,e,t)=>e.has(i)||yv("Cannot "+t),Ai=(i,e,t)=>(bv(i,e,"read from private field"),t?t.call(i):e.get(i)),Da=(i,e,t)=>e.has(i)?yv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Op=(i,e,t,r)=>(bv(i,e,"write to private field"),e.set(i,t),t),_A=j_,{Transformer:vA}=fv,Rp=class{constructor(e,t){Da(this,Ma,[]),Da(this,La,null),Da(this,ir,{}),Da(this,Ua,{}),Op(this,Ma,e),Op(this,La,t||"diagnostics_channel")}free(){Op(this,ir,{})}addTransform(e,t){Ai(this,Ua)[e]=t}getTransformer(e,t,r){r=r.replace(/\\/g,"/");let n=`${e}/${r}@${t}`;if(Ai(this,ir)[n])return Ai(this,ir)[n];let s=Ai(this,Ma).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 Ai(this,ir)[n]=new vA(e,t,r,s,Ai(this,La),Ai(this,Ua)),Ai(this,ir)[n]}};Ma=new WeakMap;La=new WeakMap;ir=new WeakMap;Ua=new WeakMap;_v={InstrumentationMatcher:Rp}});function kA(i,e){return new wA(i,e)}var wA,wv,kv=k(()=>{vv();({InstrumentationMatcher:wA}=_v);wv={create:kA}});var qa,Np=k(()=>{kv();qa=wv});import SA from"node:path";var Pp,Cp,Sv,Dp=k(()=>{Fn();Pp=SA.sep,Cp=function(i){var e=i.split(Pp),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]+Pp;for(var c="",p=e.length-1,d=t+s;d<=p;d++)d===p?c+=e[d]:c+=e[d]+Pp;return{name:n,basedir:o,path:c}}},Sv=Dr(Cp)});import EA from"node:fs";import TA from"node:path";function AA(i){if(Mp.has(i))return Mp.get(i);try{let e=xA(i,"package.json"),t=IA(e),{version:r}=JSON.parse(t);return Mp.set(i,r),r}catch{return process.version.slice(1)}}var IA,xA,Mp,Lp,Ev,Up=k(()=>{Fn();({readFileSync:IA}=EA),{join:xA}=TA,Mp=new Map;Lp=AA,Ev=Dr(Lp)});function OA(i){qp=i}function RA(i){qp&&qp(i)}var qp,pi,ja=k(()=>{pi={setDiagnosticsHook:OA,emitDiagnostics:RA}});var Fp={};wu(Fp,{default:()=>jp});import{format as NA}from"node:util";function jp(i){return(...e)=>{z.isEnabled()&&z.log(`[${i}]`,NA(...e))}}var Bp=k(()=>{Wt()});var Tv,Iv=k(()=>{Bp();Fn();Tv=U_(Fp)});import PA from"node:module";import CA from"node:url";import DA from"node:os";import MA from"node:path";import LA from"node:fs";function FA(i,e){let t=DA,r=MA,n=LA,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);Fa("Dumping patched code to: %s",c),n.mkdirSync(a,{recursive:!0}),n.writeFileSync(c,i)}var UA,Hp,qA,xv,jA,Av,Fa,Gp,BA,Wp,Ov=k(()=>{Fn();Np();Dp();Up();ja();Iv();({create:UA}=qa),Hp=PA,qA=Cp,{pathToFileURL:xv}=CA,jA=Lp,{emitDiagnostics:Av}=pi,Fa=Tv("@apm-js-collab/tracing-hooks:module-patch"),Gp=class{constructor({instrumentations:e=[]}={}){this.packages=new Set(e.map(t=>t.module.name)),this.instrumentator=UA(e),this.compile=Hp.prototype._compile}patch(){let e=this;Hp.prototype._compile=function(...r){let[n,s]=r,o=qA(s);if(o&&e.packages.has(o.name)){Fa("found resolved module, checking if there is a transformer %s",s);let l=jA(o.basedir,o.name),a=e.instrumentator.getTransformer(o.name,l,o.path);if(a){Fa("transforming file %s",s);try{let c=a.transform(n,"cjs");r[0]=c?.code,Av({url:xv(s).href,moduleName:a.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&FA(r[0],s)}catch(c){Fa("Error transforming module %s: %o",s,c),Av({url:xv(s).href,moduleName:a.moduleName,error:c})}finally{a.free()}}}return e.compile.apply(this,r)}}unpatch(){Hp.prototype._compile=this.compile}};BA=Gp,Wp=Dr(BA)});import{fileURLToPath as Rv}from"node:url";import{dirname as Nv,join as HA}from"node:path";import{MessageChannel as GA}from"node:worker_threads";import{readFileSync as Pv}from"node:fs";function Mv(){let{port1:i,port2:e}=new GA;return i.on("message",pi.emitDiagnostics),i.unref(),e}function Lv(i={}){let e=i?.instrumentations||[];Dv=qa.create(e),Cv=new Set(e.map(t=>t.module.name)),Wn=new Map,zp=i?.diagnosticsPort?WA(i.diagnosticsPort):pi.emitDiagnostics}function WA(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){Vp("failed to post diagnostics for %s: %o",e.url,t)}}}function $A(i){if(!i.url.startsWith("file:"))return i;let e=Sv(Rv(i.url));if(e&&Cv.has(e.name)){let t=e.basedir,r=Ev(t),n=Dv.getTransformer(e.name,r,e.path);n&&Wn.set(i.url,n)}return i}function Uv(i,e,t){return $A(t(i,e))}function Kp(i,e,t){let r=t(i,e);if(Wn.has(i)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??i);r.source??=Pv(n)}return VA(i,r)}function VA(i,e){let t=e.source;if(t){let r=Wn.get(i);if(KA(i,e.format))return Vp("skipping json module %s",i),r.free(),Wn.delete(i),e;try{let n=typeof t=="string"?t:Buffer.from(t).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":QA(i,n),o=r.transform(n,s);e.source=o?.code,e.shortCircuit=!0,zp({url:i,moduleName:r.moduleName})}catch(n){Vp("Error transforming module %s: %o",i,n),zp({url:i,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function KA(i,e){return e==="json"||zA.test(i)}function QA(i,e){return JA(i)??(YA.test(e)?"esm":"cjs")}function JA(i){let e;try{e=Rv(i)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let t=qv(Nv(e));return t==="module"?"esm":t==="commonjs"?"cjs":void 0}function qv(i){if($p.has(i))return $p.get(i);let e;try{e=JSON.parse(Pv(HA(i,"package.json"),"utf8")).type}catch{let t=Nv(i);t!==i&&(e=qv(t))}return $p.set(i,e),e}var Vp,Wn,Cv,Dv,zp,zA,YA,$p,A6,jv=k(()=>{Bp();Np();Dp();Up();ja();Vp=jp("@apm-js-collab/tracing-hooks:esm-hook"),Wn=null,Cv=null,Dv=null,zp=pi.emitDiagnostics;zA=/\.json([?#]|$)/;YA=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;$p=new Map;A6=pi.setDiagnosticsHook});import{createHash as Fv}from"node:crypto";import{existsSync as Gv,readFileSync as XA}from"node:fs";import*as ZA from"node:module";import{join as Wv,dirname as $n}from"node:path";import{pathToFileURL as Ba,fileURLToPath as Qp}from"node:url";function tO(i){if(i)return!0;let{major:e=0,minor:t=0}=dl(process.versions.node??"0.0.0");return e>25||e===25&&t>=1||e===24&&t>=13}function $v(i){if(Yp.has(i))return Yp.get(i);let e,t=Wv(i,"package.json");if(Gv(t))try{e=JSON.parse(XA(t,"utf8")).type}catch{e=void 0}else $n(i)!==i&&(e=$v($n(i)));return Yp.set(i,e),e}function iO(i){if(i.endsWith(".json"))return"json";if(i.endsWith(".mjs")||i.startsWith("file:")&&i.endsWith(".js")&&$v($n(Qp(i)))==="module")return"module"}function rO(i){return(e,t,r)=>i(e,t,(n,s)=>{let o=r(n,s);if(o&&o.format==null){let l=iO(n);l&&(o.format=l)}return o})}function Vv(i){At(()=>{console.warn(`[Sentry] ${i}`)})}function zv(i){Vv(`${i} See ${eO}`)}function nO(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(Hv.has(i))return;Hv.add(i),Vv(`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}Bv||(Bv=!0,zv(`\`@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 Kv(){var i;let e=(i=pe).__SENTRY_ORCHESTRION__??(i.__SENTRY_ORCHESTRION__={});if(e.runtime||e.runtimeUnavailable)return;let t=globalThis,r=tO(!!t.Deno),n=ZA;pi.setDiagnosticsHook(({url:s,moduleName:o,error:l})=>{var a;l?(l instanceof TypeError&&nO(o,l),z.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,Bt()?.emit("orchestrion.module-injected",o))});try{if(typeof n.registerHooks=="function"&&r){Lv({instrumentations:jn});let s=new Map,o=t.Deno?rO(Kp):Kp;n.registerHooks({resolve:Uv,load:(p,d,g)=>{let f=o(p,d,g),_=f?.format??d.format;if((_==null||_==="commonjs")&&f?.shortCircuit===!0&&f?.source!=null&&p.startsWith("file:")){let y=Fv("sha256").update(f.source).digest("hex");s.set(Ba(Qp(p)).href,y)}return f}});let l=n.Module.prototype,a=l._compile;new Wp({instrumentations:jn}).patch();let c=l._compile;l._compile=function(p,d,...g){let f=Ba(d).href,_=s.get(f);return s.delete(f),(_!==void 0&&_===Fv("sha256").update(p).digest("hex")?a:c).call(this,p,d,...g)},z.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof n.register=="function"&&!t.Bun&&!t.Deno){let s=Mv(),o;o=import.meta.url;let l;l=Wv($n(Qp(import.meta.url)),"hook.js");let a=Gv(l);a||z.warn(`No orchestrion ESM hook at ${l}; falling back to the package specifier.`);let c=a?Ba(l).href:"@sentry/server-runtime-injection/hook";if(a){let p=`${Ba($n(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:jn,diagnosticsPort:s},transferList:[s]}),new Wp({instrumentations:jn}).patch(),z.log("Registered diagnostics-channel injection via Module.register()")}else{e.runtimeUnavailable=!0,z.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);zv(`Failed to register diagnostics-channel injection hooks (${o}), so channel-based integrations will not record spans.`),z.warn("Diagnostics-channel injection registration error:",s);return}e.runtime=e.runtime||[]}var eO,Yp,Bv,Hv,Yv=k(()=>{Wt();k_();Ov();jv();ja();eO="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";Yp=new Map;Bv=!1,Hv=new Set});import*as Qv from"node:os";import{threadId as sO,isMainThread as aO}from"worker_threads";var oO,Vn,Jv=k(()=>{Ea();Wt();cc();L_();Yv();S_();T_();oO=6e4,Vn=class extends Cn{constructor(e){let t=e.includeServerName===!1?void 0:e.serverName||global.process.env.SENTRY_NAME||Qv.hostname(),r={...e,platform:"node",runtime:e.runtime||{name:"node",version:global.process.version},serverName:t};Zl(r,"node"),z.log(`Initializing Sentry: process: ${process.pid}, thread: ${aO?"main":`worker-${sO}`}.`),super(r),this._onExitFlushListener=()=>{this.emit("flush")},t&&this.on("beforeCaptureLog",n=>{n.attributes={...n.attributes,"server.address":t}}),process.on("beforeExit",this._onExitFlushListener),Gl(this),M_(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&e.enableRuntimeChannelInjection!==!1&&Kv()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=D_():this.asyncLocalStorageLookup={asyncLocalStorage:wc()},super.init()}get tracer(){if(this._tracer)return this._tracer;let e="@sentry/node",t=ht,r=Si.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(()=>{E_&&z.log("Flushing client reports based on interval."),this._flushOutcomes()},e.clientReportFlushInterval??oO).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){Ql(),super._setupIntegrations()}}});var Xv=k(()=>{O_();Jv()});var Zv={};wu(Zv,{NodeClient:()=>Vn,Scope:()=>Je,createTransport:()=>zl,defaultStackParser:()=>lp,linkedErrorsIntegration:()=>sc});var ew=k(()=>{"use strict";Xv();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]="0115f7b2-180a-4125-81f5-772406ddc1bd",i._sentryDebugIdIdentifier="sentry-dbid-0115f7b2-180a-4125-81f5-772406ddc1bd")}catch{}})();import{delimiter as MP,dirname as LP,join as Xr,resolve as en}from"node:path";import{readFileSync as UP,realpathSync as Jd,watch as qP}from"node:fs";import{fileURLToPath as jP}from"node:url";import{DefaultPackageManager as Ek,getAgentDir as ut,ModelRuntime as FP,SessionManager as tu,SettingsManager as BP,VERSION as Xd}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as HP}from"@earendil-works/pi-ai";import{randomBytes as mw,randomUUID as Zp,timingSafeEqual as _O}from"node:crypto";import{readFile as vO,readdir as wO}from"node:fs/promises";import{createServer as kO}from"node:http";import{join as ed}from"node:path";import{getAgentDir as SO}from"@earendil-works/pi-coding-agent";import{isAbsolute as mS,relative as gS}from"node:path";var st={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var ku={id:st.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 qk}from"node:child_process";import{realpath as jk}from"node:fs/promises";import{isAbsolute as Su,relative as Fk,sep as Bk,win32 as Hk}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=qk("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 f=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",f==="outcome_unknown"?503:409,f));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 at(i){let e=await jk(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=Fk(t,e).split(Bk).join("/");if(r===".."||r.startsWith("../")||Su(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 Fi(i){if(typeof i!="string"||!i||i.length>4096||i.includes("\0")||i.includes("\\")||Su(i)||Hk.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 tS}from"node:crypto";import{lstat as Fo,realpath as Uu}from"node:fs/promises";import{dirname as Lu,isAbsolute as iS,relative as rS,resolve as sn}from"node:path";import{lstat as Xk}from"node:fs/promises";import{resolve as Zk}from"node:path";import{createHash as Gk}from"node:crypto";import{constants as Xt}from"node:fs";import{open as Uo,opendir as Wk,realpath as Eu,stat as ys}from"node:fs/promises";import{isAbsolute as Iu,relative as $k,resolve as Vk,sep as zk,win32 as Kk}from"node:path";var Yk=1e3,Qk={bytes:512*1024,lines:1e4},qo={bytes:5*1024*1024,lines:2e5},xu=8*1024*1024,Jk=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Lo=i=>Gk("sha256").update(i).digest("hex"),fe=class extends Error{status;reason;constructor(e,t=400,r){super(e),this.name="WorkspaceFileError",this.status=t,this.reason=r}};function Tu(i,e){let t=$k(i,e);return t!==".."&&!t.startsWith(`..${zk}`)&&!Iu(t)}async function rn(i,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||Iu(e)||Kk.isAbsolute(e))throw new fe("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Eu(i),r=Vk(t,e);if(!Tu(t,r))throw new fe("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await Eu(r);if(!Tu(t,n))throw new fe("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function bs(i){try{return await i()}catch(e){if(e instanceof fe)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new fe("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new fe("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function Au(i,e){return bs(async()=>{let t=await rn(i,e),r=[],n=!1;for await(let s of await Wk(t)){if(s.name===".git")continue;if(r.length===Yk){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 ys(await rn(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")||Jk.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:r,truncated:n}})}function Ou(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 nn(i,e,t=Qk){return bs(async()=>{let r=await rn(i,e);if(!(await ys(r)).isFile())throw new fe("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await Uo(r,Xt.O_RDONLY|Xt.O_NONBLOCK|(Xt.O_NOFOLLOW??0));try{let s=await n.stat();if(!s.isFile())throw new fe("\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=Ou(l),c=a?xu: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:_}=await n.read(p,d,p.length-d,d);if(!_)break;d+=_}if(d>s.size)throw new fe("\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(_=>_===0||_<32&&![9,10,12,13,27].includes(_)))return{...o,kind:"unsupported"};let f=1;for(let _=0;_<g.length-1;_++)if(g[_]===10&&++f>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:Lo(g)}}catch{return{...o,kind:"unsupported"}}}finally{await n.close()}})}async function Ru(i,e){return bs(async()=>{let t=await rn(i,e);if(!(await ys(t)).isFile())throw new fe("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Uo(t,Xt.O_RDONLY|Xt.O_NONBLOCK|(Xt.O_NOFOLLOW??0));try{let n=await r.stat();if(!n.isFile())throw new fe("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(n.size>xu)throw new fe("\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 fe("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let l=s.subarray(0,o),a=Ou(l);if(!a)throw new fe("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:l}}finally{await r.close()}})}async function Nu(i,e,t,r){if(typeof t!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new fe("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let n=Buffer.from(t,"utf8"),{bytes:s,lines:o}=qo;if(n.length>s)throw new fe(`\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 fe(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${o} \u884C`,413);return bs(async()=>{let a=await rn(i,e);if(!(await ys(a)).isFile())throw new fe("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await Uo(a,Xt.O_RDWR|Xt.O_NONBLOCK|(Xt.O_NOFOLLOW??0));try{let p=await c.stat();if(!p.isFile())throw new fe("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new fe("\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:_}=await c.read(d,g,d.length-g,g);if(!_)break;g+=_}if(g>p.size||Lo(d.subarray(0,g))!==r)throw new fe("\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 f=0;for(;f<n.length;)f+=(await c.write(n,f,n.length-f,f)).bytesWritten;return await c.sync(),{path:e,size:n.length,version:Lo(n)}}finally{await c.close()}})}var eS=1e3,Pu=512*1024,Cu=1e4;function Du(i,e){return e.startsWith(i)&&e.slice(i.length)||void 0}async function mr(i){let e=await at(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=Du(r,a.slice(d)),f=c==="2"?o[++l]:void 0;if(!g)continue;if(s.entries.length===eS){s.truncated=!0;continue}let _=a.slice(0,d).split(" "),y={path:g,index:c==="?"?"?":_[1][0],worktree:c==="?"?"?":_[1][1],conflict:c==="u",untracked:c==="?",submodule:c!=="?"&&_[2]!=="N..."},S=f===void 0?void 0:Du(r,f);S&&(y.originalPath=S),s.entries.push(y)}return s}async function Mu(i,e,t){if(Fi(e),!["staged","unstaged","untracked"].includes(t))throw new X("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await mr(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 Xk(Zk(i,e))).isFile())return{...n,kind:"unsupported"};let l=await nn(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
193
  `),c=a.at(-1)==="";c&&a.pop();let p=`--- /dev/null
194
194
  +++ b/${e.replace(/[\r\n]/g," ")}
195
195
  @@ -0,0 +1,${a.length} @@
196
196
  ${a.map(d=>`+${d}`).join(`
197
197
  `)}
198
198
  ${c?"":`\
199
- `}`;return Buffer.byteLength(p)>Nu||a.length>Pu?{...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],Nu);return l?l.split(`
200
- `).length>Pu?{...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 jo=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 Qk(i){return Lu(sn(i,(await ve(i,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Fo(i,e,t=!1){let r=null;try{let n=await at(i);n.kind==="repository"&&(r=await Qk(n.cwd))}catch(n){if(!t)throw n}if(!r)return e();if(jo.has(r))return xe("busy");jo.add(r);try{return await e()}finally{jo.delete(r)}}async function vs(i){let e=await at(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 mr(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 f=>{try{return await Bo(sn(o.replace(/\n$/,""),f)),f}catch(v){if(v.code==="ENOENT")return null;throw v}}))).filter(Boolean),c=await Promise.all(r.entries.map(async f=>{try{let v=await Bo(sn(e.root,f.path));return[f.path,v.size,v.mtimeMs,v.ctimeMs,v.ino,v.mode]}catch(v){if(["ENOENT","ENOTDIR"].includes(v.code??""))return[f.path,"missing"];throw v}})),p=s.split(`
201
- `).filter(Boolean).map(f=>{let[v,,y]=f.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(f=>f.conflict)?"operation_in_progress":null,g=zk("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(f=>!f.untracked&&f.index!==".").length,dirty:r.entries.length>0,blocked:d,branches:p.slice(0,512)}}async function Jk(i,e){Bi(e);let t=Mu(sn(i.cwd,e));for(;;)try{let s=await Lu(t),o=Yk(i.cwd,s);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||Kk(o))return xe("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;t=Mu(t)}let r=await mr(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 Bo(sn(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 Uu(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 Fo(i,async()=>{let n=await at(i);if(n.kind!=="repository")return xe("invalid_path",404);t(n.root);let s=await vs(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 Jk(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&&(Bi(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 vs(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 Xk}from"node:crypto";var an=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,qu="%H%x00%P%x00%an%x00%aI%x00%s",ju=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function Bu(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"),f=c==="commit"?p:d==="commit"?g:void 0;if(!f||!an.test(f))continue;let v=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";n.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:f,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&&an.test(t)?[t]:[]])].sort(),o=Xk("sha256").update(JSON.stringify({refs:n,head:t,symbolic:r})).digest("hex");return{refs:n,tips:s,head:t,snapshot:o}}function Fu(i){let[e,t,r,n,s]=i;if(!e||!an.test(e)||!t?.split(" ").filter(Boolean).every(o=>an.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 Hu(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 at(i),n={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return n;let s=await Bu(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=${qu}`,`--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(Fu(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 Gu(i,e){if(typeof e!="string"||!an.test(e))throw new X("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await at(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 Bu(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 Wu(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 Vu(i,e,t){let n=(await ve(i.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${qu}%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=Fu(n.slice(0,5)),o=Wu(e,s.parents,t),l=["diff-tree","--root","-r","--no-commit-id",...ju],[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 f of c.split("\0").filter(Boolean)){let v=f.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 f=0;f<d.length&&g.length<1e3;f+=2){let v=d[f+1],[y,S]=p.get(v)??[null,null];g.push({path:v,status:d[f],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 $u(i,e,t=0){return Vu(await Gu(i,e),e,t)}async function zu(i,e,t,r=0){Bi(t);let n=await Gu(i,e),s=await Vu(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",...ju,"--src-prefix=a/","--dst-prefix=b/","-p",...Wu(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 Ku=["/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 Yu(i,e,t){if(i.endsWith("/control"))return vs(e);if(i.endsWith("/status"))return mr(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 Hu(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 Du(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 $u(e,t.hash,r);if(i.endsWith("/commit-diff")&&typeof t.path=="string")return zu(e,t.hash,t.path,r);throw new X("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var ks=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),Zk=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Qu={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},eS=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"]),tS=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 Ju(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 ot(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 eS){let r=i[t];t==="toolName"?typeof r=="string"&&(ks.has(r)||r==="custom")&&(e[t]=r):t==="failureKind"?Zk.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]=tS.has(r.split("?")[0])?r.split("?")[0]:"[route]":t==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[t]=r.split("/").map(ot).join("/"):typeof r=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(r)?r:ot(r).slice(0,t==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[t]=r)}return e}function Ho(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 gr(i,e=0){let t=i instanceof Error?i:new Error(typeof i=="string"?i:"Non-Error rejection"),r=new Error(ot(t.message));if(r.name=ot(t.name).slice(0,100),t.stack){let n=t.stack.split(`
199
+ `}`;return Buffer.byteLength(p)>Pu||a.length>Cu?{...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],Pu);return l?l.split(`
200
+ `).length>Cu?{...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 jo=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 Uu(sn(i,(await ve(i,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Bo(i,e,t=!1){let r=null;try{let n=await at(i);n.kind==="repository"&&(r=await nS(n.cwd))}catch(n){if(!t)throw n}if(!r)return e();if(jo.has(r))return xe("busy");jo.add(r);try{return await e()}finally{jo.delete(r)}}async function _s(i){let e=await at(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 mr(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 f=>{try{return await Fo(sn(o.replace(/\n$/,""),f)),f}catch(_){if(_.code==="ENOENT")return null;throw _}}))).filter(Boolean),c=await Promise.all(r.entries.map(async f=>{try{let _=await Fo(sn(e.root,f.path));return[f.path,_.size,_.mtimeMs,_.ctimeMs,_.ino,_.mode]}catch(_){if(["ENOENT","ENOTDIR"].includes(_.code??""))return[f.path,"missing"];throw _}})),p=s.split(`
201
+ `).filter(Boolean).map(f=>{let[_,,y]=f.split("\0");return{name:_,current:_===r.branch,occupied:!!y&&_!==r.branch}}),d=r.truncated||p.length>512?"too_many_changes":a.includes("index.lock")?"index_locked":a.length||r.entries.some(f=>f.conflict)?"operation_in_progress":null,g=tS("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(f=>!f.untracked&&f.index!==".").length,dirty:r.entries.length>0,blocked:d,branches:p.slice(0,512)}}async function sS(i,e){Fi(e);let t=Lu(sn(i.cwd,e));for(;;)try{let s=await Uu(t),o=rS(i.cwd,s);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||iS(o))return xe("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;t=Lu(t)}let r=await mr(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 Fo(sn(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 qu(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 Bo(i,async()=>{let n=await at(i);if(n.kind!=="repository")return xe("invalid_path",404);t(n.root);let s=await _s(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 sS(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&&(Fi(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 _s(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 aS}from"node:crypto";var an=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ju="%H%x00%P%x00%an%x00%aI%x00%s",Fu=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function Bu(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"),f=c==="commit"?p:d==="commit"?g:void 0;if(!f||!an.test(f))continue;let _=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";n.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:f,kind:_})}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&&an.test(t)?[t]:[]])].sort(),o=aS("sha256").update(JSON.stringify({refs:n,head:t,symbolic:r})).digest("hex");return{refs:n,tips:s,head:t,snapshot:o}}function Hu(i){let[e,t,r,n,s]=i;if(!e||!an.test(e)||!t?.split(" ").filter(Boolean).every(o=>an.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 Gu(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 at(i),n={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return n;let s=await Bu(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=${ju}`,`--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(Hu(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 Wu(i,e){if(typeof e!="string"||!an.test(e))throw new X("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await at(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 Bu(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 $u(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 Vu(i,e,t){let n=(await ve(i.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${ju}%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=Hu(n.slice(0,5)),o=$u(e,s.parents,t),l=["diff-tree","--root","-r","--no-commit-id",...Fu],[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 f of c.split("\0").filter(Boolean)){let _=f.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);_&&p.set(_[3],[_[1]==="-"?null:Number(_[1]),_[2]==="-"?null:Number(_[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 f=0;f<d.length&&g.length<1e3;f+=2){let _=d[f+1],[y,S]=p.get(_)??[null,null];g.push({path:_,status:d[f],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 zu(i,e,t=0){return Vu(await Wu(i,e),e,t)}async function Ku(i,e,t,r=0){Fi(t);let n=await Wu(i,e),s=await Vu(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",...Fu,"--src-prefix=a/","--dst-prefix=b/","-p",...$u(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 Yu=["/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 Qu(i,e,t){if(i.endsWith("/control"))return _s(e);if(i.endsWith("/status"))return mr(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 Gu(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 Mu(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 zu(e,t.hash,r);if(i.endsWith("/commit-diff")&&typeof t.path=="string")return Ku(e,t.hash,t.path,r);throw new X("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var ws=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),oS=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Ju={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},lS=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"]),cS=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 Xu(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 ot(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 lS){let r=i[t];t==="toolName"?typeof r=="string"&&(ws.has(r)||r==="custom")&&(e[t]=r):t==="failureKind"?oS.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]=cS.has(r.split("?")[0])?r.split("?")[0]:"[route]":t==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[t]=r.split("/").map(ot).join("/"):typeof r=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(r)?r:ot(r).slice(0,t==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[t]=r)}return e}function Ho(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 gr(i,e=0){let t=i instanceof Error?i:new Error(typeof i=="string"?i:"Non-Error rejection"),r=new Error(ot(t.message));if(r.name=ot(t.name).slice(0,100),t.stack){let n=t.stack.split(`
204
204
  `).slice(1,31).map(s=>{let o=s.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${ot(s.slice(0,o.index))}${o[1]}:${o[2]}:${o[3]}${o[4]}`:ot(s)});r.stack=`${r.name}: ${r.message}
205
205
  ${n.join(`
206
206
  `)}`}else r.stack=void 0;return e<3&&t.cause!==void 0&&(r.cause=gr(t.cause,e+1)),r}function Zt(i,e){let t=new Error(e);return i instanceof Error&&(t.name=i.name,i.stack&&(t.stack=`${t.name}: ${e}
207
207
  ${i.stack.split(`
208
208
  `).slice(1).join(`
209
- `)}`)),t}function iS(i){return{...i.filename?{filename:Ho(i.filename)}:{},...i.abs_path?{abs_path:Ho(i.abs_path)}:{},...i.function?{function:ot(i.function)}:{},lineno:i.lineno,colno:i.colno,in_app:i.in_app}}function rS(i){let e=Tt(i.contexts?.diagnostic??{}),t=Xu(e);return{event_id:i.event_id,timestamp:i.timestamp,platform:i.platform,level:i.level,release:i.release,dist:i.dist,environment:ot(i.environment??"production"),...i.message?{message:ot(i.message)}:{},exception:i.exception?{values:i.exception.values?.slice(0,4).map(r=>({type:ot(r.type??"Error"),value:ot(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(iS)}}:{},...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:ot(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:Ho(r.code_file)}:{}}))}:void 0}}function Xu(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 Zu(i,e){return e.attachments=[],rS(i)}var on=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let r={timestamp:Date.now()/1e3,category:ot(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)}},Go=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}}},nS=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 Fi(i){return i instanceof Error&&(i.name==="AbortError"||nS.has(i.message))}var ws=class{budget=new Go;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,r,n,s=new on){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(Fi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let n=gr(e),s=Tt({...this.state,...t}),o=Xu(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 em(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 tm={metadata:wu,routes:Ku,coordinateStart:(i,e)=>Fo(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=(f,v)=>{let y=aS(f,v);return y!==".."&&!y.startsWith("../")&&!y.startsWith("..\\")&&!sS(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 Uu(s.cwd,e,l):await Yu(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 fe)n(o.status,{error:o.message,errorCode:"validation_error",...o instanceof X?{reason:o.reason}:{}});else throw Zt(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var im={id:st.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 oS,open as lS,opendir as cS,realpath as pS}from"node:fs/promises";import{join as sm}from"node:path";var dS=5e3,Wo=2e4,rm=100,nm=200,uS=5e3,mS=512*1024,gS=4e3,fS=240,hS=new Set([".git","node_modules",".hg",".svn"]);function yS(i,e){return e.startsWith(i)&&e.slice(i.length)||void 0}function bS(i,e){return i==="D"||e==="D"?i==="A"?"added":"deleted":i==="A"&&(e==="."||e==="M")?"added":"modified"}async function am(i){let e;try{e=await at(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 f=0;f<a;f++)c=o.indexOf(" ",c)+1;l==="2"&&s++;let p=yS(e.scope,o.slice(c));if(!p)continue;if(r.entries.length===dS){r.truncated=!0;break}let d=o.slice(2,4),g=l==="?"?"untracked":l==="!"?"ignored":l==="u"?"conflict":bS(d[0],d[1]);r.entries.push({path:p,state:g})}return r}async function _S(i){let e=await pS(i),t;try{t=await at(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,Wo),truncated:o.length>Wo}}catch(s){if(!(s instanceof X))throw s}let r=[],n=[""];for(;n.length;){let s=n.shift(),o;try{o=await cS(sm(e,s))}catch{continue}for await(let l of o){let a=s?`${s}/${l.name}`:l.name;if(l.isDirectory())hS.has(l.name)||n.push(a);else if(l.isFile()){if(r.length===Wo)return{root:e,paths:r,truncated:!0};r.push(a)}}}return{root:e,paths:r,truncated:!1}}function vS(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 om(i,e,t){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new fe("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(t!=="name"&&t!=="content")throw new fe("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:n,paths:s,truncated:o}=await _S(i);if(t==="name"){let d=s.flatMap(g=>{let f=vS(g,r);return f===void 0?[]:[{path:g,score:f}]}).sort((g,f)=>g.score-f.score||g.path.length-f.path.length||g.path.localeCompare(f.path));return{kind:"name",results:d.slice(0,rm).map(({path:g})=>({path:g})),truncated:o||d.length>rm}}let l=[],a=Date.now()+gS,c=0,p=o;for(let d of s){if(l.length>=nm||c>=uS||Date.now()>a){p=!0;break}let g=sm(n,d);try{let f=await oS(g);if(!f.isFile()||f.size===0||f.size>mS)continue;c++;let v=await lS(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 A=S[T],x=A.toLowerCase().indexOf(r);if(x<0)continue;let C=Math.max(0,x-60);if(l.push({path:d,line:T+1,text:(C?"\u2026":"")+A.slice(C,C+fS).replace(/\r$/u,"")}),l.length>=nm)break}}catch{}}return{kind:"content",results:l,truncated:p}}var lm={metadata:im,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 Ou(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 xu(s.cwd,a):o==="write"?await Ru(s.cwd,a,e.text,e.version):o==="status"?await am(s.cwd):o==="search"?await om(s.cwd,e.query,e.mode):await nn(s.cwd,a,qo);if(o!=="write"&&c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r(200,p)}catch(p){if(p instanceof fe)r(p.status,{error:p.message,errorCode:"validation_error",...p.reason?{reason:p.reason}:{}});else throw Zt(p,o==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var cm={id:st.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 um,constants as Vo,statSync as mm}from"node:fs";import{createRequire as OS}from"node:module";import{execFile as gm}from"node:child_process";import{accessSync as wS,chmodSync as kS,constants as SS,statSync as ES}from"node:fs";import{createRequire as TS}from"node:module";import{dirname as IS,join as xS}from"node:path";var pm=TS(import.meta.url);function AS(i){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=xS(i,e,"spawn-helper"),r;try{r=ES(t).mode}catch(n){if(n.code==="ENOENT")continue;throw n}try{wS(t,SS.X_OK)}catch{kS(t,r|73)}}}function dm(...i){return AS(IS(pm.resolve("node-pty/package.json"))),pm("node-pty").spawn(...i)}var ei=class extends Error{reason;constructor(e,t,r){super(t,{cause:r}),this.reason=e}},fm=OS(import.meta.url),$o=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}=fm("@xterm/headless"),{SerializeAddon:p}=fm("@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,f])=>f!==void 0&&!/^PI_WEBAPP_RESTART_/.test(g)));try{this.pty=dm(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 ei("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(f=>{if(this.disposed){f();return}this.screen.write(g,()=>{this.broadcast({type:"output",data:g});for(let v of this.outputListeners)v(g);f()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(g=>this.pty.onExit(({exitCode:f,signal:v})=>{this.exit={type:"exit",exitCode:f,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=>gm("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(n=>gm("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()}},Ss=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 ei("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(um(o,Vo.X_OK),!mm(o).isFile())throw new Error("Not a shell file")}catch(c){throw new ei("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(!mm(r).isDirectory())throw new Error("Not a directory");um(r,Vo.R_OK|Vo.X_OK)}catch(c){throw new ei("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 $o(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 hm=(i,e)=>Number.isInteger(i)&&Number.isInteger(e)&&Number(i)>=2&&Number(i)<=500&&Number(e)>=1&&Number(e)<=300,ym="terminal-input";async function bm(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")&&!hm(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 ei?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 ei?c.reason:l==="create"?"terminal_runtime_unavailable":void 0})}}var RS=/^[a-f0-9-]{36}$/i,_m=32*1024,NS=300,PS=3e4,km=i=>i<32||i>=127&&i<=159,Sm=i=>{if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid terminal tool input");return i};function Em(i){if(i!==void 0){if(typeof i!="string"||!RS.test(i))throw new Error("terminalId must be the terminal tab's contentId");return i}}function zo(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 Ts(i){let e=Sm(i);if(typeof e.text!="string")throw new Error("text must be a string");let t=e.text.replace(/\r\n?/g,`
209
+ `)}`)),t}function pS(i){return{...i.filename?{filename:Ho(i.filename)}:{},...i.abs_path?{abs_path:Ho(i.abs_path)}:{},...i.function?{function:ot(i.function)}:{},lineno:i.lineno,colno:i.colno,in_app:i.in_app}}function dS(i){let e=Tt(i.contexts?.diagnostic??{}),t=Zu(e);return{event_id:i.event_id,timestamp:i.timestamp,platform:i.platform,level:i.level,release:i.release,dist:i.dist,environment:ot(i.environment??"production"),...i.message?{message:ot(i.message)}:{},exception:i.exception?{values:i.exception.values?.slice(0,4).map(r=>({type:ot(r.type??"Error"),value:ot(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(pS)}}:{},...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:ot(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:Ho(r.code_file)}:{}}))}:void 0}}function Zu(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 em(i,e){return e.attachments=[],dS(i)}var on=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let r={timestamp:Date.now()/1e3,category:ot(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)}},Go=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}}},uS=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 Bi(i){return i instanceof Error&&(i.name==="AbortError"||uS.has(i.message))}var vs=class{budget=new Go;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,r,n,s=new on){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(Bi(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let n=gr(e),s=Tt({...this.state,...t}),o=Zu(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 tm(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 im={metadata:ku,routes:Yu,coordinateStart:(i,e)=>Bo(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=(f,_)=>{let y=gS(f,_);return y!==".."&&!y.startsWith("../")&&!y.startsWith("..\\")&&!mS(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 qu(s.cwd,e,l):await Qu(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 fe)n(o.status,{error:o.message,errorCode:"validation_error",...o instanceof X?{reason:o.reason}:{}});else throw Zt(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var rm={id:st.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 fS,open as hS,opendir as yS,realpath as bS}from"node:fs/promises";import{join as am}from"node:path";var _S=5e3,Wo=2e4,nm=100,sm=200,vS=5e3,wS=512*1024,kS=4e3,SS=240,ES=new Set([".git","node_modules",".hg",".svn"]);function TS(i,e){return e.startsWith(i)&&e.slice(i.length)||void 0}function IS(i,e){return i==="D"||e==="D"?i==="A"?"added":"deleted":i==="A"&&(e==="."||e==="M")?"added":"modified"}async function om(i){let e;try{e=await at(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 f=0;f<a;f++)c=o.indexOf(" ",c)+1;l==="2"&&s++;let p=TS(e.scope,o.slice(c));if(!p)continue;if(r.entries.length===_S){r.truncated=!0;break}let d=o.slice(2,4),g=l==="?"?"untracked":l==="!"?"ignored":l==="u"?"conflict":IS(d[0],d[1]);r.entries.push({path:p,state:g})}return r}async function xS(i){let e=await bS(i),t;try{t=await at(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,Wo),truncated:o.length>Wo}}catch(s){if(!(s instanceof X))throw s}let r=[],n=[""];for(;n.length;){let s=n.shift(),o;try{o=await yS(am(e,s))}catch{continue}for await(let l of o){let a=s?`${s}/${l.name}`:l.name;if(l.isDirectory())ES.has(l.name)||n.push(a);else if(l.isFile()){if(r.length===Wo)return{root:e,paths:r,truncated:!0};r.push(a)}}}return{root:e,paths:r,truncated:!1}}function AS(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 lm(i,e,t){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new fe("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(t!=="name"&&t!=="content")throw new fe("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:n,paths:s,truncated:o}=await xS(i);if(t==="name"){let d=s.flatMap(g=>{let f=AS(g,r);return f===void 0?[]:[{path:g,score:f}]}).sort((g,f)=>g.score-f.score||g.path.length-f.path.length||g.path.localeCompare(f.path));return{kind:"name",results:d.slice(0,nm).map(({path:g})=>({path:g})),truncated:o||d.length>nm}}let l=[],a=Date.now()+kS,c=0,p=o;for(let d of s){if(l.length>=sm||c>=vS||Date.now()>a){p=!0;break}let g=am(n,d);try{let f=await fS(g);if(!f.isFile()||f.size===0||f.size>wS)continue;c++;let _=await hS(g,"r"),y;try{y=await _.readFile()}finally{await _.close()}if(y.includes(0))continue;let S=y.toString("utf8").split(`
211
+ `);for(let T=0;T<S.length;T++){let A=S[T],I=A.toLowerCase().indexOf(r);if(I<0)continue;let C=Math.max(0,I-60);if(l.push({path:d,line:T+1,text:(C?"\u2026":"")+A.slice(C,C+SS).replace(/\r$/u,"")}),l.length>=sm)break}}catch{}}return{kind:"content",results:l,truncated:p}}var cm={metadata:rm,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 Ru(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 Au(s.cwd,a):o==="write"?await Nu(s.cwd,a,e.text,e.version):o==="status"?await om(s.cwd):o==="search"?await lm(s.cwd,e.query,e.mode):await nn(s.cwd,a,qo);if(o!=="write"&&c()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r(200,p)}catch(p){if(p instanceof fe)r(p.status,{error:p.message,errorCode:"validation_error",...p.reason?{reason:p.reason}:{}});else throw Zt(p,o==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var pm={id:st.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 mm,constants as $o,statSync as gm}from"node:fs";import{createRequire as US}from"node:module";import{execFile as fm}from"node:child_process";import{accessSync as OS,chmodSync as RS,constants as NS,statSync as PS}from"node:fs";import{createRequire as CS}from"node:module";import{dirname as DS,join as MS}from"node:path";var dm=CS(import.meta.url);function LS(i){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=MS(i,e,"spawn-helper"),r;try{r=PS(t).mode}catch(n){if(n.code==="ENOENT")continue;throw n}try{OS(t,NS.X_OK)}catch{RS(t,r|73)}}}function um(...i){return LS(DS(dm.resolve("node-pty/package.json"))),dm("node-pty").spawn(...i)}var ei=class extends Error{reason;constructor(e,t,r){super(t,{cause:r}),this.reason=e}},hm=US(import.meta.url),Vo=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}=hm("@xterm/headless"),{SerializeAddon:p}=hm("@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,f])=>f!==void 0&&!/^PI_WEBAPP_RESTART_/.test(g)));try{this.pty=um(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 ei("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(f=>{if(this.disposed){f();return}this.screen.write(g,()=>{this.broadcast({type:"output",data:g});for(let _ of this.outputListeners)_(g);f()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(g=>this.pty.onExit(({exitCode:f,signal:_})=>{this.exit={type:"exit",exitCode:f,signal:_},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=>fm("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(n=>fm("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()}},ks=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 ei("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(mm(o,$o.X_OK),!gm(o).isFile())throw new Error("Not a shell file")}catch(c){throw new ei("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(!gm(r).isDirectory())throw new Error("Not a directory");mm(r,$o.R_OK|$o.X_OK)}catch(c){throw new ei("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 Vo(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 ym=(i,e)=>Number.isInteger(i)&&Number.isInteger(e)&&Number(i)>=2&&Number(i)<=500&&Number(e)>=1&&Number(e)<=300,bm="terminal-input";async function _m(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")&&!ym(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 ei?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 ei?c.reason:l==="create"?"terminal_runtime_unavailable":void 0})}}var qS=/^[a-f0-9-]{36}$/i,vm=32*1024,jS=300,FS=3e4,Sm=i=>i<32||i>=127&&i<=159,Em=i=>{if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid terminal tool input");return i};function Tm(i){if(i!==void 0){if(typeof i!="string"||!qS.test(i))throw new Error("terminalId must be the terminal tab's contentId");return i}}function zo(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 Es(i){let e=Em(i);if(typeof e.text!="string")throw new Error("text must be a string");let t=e.text.replace(/\r\n?/g,`
215
215
  `);if(Buffer.byteLength(t)>4096)throw new Error(`text is longer than ${4096} bytes`);if([...t].some(n=>n!==" "&&n!==`
216
- `&&km(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:Em(e.terminalId),text:t,enter:r,waitMs:zo(e.waitMs,3e3,0,PS,"waitMs"),lines:zo(e.lines,40,1,500,"lines")}}function vm(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):!km(r)&&!/\s/u.test(i[t])&&(e+=i[t])}return e}var CS=i=>{let e=vm(i);return t=>{let r=vm(t);return!!r&&!e.startsWith(r)}};async function wm(i,e,t){let r=await e.text(t),n=r.length>_m;return{terminalId:i,output:n?r.slice(-_m):r,truncated:n,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}}async function Tm(i,e,t,r,n){if(t==="prepare"){let s=Ts(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=Ts(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(NS,s.waitMs,n,CS(s.text)),wm(o,l,s.lines)}if(t==="read"){let s=Sm(r),{id:o,terminal:l}=i.resolve(Em(s.terminalId),e);return wm(o,l,zo(s.lines,100,1,500,"lines"))}throw new Error(`Unknown terminal action: ${t}`)}function Im(){let i=new Ss,e=new Set,t=async()=>{for(let r of e)r.end();e.clear(),await i.clear()};return{metadata:cm,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),agentAction:(r,n,s,o,l)=>Tm(i,n,s,o,l),handle:r=>bm(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 DS}from"node:crypto";import{Type as ft}from"@earendil-works/pi-ai";var xm=ft.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.`}),Am=i=>ft.Optional(ft.Integer({minimum:1,maximum:500,description:`How many trailing lines of the terminal to return (default ${i}).`}));function Om(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 Rm(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:ft.Object({terminalId:ft.Optional(xm),text:ft.String({maxLength:4096,description:"Text to type. Newlines separate lines; no other control characters."}),enter:ft.Optional(ft.Boolean({description:"Press Enter after the text (default true)."})),waitMs:ft.Optional(ft.Integer({minimum:0,maximum:3e4,description:"Longest time to wait for output before returning (default 3000)."})),lines:Am(40)}),async execute(e,t,r,n,s){r?.throwIfAborted();let o=s.sessionManager.getSessionId(),l=Ts(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:DS(),sessionId:o,pluginId:st.terminal,kind:ym,data:c},r);if(!p||typeof p!="object"||p.allow!==!0)throw new Error("The user declined; nothing was typed into the terminal.");return Om(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:ft.Object({terminalId:ft.Optional(xm),lines:Am(100)}),async execute(e,t,r,n,s){return r?.throwIfAborted(),Om(await i.run(s.cwd,s.sessionManager.getSessionId(),"read",t,r))}}]}function Nm(i){let e={run:(...t)=>i.run(st.terminal,...t),ask:i.ask};return Rm(e)}function Pm(){return[lm,Im(),tm]}import{createHash as MS,randomUUID as LS}from"node:crypto";import{mkdir as US,open as qS,readFile as jS,rename as BS,rm as Cm,writeFile as FS}from"node:fs/promises";import{dirname as HS}from"node:path";var De=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},xs=class i{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await jS(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 MS("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}.${LS()}.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 US(HS(this.file),{recursive:!0});try{l=await qS(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 FS(s,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
219
- `,{mode:384}),n(),await BS(s,this.file),this.disabled=a}finally{this.changing=!1;try{await Cm(s,{force:!0})}finally{l&&(await l.close(),await Cm(o,{force:!0}))}}}};var As=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 GS,opendir as WS,stat as VS}from"node:fs/promises";import{homedir as $S}from"node:os";import{basename as zS,dirname as Dm,join as Mm,posix as KS,resolve as Lm,win32 as YS}from"node:path";function Um(i){return process.platform==="win32"?YS.isAbsolute(i)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(i):KS.isAbsolute(i)}function QS(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 qm(i){if(i!==void 0&&!Um(i))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=$S(),t=Lm(i??e),r=[];for(let a=t;;a=Dm(a)){let c=Dm(a);if(r.unshift({name:c===a?a:zS(a),path:a,hidden:!1}),c===a)break}let n=[],s=!1,o=await WS(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||QS(n,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(s=!0);let l=[];for(let a of n){let c=Mm(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await VS(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 jm(i,e){if(!Um(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=Mm(Lm(i),e);return await GS(t),t}import{execFile as JS}from"node:child_process";import{accessSync as XS,constants as ZS}from"node:fs";import{delimiter as eE,join as tE}from"node:path";var iE=(i,e,t)=>new Promise((r,n)=>{JS(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 rE(i){for(let e of(i??"").split(eE))if(e)for(let t of["zenity","kdialog"])try{return XS(tE(e,t),ZS.X_OK),!0}catch{}return!1}function Bm(i=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":i==="darwin"||i==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&rE(e.PATH)?"native":"browse"}function Os(i){if(!(typeof i!="object"||i===null||!("code"in i)))return typeof i.code=="string"||typeof i.code=="number"?i.code:void 0}function nE(i){return typeof i=="object"&&i!==null&&"stderr"in i&&typeof i.stderr=="string"?i.stderr:""}function Ko(i){return i.replace(/[\r\n]+$/,"")||null}async function Fm(i,e=process.platform,t=iE){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 Ko(r.stdout)}catch(r){if(!i.aborted&&Os(r)===1&&/(?:User canceled|-128)/i.test(nE(r)))return null;throw r}if(e==="linux"){try{return Ko((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],i)).stdout)}catch(r){if(i.aborted)throw r;if(Os(r)===1)return null;if(Os(r)!=="ENOENT")throw r}try{return Ko((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],i)).stdout)}catch(r){if(i.aborted)throw r;if(Os(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 sE,randomUUID as aE}from"node:crypto";import{mkdir as oE,readFile as lE,writeFile as cE}from"node:fs/promises";import{join as Hm}from"node:path";import{getAgentDir as pE}from"@earendil-works/pi-coding-agent";var Rs=20*1024*1024,Gm=20,dE=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function uE(i){let e=i.indexOf("."),t=(e<0?i:i.slice(0,e)).replace(/[. ]+$/u,"");return dE.test(t)}function mE(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 gE(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 uE(t)&&(t=`_${t}`),t=mE(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function fE(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 Wm(i,e,t,r){if(r.byteLength===0||r.byteLength>Rs)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let n=gE(e),s=sE("sha256").update(r).digest("hex"),o=Hm(pE(),"pi-web","attachments",s);await oE(o,{recursive:!0});let l=Hm(o,n);try{await cE(l,r,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:aE(),name:n,bytes:r.byteLength,path:l,mediaType:fE(r)??t.replace(/^image\//,"application/"),sessionId:i}}async function Vm(i){return{type:"image",data:(await lE(i.path)).toString("base64"),mimeType:i.mediaType}}import{randomBytes as hE}from"node:crypto";function $m(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 Ns=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=hE(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,...f}=c;a.answer=p,a.reject=d,a.view={...a.view,status:"waiting",prompt:f},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}
216
+ `&&Sm(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:Tm(e.terminalId),text:t,enter:r,waitMs:zo(e.waitMs,3e3,0,FS,"waitMs"),lines:zo(e.lines,40,1,500,"lines")}}function wm(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):!Sm(r)&&!/\s/u.test(i[t])&&(e+=i[t])}return e}var BS=i=>{let e=wm(i);return t=>{let r=wm(t);return!!r&&!e.startsWith(r)}};async function km(i,e,t){let r=await e.text(t),n=r.length>vm;return{terminalId:i,output:n?r.slice(-vm):r,truncated:n,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}}async function Im(i,e,t,r,n){if(t==="prepare"){let s=Es(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=Es(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(jS,s.waitMs,n,BS(s.text)),km(o,l,s.lines)}if(t==="read"){let s=Em(r),{id:o,terminal:l}=i.resolve(Tm(s.terminalId),e);return km(o,l,zo(s.lines,100,1,500,"lines"))}throw new Error(`Unknown terminal action: ${t}`)}function xm(){let i=new ks,e=new Set,t=async()=>{for(let r of e)r.end();e.clear(),await i.clear()};return{metadata:pm,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),agentAction:(r,n,s,o,l)=>Im(i,n,s,o,l),handle:r=>_m(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 HS}from"node:crypto";import{Type as ft}from"@earendil-works/pi-ai";var Am=ft.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.`}),Om=i=>ft.Optional(ft.Integer({minimum:1,maximum:500,description:`How many trailing lines of the terminal to return (default ${i}).`}));function Rm(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 Nm(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:ft.Object({terminalId:ft.Optional(Am),text:ft.String({maxLength:4096,description:"Text to type. Newlines separate lines; no other control characters."}),enter:ft.Optional(ft.Boolean({description:"Press Enter after the text (default true)."})),waitMs:ft.Optional(ft.Integer({minimum:0,maximum:3e4,description:"Longest time to wait for output before returning (default 3000)."})),lines:Om(40)}),async execute(e,t,r,n,s){r?.throwIfAborted();let o=s.sessionManager.getSessionId(),l=Es(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:HS(),sessionId:o,pluginId:st.terminal,kind:bm,data:c},r);if(!p||typeof p!="object"||p.allow!==!0)throw new Error("The user declined; nothing was typed into the terminal.");return Rm(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:ft.Object({terminalId:ft.Optional(Am),lines:Om(100)}),async execute(e,t,r,n,s){return r?.throwIfAborted(),Rm(await i.run(s.cwd,s.sessionManager.getSessionId(),"read",t,r))}}]}function Pm(i){let e={run:(...t)=>i.run(st.terminal,...t),ask:i.ask};return Nm(e)}function Cm(){return[cm,xm(),im]}import{createHash as GS,randomUUID as WS}from"node:crypto";import{mkdir as $S,open as VS,readFile as zS,rename as KS,rm as Dm,writeFile as YS}from"node:fs/promises";import{dirname as QS}from"node:path";var De=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},Is=class i{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await zS(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 GS("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}.${WS()}.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 $S(QS(this.file),{recursive:!0});try{l=await VS(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 YS(s,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
219
+ `,{mode:384}),n(),await KS(s,this.file),this.disabled=a}finally{this.changing=!1;try{await Dm(s,{force:!0})}finally{l&&(await l.close(),await Dm(o,{force:!0}))}}}};var xs=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 JS,opendir as XS,stat as ZS}from"node:fs/promises";import{homedir as eE}from"node:os";import{basename as tE,dirname as Mm,join as Lm,posix as iE,resolve as Um,win32 as rE}from"node:path";function qm(i){return process.platform==="win32"?rE.isAbsolute(i)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(i):iE.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 jm(i){if(i!==void 0&&!qm(i))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=eE(),t=Um(i??e),r=[];for(let a=t;;a=Mm(a)){let c=Mm(a);if(r.unshift({name:c===a?a:tE(a),path:a,hidden:!1}),c===a)break}let n=[],s=!1,o=await XS(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=Lm(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await ZS(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 Fm(i,e){if(!qm(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=Lm(Um(i),e);return await JS(t),t}import{execFile as sE}from"node:child_process";import{accessSync as aE,constants as oE}from"node:fs";import{delimiter as lE,join as cE}from"node:path";var pE=(i,e,t)=>new Promise((r,n)=>{sE(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 dE(i){for(let e of(i??"").split(lE))if(e)for(let t of["zenity","kdialog"])try{return aE(cE(e,t),oE.X_OK),!0}catch{}return!1}function Bm(i=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":i==="darwin"||i==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&dE(e.PATH)?"native":"browse"}function As(i){if(!(typeof i!="object"||i===null||!("code"in i)))return typeof i.code=="string"||typeof i.code=="number"?i.code:void 0}function uE(i){return typeof i=="object"&&i!==null&&"stderr"in i&&typeof i.stderr=="string"?i.stderr:""}function Ko(i){return i.replace(/[\r\n]+$/,"")||null}async function Hm(i,e=process.platform,t=pE){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 Ko(r.stdout)}catch(r){if(!i.aborted&&As(r)===1&&/(?:User canceled|-128)/i.test(uE(r)))return null;throw r}if(e==="linux"){try{return Ko((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],i)).stdout)}catch(r){if(i.aborted)throw r;if(As(r)===1)return null;if(As(r)!=="ENOENT")throw r}try{return Ko((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],i)).stdout)}catch(r){if(i.aborted)throw r;if(As(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 mE,randomUUID as gE}from"node:crypto";import{mkdir as fE,readFile as hE,writeFile as yE}from"node:fs/promises";import{join as Gm}from"node:path";import{getAgentDir as bE}from"@earendil-works/pi-coding-agent";var Os=20*1024*1024,Wm=20,_E=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function vE(i){let e=i.indexOf("."),t=(e<0?i:i.slice(0,e)).replace(/[. ]+$/u,"");return _E.test(t)}function wE(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 vE(t)&&(t=`_${t}`),t=wE(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function SE(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 $m(i,e,t,r){if(r.byteLength===0||r.byteLength>Os)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let n=kE(e),s=mE("sha256").update(r).digest("hex"),o=Gm(bE(),"pi-web","attachments",s);await fE(o,{recursive:!0});let l=Gm(o,n);try{await yE(l,r,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:gE(),name:n,bytes:r.byteLength,path:l,mediaType:SE(r)??t.replace(/^image\//,"application/"),sessionId:i}}async function Vm(i){return{type:"image",data:(await hE(i.path)).toString("base64"),mimeType:i.mediaType}}import{randomBytes as EE}from"node:crypto";function zm(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 Rs=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=EE(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,...f}=c;a.answer=p,a.reject=d,a.view={...a.view,status:"waiting",prompt:f},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}
220
220
  ${c.stack.split(`
221
221
  `).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 yE}from"node:crypto";import{readFile as bE,rename as _E,rm as vE,stat as wE,writeFile as kE,mkdir as SE}from"node:fs/promises";import{dirname as EE}from"node:path";var TE=["openai-completions","openai-responses","anthropic-messages"];function Yo(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||!TE.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 zm(i,e){if(!Yo(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 bE(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 SE(EE(i),{recursive:!0});let s=t===void 0?384:(await wE(i)).mode&511,o=`${i}.pi-web-${yE(6).toString("hex")}.tmp`;try{await kE(o,`${JSON.stringify(n,null,2)}
223
- `,{mode:s,flag:"wx"}),await _E(o,i)}finally{await vE(o,{force:!0})}}import{randomBytes as IE}from"node:crypto";import{mkdir as xE,readFile as AE,rename as OE,rm as RE,stat as NE,writeFile as PE}from"node:fs/promises";import{dirname as CE}from"node:path";function Km(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 Ym(i){if(!i||typeof i!="object")return!1;let e=i;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&Qm(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&Km(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function Qm(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 Jm(i){let e;try{e=await AE(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 DE(i,e,t){await xE(CE(i),{recursive:!0});let r=t===void 0?384:(await NE(i)).mode&511,n=`${i}.pi-web-${IE(6).toString("hex")}.tmp`;try{await PE(n,`${JSON.stringify(e,null,2)}
224
- `,{mode:r,flag:"wx"}),await OE(n,i)}finally{await RE(n,{force:!0})}}async function Xm(i,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Jm(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 Zm(i,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await Jm(i),o={...n.providers[e]??{}},l=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!Km(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(!Qm(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(f=>f.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let g={...l[d],...c};for(let f of["name","contextWindow","maxTokens","input"])c[f]===void 0&&delete g[f];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,...f}=c;a[p]={...a[p],...f};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 DE(i,n,s)}function eg(i){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(i.trim())}import{randomBytes as ew,createHash as eO}from"node:crypto";import{fileURLToPath as tO}from"node:url";var ln="pi-webapp@0.1.54+4b824f27b8e4c8fa14f3",It="4b824f27b8e4c8fa14f3";var iO="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function Ga(i=process.env,e=console.warn){let t=r=>{let n={enabled:!1,environment:i.PI_WEB_SENTRY_ENVIRONMENT||"production",release:ln,buildId:It},s=i[`PI_WEB_SENTRY_${r}_DSN`]??i.PI_WEB_SENTRY_DSN??iO;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 zt=class{config;ready;reporter;client;salt=ew(16);breadcrumbs=new on;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=Ga(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=tO(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(()=>(Zv(),Xv)).then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:It,integrations:[],transport:e.transport??(r=>em(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:Zu,sendClientReports:!1,dataCollection:{...Qu,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new ws(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||Fi(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=ew(16).toString("hex");return this.early.push({error:gr(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 eO("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 fO}from"@earendil-works/pi-coding-agent";function Oi(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 sO}from"node:crypto";var tw="[pi-web workspace tab in view] ",iw=' \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 rO(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 nO(i){let e=i.endsWith(iw)?i.slice(0,-iw.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 rO(t)}catch{return null}}function zn(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(tw);if(r!==-1&&(r===0||t.slice(r-2,r)===`
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 TE}from"node:crypto";import{readFile as IE,rename as xE,rm as AE,stat as OE,writeFile as RE,mkdir as NE}from"node:fs/promises";import{dirname as PE}from"node:path";var CE=["openai-completions","openai-responses","anthropic-messages"];function Yo(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||!CE.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 Km(i,e){if(!Yo(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 IE(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 NE(PE(i),{recursive:!0});let s=t===void 0?384:(await OE(i)).mode&511,o=`${i}.pi-web-${TE(6).toString("hex")}.tmp`;try{await RE(o,`${JSON.stringify(n,null,2)}
223
+ `,{mode:s,flag:"wx"}),await xE(o,i)}finally{await AE(o,{force:!0})}}import{randomBytes as DE}from"node:crypto";import{mkdir as ME,readFile as LE,rename as UE,rm as qE,stat as jE,writeFile as FE}from"node:fs/promises";import{dirname as BE}from"node:path";function Ym(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 Qm(i){if(!i||typeof i!="object")return!1;let e=i;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&Jm(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&Ym(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function Jm(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 Xm(i){let e;try{e=await LE(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 HE(i,e,t){await ME(BE(i),{recursive:!0});let r=t===void 0?384:(await jE(i)).mode&511,n=`${i}.pi-web-${DE(6).toString("hex")}.tmp`;try{await FE(n,`${JSON.stringify(e,null,2)}
224
+ `,{mode:r,flag:"wx"}),await UE(n,i)}finally{await qE(n,{force:!0})}}async function Zm(i,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Xm(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 eg(i,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await Xm(i),o={...n.providers[e]??{}},l=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!Ym(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(!Jm(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(f=>f.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let g={...l[d],...c};for(let f of["name","contextWindow","maxTokens","input"])c[f]===void 0&&delete g[f];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,...f}=c;a[p]={...a[p],...f};for(let _ of["name","contextWindow","maxTokens","input"])c[_]===void 0&&delete a[p][_]}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 HE(i,n,s)}function tg(i){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(i.trim())}import{randomBytes as tw,createHash as lO}from"node:crypto";import{fileURLToPath as cO}from"node:url";var ln="pi-webapp@0.1.55-alpha.1+bcba00f6aa60f5a0f2eb",It="bcba00f6aa60f5a0f2eb";var pO="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function Ha(i=process.env,e=console.warn){let t=r=>{let n={enabled:!1,environment:i.PI_WEB_SENTRY_ENVIRONMENT||"production",release:ln,buildId:It},s=i[`PI_WEB_SENTRY_${r}_DSN`]??i.PI_WEB_SENTRY_DSN??pO;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 zt=class{config;ready;reporter;client;salt=tw(16);breadcrumbs=new on;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=Ha(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=cO(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(()=>(ew(),Zv)).then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:It,integrations:[],transport:e.transport??(r=>tm(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:em,sendClientReports:!1,dataCollection:{...Ju,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new vs(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||Bi(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=tw(16).toString("hex");return this.early.push({error:gr(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 lO("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 EO}from"@earendil-works/pi-coding-agent";function Oi(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 mO}from"node:crypto";var iw="[pi-web workspace tab in view] ",rw=' \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 dO(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 uO(i){let e=i.endsWith(rw)?i.slice(0,-rw.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 dO(t)}catch{return null}}function zn(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(iw);if(r!==-1&&(r===0||t.slice(r-2,r)===`
225
225
 
226
226
  `)&&!t.slice(r).includes(`
227
- `)){let n=nO(t.slice(r+tw.length));if(n)return{text:t.slice(0,Math.max(0,r-2)),attachments:e,context:n}}return{text:t,attachments:e}}var Kn=i=>Buffer.byteLength(i.text)+i.images.reduce((e,t)=>e+t.data.length,0),et=class extends Error{status=409},Ri=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,...zn(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+Kn(s),Kn({text:e,images:t}))>64*1024*1024)throw new et("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:sO(),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 et("\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 et("\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 et("\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=zn(s.text),l=s.text.slice(o.text.length).replace(/^\n\n/u,""),a=[r.text.trim(),l].filter(Boolean).join(`
227
+ `)){let n=uO(t.slice(r+iw.length));if(n)return{text:t.slice(0,Math.max(0,r-2)),attachments:e,context:n}}return{text:t,attachments:e}}var Kn=i=>Buffer.byteLength(i.text)+i.images.reduce((e,t)=>e+t.data.length,0),et=class extends Error{status=409},Ri=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,...zn(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+Kn(s),Kn({text:e,images:t}))>64*1024*1024)throw new et("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:mO(),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 et("\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 et("\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 et("\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=zn(s.text),l=s.text.slice(o.text.length).replace(/^\n\n/u,""),a=[r.text.trim(),l].filter(Boolean).join(`
228
228
 
229
- `);if(this.validateText(a),this.entries.reduce((c,p)=>c+Kn(p),0)-Kn(s)+Kn({text:a,images:s.images})>64*1024*1024)throw new et("\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 b=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 Ni=i=>i.code==="ENOENT";var rw=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function Jp(i,e,t,r){if(!i)throw new b("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 b("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 b("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 b("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:Wa(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new b("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 b("invalid_input","Invalid approval decision",{status:400});if(!i.decide)throw new b("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 b("host_restarting","Host is updating; secret changes are fenced",{status:409});if(n.auth!==void 0){if(!i.secretAuth)throw new b("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 b("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 b("invalid_input","Invalid secret request",{status:400});if(!i.secret)throw new b("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 b("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new b("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 b("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 b("invalid_input","Exact download identity required",{status:400});if(n.reopenEditors!==void 0&&typeof n.reopenEditors!="boolean")throw new b("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 b("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 b("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 b("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 b("invalid_route","Unknown hosted plugin route",{status:404})}function Wa(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 nw}from"node:fs/promises";import{join as sw}from"node:path";async function aw(i){try{let e=JSON.parse(await nw(sw(i,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await nw(sw(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 oO,readFile as cw,realpath as za,rename as lW,rm as cW,writeFile as pW}from"node:fs/promises";import{dirname as $a,join as di,resolve as lO,sep as lw}from"node:path";import{createRequire as cO}from"node:module";var aO=/^(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"&&aO.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 ct(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 ow(i){try{return Kt(i).prerelease.length===0}catch{return!1}}function Va(i){try{return Kt(i),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(i)}catch{return!1}}var Pi=1;async function jr(i,e){let t=cO(di(i,"package.json"));for(let r of t.resolve.paths(e)??[]){let n=di(r,e);try{if(JSON.parse(await cw(di(n,"package.json"),"utf8")).name===e)return await za(n)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function Xp(i,e){if(ct(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 za(lO($a(e.launcher),"..")),r=await za(di(i,"pi-web","releases")),n=$a($a(t));if(await za(e.launcher)!==di(t,"bin","pi-webapp.mjs")||$a(n)!==r||!n.startsWith(r+lw)||!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 cw(di(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 jr(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(n+lw))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let l=di(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,l,di(t,"dist","extension.js"),di(t,"web","dist","index.html")].map(a=>oO(a))),e.fallbackVersion!==void 0&&Kt(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:l,desktopProtocolVersion:Pi,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var hO={"/":{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 yO(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&&pO(r,e)}async function dw(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 bO(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>Rs)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(n)}return Buffer.concat(t)}async function _O(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 uw(i,e,t=new zt,r={}){t.setState({piVersion:fO});let n=process.env.PI_WEBAPP_RESTART_TOKEN,s=n&&/^[A-Za-z0-9_-]{32}$/.test(n)?n:pw(24).toString("base64url"),o=Buffer.from(s),l=Bm(),a=new Set,c=new xs(r.pluginSettingsFile??ed(gO(),"pi-web","plugins.json"));try{await c.load()}catch(w){throw await t.close(),w}let p=new As(Pm(),c),d=async()=>await i.plugins?.()??{plugins:[],errors:[]},g=()=>({type:"plugin_state",disabled:p.plugins.filter(w=>!c.enabled(w.metadata.id)).map(w=>w.metadata.id)}),f=()=>{for(let w of a)w.write(`${JSON.stringify(g())}
230
- `)},v=new Map,y=new Ns((w,h)=>t.capture(w,h)),S=w=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(w.sessionId),idle:w.idle,model:w.model,thinkingLevel:w.thinkingLevel,messageCount:w.messages.length}),T="",A=!1,x=!1,C={...hO,...await aw(e)};for(let w of await uO(ed(e,"assets")).catch(()=>[])){let h=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(w);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"};C[`/assets/${w}`]={path:`assets/${w}`,type:M[h[1]]}}let q=mO(async(w,h)=>{let M=pw(18).toString("base64"),Z=be=>typeof be=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(be),re=Z(w.headers["x-request-id"])?w.headers["x-request-id"]:Zp(),ae={requestId:re,operationId:Z(w.headers["x-operation-id"])?w.headers["x-operation-id"]:void 0};h.setHeader("X-Request-ID",re),ae.operationId&&h.setHeader("X-Operation-ID",ae.operationId);let P="/",Se=performance.now(),me=(be,_,D)=>{let ie=!Fi(be)&&Ju(P)?Zt(be,"Agent or provider operation failed"):be,ue=t.capture(ie,{...ae,route:P,method:w.method,status:_,stage:"http"});O(h,_,{error:D,errorId:ue,errorReported:t.enabled,errorCode:Fi(be)?"validation_error":"unexpected_error"})};h.once("finish",()=>{P.startsWith("/api/telemetry/")||t.breadcrumb("request",{...ae,route:P,method:w.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{P=new URL(w.url??"/",T).pathname}catch{O(h,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let be=C[P];if(w.method==="GET"&&be){try{let _=await dO(ed(e,be.path));h.writeHead(200,{"Content-Type":be.type,"Cache-Control":"no-store"}),h.end(P==="/"?_.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${M}">`):_)}catch(_){me(_,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P.startsWith("/hosted-plugins/")){try{let _=await i.hosted?.asset(P);if(!_){O(h,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}h.setHeader("Content-Security-Policy","default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),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(w.method==="GET"&&P.startsWith("/plugins/")){try{let _=await i.pluginAsset?.(w.url??P);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(!P.startsWith("/api/")){O(h,404,{error:"\u672A\u627E\u5230"});return}if(!yO(w,o)){O(h,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(w.method==="GET"&&P==="/api/hosted-plugins"){try{O(h,200,await Jp(i.hosted,P,void 0))}catch(_){let D=Wa(_);O(h,D.status,D.body)}return}if(w.method==="POST"&&rw.includes(P)){if(w.headers.origin!==void 0&&w.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!w.headers["content-type"]?.startsWith("application/json")){O(h,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let _;try{_=await dw(w,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 Jp(i.hosted,P,_,{draining:A}))}catch(D){let V=Wa(D);O(h,V.status,V.body)}return}if(w.method==="GET"&&P==="/api/telemetry/config"){O(h,200,t.config.browser);return}if(w.method==="GET"&&P==="/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(w.method==="GET"&&P==="/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(w.method==="GET"&&P==="/api/image"){let _=new URL(w.url??P,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(w.method==="POST"&&P==="/api/attachment"){if(w.headers.origin!==void 0&&w.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let _=new URL(w.url??P,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(w.headers["content-length"]??0)>Rs){O(h,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let ie=await Wm(D,V,w.headers["content-type"]??"application/octet-stream",await bO(w));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(w.method==="GET"&&P==="/api/session"){try{let _=i.snapshot();S(_),O(h,200,_)}catch(_){me(_,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/plugin-management"){try{O(h,200,p.inventory(await d()))}catch(_){me(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/plugins"){try{O(h,200,p.catalog(await d()))}catch(_){me(_,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/providers"){try{O(h,200,await i.providers?.()??[])}catch(_){me(_,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/provider/models"){let _=new URL(w.url??P,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(w.method==="GET"&&P==="/api/provider/login/active"){O(h,200,{active:y.getActive()??null});return}if(w.method==="GET"&&P==="/api/provider/login"){let _=new URL(w.url??P,T).searchParams.get("id")??"",D=y.get(_);O(h,D?200:404,D??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(w.method==="GET"&&(P==="/api/models"||P==="/api/config"||P==="/api/workspaces"||P==="/api/commands")){try{O(h,200,P==="/api/models"?await i.models():P==="/api/config"?await i.config():P==="/api/commands"?i.commands?.()??[]:await i.workspaces())}catch(_){me(_,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/directory/capability"){O(h,200,{kind:l});return}if(w.method==="GET"&&P==="/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(w.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(P)){if(w.headers.origin!==void 0&&w.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!w.headers["content-type"]?.startsWith("application/json")){O(h,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let _;try{_=await dw(w,P==="/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||Fi(D)){O(h,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw D}if(P==="/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(A||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}A=!0;try{await i.selfUpdate.requestLauncherHandoff(D.nonce,D.requestId)}catch(ie){throw A=!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(A&&P!=="/api/update/cancel"){O(h,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(P==="/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{f()}return}if(p.mutating&&P!=="/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:P,body:_,res:h,snapshot:()=>i.snapshot(),busyWorkspaces:()=>i.busyGitWorkspaces?.()??[],json:(D,V)=>O(h,D,V)}))return;if(P==="/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(P==="/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,Ut)=>O(h,je,je>=200&&je<300?{value:Ut}:Ut)});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(P==="/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(P==="/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(P==="/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"}),Ut=p.restartConfirmations();if(Ut.length&&!ue){je(Ut);return}x=!0;let mi;try{mi=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(),A=!0;try{await i.selfUpdate.requestRestart(mi,{force:ue})}catch(ms){let tn=ms?.code;if(!ue&&(tn==="view_barrier"||tn==="drain_pending")){A=!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 ms}}catch(ge){throw A=!1,ge}finally{x=!1}O(h,202,{accepted:!0,version:mi.version});return}if(P==="/api/provider/custom"){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in _)||!Yo(_.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(P==="/api/provider/models"||P==="/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(P==="/api/provider/models"){if(!("change"in _)||!Ym(_.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(P.startsWith("/api/provider/login")){if(_.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(P==="/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(P==="/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(P==="/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(P==="/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 Fm(D.signal)});return}if(P==="/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 qm("path"in _?_.path:void 0));return}if(P==="/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 jm(_.path,_.name)});return}if(P==="/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(P==="/api/workspace/select"||P==="/api/workspace/remove"||P==="/api/workspace/new-session"){if(!("id"in _)||typeof _.id!="string"){O(h,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}P==="/api/workspace/select"?await i.selectWorkspace(_.id):P==="/api/workspace/new-session"?await i.newSessionInWorkspace(_.id):await i.removeWorkspace(_.id),O(h,202,{accepted:!0});return}if(P==="/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(P==="/api/session/rename"||P==="/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(P==="/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(P==="/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(P==="/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(P==="/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"&&eg(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(P==="/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(P==="/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>Gm||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{Oi(ue,_.text,D)}catch(ge){O(h,409,{error:ge.message});return}let je=ie,Ut=[_.text.trim(),...je.map(ge=>`\u9644\u4EF6 ${JSON.stringify(ge.name)}\uFF1A${ge.path}`)].filter(Boolean).join(`
229
+ `);if(this.validateText(a),this.entries.reduce((c,p)=>c+Kn(p),0)-Kn(s)+Kn({text:a,images:s.images})>64*1024*1024)throw new et("\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 b=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 Ni=i=>i.code==="ENOENT";var nw=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function Jp(i,e,t,r){if(!i)throw new b("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 b("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 b("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 b("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:Ga(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new b("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 b("invalid_input","Invalid approval decision",{status:400});if(!i.decide)throw new b("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 b("host_restarting","Host is updating; secret changes are fenced",{status:409});if(n.auth!==void 0){if(!i.secretAuth)throw new b("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 b("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 b("invalid_input","Invalid secret request",{status:400});if(!i.secret)throw new b("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 b("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new b("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 b("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 b("invalid_input","Exact download identity required",{status:400});if(n.reopenEditors!==void 0&&typeof n.reopenEditors!="boolean")throw new b("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 b("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 b("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 b("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 b("invalid_route","Unknown hosted plugin route",{status:404})}function Ga(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 sw}from"node:fs/promises";import{join as aw}from"node:path";async function ow(i){try{let e=JSON.parse(await sw(aw(i,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await sw(aw(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 fO,readFile as pw,realpath as Va,rename as _W,rm as vW,writeFile as wW}from"node:fs/promises";import{dirname as $a,join as di,resolve as hO,sep as cw}from"node:path";import{createRequire as yO}from"node:module";var gO=/^(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"&&gO.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 ct(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 lw(i){try{return Kt(i).prerelease.length===0}catch{return!1}}function Wa(i){try{return Kt(i),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(i)}catch{return!1}}var Pi=1;async function jr(i,e){let t=yO(di(i,"package.json"));for(let r of t.resolve.paths(e)??[]){let n=di(r,e);try{if(JSON.parse(await pw(di(n,"package.json"),"utf8")).name===e)return await Va(n)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function Xp(i,e){if(ct(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 Va(hO($a(e.launcher),"..")),r=await Va(di(i,"pi-web","releases")),n=$a($a(t));if(await Va(e.launcher)!==di(t,"bin","pi-webapp.mjs")||$a(n)!==r||!n.startsWith(r+cw)||!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 pw(di(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 jr(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(n+cw))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let l=di(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,l,di(t,"dist","extension.js"),di(t,"web","dist","index.html")].map(a=>fO(a))),e.fallbackVersion!==void 0&&Kt(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:l,desktopProtocolVersion:Pi,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var za="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'",bO="browser.wasm";function dw(i={}){return i.wasm?za.replace("script-src 'self'","script-src 'self' 'wasm-unsafe-eval'"):za}function uw(i){let e=i;return!!e&&e.browser?.wasm===!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(bO)}var TO={"/":{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 IO(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&&_O(r,e)}async function gw(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 xO(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>Os)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(n)}return Buffer.concat(t)}async function AO(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 fw(i,e,t=new zt,r={}){t.setState({piVersion:EO});let n=process.env.PI_WEBAPP_RESTART_TOKEN,s=n&&/^[A-Za-z0-9_-]{32}$/.test(n)?n:mw(24).toString("base64url"),o=Buffer.from(s),l=Bm(),a=new Set,c=new Is(r.pluginSettingsFile??ed(SO(),"pi-web","plugins.json"));try{await c.load()}catch(w){throw await t.close(),w}let p=new xs(Cm(),c),d=async()=>await i.plugins?.()??{plugins:[],errors:[]},g=()=>({type:"plugin_state",disabled:p.plugins.filter(w=>!c.enabled(w.metadata.id)).map(w=>w.metadata.id)}),f=()=>{for(let w of a)w.write(`${JSON.stringify(g())}
230
+ `)},_=new Map,y=new Rs((w,h)=>t.capture(w,h)),S=w=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(w.sessionId),idle:w.idle,model:w.model,thinkingLevel:w.thinkingLevel,messageCount:w.messages.length}),T="",A=!1,I=!1,C={...TO,...await ow(e)};for(let w of await wO(ed(e,"assets")).catch(()=>[])){let h=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(w);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"};C[`/assets/${w}`]={path:`assets/${w}`,type:M[h[1]]}}let q=kO(async(w,h)=>{let M=mw(18).toString("base64"),Z=be=>typeof be=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(be),re=Z(w.headers["x-request-id"])?w.headers["x-request-id"]:Zp(),ae={requestId:re,operationId:Z(w.headers["x-operation-id"])?w.headers["x-operation-id"]:void 0};h.setHeader("X-Request-ID",re),ae.operationId&&h.setHeader("X-Operation-ID",ae.operationId);let P="/",Se=performance.now(),me=(be,v,D)=>{let ie=!Bi(be)&&Xu(P)?Zt(be,"Agent or provider operation failed"):be,ue=t.capture(ie,{...ae,route:P,method:w.method,status:v,stage:"http"});O(h,v,{error:D,errorId:ue,errorReported:t.enabled,errorCode:Bi(be)?"validation_error":"unexpected_error"})};h.once("finish",()=>{P.startsWith("/api/telemetry/")||t.breadcrumb("request",{...ae,route:P,method:w.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{P=new URL(w.url??"/",T).pathname}catch{O(h,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let be=C[P];if(w.method==="GET"&&be){try{let v=await vO(ed(e,be.path));h.writeHead(200,{"Content-Type":be.type,"Cache-Control":"no-store"}),h.end(P==="/"?v.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${M}">`):v)}catch(v){me(v,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P.startsWith("/hosted-plugins/")){try{let v=await i.hosted?.asset(P);if(!v){O(h,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}h.setHeader("Content-Security-Policy",v.csp??za),h.writeHead(200,{"Content-Type":v.mime,"Cache-Control":"private, no-store"}),h.end(v.bytes)}catch{O(h,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(w.method==="GET"&&P.startsWith("/plugins/")){try{let v=await i.pluginAsset?.(w.url??P);if(!v){O(h,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}h.writeHead(200,{"Content-Type":v.type,"Cache-Control":"no-store"}),h.end(v.bytes)}catch(v){me(v,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!P.startsWith("/api/")){O(h,404,{error:"\u672A\u627E\u5230"});return}if(!IO(w,o)){O(h,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(w.method==="GET"&&P==="/api/hosted-plugins"){try{O(h,200,await Jp(i.hosted,P,void 0))}catch(v){let D=Ga(v);O(h,D.status,D.body)}return}if(w.method==="POST"&&nw.includes(P)){if(w.headers.origin!==void 0&&w.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!w.headers["content-type"]?.startsWith("application/json")){O(h,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let v;try{v=await gw(w,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 Jp(i.hosted,P,v,{draining:A}))}catch(D){let $=Ga(D);O(h,$.status,$.body)}return}if(w.method==="GET"&&P==="/api/telemetry/config"){O(h,200,t.config.browser);return}if(w.method==="GET"&&P==="/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(v){me(v,503,v instanceof Error?v.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(w.method==="GET"&&P==="/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(v){me(v,503,v instanceof Error?v.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(w.method==="GET"&&P==="/api/image"){let v=new URL(w.url??P,T),D=v.searchParams.get("sessionId")??"",$=v.searchParams.get("messageId")??"",ie=Number(v.searchParams.get("index"));if(!D||D!==i.snapshot().sessionId||!$||!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,$,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(w.method==="POST"&&P==="/api/attachment"){if(w.headers.origin!==void 0&&w.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let v=new URL(w.url??P,T),D=v.searchParams.get("sessionId"),$=v.searchParams.get("name");try{if(!D||!$||$.length>1024||D!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(w.headers["content-length"]??0)>Os){O(h,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let ie=await $m(D,$,w.headers["content-type"]??"application/octet-stream",await xO(w));if(D!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}_.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(w.method==="GET"&&P==="/api/session"){try{let v=i.snapshot();S(v),O(h,200,v)}catch(v){me(v,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/plugin-management"){try{O(h,200,p.inventory(await d()))}catch(v){me(v,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/plugins"){try{O(h,200,p.catalog(await d()))}catch(v){me(v,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/providers"){try{O(h,200,await i.providers?.()??[])}catch(v){me(v,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/provider/models"){let v=new URL(w.url??P,T).searchParams.get("providerId")??"";try{if(!v||!i.providerModels){O(h,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}O(h,200,await i.providerModels(v))}catch(D){me(D,400,D instanceof Error?D.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/provider/login/active"){O(h,200,{active:y.getActive()??null});return}if(w.method==="GET"&&P==="/api/provider/login"){let v=new URL(w.url??P,T).searchParams.get("id")??"",D=y.get(v);O(h,D?200:404,D??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(w.method==="GET"&&(P==="/api/models"||P==="/api/config"||P==="/api/workspaces"||P==="/api/commands")){try{O(h,200,P==="/api/models"?await i.models():P==="/api/config"?await i.config():P==="/api/commands"?i.commands?.()??[]:await i.workspaces())}catch(v){me(v,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(w.method==="GET"&&P==="/api/directory/capability"){O(h,200,{kind:l});return}if(w.method==="GET"&&P==="/api/events"){let v;try{v=i.snapshot(),S(v)}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:v})}
231
+ `),h.on("close",()=>a.delete(h));return}if(w.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(P)){if(w.headers.origin!==void 0&&w.headers.origin!==T){O(h,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!w.headers["content-type"]?.startsWith("application/json")){O(h,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let v;try{v=await gw(w,P==="/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||Bi(D)){O(h,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw D}if(P==="/api/desktop/handoff"){let D=v;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(A||I||y.getActive()){O(h,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let $=p.restartBlocker()??p.restartConfirmations()[0];if(!i.snapshot().idle||(i.busyGitWorkspaces?.()??[]).length||$){O(h,409,{error:$??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}A=!0;try{await i.selfUpdate.requestLauncherHandoff(D.nonce,D.requestId)}catch(ie){throw A=!1,ie}O(h,202,{accepted:!0,protocol:1,requestId:D.requestId});return}if(typeof v!="object"||v===null||!("sessionId"in v)||typeof v.sessionId!="string"){O(h,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(A&&P!=="/api/update/cancel"){O(h,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(P==="/api/plugin-management"){let D=v;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 $=()=>{if(i.snapshot().sessionId!==v.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,$),O(h,200,p.inventory(await d()))}catch(ie){if(ie instanceof De)O(h,ie.status,{error:ie.message});else throw ie}finally{f()}return}if(p.mutating&&P!=="/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:P,body:v,res:h,snapshot:()=>i.snapshot(),busyWorkspaces:()=>i.busyGitWorkspaces?.()??[],json:(D,$)=>O(h,D,$)}))return;if(P==="/api/plugin-interaction"){if(v.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in v)||typeof v.pluginId!="string"||v.pluginId.length>200||!("requestId"in v)||typeof v.requestId!="string"||v.requestId.length>200||!i.resolvePluginInteraction||!("value"in v)){O(h,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(i.snapshot().cwd,async()=>i.resolvePluginInteraction(v.sessionId,v.pluginId,v.requestId,v.value)),O(h,200,{accepted:!0});return}if(P==="/api/plugin-action"){if(v.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in v)||typeof v.pluginId!="string"||v.pluginId.length>200||!("action"in v)||typeof v.action!="string"||v.action.length>100){O(h,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(ie=>ie.metadata.id===v.pluginId)){let ie=p.actionRoute(v.pluginId,v.action);if(!ie){O(h,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let ue="input"in v?v.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:v.sessionId},res:h,snapshot:()=>i.snapshot(),busyWorkspaces:()=>i.busyGitWorkspaces?.()??[],json:(je,Ut)=>O(h,je,je>=200&&je<300?{value:Ut}:Ut)});return}if(!i.invokePluginAction){O(h,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let $=await p.coordinateStart(i.snapshot().cwd,async()=>i.invokePluginAction(v.sessionId,v.pluginId,v.action,"input"in v?v.input:void 0));O(h,200,{value:$});return}if(P==="/api/update/channel"){if(v.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in v)||v.channel!=="stable"&&v.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(v.channel));return}if(P==="/api/update/cancel"){if(v.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(P==="/api/update"){if(I){O(h,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(v.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 $||"version"in $||"allowDowngrade"in $;if(ie&&($.channel!=="stable"&&$.channel!=="alpha"||typeof $.version!="string"||$.allowDowngrade!==void 0&&typeof $.allowDowngrade!="boolean")){O(h,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if($.force!==void 0&&typeof $.force!="boolean"){O(h,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let ue=$.force===!0,je=ge=>O(h,409,{error:ge.join("\uFF1B"),reason:"update_confirm_required"}),Ut=p.restartConfirmations();if(Ut.length&&!ue){je(Ut);return}I=!0;let mi;try{mi=await i.selfUpdate.prepare(ie?{channel:$.channel,version:$.version,allowDowngrade:$.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(),A=!0;try{await i.selfUpdate.requestRestart(mi,{force:ue})}catch(us){let tn=us?.code;if(!ue&&(tn==="view_barrier"||tn==="drain_pending")){A=!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 us}}catch(ge){throw A=!1,ge}finally{I=!1}O(h,202,{accepted:!0,version:mi.version});return}if(P==="/api/provider/custom"){if(v.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in v)||!Yo(v.provider)||!i.addCustomProvider){O(h,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await i.addCustomProvider(v.sessionId,v.provider),O(h,201,{accepted:!0});return}if(P==="/api/provider/models"||P==="/api/provider/logout"){if(v.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in v)||typeof v.providerId!="string"){O(h,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(P==="/api/provider/models"){if(!("change"in v)||!Qm(v.change)||!i.updateProviderModel){O(h,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await i.updateProviderModel(v.sessionId,v.providerId,v.change)}else{if(!i.logoutProvider){O(h,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await i.logoutProvider(v.sessionId,v.providerId)}O(h,200,{accepted:!0});return}if(P.startsWith("/api/provider/login")){if(v.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(P==="/api/provider/login"){if(!("providerId"in v)||typeof v.providerId!="string"||!("method"in v)||v.method!=="api_key"&&v.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===v.providerId&&ue.methods.includes(v.method))){O(h,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let $="initialSecret"in v?v.initialSecret:void 0;if($!==void 0&&(v.method!=="api_key"||typeof $!="string"||!$.trim()||$.length>16384)){O(h,400,{error:"API Key \u65E0\u6548"});return}let ie=y.start(v.providerId,v.method,i.loginProvider,$,ae);O(h,202,{id:ie.id});return}if(!("id"in v)||typeof v.id!="string"){O(h,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(P==="/api/provider/login/cancel"){O(h,y.cancel(v.id)?202:404,{accepted:!0});return}if(!("value"in v)||typeof v.value!="string"||v.value.length>16384||!y.respond(v.id,v.value)){O(h,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}O(h,202,{accepted:!0});return}if(P==="/api/attachment/remove"){if(!("id"in v)||typeof v.id!="string"||v.sessionId!==i.snapshot().sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}_.get(v.id)?.sessionId===v.sessionId&&_.delete(v.id),O(h,202,{accepted:!0});return}if(P==="/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 Hm(D.signal)});return}if(P==="/api/directory/list"){if("path"in v&&(typeof v.path!="string"||v.path.length>4096)){O(h,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}O(h,200,await jm("path"in v?v.path:void 0));return}if(P==="/api/directory/create"){if(!("path"in v)||typeof v.path!="string"||v.path.length>4096||!("name"in v)||typeof v.name!="string"||v.name.length>255){O(h,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}O(h,200,{path:await Fm(v.path,v.name)});return}if(P==="/api/workspace/add"){if(!("path"in v)||typeof v.path!="string"||v.path.length>4096||!("create"in v)||typeof v.create!="boolean"){O(h,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await i.addWorkspace(v.path,v.create),O(h,202,{accepted:!0});return}if(P==="/api/workspace/select"||P==="/api/workspace/remove"||P==="/api/workspace/new-session"){if(!("id"in v)||typeof v.id!="string"){O(h,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}P==="/api/workspace/select"?await i.selectWorkspace(v.id):P==="/api/workspace/new-session"?await i.newSessionInWorkspace(v.id):await i.removeWorkspace(v.id),O(h,202,{accepted:!0});return}if(P==="/api/session/select"){if(!("workspaceId"in v)||typeof v.workspaceId!="string"||!("id"in v)||typeof v.id!="string"||!("path"in v)||typeof v.path!="string"){O(h,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await i.selectSession(v.workspaceId,v.id,v.path),O(h,202,{accepted:!0});return}if(P==="/api/session/rename"||P==="/api/session/delete"){if(!("workspaceId"in v)||typeof v.workspaceId!="string"||!("id"in v)||typeof v.id!="string"||!("path"in v)||typeof v.path!="string"||v.path.length>4096){O(h,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(P==="/api/session/rename"){if(!("name"in v)||typeof v.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(v.workspaceId,v.id,v.path,v.name)}else{if(!i.deleteSession){O(h,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await i.deleteSession(v.workspaceId,v.id,v.path)}O(h,202,{accepted:!0});return}if(P==="/api/thinking-level"){if(!("level"in v)||typeof v.level!="string"){O(h,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await i.setThinkingLevel(v.sessionId,v.level)}else if(P==="/api/model"){if(!("provider"in v)||typeof v.provider!="string"||!("id"in v)||typeof v.id!="string"){O(h,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await i.setModel(v.sessionId,v.provider,v.id)}else if(P==="/api/config"){let D=v;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"&&tg(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(P==="/api/prompt-queue"){let D=v,$=D.action;if(typeof D.id!="string"||D.id.length>100||!Number.isSafeInteger(D.revision)||D.revision<1||!$||typeof $!="object"||!["edit","remove","steer"].includes($.kind)||$.kind==="edit"&&(typeof $.text!="string"||$.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($.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($.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(v.sessionId,D.id,D.revision,$))}else if(P==="/api/message"){let D="delivery"in v?v.delivery:void 0;if(D!==void 0&&D!=="steer"&&D!=="followUp"){O(h,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let $="attachments"in v?v.attachments:[];if(!Array.isArray($)||$.length>Wm||$.some(ge=>typeof ge!="string")||new Set($).size!==$.length){O(h,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let ie=$.map(ge=>_.get(ge));if(ie.some(ge=>!ge||ge.sessionId!==v.sessionId)){O(h,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in v)||typeof v.text!="string"||!v.text.trim()&&$.length===0||v.text.length>32e3){O(h,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let ue=i.snapshot();if(v.sessionId!==ue.sessionId){O(h,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{Oi(ue,v.text,D)}catch(ge){O(h,409,{error:ge.message});return}let je=ie,Ut=[v.text.trim(),...je.map(ge=>`\u9644\u4EF6 ${JSON.stringify(ge.name)}\uFF1A${ge.path}`)].filter(Boolean).join(`
232
232
 
233
- `),mi=await Promise.all(je.filter(ge=>["image/png","image/jpeg","image/webp","image/gif"].includes(ge.mediaType)).map(Vm));ae.operationId??=Zp(),h.setHeader("X-Operation-ID",ae.operationId),t.breadcrumb("send",{...ae,attachmentCount:je.length}),await p.coordinateStart(ue.cwd,async()=>i.send(_.sessionId,Ut,mi,ae,D));for(let ge of V)v.delete(ge)}else if(P==="/api/compact"){if(!i.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await i.compact(_.sessionId)}else if(P==="/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??=Zp(),h.setHeader("X-Operation-ID",ae.operationId),t.breadcrumb("resume",{...ae}),await p.coordinateStart(D.cwd,async()=>i.resume(_.sessionId,ae))}else P==="/api/abort"?await i.abort(_.sessionId):await i.newSession(_.sessionId);O(h,202,{accepted:!0})}catch(_){if(_ instanceof et){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(be){h.headersSent?(t.capture(be,{...ae,route:P,stage:"http_stream"}),h.end()):me(be,500,"\u8BF7\u6C42\u5931\u8D25")}}),B=Number(process.env.PI_WEBAPP_RESTART_PORT),N;try{N=await _O(q,Number.isInteger(B)&&B>0&&B<65536&&n===s?B:0)}catch(w){throw t.capture(w,{stage:"listen"}),await t.close(),w}return T=`http://127.0.0.1:${N}`,{protocolVersion:7,buildId:It,runPluginTool:(w,h,M,Z,re,ae)=>p.runAgentAction(w,h,M,Z,re,ae),reportError(w,h){return t.capture(w,h)},breadcrumb(w,h){t.breadcrumb(w,h)},url:`${T}/#${s}`,publish(w){if(w.type==="snapshot"&&S(w.session),w.type==="error"&&!w.errorCode&&(w={...w,errorCode:"unexpected_error",errorId:t.capture(new Error("Agent execution failed"),{stage:"agent",requestId:w.requestId,operationId:w.operationId})}),w.type==="error"&&(w={...w,errorReported:w.errorReported??t.enabled}),w.type==="snapshot")for(let[M,Z]of v)Z.sessionId!==w.session.sessionId&&v.delete(M);let h=`${JSON.stringify(w)}
233
+ `),mi=await Promise.all(je.filter(ge=>["image/png","image/jpeg","image/webp","image/gif"].includes(ge.mediaType)).map(Vm));ae.operationId??=Zp(),h.setHeader("X-Operation-ID",ae.operationId),t.breadcrumb("send",{...ae,attachmentCount:je.length}),await p.coordinateStart(ue.cwd,async()=>i.send(v.sessionId,Ut,mi,ae,D));for(let ge of $)_.delete(ge)}else if(P==="/api/compact"){if(!i.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await i.compact(v.sessionId)}else if(P==="/api/resume"){let D=i.snapshot();if(v.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??=Zp(),h.setHeader("X-Operation-ID",ae.operationId),t.breadcrumb("resume",{...ae}),await p.coordinateStart(D.cwd,async()=>i.resume(v.sessionId,ae))}else P==="/api/abort"?await i.abort(v.sessionId):await i.newSession(v.sessionId);O(h,202,{accepted:!0})}catch(v){if(v instanceof et){O(h,v.status,{error:v.message});return}let D=p.requestFailure(v);if(D){O(h,D.status,D.body);return}let $=v instanceof Error?v.message:"\u8BF7\u6C42\u5931\u8D25";me(v,$==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,$)}return}O(h,404,{error:"\u672A\u627E\u5230"})}catch(be){h.headersSent?(t.capture(be,{...ae,route:P,stage:"http_stream"}),h.end()):me(be,500,"\u8BF7\u6C42\u5931\u8D25")}}),F=Number(process.env.PI_WEBAPP_RESTART_PORT),N;try{N=await AO(q,Number.isInteger(F)&&F>0&&F<65536&&n===s?F:0)}catch(w){throw t.capture(w,{stage:"listen"}),await t.close(),w}return T=`http://127.0.0.1:${N}`,{protocolVersion:7,buildId:It,runPluginTool:(w,h,M,Z,re,ae)=>p.runAgentAction(w,h,M,Z,re,ae),reportError(w,h){return t.capture(w,h)},breadcrumb(w,h){t.breadcrumb(w,h)},url:`${T}/#${s}`,publish(w){if(w.type==="snapshot"&&S(w.session),w.type==="error"&&!w.errorCode&&(w={...w,errorCode:"unexpected_error",errorId:t.capture(new Error("Agent execution failed"),{stage:"agent",requestId:w.requestId,operationId:w.operationId})}),w.type==="error"&&(w={...w,errorReported:w.errorReported??t.enabled}),w.type==="snapshot")for(let[M,Z]of _)Z.sessionId!==w.session.sessionId&&_.delete(M);let h=`${JSON.stringify(w)}
234
234
  `;for(let M of a)M.write(h)},async close(w){y.close(),await p.close();for(let M of a)M.end(`${JSON.stringify({type:"shutdown",reconnect:w?.reconnect??A})}
235
- `);a.clear();let h;try{await new Promise((M,Z)=>{q.close(re=>re?Z(re):M()),h=setTimeout(()=>q.closeAllConnections(),50).unref()})}finally{clearTimeout(h),await t.close()}}}}import{getSupportedThinkingLevels as vO}from"@earendil-works/pi-ai";var Yn="pi-webapp/paused",td="pi-webapp/resume";function Br(i){for(let e=i.length-1;e>=0;e--){let t=i[e];if(t.type==="custom_message"&&t.customType===td)return!1;if(t.type==="custom"&&t.customType===Yn)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 id(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 rr(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 Qn(i){if(i.type==="custom_message")return i.display?{id:i.id,role:"notice",timestamp:i.timestamp,blocks:rr(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:rr(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:rr(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function Ka(i,e){let t=i?.trim();if(t)return t;let r=e.find(s=>s.role==="user");return zn(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function mw(i,e,t=[]){let r=i.sessionManager.getBranch().flatMap(n=>{let s=Qn(n);return s?[s]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:i.cwd,name:Ka(e,r),model:i.model?`${i.model.provider}/${i.model.id}`:null,thinkingLevel:i.thinkingLevel??null,thinkingLevels:i.model?vO(i.model):["off"],idle:i.isIdle(),paused:Br(i.sessionManager.getBranch()),contextUsage:i.getContextUsage()??null,messages:r,pluginEntries:id(i.sessionManager.getBranch(),t)}}import{randomUUID as rd}from"node:crypto";import{mkdir as gw,readFile as wO,realpath as nd,rename as kO,rm as SO,stat as sd,writeFile as EO}from"node:fs/promises";import{basename as fw,dirname as TO,isAbsolute as hw,join as IO}from"node:path";var Jn=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 nr(i){try{let e=await nd(i);return(await sd(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Yt(i){let e=await nr(i);if(e===null)throw new Jn;return e}var Ya=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await wO(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(!hw(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await gw(e,{recursive:!0});let r=await nd(e);if(!(await sd(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:rd(),path:r,title:fw(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(hw).map(async r=>{try{let n=await nd(r);return(await sd(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:rd(),path:o,title:fw(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 gw(TO(this.file),{recursive:!0});let r=`${this.file}.${rd()}.tmp`;try{await EO(r,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await kO(r,this.file)}catch(n){throw await SO(r,{force:!0}),n}}};function yw(i){return IO(i,"pi-web","workspaces.json")}import{createAgentSession as mR,createEventBus as gR,DefaultResourceLoader as fR,getAgentDir as hR,SessionManager as es,VERSION as eo}from"@earendil-works/pi-coding-agent";function Xn(i,e){return!!i?.has(e)||Object.values(st).includes(e)}var bw="pi-webapp:interaction-open:v1",_w="pi-webapp:interaction-accept:v1",ad="pi-webapp:interaction-settle:v1",vw="pi-webapp:interaction-cancel:v1",od=class extends Error{};function Qa(i,e,t,r=300){return new Promise((n,s)=>{let o=!1,l,a=(g,f)=>{o||(o=!0,clearTimeout(l),p(),d(),t?.removeEventListener("abort",c),g?s(g):n(f))},c=()=>{i.emit(vw,e),a(new Error("Interaction cancelled"))},p=i.on(_w,g=>{g?.requestId===e.requestId&&clearTimeout(l)}),d=i.on(ad,g=>{let f=g;f?.requestId===e.requestId&&a(f.error?new Error(f.error):null,f.value)});l=setTimeout(()=>a(new od("No Web interaction host")),r),t?.addEventListener("abort",c,{once:!0}),t?.aborted?c():i.emit(bw,e)})}var Fr=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(bw,n=>{!xO(n)||!t(n)||this.requests.has(n.requestId)||(this.requests.set(n.requestId,n),e.emit(_w,{requestId:n.requestId}),r())}),e.on(vw,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(ad,{requestId:r,value:n}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(ad,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function xO(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 sr(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 Ci(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&&sr(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&sr(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&sr(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&sr(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 AO=1,OO="pi-webapp:action:v1",RO="pi-webapp:action-response:v1",Ja="pi-webapp:plugin-changed:v1";function ww(i){if(!i||typeof i!="object")return!1;let e=i;return e.apiVersion===AO&&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 Xa(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(RO,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(OO,e)}catch(d){l(d instanceof Error?d:new Error(String(d)))}})}import{realpath as yR}from"node:fs/promises";import{readFile as ld,realpath as Tw,stat as Iw}from"node:fs/promises";import{createHash as NO}from"node:crypto";import{dirname as kw,isAbsolute as PO,join as cd,parse as CO,resolve as DO,sep as MO,delimiter as LO}from"node:path";import{DefaultPackageManager as UO,getAgentDir as qO,SettingsManager as jO}from"@earendil-works/pi-coding-agent";async function Sw(i,e){let t=await ld(i),r=e?await ld(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=NO("sha256").update(t).update("\0").update(r??"").digest("hex");return{clientBytes:t,styleBytes:r,revision:n}}function BO(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(LO).filter(Boolean).map(i=>DO(i))}async function FO(i){let e=kw(i);for(;e!==CO(e).root;)try{return await Iw(cd(e,"package.json")),e}catch{e=kw(e)}return null}async function Ew(i,e){let t=await Tw(cd(i,e));if(!t.startsWith(i+MO))throw new Error("Asset escapes package root");let r=await Iw(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 ar=class i{plugins;errors;extensionRoots;constructor(e,t,r){this.plugins=e,this.errors=t,this.extensionRoots=r}static async discover(e,t,r=BO()){let n=jO.create(e,void 0,{projectTrusted:t}),s=new UO({cwd:e,agentDir:qO(),settingsManager:n}),o=await s.resolve(async()=>"skip"),l=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},a=new Set;for(let f of[...o.extensions,...l.extensions]){if(!f.enabled)continue;let v=await FO(f.path);v&&a.add(v)}for(let f of r)PO(f)&&a.add(f);let c=[],p=[],d=[],g=new Set;for(let f of a)try{let v=await Tw(f),y=JSON.parse(await ld(cd(v,"package.json"),"utf8"));if(y.piWebapp===void 0)continue;if(typeof y.name!="string"||!y.name)throw new Error("Missing package name");if(!ww(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 Ew(v,y.piWebapp.client),T=y.piWebapp.style?await Ew(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 Sw(S,T)}),d.push(v)}catch(v){p.push(`${f}: ${v instanceof Error?v.message:String(v)}`)}return c.sort((f,v)=>f.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 Sw(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 HO}from"node:fs/promises";import{SessionManager as GO}from"@earendil-works/pi-coding-agent";async function Hr(i,e){let t=await Yt(i),r=e??await GO.listAll(),n=await Promise.all(r.map(async s=>s.cwd!==""&&await HO(s.cwd).catch(()=>null)===t));return r.filter((s,o)=>n[o])}var or=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))}},xw=new WeakMap;function Aw(i,e,t,r=5e3,n=()=>{}){let s=xw.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 xw.set(i,o),o}function Za(i){let t=[...i].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
235
+ `);a.clear();let h;try{await new Promise((M,Z)=>{q.close(re=>re?Z(re):M()),h=setTimeout(()=>q.closeAllConnections(),50).unref()})}finally{clearTimeout(h),await t.close()}}}}import{getSupportedThinkingLevels as OO}from"@earendil-works/pi-ai";var Yn="pi-webapp/paused",td="pi-webapp/resume";function Fr(i){for(let e=i.length-1;e>=0;e--){let t=i[e];if(t.type==="custom_message"&&t.customType===td)return!1;if(t.type==="custom"&&t.customType===Yn)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 id(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 rr(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 Qn(i){if(i.type==="custom_message")return i.display?{id:i.id,role:"notice",timestamp:i.timestamp,blocks:rr(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:rr(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:rr(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function Ka(i,e){let t=i?.trim();if(t)return t;let r=e.find(s=>s.role==="user");return zn(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function hw(i,e,t=[]){let r=i.sessionManager.getBranch().flatMap(n=>{let s=Qn(n);return s?[s]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:i.cwd,name:Ka(e,r),model:i.model?`${i.model.provider}/${i.model.id}`:null,thinkingLevel:i.thinkingLevel??null,thinkingLevels:i.model?OO(i.model):["off"],idle:i.isIdle(),paused:Fr(i.sessionManager.getBranch()),contextUsage:i.getContextUsage()??null,messages:r,pluginEntries:id(i.sessionManager.getBranch(),t)}}import{randomUUID as rd}from"node:crypto";import{mkdir as yw,readFile as RO,realpath as nd,rename as NO,rm as PO,stat as sd,writeFile as CO}from"node:fs/promises";import{basename as bw,dirname as DO,isAbsolute as _w,join as MO}from"node:path";var Jn=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 nr(i){try{let e=await nd(i);return(await sd(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Yt(i){let e=await nr(i);if(e===null)throw new Jn;return e}var Ya=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await RO(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(!_w(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await yw(e,{recursive:!0});let r=await nd(e);if(!(await sd(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:rd(),path:r,title:bw(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(_w).map(async r=>{try{let n=await nd(r);return(await sd(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:rd(),path:o,title:bw(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 yw(DO(this.file),{recursive:!0});let r=`${this.file}.${rd()}.tmp`;try{await CO(r,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await NO(r,this.file)}catch(n){throw await PO(r,{force:!0}),n}}};function vw(i){return MO(i,"pi-web","workspaces.json")}import{createAgentSession as kR,createEventBus as SR,DefaultResourceLoader as ER,getAgentDir as TR,SessionManager as es,VERSION as eo}from"@earendil-works/pi-coding-agent";function Xn(i,e){return!!i?.has(e)||Object.values(st).includes(e)}var ww="pi-webapp:interaction-open:v1",kw="pi-webapp:interaction-accept:v1",ad="pi-webapp:interaction-settle:v1",Sw="pi-webapp:interaction-cancel:v1",od=class extends Error{};function Qa(i,e,t,r=300){return new Promise((n,s)=>{let o=!1,l,a=(g,f)=>{o||(o=!0,clearTimeout(l),p(),d(),t?.removeEventListener("abort",c),g?s(g):n(f))},c=()=>{i.emit(Sw,e),a(new Error("Interaction cancelled"))},p=i.on(kw,g=>{g?.requestId===e.requestId&&clearTimeout(l)}),d=i.on(ad,g=>{let f=g;f?.requestId===e.requestId&&a(f.error?new Error(f.error):null,f.value)});l=setTimeout(()=>a(new od("No Web interaction host")),r),t?.addEventListener("abort",c,{once:!0}),t?.aborted?c():i.emit(ww,e)})}var Br=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(ww,n=>{!LO(n)||!t(n)||this.requests.has(n.requestId)||(this.requests.set(n.requestId,n),e.emit(kw,{requestId:n.requestId}),r())}),e.on(Sw,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(ad,{requestId:r,value:n}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(ad,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function LO(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 sr(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 Ci(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&&sr(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&sr(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&sr(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&sr(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 UO=1,qO="pi-webapp:action:v1",jO="pi-webapp:action-response:v1",Ja="pi-webapp:plugin-changed:v1";function Ew(i){if(!i||typeof i!="object")return!1;let e=i;return e.apiVersion===UO&&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 Xa(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(jO,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(qO,e)}catch(d){l(d instanceof Error?d:new Error(String(d)))}})}import{realpath as IR}from"node:fs/promises";import{readFile as ld,realpath as Aw,stat as Ow}from"node:fs/promises";import{createHash as FO}from"node:crypto";import{dirname as Tw,isAbsolute as BO,join as cd,parse as HO,resolve as GO,sep as WO,delimiter as $O}from"node:path";import{DefaultPackageManager as VO,getAgentDir as zO,SettingsManager as KO}from"@earendil-works/pi-coding-agent";async function Iw(i,e){let t=await ld(i),r=e?await ld(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=FO("sha256").update(t).update("\0").update(r??"").digest("hex");return{clientBytes:t,styleBytes:r,revision:n}}function YO(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split($O).filter(Boolean).map(i=>GO(i))}async function QO(i){let e=Tw(i);for(;e!==HO(e).root;)try{return await Ow(cd(e,"package.json")),e}catch{e=Tw(e)}return null}async function xw(i,e){let t=await Aw(cd(i,e));if(!t.startsWith(i+WO))throw new Error("Asset escapes package root");let r=await Ow(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 ar=class i{plugins;errors;extensionRoots;constructor(e,t,r){this.plugins=e,this.errors=t,this.extensionRoots=r}static async discover(e,t,r=YO()){let n=KO.create(e,void 0,{projectTrusted:t}),s=new VO({cwd:e,agentDir:zO(),settingsManager:n}),o=await s.resolve(async()=>"skip"),l=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},a=new Set;for(let f of[...o.extensions,...l.extensions]){if(!f.enabled)continue;let _=await QO(f.path);_&&a.add(_)}for(let f of r)BO(f)&&a.add(f);let c=[],p=[],d=[],g=new Set;for(let f of a)try{let _=await Aw(f),y=JSON.parse(await ld(cd(_,"package.json"),"utf8"));if(y.piWebapp===void 0)continue;if(typeof y.name!="string"||!y.name)throw new Error("Missing package name");if(!Ew(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 xw(_,y.piWebapp.client),T=y.piWebapp.style?await xw(_,y.piWebapp.style):void 0;g.add(y.name),c.push({id:y.name,root:_,manifest:y.piWebapp,clientPath:S,stylePath:T,...await Iw(S,T)}),d.push(_)}catch(_){p.push(`${f}: ${_ instanceof Error?_.message:String(_)}`)}return c.sort((f,_)=>f.id.localeCompare(_.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 Iw(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 JO}from"node:fs/promises";import{SessionManager as XO}from"@earendil-works/pi-coding-agent";async function Hr(i,e){let t=await Yt(i),r=e??await XO.listAll(),n=await Promise.all(r.map(async s=>s.cwd!==""&&await JO(s.cwd).catch(()=>null)===t));return r.filter((s,o)=>n[o])}var or=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))}},Rw=new WeakMap;function Nw(i,e,t,r=5e3,n=()=>{}){let s=Rw.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 Rw.set(i,o),o}function Za(i){let t=[...i].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
236
236
  `);return{customType:td,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?`
237
237
  Already displayed assistant text (reference data):
238
- ${JSON.stringify(t)}`:"")}}import{createHash as WO}from"node:crypto";import{readFile as Rw,realpath as Ow,writeFile as VO,unlink as $O}from"node:fs/promises";import{basename as zO,dirname as pd,extname as KO,isAbsolute as YO,join as Nw,parse as QO,relative as JO,sep as XO}from"node:path";import{DefaultPackageManager as Pw,getAgentDir as Cw,SettingsManager as Dw}from"@earendil-works/pi-coding-agent";var Zn=new Map;async function ZO(i){let e=pd(i);for(;e!==QO(e).root;){try{let t=JSON.parse(await Rw(Nw(e,"package.json"),"utf8"));if(typeof t.name=="string")return t.name}catch{}e=pd(e)}return null}function eR(i,e){let t=JO(i,e);return t===""||t!==".."&&!t.startsWith(`..${XO}`)&&!YO(t)}async function Mw(i,e,t){let r=Dw.create(i,void 0,{projectTrusted:t}),s=await new Pw({cwd:i,agentDir:Cw(),settingsManager:r}).resolve(async()=>"skip"),o=await Promise.all(e.map(c=>Ow(c))),l=new Set;for(let c of s.extensions){if(!c.enabled||c.path.startsWith("builtin:"))continue;let p=await Ow(c.path);await ZO(p)!=="pi-webapp"&&(o.some(d=>eR(d,p))||l.add(p))}let a=await tR(i,o);return{paths:[...a.paths,...l],release:a.release}}async function tR(i,e){let r=await new Pw({cwd:i,agentDir:Cw(),settingsManager:Dw.create(i)}).resolveExtensionSources([...e],{temporary:!0}),n=[],s=[],o=async()=>{for(let a of n.splice(0)){let c=(Zn.get(a)??1)-1;c?Zn.set(a,c):(Zn.delete(a),await $O(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=KO(a.path);if(![".js",".mjs"].includes(c)){s.push(a.path);continue}let p=await Rw(a.path),d=WO("sha256").update(p).digest("hex"),g=Nw(pd(a.path),`.pi-web-runtime-${zO(a.path,c)}-${d}${c}`);await VO(g,p,{flag:"wx"}).catch(f=>{if(f.code!=="EEXIST")throw f}),Zn.set(g,(Zn.get(g)??0)+1),n.push(g),s.push(g)}return{paths:s,release:o}}catch(a){throw await o(),a}}import{createHash as iR}from"node:crypto";var dd={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"}},Di=i=>i!==null&&typeof i=="object"?i:void 0,rR=[{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 Uw(i,e){let t=i instanceof Error?i:Di(i)?.error instanceof Error?Di(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=Di(t)?.code;if(typeof s=="string"&&dd[s]){let p=dd[s];return n(p.kind,s,`${s}: ${p.summary}`),r}let o=t?.message??"";if(!t){let p=Di(i)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(d=>{let g=Di(d);return g?.type==="text"&&typeof g.text=="string"?[g.text.length>16384?`${g.text.slice(0,8192)}
238
+ ${JSON.stringify(t)}`:"")}}import{createHash as ZO}from"node:crypto";import{readFile as Cw,realpath as Pw,writeFile as eR,unlink as tR}from"node:fs/promises";import{basename as iR,dirname as pd,extname as rR,isAbsolute as nR,join as Dw,parse as sR,relative as aR,sep as oR}from"node:path";import{DefaultPackageManager as Mw,getAgentDir as Lw,SettingsManager as Uw}from"@earendil-works/pi-coding-agent";var Zn=new Map;async function lR(i){let e=pd(i);for(;e!==sR(e).root;){try{let t=JSON.parse(await Cw(Dw(e,"package.json"),"utf8"));if(typeof t.name=="string")return t.name}catch{}e=pd(e)}return null}function cR(i,e){let t=aR(i,e);return t===""||t!==".."&&!t.startsWith(`..${oR}`)&&!nR(t)}async function qw(i,e,t){let r=Uw.create(i,void 0,{projectTrusted:t}),s=await new Mw({cwd:i,agentDir:Lw(),settingsManager:r}).resolve(async()=>"skip"),o=await Promise.all(e.map(c=>Pw(c))),l=new Set;for(let c of s.extensions){if(!c.enabled||c.path.startsWith("builtin:"))continue;let p=await Pw(c.path);await lR(p)!=="pi-webapp"&&(o.some(d=>cR(d,p))||l.add(p))}let a=await pR(i,o);return{paths:[...a.paths,...l],release:a.release}}async function pR(i,e){let r=await new Mw({cwd:i,agentDir:Lw(),settingsManager:Uw.create(i)}).resolveExtensionSources([...e],{temporary:!0}),n=[],s=[],o=async()=>{for(let a of n.splice(0)){let c=(Zn.get(a)??1)-1;c?Zn.set(a,c):(Zn.delete(a),await tR(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=rR(a.path);if(![".js",".mjs"].includes(c)){s.push(a.path);continue}let p=await Cw(a.path),d=ZO("sha256").update(p).digest("hex"),g=Dw(pd(a.path),`.pi-web-runtime-${iR(a.path,c)}-${d}${c}`);await eR(g,p,{flag:"wx"}).catch(f=>{if(f.code!=="EEXIST")throw f}),Zn.set(g,(Zn.get(g)??0)+1),n.push(g),s.push(g)}return{paths:s,release:o}}catch(a){throw await o(),a}}import{createHash as dR}from"node:crypto";var dd={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"}},Di=i=>i!==null&&typeof i=="object"?i:void 0,uR=[{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 Fw(i,e){let t=i instanceof Error?i:Di(i)?.error instanceof Error?Di(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=Di(t)?.code;if(typeof s=="string"&&dd[s]){let p=dd[s];return n(p.kind,s,`${s}: ${p.summary}`),r}let o=t?.message??"";if(!t){let p=Di(i)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(d=>{let g=Di(d);return g?.type==="text"&&typeof g.text=="string"?[g.text.length>16384?`${g.text.slice(0,8192)}
239
239
  [truncated]
240
240
  ${g.text.slice(-8192)}`:g.text]:[]}).join(`
241
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=dd[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=rR.find(g=>g.pattern.test(o));d&&n("validation",d.code,d.summary)}}return r}var nR=256;function Lw(i,e,t){i.delete(e),i.set(e,t),i.size>nR&&i.delete(i.keys().next().value)}var Gr=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:ks.has(e.toolName)?e.toolName:"custom",...ks.has(e.toolName)?{}:{toolId:iR("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"?Di(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"};Lw(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),Lw(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:Di(e.result)?.error instanceof Error?Di(e.result).error:void 0,l=n?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:Uw(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=qw(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 qw(i,e,t=0){let r=Uw(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}
242
+ `)||/^Validation failed for tool\b/.test(c)){let p=c.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let d=dd[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=uR.find(g=>g.pattern.test(o));d&&n("validation",d.code,d.summary)}}return r}var mR=256;function jw(i,e,t){i.delete(e),i.set(e,t),i.size>mR&&i.delete(i.keys().next().value)}var Gr=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:ws.has(e.toolName)?e.toolName:"custom",...ws.has(e.toolName)?{}:{toolId:dR("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"?Di(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"};jw(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),jw(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:Di(e.result)?.error instanceof Error?Di(e.result).error:void 0,l=n?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:Fw(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=Bw(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 Bw(i,e,t=0){let r=Fw(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
243
  ${i.stack.split(`
244
244
  `).slice(1).join(`
245
- `)}`:void 0,t<3&&i.cause instanceof Error&&(n.cause=qw(i.cause,e,t+1)),gr(n)}import{randomUUID as Fw}from"node:crypto";import{randomUUID as sR}from"node:crypto";import{EnvHttpProxyAgent as aR,getGlobalDispatcher as SV,setGlobalDispatcher as EV}from"undici";var jw=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 oR(i,e){let t=jw(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 lR(i){let e=jw(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 aR(e)}function ud({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:sR(),phase:"headers",proxied:o&&oR(i,p)},f=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(f).catch(()=>{}))},A;try{o?(f??=lR(i),s.add(f),r||(n=f),A=await t(p,{...d,dispatcher:f})):A=await t(p,d)}catch(B){throw l(B,g),T(),B}if(A.ok||l(void 0,{...g,status:A.status}),!A.body)return T(),A;let x=A.body.getReader();y?.addEventListener("abort",S,{once:!0}),y?.aborted&&T();let C=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()}}}),q=new Response(C,{status:A.status,statusText:A.statusText,headers:A.headers});return Object.defineProperties(q,{url:{value:A.url},redirected:{value:A.redirected},type:{value:A.type}}),q},close:async()=>{await Promise.all([...s].map(a))}}}var Bw=(i,e)=>ud({autoClose:!0}).fetch(i,e);var cR=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),pR=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 md(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=pR(a.code);if(t.push({name:cR.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:Fw(),requestId:l(e.requestId)??Fw(),...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 Hw({env:i=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return ud({env:i,fetchRequest:t,onFailure:(r,n)=>e(md(r,{...n,stage:n.phase==="body"?"model_stream":"model_headers"}))})}function dR(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 uR=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function Gw(i,e,t=()=>{}){let r=i.agent.streamFunction;i.agent.streamFunction=async(n,s,o)=>{if(!uR.has(n.api))return r(n,s,o);let l=t(),a=Hw({env:dR(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 Wr(i,e,t){try{i()}catch(r){let n=md(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 bR=["read","grep","find","ls"];var Ww=200,to=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new or;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 Yt(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=es.create(r);else if(t==="continue"){let l=(await Hr(r))[0];s=l?es.open(l.path):es.create(r)}else s="sessionManager"in t?t.sessionManager:es.open(t.sessionFile);if(await yR(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 Yt(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=Qn(l);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:r,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!n.sending,name:Ka(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=>Qn(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 ar.discover(e,this.isProjectTrusted(e)),l=gR(),a=await Mw(e,o.extensionRoots,this.isProjectTrusted(e)),c=new fR({cwd:e,agentDir:hR(),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(w=>`${w.path}: ${w.error}`).join("; "));let g=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:f}=await mR({cwd:e,sessionManager:t,model:g,resourceLoader:c,customTools:this.customTools}),v=new Gr({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(w,h)=>this.telemetry.breadcrumb(w,h),anonymize:w=>this.telemetry.anonymize(w)}),y={session:f,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 Ri(()=>{let w=this.runtimes.get(t.getSessionId())??y;this.publishFor(w,{type:"snapshot",session:this.snapshotOf(w)}),!this.disposed&&!w.closing&&this.onSessionsChanged()}),p=y,Gw(f,w=>{y.networkDiagnostic=w},()=>y.operation?.operationId);let S=w=>this.publishFor(y,w),T=y.detached,A=(w,h)=>{T&&(T.events.push({seq:++T.seq,type:w,...h===void 0?{}:{text:h}}),T.events.length>Ww&&T.events.splice(0,T.events.length-Ww))};y.interactions=new Fr(l,w=>!y.closing&&w.sessionId===f.sessionManager.getSessionId()&&Xn(o,w.pluginId),()=>S({type:"snapshot",session:this.snapshotOf(y)}));let x=0,C=l.on(Ja,()=>S({type:"snapshot",session:this.snapshotOf(y)})),q=f.subscribe(w=>{if(T&&!y.closing&&(w.type==="message_end"&&w.message.role==="assistant"&&(w.message.stopReason==="error"?A("error",w.message.errorMessage??"Agent response failed"):T.lastText=w.message.content.flatMap(h=>h.type==="text"?[h.text]:[]).join(`
246
- `)),w.type==="agent_settled"&&A("turn_end",T.lastText)),!this.disposed&&!y.closing){let h={...y.operation,session:this.telemetry.anonymize(f.sessionManager.getSessionId()),piVersion:eo,model:f.model?`${f.model.provider}/${f.model.id}`:null,thinkingLevel:f.thinkingLevel};if(w.type==="agent_start"&&(y.activityId++,this.telemetry.breadcrumb("agent_start",h)),w.type==="tool_execution_start"&&v.start(w,h),w.type==="tool_execution_end"&&v.end(w,h),w.type==="message_end"&&w.message.role==="assistant"&&w.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:eo,...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:w.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:Z,inTranscript:!0,...y.operation})}w.type==="message_end"&&w.message.role==="toolResult"&&v.message(w.message,h),w.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",h),v.clear(),y.operation=void 0)}w.type==="message_update"&&w.message.role==="assistant"&&(y.streaming={id:"stream",role:"assistant",timestamp:new Date(w.message.timestamp).toISOString(),blocks:rr(w.message.content)},Date.now()-x>=60&&(x=Date.now(),S({type:"stream",message:y.streaming}))),w.type==="agent_settled"&&this.scheduleQueued(y),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(w.type)&&((w.type==="message_end"&&w.message.role==="assistant"||w.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(w.type)&&this.onSessionsChanged())});y.detach=()=>{C(),q()},y.releaseHosted=this.hosted?.adapter.attach(f);let B=[],N=!0;if(await f.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:w=>{N&&B.push(w.error),this.diagnostic(y,o.plugins.find(h=>w.extensionPath.startsWith(h.root+"/"))?.id??w.extensionPath,w.event??"runtime",w.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=f.getActiveToolNames(),f.setActiveToolsByName(bR)),this.runtimes.set(f.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 Aw(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=Qn(o);return l?[l]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:Ka(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:Br(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:id(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 Xa(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")):Qa(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(Oi(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 et("\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");Wr(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),Oi({...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:eo});let a=!1,c,p,d=new Promise((g,f)=>{c=g,p=f});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 f=this.reportError(Zt(g,"Agent response failed"),{...n,stage:"agent",code:"agent_failed",piVersion:eo});this.publishFor(e,{type:"error",message:g instanceof Error?g.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:f,...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&&!Br(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 et("\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(Yn),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");Wr(()=>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(!Br(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(!Br(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=Za(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(Zt(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 Yt(e),s=es.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 _R,mkdir as vR,rename as wR,unlink as kR}from"node:fs/promises";import{basename as SR,join as Vw}from"node:path";var ER=i=>Vw(i,"pi-web","trash");async function $w(i,e){let t=ER(e);await vR(t,{recursive:!0});let r=Vw(t,`${Date.now()}_${SR(i)}`);try{await wR(i,r)}catch(n){let s=n.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw n;await _R(i,r),await kR(i)}return r}import{basename as gd,dirname as TR}from"node:path";function zw(i,e){let t=r=>e[r].map(n=>({name:r==="skills"&&gd(n.path).toLowerCase()==="skill.md"?gd(TR(n.path)):gd(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 IR}from"node:child_process";var xR=(i,e)=>new Promise((t,r)=>{IR(i,[...e],{windowsHide:!0},n=>{n?r(n):t()})});async function fd(i,e=process.platform,t=process.env,r=xR){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 EN}from"node:child_process";import{randomUUID as Cd}from"node:crypto";import{existsSync as S0}from"node:fs";import{access as TN,mkdir as ns,mkdtemp as IN,readFile as Li,realpath as xN,rename as E0,rm as T0,writeFile as I0}from"node:fs/promises";import{join as Oe}from"node:path";import{createHash as bd}from"node:crypto";import{readdir as MR,realpath as Zw,rename as LR,stat as UR}from"node:fs/promises";import{join as Mi}from"node:path";import{constants as hd}from"node:fs";import{DatabaseSync as AR}from"node:sqlite";import{lstat as Qw,mkdir as OR,open as ts,rename as RR,unlink as Jw}from"node:fs/promises";import{dirname as NR,join as Kw,resolve as PR}from"node:path";import{randomUUID as CR}from"node:crypto";import{setTimeout as DR}from"node:timers/promises";async function Le(i){await OR(i,{recursive:!0,mode:448});let e=await Qw(i);if(!e.isDirectory()||e.isSymbolicLink())throw new b("invalid_storage","Plugin storage must be a real directory")}async function Pe(i,e){let t;try{t=await ts(i,hd.O_RDONLY|hd.O_NONBLOCK|(hd.O_NOFOLLOW??0))}catch(r){if(Ni(r))return null;throw r}try{let r=await t.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new b("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 b("invalid_storage","Storage record changed during read");return n.subarray(0,s)}finally{await t.close()}}async function Ue(i,e=2*1024*1024){let t=await Pe(i,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new b("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function pt(i){let e=await Pe(i,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new b("gc_recovery_required",`Invalid journal ${i}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new b("gc_recovery_required",`Invalid journal ${i}; original bytes preserved`);return t}async function ye(i,e){let t=`${i}.${CR()}.tmp`,r=await ts(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await RR(t,i);let n;try{n=await ts(NR(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 Jw(t).catch(()=>{})}}var Xw='{"version":2,"mechanism":"sqlite-exclusive"}',Yw=i=>i.toString("utf8")===Xw,io=new Set;async function yd(i,e,t=0){await Le(i);let r=Kw(i,`${e}.lock`),n=Kw(i,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new b(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 ts(n,"wx",384)}catch(v){if(v.code!=="EEXIST")throw v}finally{await l?.close()}let a=await Qw(n);if(!a.isFile()||a.isSymbolicLink()||a.nlink!==1||a.size>1024*1024)throw new b("invalid_storage","Ownership database must be a small, single-link regular file");let c=new AR(n,{allowExtension:!1}),p=PR(n),d=Date.now()+t,g=!1;try{for(;;){if(!io.has(p))try{c.exec("BEGIN EXCLUSIVE"),io.add(p),g=!0;break}catch(y){if(y.errcode!==5)throw y}if(Date.now()>=d)throw new b(s,"Another host owns this plugin storage; wait for it to stop before retrying");await DR(10)}let v=await Pe(r,4096);if(v===null){let y;try{y=await ts(r,"wx",384),await y.writeFile(Xw),await y.sync()}catch(S){if(S.code!=="EEXIST")throw S}finally{await y?.close()}v=await Pe(r,4096)}if(v===null||!Yw(v))throw o()}catch(v){throw c.close(),g&&io.delete(p),v}let f=!1;return async()=>{if(f)return;let v=await Pe(r,4096);if(v===null||!Yw(v))throw new b("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Jw(r),c.close(),io.delete(p),f=!0}}async function qe(i,e,t=2e3){let r=await yd(i,"transaction",t);try{return await e()}finally{await r()}}var ro=i=>Mi(i,"host-pair"),qR=i=>bd("sha256").update(JSON.stringify(i)).digest("hex"),jR=10*6e4;async function BR(i){let e=bd("sha256"),t=0,r=0;async function n(s){let o=(await MR(Mi(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 b("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new b("host_pair_required","Candidate package resource budget exceeded");if(l.isDirectory()){await n(a);continue}let c=await Pe(Mi(i,a),64*1024*1024);if(!c||(r+=c.length)>256*1024*1024)throw new b("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,bd("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function _d(i,e){let t=await Zw(e),r=Mi(e,"dist","hosted-worker.js");if(await Zw(r)!==Mi(t,"dist","hosted-worker.js"))throw new b("host_pair_required","Candidate worker must remain inside the staged host");let n=await Pe(Mi(e,"package.json"),512*1024);if(!n)throw new b("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 b("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 Pe(r,32*1024*1024);if(!l)throw new b("host_pair_required","Candidate worker missing");return qR([n.toString("base64"),l.toString("base64"),await BR(e)])}async function no(i){await LR(i,`${i}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var FR=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 vd(i){let e=Mi(ro(i),"intent.json"),t,r=!0;try{t=await pt(e)}catch{t=null,r=!1}if(!r||t&&!FR(t))return await no(e),null;if(t){let{lifecyclePhase:n,...s}=t,o=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await UR(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 so(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(Mi(ro(i),"intent.json"),n)}var wd=i=>i&&["selecting","selected","restart-requested"].includes(i.phase),e0=(i,e=Date.now())=>!!i&&!!wd(i)&&e-Date.parse(i.updatedAt??"")<jR;import{promisify as AN}from"node:util";import{realpathSync as r0,statSync as HR}from"node:fs";import{basename as GR,delimiter as WR,dirname as t0,join as kd,resolve as VR}from"node:path";function i0(i){if(!i)return null;try{let e=r0(i);return GR(e)==="npm-cli.js"&&HR(e).isFile()?e:null}catch{return null}}function $R({execPath:i=process.execPath,env:e=process.env}={}){let t=i0(e.npm_execpath);if(t)return t;let r=new Set([t0(i)]);try{r.add(t0(r0(i)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(WR).filter(Boolean))r.add(VR(s));for(let s of r)for(let o of[kd(s,"node_modules","npm","bin","npm-cli.js"),kd(s,"..","lib","node_modules","npm","bin","npm-cli.js"),kd(s,"npm")]){let l=i0(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 n0(i){return{file:process.execPath,args:[$R(),...i]}}import{randomUUID as zR}from"node:crypto";import{mkdir as o0,readFile as KR,rename as Ed,rm as YR,unlink as x$,writeFile as QR}from"node:fs/promises";import{isAbsolute as s0,join as is}from"node:path";var Td=1,JR=1440*6e4,ao=i=>is(i,"pi-web","upgrade"),Id=i=>is(ao(i),"candidate.json"),XR=i=>is(ao(i),"transaction.json"),a0=i=>is(ao(i),"history"),l0=/^[a-f0-9-]{36}$/i;async function ZR(i,e){let t=`${i}.${zR()}.tmp`;try{await QR(t,e,{mode:384}),await Ed(t,i)}finally{await YR(t,{force:!0})}}var eN=(i,e)=>ZR(i,JSON.stringify(e));async function Sd(i,e){await Ed(i,`${i}.${e}-${Date.now()}`).catch(t=>{if(t?.code!=="ENOENT")throw t})}async function c0(i,e,t=()=>!1){let r;try{r=JSON.parse(await KR(i,"utf8"))}catch(n){return n?.code==="ENOENT"||await Sd(i,"invalid"),null}return e(r)?t(r)?(await Sd(i,"expired"),null):r:(await Sd(i,"invalid"),null)}function p0(i){if(!i||typeof i!="object"||i.schema!==Td||!l0.test(i.id??""))return!1;try{Kt(i.version)}catch{return!1}return typeof i.launcher=="string"&&s0(i.launcher)&&typeof i.packageRoot=="string"&&s0(i.packageRoot)&&["stable","alpha"].includes(i.channel)&&typeof i.downgrade=="boolean"&&!Number.isNaN(Date.parse(i.createdAt??""))}async function oo(i,e=Date.now()){return c0(Id(i),p0,t=>e-Date.parse(t.createdAt)>JR)}async function d0(i,e){let t={schema:Td,createdAt:new Date().toISOString(),...e};if(!p0(t))throw new Error("Invalid upgrade candidate");return await o0(ao(i),{recursive:!0,mode:448}),await eN(Id(i),t),t}async function xd(i,e,t){let r=await oo(i);!r||e&&r.id!==e||(await o0(a0(i),{recursive:!0,mode:448}),await Ed(Id(i),is(a0(i),`${r.id}-candidate-${t}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var tN=["selected","committed","rolled-back"];function iN(i){return!!i&&typeof i=="object"&&i.schema===Td&&l0.test(i.id??"")&&tN.includes(i.phase)&&typeof i.version=="string"&&typeof i.from=="string"&&!Number.isNaN(Date.parse(i.updatedAt??""))}async function u0(i){return c0(XR(i),iN)}import{readFile as rN,rename as nN,writeFile as sN,unlink as aN}from"node:fs/promises";import{join as oN}from"node:path";import{randomUUID as lN}from"node:crypto";var Ad=1,m0=i=>oN(i,"pi-web","launcher-handoff.json");function g0(i){return i?.protocol===Ad&&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 Od(i){try{let e=JSON.parse(await rN(m0(i),"utf8"));if(!g0(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 cN(i,e){let t=`${i}.${lN()}.tmp`;try{await sN(t,JSON.stringify(e),{mode:384}),await nN(t,i)}finally{await aN(t).catch(()=>{})}}async function f0(i,e){if(!g0(e))throw new Error("Invalid launcher handoff receipt");await cN(m0(i),e)}import{execFile as pN}from"node:child_process";import{cp as dN,readFile as Rd,realpath as uN,rm as mN}from"node:fs/promises";import{join as Vr,sep as gN}from"node:path";import{promisify as fN}from"node:util";var h0=fN(pN),Nd=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Pd(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 Nd.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 lo(i){return Promise.all(Nd.map(async e=>{let t=await jr(i,e),r=JSON.parse(await Rd(Vr(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 y0(i,e){let t=JSON.parse(await Rd(Vr(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 lo(i):Pd(t.peerDependencies);if(JSON.stringify(await lo(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 jr(i,"node-pty"),s=await jr(e,"node-pty"),o=await uN(Vr(e,"../.."));if(n===s||!s.startsWith(o+gN))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 Rd(Vr(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 mN(s,{recursive:!0,force:!0}),await dN(n,s,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await h0(process.execPath,[Vr(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await jr(e,Nd[0]),{stdout:p}=await h0(process.execPath,[Vr(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 _0,readdir as v0,readFile as hN,realpath as b0,rm as yN}from"node:fs/promises";import{join as rs,relative as bN,sep as w0}from"node:path";var _N=1440*6e4,vN=1024*1024,wN=4,kN=i=>i==="releases"||i==="history"||i.endsWith("-history");async function SN(i,e){let t=new Set,r=[...new Set(e.flatMap(o=>[o+w0,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 v0(o,{withFileTypes:!0}).catch(()=>[]);for(let c of a){let p=rs(o,c.name);if(c.isDirectory()){l<wN&&!kN(c.name)&&await s(p,l+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await _0(p)).size>vN)continue;n(JSON.parse(await hN(p,"utf8")))}catch{}}};return await s(i,0),t}async function k0(i){let e=rs(i.agentDir,"pi-web"),t;try{t=await b0(rs(e,"releases"))}catch{return[]}let r=i.now??Date.now(),n=i.graceMs??_N,s=await SN(e,[rs(e,"releases"),t]);try{let l=bN(t,await b0(i.packageRoot));l&&!l.startsWith("..")&&s.add(l.split(w0)[0])}catch{}let o=[];for(let l of await v0(t,{withFileTypes:!0}).catch(()=>[])){if(!l.isDirectory()||s.has(l.name))continue;let a=rs(t,l.name);try{if(r-(await _0(a)).mtimeMs<n)continue;await yN(a,{recursive:!0,force:!0}),o.push(l.name)}catch{}}return o}var ON=AN(EN),$r=i=>["committed","cancelled","failed"].includes(i);function x0(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 RN(i,e){try{let t=n0(i),{stdout:r}=await ON(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 co=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??RN,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 lo(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Pd(s)},this.verifyPackage=e.verifyPackage??y0,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"?Ad: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&&!$r(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 Li(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 Od(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 Li(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 f0(this.agentDir,p),c=!0}catch(d){let g=await Od(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 Li(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&&!$r(e.phase)?[]:k0({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),t=await this.transaction();if(!t||$r(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 u0(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 xd(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 pt(this.transactionPath)}catch{return await no(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 no(this.transactionPath),null):e:null}async record(e){if(await ns(Oe(this.agentDir,"pi-web"),{recursive:!0}),await ye(this.transactionPath,e),$r(e.phase)){let t=Oe(this.agentDir,"pi-web","update-history");await ns(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 oo(this.agentDir);t&&(!e||t.id===e.id)&&await xd(this.agentDir,t.id,"cancelled"),e&&!$r(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 Li(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}.${Cd()}.tmp`;try{await ns(Oe(this.agentDir,"pi-web"),{recursive:!0}),await I0(t,JSON.stringify({channel:e}),{mode:384}),await E0(t,this.preferencePath)}finally{this.savingPreference=!1,await T0(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=S0(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&&!$r(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||!ow(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(!Va(a.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ct(a.alpha,c)>0&&(c=a.alpha)}if(n.latest=c,n.downgrade=ct(c,e)<0,n.available=t==="stable"?ct(c,e)!==0:ct(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&&ct(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(S0(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 ns(r,{recursive:!0});let n=await IN(Oe(await xN(r),`${t.latest}-`)),s=Oe(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:Cd(),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 Li(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 Li(Oe(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&x0(c)!==x0(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=>TN(g))),this.desktopManaged&&(await Xp(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 d0(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 T0(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 oo(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 Li(o,"utf8"))?.nonce!==this.launcherNonce){let c=Oe(this.agentDir,"pi-web","restart-history");await ns(c,{recursive:!0,mode:448}),await E0(o,Oe(c,`stale-${Cd()}.json`))}}catch{}try{await I0(o,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(a){try{let c=JSON.parse(await Li(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 uk,randomUUID as PP}from"node:crypto";import{randomUUID as oP}from"node:crypto";import{join as Kd}from"node:path";import{randomUUID as R0}from"node:crypto";import{randomUUID as NN}from"node:crypto";function A0(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_${NN().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 PN;function O0(){return PN??=CN().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function CN(){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,f=!1,v=!1;try{let y=(q,B,N)=>({name:q,label:q,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:[q=>{q.on("tool_call",B=>{if(B.toolName==="__contract_direct"&&(f=!!B.parentToolCallId),B.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let B of["hidden","model-only"])q.registerTool(y(`__contract_${B.replace("-","_")}`,B,async()=>(g++,S())));q.registerTool(y("__contract_protected","direct",async()=>(g++,S()))),q.registerTool(y("__contract_direct","direct",async()=>(d++,S()))),q.registerTool(y("__contract_driver","direct",async(B,N,w,h,M)=>{let Z=await M.executeTool("__contract_hidden",{}),re=await M.executeTool("__contract_model_only",{}),ae=await M.executeTool("__contract_direct",{}),P=await M.executeTool("__contract_protected",{});return(!Z.isError||!re.isError)&&p.push("nested-tool-exposure"),(ae.isError||d!==1)&&p.push("nested-tool-execution"),(!P.isError||g!==0)&&p.push("nested-tool-permission-guard"),f||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 A=c.modelRuntime.getModels("openai")[0];if(!A)return{supported:!1,missing:["sdk-model-contract"]};await c.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await c.setModel(A);let x=0;c.agent.streamFunction=async q=>{let B=x++===0,N={role:"assistant",api:q.api,provider:q.provider,model:q.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}}},w=r();return w.push({type:"start",partial:N}),w.push({type:"done",reason:B?"toolUse":"stop",message:N}),w.end(N),w};let C;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((q,B)=>{C=setTimeout(()=>B(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(C)}return v||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(a,{recursive:!0,force:!0})}}var po=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??=O0().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=A0(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:R0(),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:DN};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:R0(),scope:t,kind:"action",action:r,input:n},s)}};async function DN(){throw new Error("Hosted tool unavailable")}import{randomBytes as D1,randomUUID as M1,timingSafeEqual as L1}from"node:crypto";import{join as kt}from"node:path";var MN=30,N0=/^[a-z][a-z0-9-]{0,63}$/,LN=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,ss=i=>{throw new b("invalid_package",i)},Dd=(i,e)=>i===void 0?[]:!Array.isArray(i)||i.length>32?ss(`Invalid ${e} declaration`):i;function zr(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")?Dd(e.secrets,"secrets").map(l=>{let a=l?.name;return typeof a=="string"&&N0.test(a)?a:ss("Invalid secret name")}):[],n=e.network,s=t.has("network")?Dd(n?.hosts,"network").map(l=>typeof l=="string"&&LN.test(l)?l:ss("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Dd(e.schedules,"schedules").map(l=>{let a=l;return!a||typeof a.id!="string"||!N0.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<MN||a.intervalSec>86400?ss("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(l=>l.id)).size!==o.length&&ss("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:o,sessions:t.has("sessions")}}import{lookup as UN}from"node:dns/promises";import{isIP as qN}from"node:net";var jN=new Set(["GET","POST","PATCH","PUT","DELETE"]),BN=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),FN=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),uo=(i,e)=>{throw new b("network_denied",i,{status:403,reason:e})};function HN(i){let e=i.toLowerCase().replace(/^::ffff:/,"");if(qN(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 P0(i,e,t,r,n){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new b("invalid_input","Invalid network request");let o;try{o=new URL(s.url)}catch{throw new b("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&uo("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||uo("Host is not declared by the plugin","host");let l=(s.method??"GET").toUpperCase();if(!jN.has(l))throw new b("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new b("invalid_input","Invalid body");let a={};for(let[A,x]of Object.entries(s.headers??{})){if(typeof x!="string"||BN.has(A.toLowerCase())||!/^[\w-]{1,64}$/.test(A)||/[\r\n]/.test(x))throw new b("invalid_input",`Header not allowed: ${A.slice(0,64)}`);a[A]=x}let c=null;if(s.secret!==void 0){if(t.includes(s.secret)||uo("Secret is not declared by the plugin","secret"),c=await n.secrets.get(i,s.secret),!c)throw new b("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${c}`}let p=await(n.resolve??(async A=>(await UN(A,{all:!0})).map(x=>x.address)))(o.hostname);(!p.length||p.some(HN))&&uo("Host resolves to a non-public address","address");let d=n.timeoutMs??2e4,g=n.maxResponseBytes??2*1024*1024,f=await(n.fetch??fetch)(o,{method:l,headers:a,body:s.body,redirect:"manual",signal:AbortSignal.timeout(d)}),v=[],y=0;if(f.body)for await(let A of f.body){if(y+=A.byteLength,y>g)throw new b("response_too_large","Network response exceeds limit",{status:502});v.push(Buffer.from(A))}let S=Buffer.concat(v).toString("utf8"),T={};return f.headers.forEach((A,x)=>{FN.has(x.toLowerCase())&&(T[x.toLowerCase()]=A)}),c&&(S=S.split(c).join("[redacted]")),{status:f.status,headers:T,body:S}}var mo=(i,e,t)=>{if(typeof i!="string"||!i||i.length>e)throw new b("invalid_input",`Invalid ${t}`);return i};async function C0(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 b("invalid_input","Plugin sessions must start in plan mode");if(i.activeCount(e)>=s)throw new b("quota_exceeded","Too many active plugin sessions",{status:429});return i.create({pluginId:e,cwd:t,title:mo(o.title,200,"title"),prompt:mo(o.prompt,64*1024,"prompt"),mode:"plan"})}let l=mo(o.sessionId,200,"sessionId");if(i.ownerOf(l)!==e)throw new b("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 b("invalid_input","Invalid mode");return await i.send(l,mo(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 b("method_denied","Unknown sessions method")}}var GN=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),go=class{options;constructor(e){this.options=e}handles(e){return GN.has(e)}async call(e,t,r,n,s){let o=zr(t);if(n==="network.fetch"){if(!o.networkHosts.length)throw new b("capability_denied","Plugin did not declare network access",{status:403});return P0(e,o.networkHosts,o.secrets,s,this.options)}if(!o.sessions||!this.options.sessions)throw new b("capability_denied","Sessions capability is unavailable",{status:403});return C0(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var fo=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 Fd,timingSafeEqual as d1}from"node:crypto";import{lstat as W0,mkdtemp as Bd,readdir as u1,readFile as m1,realpath as g1,rename as f1,rm as Ui,writeFile as h1}from"node:fs/promises";import{tmpdir as y1}from"node:os";import{join as Ie}from"node:path";import{gunzipSync as QN}from"node:zlib";import{mkdir as JN,writeFile as XN}from"node:fs/promises";import{dirname as ZN,join as e1}from"node:path";import{constants as Md}from"node:fs";import{lstat as L0,open as WN,readdir as D0,realpath as U0}from"node:fs/promises";import{createHash as VN}from"node:crypto";import{join as q0,relative as $N,resolve as zN,sep as KN}from"node:path";var Re={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},YN={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"]},Te=i=>VN("sha256").update(i).digest("hex");function Ee(i){throw new b("invalid_package",i)}async function lr(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=q0(n,r[l]);let a=await L0(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 U0(n);(s!==zN(i,e)||$N(i,s).startsWith(`..${KN}`))&&Ee("Resource escapes package root");let o=await WN(n,Md.O_RDONLY|Md.O_NONBLOCK|(Md.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 M0(i){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{return Ee("Invalid package JSON")}}async function cr(i,e){let t=await U0(i);(await L0(i)).isSymbolicLink()&&Ee("Package root cannot be a symlink");let r=M0(await lr(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"),Ci(r.piWebapp)||Ee("Unsupported hosted manifest"),r.type!=="module"&&Ee("Hosted package must declare ESM module type");for(let d of await D0(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=M0(await lr(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,f={...g,path:typeof g.path=="string"&&g.path.startsWith("./")?g.path.slice(2):g.path};(!sr(`./${f.path}`)||typeof f.sha256!="string"||!/^[a-f0-9]{64}$/.test(f.sha256)||!Number.isSafeInteger(f.bytes)||f.bytes<0||o.has(f.path))&&Ee("Invalid or duplicate resource");let v=f.path.split(".").at(-1);YN[v]?.includes(f.mime)||Ee("Unsupported resource MIME");let y=v==="js"||v==="mjs"?Re.js:v==="css"?Re.css:v==="woff"||v==="woff2"?Re.font:Re.other;(f.bytes>y||(l+=f.bytes)>Re.total)&&Ee("Resource budget exceeded");let S=await lr(t,f.path,y);(S.length!==f.bytes||Te(S)!==f.sha256)&&Ee("Resource integrity mismatch"),o.set(f.path,Object.freeze({...f}))}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 f of await D0(q0(t,d),{withFileTypes:!0})){++a>Re.files*2&&Ee("Too many package entries");let v=`${d}/${f.name}`;(f.isSymbolicLink()||!f.isDirectory()&&!f.isFile())&&Ee("Invalid archive member"),f.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 j0(i,e,t){if(t!==i.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!sr(`./${r}`))return null;let n=i.resources.get(r);if(!n||r===i.manifest.backend.entry.slice(2))return null;let s=await lr(i.root,r,n.bytes);if(s.length!==n.bytes||Te(s)!==n.sha256)throw new b("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:n.mime}}var ho=64*1024*1024,t1=Re.total+Re.files*2048,ke=i=>{throw new b("invalid_archive",i)};function Kr(i){let e=i.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?i:i.subarray(0,e))}catch{return ke("Archive has invalid UTF-8 paths")}}function B0(i){let e=Kr(i).trim();if(!/^[0-7]+$/.test(e))return ke("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:ke("Archive number exceeds limits")}function i1(i){let e=i.endsWith("/")?i.slice(0,-1):i;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return ke("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))?ke("Archive path is not a safe relative package path"):t}function r1(i){let e={},t=0;for(;t<i.length;){let r=i.indexOf(32,t);if(r<0)return ke("Invalid PAX header");let n=i.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(n))return ke("Invalid PAX record length");let s=Number(n),o=t+s;if(o>i.length||o<=r+2||i[o-1]!==10)return ke("Truncated PAX record");let l=Kr(i.subarray(r+1,o-1)),a=l.indexOf("=");if(a<1)return ke("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 ke("Unsupported PAX feature");e[c]=p,t=o}return e}function n1(i){if(!i.length||i.length>ho)return ke("Compressed archive exceeds budget");let e;try{e=QN(i,{maxOutputLength:t1})}catch{return ke("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(C=>C===0)){if(a||e.subarray(n).some(C=>C!==0))return ke("Unexpected archive data after end marker");c=!0;break}if(++l>Re.files*2)return ke("Too many archive headers");let g=0;for(let C=0;C<512;C++)g+=C>=148&&C<156?32:d[C];if(B0(d.subarray(148,156))!==g)return ke("Invalid tar header checksum");let f=Kr(d.subarray(257,263));if(f&&f!=="ustar"&&f!=="ustar ")return ke("Unsupported tar format");let v=d[156],y=Kr(d.subarray(345,500)),S=(y?y+"/":"")+Kr(d.subarray(0,100)),T=B0(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 ke("Invalid PAX size");T=Number(a.size)}if(!Number.isSafeInteger(T)||T<0||T>Re.total||n+T>e.length)return ke("Truncated or oversized tar member");let A=e.subarray(n,n+T);if(n+=Math.ceil(T/512)*512,v===120){if(a||T>8192)return ke("Oversized or chained PAX header");a=r1(A);continue}if(a=null,v!==0&&v!==48&&v!==53)return ke("Links and special archive members are forbidden");let x=v===53;if(x&&T!==0||Kr(d.subarray(157,257)))return ke("Invalid archive link or directory");if(S=i1(S),!S&&!x)return ke("Invalid package root member");if(r.has(S))return ke("Duplicate archive member");if(r.add(S),++s>Re.files||(o+=T)>Re.total)return ke("Unpacked archive exceeds budget");t.push({path:S,data:A,directory:x})}if(!c||!r.has("package.json"))return ke("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 f=1;f<g.length;f++)if(p.has(g.slice(0,f).join("/")))return ke("Archive file/directory collision")}return t}async function Ld(i,e){let t=n1(i);for(let r of t){if(!r.path)continue;let n=e1(e,r.path);await JN(r.directory?n:ZN(n),{recursive:!0,mode:448}),r.directory||await XN(n,r.data,{flag:"wx",mode:384})}}import{lstat as s1,mkdir as a1,readdir as o1,realpath as l1,writeFile as c1}from"node:fs/promises";import{dirname as p1,join as Ud}from"node:path";async function F0(i,e){let t=await l1(i),r=await lr(t,"package.json",Re.other),n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new b("invalid_package","package.json is not valid JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new b("invalid_package","package.json must be an object");let s=[],o=0,l=0;async function a(g,f){if(f>16)throw new b("invalid_package","Package directory nesting limit exceeded");for(let v of await o1(Ud(t,g),{withFileTypes:!0})){let y=`${g}/${v.name}`;if(++o>Re.files)throw new b("invalid_package","Too many package entries");if(v.isDirectory()){await a(y,f+1);continue}if(!v.isFile())throw new b("invalid_package",`Links and non-regular files are forbidden: ${y}`);let S=await lr(t,y,Re.js);if((l+=S.length)>Re.total)throw new b("invalid_package","Resource budget exceeded");let T=Ud(e,y);await a1(p1(T),{recursive:!0,mode:448}),await c1(T,S,{flag:"wx",mode:384}),s.push([y,Te(S)])}}let c;try{c=await s1(Ud(t,"dist"))}catch(g){throw g.code==="ENOENT"?new b("dist_missing","dist/ does not exist yet; build the plugin first"):g}if(!c.isDirectory())throw new b("invalid_package","dist must be a real directory");await a("dist",0);let{version:p,...d}=n;return s.sort((g,f)=>g[0].localeCompare(f[0])),{contentHash:Te(JSON.stringify({package:d,files:s})),packageJson:n}}function vt(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=vt(i),r=vt(e);if(!t||!r)throw new b("invalid_version","Only exact stable semantic versions are supported");return t.major-r.major||t.minor-r.minor||t.patch-r.patch}function H0(i){let e=vt(i);if(e)return e;if(!Va(i))return null;let[t,r]=i.split("-alpha."),n=vt(t),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function qd(i){return!!H0(i)}function Yr(i,e){if(!qd(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&&H0(a[2]);if(!a||!c)return!1;let p=a[2],d=ct(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&&ct(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&&ct(i,`${g}-0`)<0;break}}}r.push(o)}return r.some(Boolean)}var wt=Object.freeze([Object.freeze({id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"]})]);function dt(i,e=wt){let t=e.find(r=>r.id===i);if(!t)throw new b("unknown_plugin","Plugin is not in the trusted official catalog");return t}function jd(i,e,t){let r=i.piWebapp;return i.name===e.id&&!!vt(i.version)&&!i.deprecated&&Ci(r)&&Yr(t,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function G0(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 b("registry_invalid","Invalid registry version catalog");let s=Object.entries(i.versions);if(s.length>1e4)throw new b("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&&jd(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 b("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 b("registry_invalid","Release is missing its immutable tarball integrity");return l}function b1(i,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new b("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(t[1],"base64"),n=Fd("sha512").update(i).digest();if(r.length!==n.length||!d1(r,n))throw new b("integrity_mismatch","Downloaded package failed integrity verification")}var Qr=class{root;hostVersion;catalog;fetcher;constructor(e){if(!qd(e.hostVersion))throw new b("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??wt,this.fetcher=e.fetch??Bw}async index(){let e=await Ue(Ie(this.root,"installed.json"));if(!e){if(await Pe(Ie(this.root,"installed.json"),2*1024*1024))throw new b("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 b("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 b("invalid_storage","Invalid installed version list");for(let n of r)this.validateRecord(t,n)}return e}validateRecord(e,t){if(!t||!vt(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 b("invalid_storage","Invalid installed plugin record")}path(e){return Ie(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await pt(Ie(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(s=>!["schema","pluginId","next"].includes(s)))throw new b("invalid_storage","Invalid install journal");dt(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 b("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 u1(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await W0(Ie(r,n))).isSymbolicLink())throw new b("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 pt(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 b("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");dt(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 b("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 dt(e,this.catalog),qe(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 qe(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 b("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 b("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 b("registry_unreachable",d instanceof Error?d.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new b(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 b("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 b("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 b("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 b?d:new b("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=dt(e,this.catalog);if(r&&!vt(r))throw new b("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 b("registry_invalid","Invalid registry metadata JSON")}return G0(l,s,this.hostVersion,t,r)}async install(e,t,r){let n=dt(e,this.catalog);if(!jd(t,n,this.hostVersion))throw new b("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(t.dist.tarball,n),ho,r);return this.installArchive(e,s,t.dist.integrity,t.version,r)}async installArchive(e,t,r,n,s){let o=dt(e,this.catalog);if(!vt(n))throw new b("invalid_version","Choose an exact stable version");if(t.length>ho)throw new b("download_too_large","Package archive exceeds budget");return b1(t,r),qe(this.root,async()=>{let l=await this.recoverLocked();s?.throwIfAborted();let a=await Bd(Ie(this.root,"staging","stage-"));try{await Ld(t,a),s?.throwIfAborted();let c=await cr(a,e);if(c.version!==n||!Ci(c.manifest)||!Yr(this.hostVersion,c.manifest.hostRange)||!o.requiredCapabilities.every(p=>c.manifest.capabilities.includes(p)))throw new b("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 b("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 b("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 W0(c),p=!0}catch(d){if(!Ni(d))throw d}if(p){if((await cr(c,e)).digest!==n.digest)throw new b("resource_changed","Installed package content was modified")}else await f1(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 g1(c)}}async installDevArchive(e,t,r){dt(e,this.catalog);let n=await m1(t),s="sha512-"+Fd("sha512").update(n).digest("base64"),o=await Bd(Ie(y1(),"pi-dev-archive-"));try{await Ld(n,o);let l=(await cr(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=dt(e,this.catalog);return qe(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let o=await Bd(Ie(this.root,"staging","stage-"));try{let{contentHash:l,packageJson:a}=await F0(t,o);r?.throwIfAborted();let c=Ie(this.root,"dev-sources.json"),p=await Ue(c)??{},d=p[e],g=s.versions[e]??[],f=d?.contentHash===l?g.find(B=>B.version===d.version):void 0;if(f){let B=await cr(this.path(f),e);if(B.digest!==f.digest)throw new b("resource_changed","Installed package integrity changed");return B}let v=typeof a.version=="string"?vt(a.version):null;if(!v)throw new b("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let y=Math.max(-1,...g.map(B=>vt(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 h1(Ie(o,"package.json"),JSON.stringify({...a,version:T},null,2),{flag:"wx",mode:384});let A=await cr(o,e);if(!Yr(this.hostVersion,A.manifest.hostRange))throw new b("incompatible_plugin",`Package hostRange ${A.manifest.hostRange} does not include host ${this.hostVersion}`);let x=n.requiredCapabilities.filter(B=>!A.manifest.capabilities.includes(B));if(x.length)throw new b("incompatible_plugin",`Package lacks required capabilities: ${x.join(", ")}`);let C="sha512-"+Fd("sha512").update(l).digest("base64"),q=await this.commitStaged(e,s,o,A,C,r);return p[e]={contentHash:l,version:T},await ye(c,p),q}finally{await Ui(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let r=dt(e,this.catalog);return qe(this.root,async()=>{let n=await this.recoverLocked(),s=n.versions[e]?.find(l=>l.version===t);if(!s)throw new b("not_installed","Plugin version is not installed");let o=await cr(this.path(s),e);if(o.digest!==s.digest)throw new b("resource_changed","Installed package integrity changed");if(!Yr(this.hostVersion,o.manifest.hostRange)||!r.requiredCapabilities.every(l=>o.manifest.capabilities.includes(l)))throw new b("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){dt(e,this.catalog),await qe(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 yo,mkdir as _1,open as V0,realpath as $0,readdir as Hd,link as v1,rename as w1,unlink as pr,copyFile as k1,rm as S1}from"node:fs/promises";import{dirname as E1,isAbsolute as z0,join as de,relative as K0,resolve as T1,sep as Gd,win32 as I1}from"node:path";import{randomUUID as Wd}from"node:crypto";var as=192*1024*1024,os=512*1024,Q0=i=>typeof i=="string"&&/^[a-f0-9-]{36}$/.test(i);function x1(i){if(!i||typeof i!="object"||Array.isArray(i))throw new b("invalid_input","Expected object input");return i}function Y0(i){if(typeof i!="string"||!/^[\w.-]{1,160}$/.test(i)||i==="."||i==="..")throw new b("invalid_input","Invalid state key");return i}function ls(i){if(i&&(!Q0(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 b("invalid_storage","Invalid active plugin record");return i}var dr=class{root;pluginId;legacy;checkpoint;constructor(e,t,r,n){this.root=de(e,Te(t)),this.pluginId=t,this.legacy=r,this.checkpoint=n}active(){return Ue(de(this.root,"active.json")).then(ls)}async recover(){return qe(this.root,async()=>{let e=await this.active(),t=await pt(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 b("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");ls(t.next),ls(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 b("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 pt(de(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(l=>["version","stateRef"].includes(l))&&await pr(de(this.root,"fork.json"))}return await pr(de(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,t){return qe(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new b("stale_generation","Plugin activation changed concurrently");let n=await pt(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 b("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=ls({...t,generation:e+1,operationId:Wd()});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 pr(de(this.root,"transition.json")),await pr(de(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return qe(this.root,async()=>{let t=await this.assertGeneration(e,!1),r=Wd(),n=de(this.root,"states",r);if(await pt(de(this.root,"fork.json")))throw new b("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 Hd(s)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new b("invalid_storage","Unexpected state file");if(!await Pe(de(s,o),as))throw new b("invalid_storage","Missing state file");await k1(de(s,o),de(n,o))}return await this.checkpoint?.("forked"),r})}async collect(e){return qe(this.root,async()=>{for(let c of["transition.json","fork.json"])if(await Pe(de(this.root,c),2*1024*1024))throw new b("gc_recovery_required",`GC refused: unresolved ${c}; stop all owners and inspect recovery references`);let t=await this.active(),r=ls(await pt(de(this.root,"previous.json")));if(!t&&await Pe(de(this.root,"active.json"),2*1024*1024))throw new b("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 Hd(s),l=new Set(n.map(c=>c.stateRef));for(let c of o){if(!Q0(c))throw new b("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=de(s,c),d=await yo(p);if(!d.isDirectory()||d.isSymbolicLink())throw new b("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let g of await Hd(p)){let f=await yo(de(p,g));if(!/^[a-f0-9]{64}\.json$/.test(g)||!f.isFile()||f.isSymbolicLink()||f.nlink!==1)throw new b("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!l.has(c)){let v=await Ue(de(p,g),as);if(!v)throw new b("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 b("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 b("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 b("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 S1(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 b("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 b("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 b("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 b("invalid_lease","Invalid invocation lease");this.scopeKey(e);let n=x1(r);return qe(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await Ue(this.statePath(s,e,Y0(n.key),n.scope),as);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(s,e,Y0(n.key),n.scope);if(!Number.isSafeInteger(n.expectedRevision)||n.expectedRevision<0||n.schema!==s.schema||!Object.hasOwn(n,"value"))throw new b("invalid_input","Invalid state revision or schema");if(JSON.stringify(n.value)===void 0)throw new b("invalid_input","State value must be JSON serializable");let l=JSON.stringify(n);if(Buffer.byteLength(l)>as)throw new b("state_too_large","Plugin state exceeds limit");let a=await Ue(o,as);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 b("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{target:o}=await this.fileTarget(e.scope.cwd,n.path),l=n.maxBytes===void 0?os:n.maxBytes;if(!Number.isSafeInteger(l)||l<=0||l>os)throw new b("invalid_input","Invalid workspace read limit");let a=await Pe(o,l);return a?{text:new TextDecoder("utf-8",{fatal:!0}).decode(a),hash:Te(a)}:null}case"workspace.commit":return this.commitFile(s,e,n);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new b("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 b("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,r=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||z0(t)||I1.isAbsolute(t))throw new b("invalid_path","Use a workspace-relative .excalidraw path");let n=await $0(e),s=T1(n,t),o=K0(n,s);if(!o||o===".."||o.startsWith(`..${Gd}`)||z0(o))throw new b("invalid_path","Workspace path escapes root");let l=n,a=o.split(Gd);for(let p=0;p<a.length;p++){l=de(l,a[p]);let d;try{d=await yo(l)}catch(g){if(!Ni(g))throw g;if(p<a.length-1){if(!r||K0(n,l)!=="diagrams")throw new b("invalid_path","Workspace directory does not exist");try{await _1(l,{mode:448})}catch(f){if(f.code!=="EEXIST")throw f}d=await yo(l)}}if(d&&(d.isSymbolicLink()||(p<a.length-1?!d.isDirectory():!d.isFile()||d.nlink!==1)))throw new b("invalid_path","Workspace path contains a link or non-regular file")}let c=await $0(E1(s));if(c!==n&&!c.startsWith(n+Gd))throw new b("invalid_path","Workspace directory changed");return{target:s,parent:c}}async commitFile(e,t,r){if(typeof r.text!="string"||Buffer.byteLength(r.text)>os||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new b("invalid_input","Invalid file content or expected hash");let{target:n,parent:s}=await this.fileTarget(t.scope.cwd,r.path,!0),o=de(this.root,"states",e.stateRef,`${Te(this.scopeKey(t)+":file:"+t.requestId+":"+String(r.path))}.json`),l=Te(JSON.stringify(r)),a=Te(r.text),c=await Ue(o);if(c&&(c.requestId!==t.requestId||c.inputHash!==l||c.nextHash!==a))throw new b("duplicate_request","Request ID was reused with different content");let p;try{p=await V0(`${n}.lock`,"wx",384)}catch(g){throw g.code==="EEXIST"?new b("file_busy","Workspace file is locked; original file preserved"):g}let d;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let g=await Pe(n,os),f=g?Te(g):null;if(c&&f===a)return{hash:a};if(c?.committed||f!==r.expectedHash)throw new b("file_conflict","Workspace file already exists or changed externally");await ye(o,{requestId:t.requestId,inputHash:l,nextHash:a,committed:!1}),d=de(s,`.plugin-${Wd()}.tmp`);let v=await V0(d,"wx",384);try{await v.writeFile(r.text),await v.sync()}finally{await v.close()}if((await this.fileTarget(t.scope.cwd,r.path)).parent!==s)throw new b("file_conflict","Workspace directory changed during save");let S=await Pe(n,os);if((S?Te(S):null)!==r.expectedHash)throw new b("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),r.expectedHash===null){try{await v1(d,n)}catch(T){throw T.code==="EEXIST"?new b("file_conflict","Workspace file was created concurrently"):T}await pr(d),d=void 0}else await w1(d,n),d=void 0;return await ye(o,{requestId:t.requestId,inputHash:l,nextHash:a,committed:!0}),{hash:a}}finally{d&&await pr(d).catch(()=>{}),await p.close(),await pr(`${n}.lock`)}}};import{randomUUID as P1}from"node:crypto";import{fork as A1}from"node:child_process";import{randomUUID as O1}from"node:crypto";import{join as R1}from"node:path";import{EventEmitter as N1}from"node:events";var J0=192*1024*1024,cs=class i{child;pending=new Map;events=new N1;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=A1(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 b("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:R1(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 b("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 b("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>J0){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 b(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 b("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 b("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new b("worker_busy","Too many plugin requests"));let s=n?.requestId??O1();if(this.pending.has(s))return Promise.reject(new b("duplicate_request","An identical request is still running"));let o={type:"request",id:s,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>J0?Promise.reject(new b("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 b("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 b("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 b("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 C1={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},bo=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,r=C1,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 yd(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 b("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 b("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 b("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 b("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 b("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 cs.start(e,n+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(t))throw new b("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 b("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new b("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):P1(),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 b("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await cs.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 b("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 b("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 b("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 b("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new b("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 b("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new b("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 X0}from"node:fs/promises";var _o=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 Qr({root:kt(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new go(e.capabilities):void 0;this.scheduler=new fo({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:M1(),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 dr(kt(e.root,"data"),r.id,e.legacy?.(r.id)),s=e.hooks(r.id);this.supervisors.set(r.id,new bo(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,D1(24).toString("base64url"));try{this.scheduler.start(r.id,zr(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?n=>this.installer.installDevDirectory(e,t,n):r?n=>this.installer.installDevArchive(e,r,n):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){dt(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new b("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new b("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 Ue(kt(this.options.root,"policies","policies.json"));if(!e){if(await Pe(kt(this.options.root,"policies","policies.json"),2*1024*1024))throw new b("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 b("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await Ue(kt(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await qe(kt(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await ye(kt(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 b("invalid_input","Invalid plugin update policy");await qe(kt(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await ye(kt(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return qe(ro(this.options.root),async()=>{let e=await vd(this.options.root);if(!e)return{intent:e,admitted:!1};if(!wd(e))return e.phase==="required-action"&&await so(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await _d(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await _d(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await X0(this.options.workerEntry)).equals(await X0(kt(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(t){return await so(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 so(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 qe(kt(this.options.root,"policies"),async()=>{let t=await this.policies();await ye(kt(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:!0,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 b("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 b("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 f=await this.lifecycle(e,()=>s.replace(g));return f.pending||this.packages.set(e,g),f}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 b("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 b("stale_generation","Reconnect the plugin view before editing",{status:409})):n.invoke(r)}flush(e,t,r){let n=this.supervisor(e);return t!==n.generation?Promise.reject(new b("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 j0(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]);return!n||s.length!==Buffer.byteLength(n)||!L1(s,Buffer.from(n))?null:this.asset(r,t[3],t[4])}async reconcileHostUpgrade(){if(e0(await vd(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 Qr({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 Qr({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());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let t=[],r=async()=>{let 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 U1}from"node:crypto";var oe=i=>Object.assign(new Error(i),{status:409,code:"view_barrier"}),ps=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)));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??U1();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(r=>r.activeActions||r.kind!=="controller"&&!r.frozen&&(r.busy||!this.immediate&&["editor","workspace"].includes(r.kind)));throw oe(`Close editors before updating; old version retained. Pending views: ${t.map(r=>`${r.kind}:${r.identity.mountId}${r.activeActions?` (action in flight x${r.activeActions})`:r.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,r)=>{let 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 q1="@chengzhiyi/pi-excalidraw",j1={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"}}},B1="@chengzhiyi/pi-github",F1={tools:{},readonlyActions:[],actions:["get","configure","pickup","sync","cancel","approve","reject","answer","remove"],checkpointActions:["get"],contribution:{entry:{label:"GitHub",description:{zh:"GitHub \u4EFB\u52A1",en:"GitHub tasks"},kind:"workspace"},panels:["workspace"],artifactTools:[],toolViews:[],panelAlias:{prefix:"github:",kind:"workspace",title:"GitHub"}}},Z0=new Map([[q1,j1],[B1,F1]]);function Vd(i,e){let t=i.get(e);if(!t)throw new b("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as H1}from"node:crypto";var G1="https://github.com/settings/personal-access-tokens/new?"+new URLSearchParams({name:"pi-webapp",description:"pi-webapp GitHub plugin",issues:"write",pull_requests:"write",contents:"write"}),W1="Ov23limJmKiuu8cOP83E";function $d(i,e,t=process.env){if(i==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||W1,scope:"repo",createUrl:G1}}var V1="https://github.com/login/device/code",$1="https://github.com/login/oauth/access_token",z1=8,vo=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 b("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 b("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return n}async start(e,t,r){if(!r.clientId)throw new b("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>=z1)throw new b("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(V1,{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 b("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=H1();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($1,{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 tk,readFileSync as ik,statSync as K1}from"node:fs";import{lstat as Y1,readdir as Q1,writeFile as J1,mkdir as X1,rename as Z1}from"node:fs/promises";import{delimiter as eP,dirname as tP,isAbsolute as iP,join as ur,resolve as ds}from"node:path";var ek="@chengzhiyi/pi-github",So={[ek]:{id:ek,name:"GitHub",icon:"github",description:{zh:"\u628A GitHub issue \u4EA4\u7ED9 agent\uFF1A\u5148\u51FA\u65B9\u6848\uFF0C\u7ECF\u4F60\u6279\u51C6\u540E\u5B9E\u73B0\u5E76\u63D0\u4EA4\u8349\u7A3F PR\u3002",en:"Hand GitHub issues to an agent: it plans, you approve, then it implements and opens a draft PR."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","panels","scheduler","network","secrets","sessions"]}},rk=i=>wt.some(e=>e.id===i),zd=i=>!!So[i]||rk(i),nk=()=>[...Object.keys(So),...wt.map(i=>i.id)].join(", ");function rP(i=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,r=[],n="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let s of(i??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=s.lastIndexOf("="),l=s.slice(0,o),a=s.slice(o+1),c=So[l],p=o<1?`entry "${s}" is not <id>=<path.tgz>`:zd(l)?a.endsWith(".tgz")?tk(ds(a))?null:`archive not found: ${ds(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${l}" (known: ${nk()})`;if(p){r.push({level:"error",source:n,...zd(l)?{pluginId:l}:{},message:p});continue}c&&e.push(c),t.set(l,ds(a))}return{catalog:e,archives:t,notices:r}}var sk=i=>ur(i,"pi-web","hosted-dev.json"),ak=i=>ur(i,"pi-web","hosted-dev-status.json");function nP(i,e,t=process.cwd()){let r=[],n=[],s=(i.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(eP).map(l=>l.trim()).filter(Boolean);for(let l of s)r.push({path:ds(t,l),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=s.length>0;if(e&&tk(e)){o=!0;try{let l=JSON.parse(ik(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"||!iP(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:ds(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 sP(i){let e=(n,s)=>({notice:{level:"error",source:i.source,...s?{pluginId:s}:{},message:`${i.path}: ${n}`}}),t;try{t=K1(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(ik(ur(i.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof r.name!="string"?e("package.json has no name"):zd(r.name)?Ci(r.piWebapp)?{pluginId:r.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name):e(`unknown plugin id "${r.name}" (known: ${nk()})`)}var wo=class{catalog;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let t=rP(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.catalog=[...t.catalog],this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let t=nP(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let o of t.specs){let l=sP(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`}),!rk(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}this.catalog.push(So[a])}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]}},ko=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 aP(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}s===n.applied||this.stopped||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){this.set(e,t,"switching");try{let s=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=r,s?.installed?s.pendingVersion?this.set(e,t,"pending",{version:s.version,message:`Waiting for editors to close before switching to ${s.pendingVersion}`}):this.set(e,t,"synced",{version:s.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(n){let s=Ne(n);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(s.code)||(t.applied=r),s.code==="not_installed"?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:s.code,message:`${s.message} (${s.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let 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 X1(tP(r),{recursive:!0}),await J1(o,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await Z1(o,r)}catch{}}};async function aP(i){let e=[],t=async(r,n)=>{let s=await Y1(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await t(ur(i,"package.json"),"package.json");let r=async(n,s,o)=>{if(!(o>16||e.length>8192))for(let l of(await Q1(n,{withFileTypes:!0})).sort((a,c)=>a.name.localeCompare(c.name)))l.isDirectory()?await r(ur(n,l.name),`${s}/${l.name}`,o+1):await t(ur(n,l.name),`${s}/${l.name}`)};if(await r(ur(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 lP(i){try{return[...zr(i).secrets]}catch{return[]}}var Eo=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new vo;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Z0,e.dev?.enabled&&(this.devWatcher=new ko({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}}})),this.adapter=new po({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 b("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,s.generation,r);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new _o({...e,lifecycle:(t,r,n)=>this.lifecycle(t,r,n),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(Vd(this.trusted,t).tools).length)throw new b("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:lP(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 b("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(r))throw new b("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 b("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)?$d(t.pluginId,t.name):void 0;if(!s)throw new b("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 b("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 b("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:t=>this.manager.assetRequest(t)}}verifyTools(e,t){let r=Vd(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 b("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new b("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 b("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 b("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 b("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 b("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 dr(Kd(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new b("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??wt)try{let t=await new dr(Kd(this.options.root,"data"),e.id).active();this.views.set(e.id,new ps(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new ps(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Kd(this.options.root,"host-version.json");(await Ue(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??wt)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=$d(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??wt).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 b("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new b("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 b("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 b("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 b("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 b("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:oP(),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 b("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new b("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 cP,readdir as pP,unlink as dP}from"node:fs/promises";import{join as Jr}from"node:path";import{randomUUID as uP}from"node:crypto";var Yd="hosted-migration.json";function ok(i,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:n}=t.scope,s=Jr(i,Te(JSON.stringify([r,n])));await Le(i),await Le(s);let o=Jr(s,"scope.lock"),l;try{l=await cP(o,"wx",384)}catch(a){throw a.code==="EEXIST"?new b("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:uP()}));let a=await Ue(Jr(s,Yd));if(a&&(a.version!==1||a.pluginId!==e))throw new b("invalid_storage","Legacy scope belongs to another migration");let c=await pP(s),p=[];for(let g of c){if(g==="scope.lock"||g==="focus.json"||g===Yd||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(g))continue;if(!/^[\w-]{1,80}\.json$/.test(g))throw new b("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new b("invalid_storage","Too many legacy checkpoints");let f=await Ue(Jr(s,g),3*512*1024);if(!f||f.version!==1||f.cwd!==r||f.sessionId!==n||!f.draft||g!==`${f.draft.id}.json`)throw new b("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(f.draft)}let d=await Ue(Jr(s,"focus.json"),1024);if(d!==null&&(typeof d!="string"||!p.some(g=>g.id===d)))throw new b("invalid_storage","Invalid legacy focused drawing");return a||await ye(Jr(s,Yd),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:d}}finally{await l.close(),await dP(o)}}}import{join as wP}from"node:path";import{randomUUID as mP}from"node:crypto";var gP=6e4,To=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 b("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new b("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<gP?new b("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:mP(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new b("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 b("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 fP,readFile as hP,rename as yP,writeFile as bP}from"node:fs/promises";import{randomUUID as _P,createHash as vP}from"node:crypto";import{join as lk}from"node:path";var Io=class{dir;queue=Promise.resolve();constructor(e){this.dir=lk(e,"secrets")}file=e=>lk(this.dir,`${vP("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await hP(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!Ni(t))throw new b("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 fP(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${_P()}.tmp`;await bP(n,JSON.stringify(r),{mode:384}),await yP(n,this.file(e))})}};function ck(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 kP="scheduler";function pk(i){let e=new To({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 Io(wP(i.root,"capability-secrets")),sessions:ck(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=i.activeWorkspace();if(!n)return null;try{return i.trustedScope(n,kP)}catch{return null}}}}async function SP(){for(let i of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=Ga(i),t=new zt({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:ln,buildId:It,browser:Ga({}).browser}}async function dk(){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 zt({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:ln,buildId:It}}finally{await i.close()}}var us=en(TP(AP(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),CP=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),m=globalThis[CP]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new Ri(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:ui()}),Ge()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new or,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};m.lifecycle??=new or;m.tuiGeneration??=0;m.stopChanged??=null;m.tuiWaitController??=new AbortController;m.tuiStreaming??=null;m.tuiPrompts??=new Ri(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:ui()}),Ge()});m.tuiPromptSessionId??=null;m.tuiAgentError??=!1;var mk=!1;function DP(i){return mk||(mk=!0,setTimeout(()=>{i.pruneReleases().catch(()=>{})},6e4).unref()),i}function xo(){return m.selected==="sdk"?m.workspaceSessions?.catalog??null:m.tuiCatalog}var MP=null;function LP(){return MP??=OP.create({refreshOnCreate:!1})}var Ao=new Map;async function Zr(){let i=await LP(),e=m.selected==="tui"?m.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Ao.keys())t.has(r)||(i.unregisterProvider(r),Ao.delete(r));for(let r of t){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),o=n??s;!o||Ao.get(r)===o||(n?i.registerNativeProvider(n):s&&i.registerProvider(r,s),Ao.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")})():ui()}function ui(){if(m.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...mw(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 tu(i,e,t,r,n){let s=nt(i);Oi({...ui(),idle:s.isIdle()},e,n);let o=s.isIdle();o&&Wr(()=>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:ui()})}catch(l){throw o&&(m.operation=void 0),l}}function Xd(){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=ui();return!m.hosted?.adapter.isFrozen&&m.current.isIdle()&&!r.paused&&!r.interactions.length};m.tuiPrompts.schedule(t,(r,n,s)=>tu(i,r,n,s))}function Ye(i){if(We().sessionId!==i)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function yk(){let i=(m.workspaces?.list()??[]).map(p=>({...p})),e=m.activeWorkspaceId,t=We(),n=m.current?ui():null,s=await nr(t.cwd).catch(p=>(m.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=n?await nr(n.cwd).catch(p=>(m.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,l=await eu.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 Hr(p.path,l).catch(f=>(f instanceof Jn?p.available=!1:m.bridge?.reportError?.(f,{stage:"workspace_sessions"}),[]))).map(f=>({id:f.id,workspaceId:p.id,path:f.path,name:f.name||f.firstMessage?.slice(0,50)||"",modified:f.modified.toISOString(),idle:!0}));for(let f of a.filter(v=>v.cwd===p.path)){if(f.blank&&f.sessionId!==t.sessionId)continue;let v=g.findIndex(S=>S.id===f.sessionId),y={id:f.sessionId,workspaceId:p.id,path:f.path??g[v]?.path??null,name:f.name,modified:f.modified,idle:f.idle};v<0?g.unshift(y):g[v]=y}return p.path===s&&!g.some(f=>f.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 gk=0;async function Ge(){if(!m.bridge)return;let i=++gk;try{let e=await yk();i===gk&&m.bridge?.publish({type:"workspaces",value:e})}catch(e){m.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function Zd(i,e=!1){let t=m.workspaces?.get(i);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Yt(t.path),!e&&m.current&&t.path===await nr(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 Ge()}async function fk(i,e,t){let r=m.workspaces?.get(i);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await Yt(r.path);if(m.workspaceSessions?.hasSession(n,e)||m.current?.sessionManager.getSessionId()===e&&await nr(m.current.cwd)===n)return r;if(!(await Hr(n)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function nt(i){let e=m.current;if(e===null||e.sessionManager.getSessionId()!==i)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function tt(i){m.current=i,m.selected==="tui"&&m.bridge?.publish({type:"snapshot",session:We()})}function bk(){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 RP.create(i,void 0,{projectTrusted:e})}async function _k(){let i=bk(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),t=new hk({cwd:We().cwd,agentDir:ut(),settingsManager:i}),r=zw(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:i.isProjectTrusted(),global:e(i.getGlobalSettings()),project:e(i.getProjectSettings()),installed:r}}async function UP(i){Ye(i.sessionId);let e=m.selected==="tui"?nt(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=bk();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 hk({cwd:We().cwd,agentDir:ut(),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&&tt(m.current)):(await m.workspaceSessions?.reload(),m.bridge?.publish({type:"plugins_changed"})),await _k()}function Oo(i,e=fd){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=Qd(c);return{cwd:d,sessionId:p,workspaceId:uk("sha256").update(d).digest("hex")}},r=Xr(ut(),"pi-web","hosted"),n=new wo({configPath:sk(ut())});m.hosted??=new Eo({root:r,...n.enabled?{dev:n,devStatusPath:ak(ut())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...wt,...n.catalog]}:{},...pk({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(IP(en(us,"../../package.json"),"utf8")).version,packageRoot:en(us,"../.."),workerEntry:en(us,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${uk("sha256").update(ut()).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:()=>ok(Xr(ut(),"pi-web","diagrams")),changed:()=>m.bridge?.publish({type:"hosted_plugins_changed"})}),m.offHostedThaw?.(),m.offHostedThaw=m.hosted?.adapter.onThaw(Xd),m.pi=i;let s=Nm({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 Qa(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 Gr({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:Jd,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});m.interactions?.dispose(),m.interactions=new Fr(i.events,c=>!!m.bridge&&c.sessionId===m.current?.sessionManager.getSessionId()&&Xn(m.tuiCatalog,c.pluginId),()=>{m.current&&m.selected==="tui"&&tt(m.current)});let l=()=>{m.stopChanged?.(),m.stopChanged=i.events.on(Ja,()=>{m.selected==="tui"&&m.current&&tt(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 Ri(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:ui()}),Ge()}),m.tuiPromptSessionId=p.sessionManager.getSessionId()),m.tuiAgentError=!1,m.bridge){let d=await ar.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),tt(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 Ge())}).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)),tt(p),Ge()}),i.on("agent_end",(c,p)=>tt(p)),i.on("agent_settled",(c,p)=>{m.bridge?.breadcrumb?.("agent_end",o(p)),m.tools?.clear(),m.operation=void 0,m.tuiStreaming=null,Xd(),tt(p),Ge()}),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)=>tt(p)),i.on("thinking_level_select",(c,p)=>tt(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:Jd});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}),tt(p),Ge()}),i.on("session_info_changed",(c,p)=>tt(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:rr(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 zt;try{m.current=c,m.commandContext="newSession"in c?c:null,m.pi=i,m.tuiCatalog=await ar.discover(c.cwd,c.isProjectTrusted?.()??!1),m.workspaces===null&&(m.workspaces=new Ya(yw(ut())),await m.workspaces.load());try{await m.workspaces.discover((await eu.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 zt}if(m.bridge===null){let g=m.workspaceSessions&&(m.workspaceSessions.telemetryVersion!==2||m.workspaceSessions.runtimeVersion!==4)?m.workspaceSessions:null,f=g?.session&&g.path?{path:g.path,sessionManager:g.session.sessionManager}:null;g&&(await g.dispose(),m.workspaceSessions=null),m.workspaceSessions??=new to(y=>{m.selected==="sdk"&&m.bridge?.publish(y)},()=>m.current?.model,y=>{try{return!!m.current&&Qd(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"},()=>{Ge()},s,{adapter:m.hosted.adapter,scope:t}),f&&await m.workspaceSessions.open(f.path,{sessionManager:f.sessionManager});let v={hosted:m.hosted?.handlers,selfUpdate:DP(new co({agentDir:ut(),packageRoot:en(us,"../.."),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(Qd(m.current.cwd))}catch{y.push(m.current.cwd)}return y},plugins:async()=>{let y=xo();return await y?.refreshAssets(),y?.view()??{plugins:[],errors:[]}},pluginAsset:async y=>xo()?.asset(y)??null,async invokePluginAction(y,S,T,A){if(Ye(y),!xo()?.has(S))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let x=m.selected,C=m.tuiGeneration,q=m.workspaceSessions?.session,B={requestId:PP(),sessionId:y,pluginId:S,action:T,input:A},N=m.selected==="sdk"?await m.workspaceSessions.invokePluginAction(B):await Xa(m.pi.events,B,15e3,m.tuiWaitController.signal);if(Ye(y),x!==m.selected||(x==="tui"?C!==m.tuiGeneration:q!==m.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return m.selected==="tui"&&m.current&&tt(m.current),N},async resolvePluginInteraction(y,S,T,A){if(Ye(y),!Xn(xo(),S))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");m.selected==="sdk"?m.workspaceSessions.resolveInteraction(y,S,T,A):m.interactions.resolve(y,S,T,A)},image(y,S,T){Ye(y);let x=(m.selected==="sdk"?m.workspaceSessions?.session?.sessionManager.getBranch():m.current?.sessionManager.getBranch())?.find(q=>q.id===S);if(x?.type!=="message"||x.message.role!=="user"||!Array.isArray(x.message.content))return null;let C=x.message.content[T];return C?.type!=="image"?null:{data:Buffer.from(C.data,"base64"),mimeType:C.mimeType}},async workspaces(){return yk()},async addWorkspace(y,S){let T=await m.workspaces.add(y,S);try{await Zd(T.id,!0)}catch(A){throw await Ge(),A}},async selectWorkspace(y){await Zd(y)},async newSessionInWorkspace(y){await Zd(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 Ge()},async selectSession(y,S,T){let A=m.workspaces?.get(y);if(!A)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Yt(A.path),S===m.current?.sessionManager.getSessionId()&&A.path===await nr(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===A.path)return;if(m.workspaceSessions?.hasSession(A.path,S))await m.workspaceSessions.open(A.path,{sessionId:S});else{if(!(await Hr(A.path)).some(C=>C.id===S&&C.path===T))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await m.workspaceSessions.open(A.path,{sessionFile:T})}m.selected="sdk",m.activeWorkspaceId=y,m.bridge?.publish({type:"snapshot",session:We()})}await Ge()},async renameSession(y,S,T,A){let x=A.replace(/\s+/g," ").trim();if(x.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await fk(y,S,T),m.current?.sessionManager.getSessionId()===S&&m.pi?m.pi.setSessionName(x):m.workspaceSessions?.rename(S,x)||eu.open(T).appendSessionInfo(x),m.selected==="tui"&&m.current?.sessionManager.getSessionId()===S&&m.bridge?.publish({type:"snapshot",session:We()}),await Ge()},async deleteSession(y,S,T){let A=await fk(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,C=x?.path??(T||null);C&&await $w(C,ut()),x?.wasActive&&m.selected==="sdk"&&(await m.workspaceSessions.open(A.path,"new"),m.selected="sdk",m.activeWorkspaceId=y,m.bridge?.publish({type:"snapshot",session:We()})),await Ge()},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 Zr(),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(A=>A!==null)}))},async providerModels(y){let S=await Zr();return Xm(Xr(ut(),"models.json"),y,S)},async updateProviderModel(y,S,T){if(Ye(y),m.selected==="tui"?!nt(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 A=We().model;if(T.action==="remove"&&A===`${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&&A===`${S}/${T.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let x=await Zr();await Zm(Xr(ut(),"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 C=T.action==="save"?T.model.id:T.action==="base_url"&&A?.startsWith(`${S}/`)?A.slice(S.length+1):null;if(C&&A===`${S}/${C}`)if(m.selected==="sdk")try{await m.workspaceSessions.setModel(S,C)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let q=nt(y),B=q.modelRegistry.find(S,C);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");tt(q)}},async logoutProvider(y,S){if(Ye(y),m.selected==="tui"?!nt(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 Zr();if(!(await T.listCredentials()).some(A=>A.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 A=await Zr();await A.login(y,S,$m(y,S,T)),await A.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(Ye(y),m.selected==="tui"?!nt(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 Zr();if(T.getProvider(S.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await zm(Xr(ut(),"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(Ye(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=nt(y);if(!S.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");S.compact()},async setModel(y,S,T){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.setModel(S,T);return}let A=nt(y);if(!A.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let x=A.modelRegistry.find(S,T);if(!x||!A.modelRegistry.getAvailable().some(C=>C.provider===S&&C.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");tt(A)},async setThinkingLevel(y,S){if(Ye(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 A=nt(y);if(!A.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!A.model||!NP(A.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),tt(A)},config:_k,updateConfig:UP,async send(y,S,T=[],A,x){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.send(S,T,A,x);return}let C=nt(y);if(Oi(ui(),S,x),x==="followUp"&&(!C.isIdle()||m.tuiPrompts.length>0)){m.tuiPrompts.enqueue(S,T,A),Xd();return}if(C.isIdle()&&m.tuiPrompts.sending)throw new et("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await tu(y,S,T,A,x)},async updateQueuedPrompt(y,S,T,A){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.updateQueuedPrompt(S,T,A);return}if(A.kind==="steer"&&nt(y).isIdle())throw new et("\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,A,(x,C,q)=>tu(y,x,C,q,"steer"))},async abort(y){if(Ye(y),m.selected==="sdk")await m.workspaceSessions.stop();else{let S=nt(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(Yn),S.abort()}},async resume(y,S){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.resume(S);return}let T=nt(y);if(Wr(()=>m.hosted?.adapter.assertAdmission(),S,(A,x)=>m.bridge?.reportError?.(A,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(Za(We().messages),{triggerTurn:!0})}catch(A){throw m.operation=void 0,A}},async newSession(y){if(Ye(y),m.selected==="sdk"){let A=m.workspaces?.get(m.activeWorkspaceId??"");if(!A)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await m.workspaceSessions.reuseBlank(A.path)||await m.workspaceSessions.open(A.path,"new"),await Ge();return}let S=nt(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 Ge();return}if((await m.commandContext.newSession({withSession:async A=>{m.commandContext=A,m.replacementContext=A,m.replacementSessionId=A.sessionManager.getSessionId(),m.current=A}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await Ge()}};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 uw(v,us,m.telemetry)}if(m.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let g=[],f=null;for(let v of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(EP).filter(Boolean))try{g.push(xP(Xr(en(v),"dist"),(y,S)=>{let T=String(S??"");["client.js","client.css"].includes(T)&&(f&&clearTimeout(f),f=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();f&&clearTimeout(f)}}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:Jd}),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 R9=Oo;export{R9 as default,SP as verifySentryDisabledRelease,dk as verifySentryNodeRelease};
245
+ `)}`:void 0,t<3&&i.cause instanceof Error&&(n.cause=Bw(i.cause,e,t+1)),gr(n)}import{randomUUID as Ww}from"node:crypto";import{randomUUID as gR}from"node:crypto";import{EnvHttpProxyAgent as fR,getGlobalDispatcher as L$,setGlobalDispatcher as U$}from"undici";var Hw=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 hR(i,e){let t=Hw(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 yR(i){let e=Hw(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 fR(e)}function ud({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:gR(),phase:"headers",proxied:o&&hR(i,p)},f=r?void 0:n,_=!1,y=d?.signal??(p instanceof Request?p.signal:void 0),S=()=>T(),T=()=>{y?.removeEventListener("abort",S),!_&&r&&(_=!0,a(f).catch(()=>{}))},A;try{o?(f??=yR(i),s.add(f),r||(n=f),A=await t(p,{...d,dispatcher:f})):A=await t(p,d)}catch(F){throw l(F,g),T(),F}if(A.ok||l(void 0,{...g,status:A.status}),!A.body)return T(),A;let I=A.body.getReader();y?.addEventListener("abort",S,{once:!0}),y?.aborted&&T();let C=new ReadableStream({async pull(F){try{let N=await I.read();N.done?(F.close(),I.releaseLock(),T()):F.enqueue(N.value)}catch(N){l(N,{...g,phase:"body"}),F.error(N),I.releaseLock(),T()}},async cancel(F){try{await I.cancel(F)}finally{I.releaseLock(),T()}}}),q=new Response(C,{status:A.status,statusText:A.statusText,headers:A.headers});return Object.defineProperties(q,{url:{value:A.url},redirected:{value:A.redirected},type:{value:A.type}}),q},close:async()=>{await Promise.all([...s].map(a))}}}var Gw=(i,e)=>ud({autoClose:!0}).fetch(i,e);var bR=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),_R=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 md(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=_R(a.code);if(t.push({name:bR.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:Ww(),requestId:l(e.requestId)??Ww(),...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 $w({env:i=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return ud({env:i,fetchRequest:t,onFailure:(r,n)=>e(md(r,{...n,stage:n.phase==="body"?"model_stream":"model_headers"}))})}function vR(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 wR=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function Vw(i,e,t=()=>{}){let r=i.agent.streamFunction;i.agent.streamFunction=async(n,s,o)=>{if(!wR.has(n.api))return r(n,s,o);let l=t(),a=$w({env:vR(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 Wr(i,e,t){try{i()}catch(r){let n=md(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 xR=["read","grep","find","ls"];var zw=200,to=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new or;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 Yt(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=es.create(r);else if(t==="continue"){let l=(await Hr(r))[0];s=l?es.open(l.path):es.create(r)}else s="sessionManager"in t?t.sessionManager:es.open(t.sessionFile);if(await IR(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 Yt(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=Qn(l);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:r,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!n.sending,name:Ka(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=>Qn(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 ar.discover(e,this.isProjectTrusted(e)),l=SR(),a=await qw(e,o.extensionRoots,this.isProjectTrusted(e)),c=new ER({cwd:e,agentDir:TR(),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(w=>`${w.path}: ${w.error}`).join("; "));let g=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:f}=await kR({cwd:e,sessionManager:t,model:g,resourceLoader:c,customTools:this.customTools}),_=new Gr({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(w,h)=>this.telemetry.breadcrumb(w,h),anonymize:w=>this.telemetry.anonymize(w)}),y={session:f,cwd:e,catalog:o,bus:l,generation:++this.generation,activityId:0,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:_,streaming:null,prompts:null,detached:n?{owner:n,events:[],seq:0,lastText:"",restoreTools:null}:void 0};y.prompts=s?.prompts??new Ri(()=>{let w=this.runtimes.get(t.getSessionId())??y;this.publishFor(w,{type:"snapshot",session:this.snapshotOf(w)}),!this.disposed&&!w.closing&&this.onSessionsChanged()}),p=y,Vw(f,w=>{y.networkDiagnostic=w},()=>y.operation?.operationId);let S=w=>this.publishFor(y,w),T=y.detached,A=(w,h)=>{T&&(T.events.push({seq:++T.seq,type:w,...h===void 0?{}:{text:h}}),T.events.length>zw&&T.events.splice(0,T.events.length-zw))};y.interactions=new Br(l,w=>!y.closing&&w.sessionId===f.sessionManager.getSessionId()&&Xn(o,w.pluginId),()=>S({type:"snapshot",session:this.snapshotOf(y)}));let I=0,C=l.on(Ja,()=>S({type:"snapshot",session:this.snapshotOf(y)})),q=f.subscribe(w=>{if(T&&!y.closing&&(w.type==="message_end"&&w.message.role==="assistant"&&(w.message.stopReason==="error"?A("error",w.message.errorMessage??"Agent response failed"):T.lastText=w.message.content.flatMap(h=>h.type==="text"?[h.text]:[]).join(`
246
+ `)),w.type==="agent_settled"&&A("turn_end",T.lastText)),!this.disposed&&!y.closing){let h={...y.operation,session:this.telemetry.anonymize(f.sessionManager.getSessionId()),piVersion:eo,model:f.model?`${f.model.provider}/${f.model.id}`:null,thinkingLevel:f.thinkingLevel};if(w.type==="agent_start"&&(y.activityId++,this.telemetry.breadcrumb("agent_start",h)),w.type==="tool_execution_start"&&_.start(w,h),w.type==="tool_execution_end"&&_.end(w,h),w.type==="message_end"&&w.message.role==="assistant"&&w.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:eo,...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:w.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:Z,inTranscript:!0,...y.operation})}w.type==="message_end"&&w.message.role==="toolResult"&&_.message(w.message,h),w.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",h),_.clear(),y.operation=void 0)}w.type==="message_update"&&w.message.role==="assistant"&&(y.streaming={id:"stream",role:"assistant",timestamp:new Date(w.message.timestamp).toISOString(),blocks:rr(w.message.content)},Date.now()-I>=60&&(I=Date.now(),S({type:"stream",message:y.streaming}))),w.type==="agent_settled"&&this.scheduleQueued(y),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(w.type)&&((w.type==="message_end"&&w.message.role==="assistant"||w.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(w.type)&&this.onSessionsChanged())});y.detach=()=>{C(),q()},y.releaseHosted=this.hosted?.adapter.attach(f);let F=[],N=!0;if(await f.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:w=>{N&&F.push(w.error),this.diagnostic(y,o.plugins.find(h=>w.extensionPath.startsWith(h.root+"/"))?.id??w.extensionPath,w.event??"runtime",w.error)}}),N=!1,F.length)throw new Error(F.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=f.getActiveToolNames(),f.setActiveToolsByName(xR)),this.runtimes.set(f.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 Nw(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=Qn(o);return l?[l]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:Ka(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:Fr(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:id(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 Xa(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")):Qa(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(Oi(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 et("\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");Wr(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),Oi({...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:eo});let a=!1,c,p,d=new Promise((g,f)=>{c=g,p=f});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 f=this.reportError(Zt(g,"Agent response failed"),{...n,stage:"agent",code:"agent_failed",piVersion:eo});this.publishFor(e,{type:"error",message:g instanceof Error?g.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:f,...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&&!Fr(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 et("\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(Yn),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");Wr(()=>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(!Fr(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(!Fr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=Za(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(Zt(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 Yt(e),s=es.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 AR,mkdir as OR,rename as RR,unlink as NR}from"node:fs/promises";import{basename as PR,join as Kw}from"node:path";var CR=i=>Kw(i,"pi-web","trash");async function Yw(i,e){let t=CR(e);await OR(t,{recursive:!0});let r=Kw(t,`${Date.now()}_${PR(i)}`);try{await RR(i,r)}catch(n){let s=n.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw n;await AR(i,r),await NR(i)}return r}import{basename as gd,dirname as DR}from"node:path";function Qw(i,e){let t=r=>e[r].map(n=>({name:r==="skills"&&gd(n.path).toLowerCase()==="skill.md"?gd(DR(n.path)):gd(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 MR}from"node:child_process";var LR=(i,e)=>new Promise((t,r)=>{MR(i,[...e],{windowsHide:!0},n=>{n?r(n):t()})});async function fd(i,e=process.platform,t=process.env,r=LR){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 CN}from"node:child_process";import{randomUUID as Cd}from"node:crypto";import{existsSync as I0}from"node:fs";import{access as DN,mkdir as ns,mkdtemp as MN,readFile as Li,realpath as LN,rename as x0,rm as A0,writeFile as O0}from"node:fs/promises";import{join as Oe}from"node:path";import{createHash as bd}from"node:crypto";import{readdir as WR,realpath as i0,rename as $R,stat as VR}from"node:fs/promises";import{join as Mi}from"node:path";import{constants as hd}from"node:fs";import{DatabaseSync as UR}from"node:sqlite";import{lstat as Zw,mkdir as qR,open as ts,rename as jR,unlink as e0}from"node:fs/promises";import{dirname as FR,join as Jw,resolve as BR}from"node:path";import{randomUUID as HR}from"node:crypto";import{setTimeout as GR}from"node:timers/promises";async function Le(i){await qR(i,{recursive:!0,mode:448});let e=await Zw(i);if(!e.isDirectory()||e.isSymbolicLink())throw new b("invalid_storage","Plugin storage must be a real directory")}async function Pe(i,e){let t;try{t=await ts(i,hd.O_RDONLY|hd.O_NONBLOCK|(hd.O_NOFOLLOW??0))}catch(r){if(Ni(r))return null;throw r}try{let r=await t.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new b("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 b("invalid_storage","Storage record changed during read");return n.subarray(0,s)}finally{await t.close()}}async function Ue(i,e=2*1024*1024){let t=await Pe(i,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new b("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function pt(i){let e=await Pe(i,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new b("gc_recovery_required",`Invalid journal ${i}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new b("gc_recovery_required",`Invalid journal ${i}; original bytes preserved`);return t}async function ye(i,e){let t=`${i}.${HR()}.tmp`,r=await ts(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await jR(t,i);let n;try{n=await ts(FR(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 e0(t).catch(()=>{})}}var t0='{"version":2,"mechanism":"sqlite-exclusive"}',Xw=i=>i.toString("utf8")===t0,io=new Set;async function yd(i,e,t=0){await Le(i);let r=Jw(i,`${e}.lock`),n=Jw(i,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new b(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 ts(n,"wx",384)}catch(_){if(_.code!=="EEXIST")throw _}finally{await l?.close()}let a=await Zw(n);if(!a.isFile()||a.isSymbolicLink()||a.nlink!==1||a.size>1024*1024)throw new b("invalid_storage","Ownership database must be a small, single-link regular file");let c=new UR(n,{allowExtension:!1}),p=BR(n),d=Date.now()+t,g=!1;try{for(;;){if(!io.has(p))try{c.exec("BEGIN EXCLUSIVE"),io.add(p),g=!0;break}catch(y){if(y.errcode!==5)throw y}if(Date.now()>=d)throw new b(s,"Another host owns this plugin storage; wait for it to stop before retrying");await GR(10)}let _=await Pe(r,4096);if(_===null){let y;try{y=await ts(r,"wx",384),await y.writeFile(t0),await y.sync()}catch(S){if(S.code!=="EEXIST")throw S}finally{await y?.close()}_=await Pe(r,4096)}if(_===null||!Xw(_))throw o()}catch(_){throw c.close(),g&&io.delete(p),_}let f=!1;return async()=>{if(f)return;let _=await Pe(r,4096);if(_===null||!Xw(_))throw new b("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await e0(r),c.close(),io.delete(p),f=!0}}async function qe(i,e,t=2e3){let r=await yd(i,"transaction",t);try{return await e()}finally{await r()}}var ro=i=>Mi(i,"host-pair"),zR=i=>bd("sha256").update(JSON.stringify(i)).digest("hex"),KR=10*6e4;async function YR(i){let e=bd("sha256"),t=0,r=0;async function n(s){let o=(await WR(Mi(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 b("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new b("host_pair_required","Candidate package resource budget exceeded");if(l.isDirectory()){await n(a);continue}let c=await Pe(Mi(i,a),64*1024*1024);if(!c||(r+=c.length)>256*1024*1024)throw new b("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,bd("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function _d(i,e){let t=await i0(e),r=Mi(e,"dist","hosted-worker.js");if(await i0(r)!==Mi(t,"dist","hosted-worker.js"))throw new b("host_pair_required","Candidate worker must remain inside the staged host");let n=await Pe(Mi(e,"package.json"),512*1024);if(!n)throw new b("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 b("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 Pe(r,32*1024*1024);if(!l)throw new b("host_pair_required","Candidate worker missing");return zR([n.toString("base64"),l.toString("base64"),await YR(e)])}async function no(i){await $R(i,`${i}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var QR=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 vd(i){let e=Mi(ro(i),"intent.json"),t,r=!0;try{t=await pt(e)}catch{t=null,r=!1}if(!r||t&&!QR(t))return await no(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 so(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(Mi(ro(i),"intent.json"),n)}var wd=i=>i&&["selecting","selected","restart-requested"].includes(i.phase),r0=(i,e=Date.now())=>!!i&&!!wd(i)&&e-Date.parse(i.updatedAt??"")<KR;import{promisify as UN}from"node:util";import{realpathSync as a0,statSync as JR}from"node:fs";import{basename as XR,delimiter as ZR,dirname as n0,join as kd,resolve as eN}from"node:path";function s0(i){if(!i)return null;try{let e=a0(i);return XR(e)==="npm-cli.js"&&JR(e).isFile()?e:null}catch{return null}}function tN({execPath:i=process.execPath,env:e=process.env}={}){let t=s0(e.npm_execpath);if(t)return t;let r=new Set([n0(i)]);try{r.add(n0(a0(i)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(ZR).filter(Boolean))r.add(eN(s));for(let s of r)for(let o of[kd(s,"node_modules","npm","bin","npm-cli.js"),kd(s,"..","lib","node_modules","npm","bin","npm-cli.js"),kd(s,"npm")]){let l=s0(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 o0(i){return{file:process.execPath,args:[tN(),...i]}}import{randomUUID as iN}from"node:crypto";import{mkdir as p0,readFile as rN,rename as Ed,rm as nN,unlink as FV,writeFile as sN}from"node:fs/promises";import{isAbsolute as l0,join as is}from"node:path";var Td=1,aN=1440*6e4,ao=i=>is(i,"pi-web","upgrade"),Id=i=>is(ao(i),"candidate.json"),oN=i=>is(ao(i),"transaction.json"),c0=i=>is(ao(i),"history"),d0=/^[a-f0-9-]{36}$/i;async function lN(i,e){let t=`${i}.${iN()}.tmp`;try{await sN(t,e,{mode:384}),await Ed(t,i)}finally{await nN(t,{force:!0})}}var cN=(i,e)=>lN(i,JSON.stringify(e));async function Sd(i,e){await Ed(i,`${i}.${e}-${Date.now()}`).catch(t=>{if(t?.code!=="ENOENT")throw t})}async function u0(i,e,t=()=>!1){let r;try{r=JSON.parse(await rN(i,"utf8"))}catch(n){return n?.code==="ENOENT"||await Sd(i,"invalid"),null}return e(r)?t(r)?(await Sd(i,"expired"),null):r:(await Sd(i,"invalid"),null)}function m0(i){if(!i||typeof i!="object"||i.schema!==Td||!d0.test(i.id??""))return!1;try{Kt(i.version)}catch{return!1}return typeof i.launcher=="string"&&l0(i.launcher)&&typeof i.packageRoot=="string"&&l0(i.packageRoot)&&["stable","alpha"].includes(i.channel)&&typeof i.downgrade=="boolean"&&!Number.isNaN(Date.parse(i.createdAt??""))}async function oo(i,e=Date.now()){return u0(Id(i),m0,t=>e-Date.parse(t.createdAt)>aN)}async function g0(i,e){let t={schema:Td,createdAt:new Date().toISOString(),...e};if(!m0(t))throw new Error("Invalid upgrade candidate");return await p0(ao(i),{recursive:!0,mode:448}),await cN(Id(i),t),t}async function xd(i,e,t){let r=await oo(i);!r||e&&r.id!==e||(await p0(c0(i),{recursive:!0,mode:448}),await Ed(Id(i),is(c0(i),`${r.id}-candidate-${t}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var pN=["selected","committed","rolled-back"];function dN(i){return!!i&&typeof i=="object"&&i.schema===Td&&d0.test(i.id??"")&&pN.includes(i.phase)&&typeof i.version=="string"&&typeof i.from=="string"&&!Number.isNaN(Date.parse(i.updatedAt??""))}async function f0(i){return u0(oN(i),dN)}import{readFile as uN,rename as mN,writeFile as gN,unlink as fN}from"node:fs/promises";import{join as hN}from"node:path";import{randomUUID as yN}from"node:crypto";var Ad=1,h0=i=>hN(i,"pi-web","launcher-handoff.json");function y0(i){return i?.protocol===Ad&&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 Od(i){try{let e=JSON.parse(await uN(h0(i),"utf8"));if(!y0(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 bN(i,e){let t=`${i}.${yN()}.tmp`;try{await gN(t,JSON.stringify(e),{mode:384}),await mN(t,i)}finally{await fN(t).catch(()=>{})}}async function b0(i,e){if(!y0(e))throw new Error("Invalid launcher handoff receipt");await bN(h0(i),e)}import{execFile as _N}from"node:child_process";import{cp as vN,readFile as Rd,realpath as wN,rm as kN}from"node:fs/promises";import{join as $r,sep as SN}from"node:path";import{promisify as EN}from"node:util";var _0=EN(_N),Nd=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Pd(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 Nd.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 lo(i){return Promise.all(Nd.map(async e=>{let t=await jr(i,e),r=JSON.parse(await Rd($r(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 v0(i,e){let t=JSON.parse(await Rd($r(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 lo(i):Pd(t.peerDependencies);if(JSON.stringify(await lo(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 jr(i,"node-pty"),s=await jr(e,"node-pty"),o=await wN($r(e,"../.."));if(n===s||!s.startsWith(o+SN))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 Rd($r(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 kN(s,{recursive:!0,force:!0}),await vN(n,s,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await _0(process.execPath,[$r(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await jr(e,Nd[0]),{stdout:p}=await _0(process.execPath,[$r(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 k0,readdir as S0,readFile as TN,realpath as w0,rm as IN}from"node:fs/promises";import{join as rs,relative as xN,sep as E0}from"node:path";var AN=1440*6e4,ON=1024*1024,RN=4,NN=i=>i==="releases"||i==="history"||i.endsWith("-history");async function PN(i,e){let t=new Set,r=[...new Set(e.flatMap(o=>[o+E0,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 S0(o,{withFileTypes:!0}).catch(()=>[]);for(let c of a){let p=rs(o,c.name);if(c.isDirectory()){l<RN&&!NN(c.name)&&await s(p,l+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await k0(p)).size>ON)continue;n(JSON.parse(await TN(p,"utf8")))}catch{}}};return await s(i,0),t}async function T0(i){let e=rs(i.agentDir,"pi-web"),t;try{t=await w0(rs(e,"releases"))}catch{return[]}let r=i.now??Date.now(),n=i.graceMs??AN,s=await PN(e,[rs(e,"releases"),t]);try{let l=xN(t,await w0(i.packageRoot));l&&!l.startsWith("..")&&s.add(l.split(E0)[0])}catch{}let o=[];for(let l of await S0(t,{withFileTypes:!0}).catch(()=>[])){if(!l.isDirectory()||s.has(l.name))continue;let a=rs(t,l.name);try{if(r-(await k0(a)).mtimeMs<n)continue;await IN(a,{recursive:!0,force:!0}),o.push(l.name)}catch{}}return o}var qN=UN(CN),Vr=i=>["committed","cancelled","failed"].includes(i);function R0(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 jN(i,e){try{let t=o0(i),{stdout:r}=await qN(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 co=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??jN,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 lo(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Pd(s)},this.verifyPackage=e.verifyPackage??v0,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"?Ad: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&&!Vr(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 Li(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 Od(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 Li(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 b0(this.agentDir,p),c=!0}catch(d){let g=await Od(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 Li(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&&!Vr(e.phase)?[]:T0({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),t=await this.transaction();if(!t||Vr(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 f0(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 xd(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 pt(this.transactionPath)}catch{return await no(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 no(this.transactionPath),null):e:null}async record(e){if(await ns(Oe(this.agentDir,"pi-web"),{recursive:!0}),await ye(this.transactionPath,e),Vr(e.phase)){let t=Oe(this.agentDir,"pi-web","update-history");await ns(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 oo(this.agentDir);t&&(!e||t.id===e.id)&&await xd(this.agentDir,t.id,"cancelled"),e&&!Vr(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 Li(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}.${Cd()}.tmp`;try{await ns(Oe(this.agentDir,"pi-web"),{recursive:!0}),await O0(t,JSON.stringify({channel:e}),{mode:384}),await x0(t,this.preferencePath)}finally{this.savingPreference=!1,await A0(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=I0(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&&!Vr(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||!lw(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(!Wa(a.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ct(a.alpha,c)>0&&(c=a.alpha)}if(n.latest=c,n.downgrade=ct(c,e)<0,n.available=t==="stable"?ct(c,e)!==0:ct(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&&ct(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(I0(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 ns(r,{recursive:!0});let n=await MN(Oe(await LN(r),`${t.latest}-`)),s=Oe(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:Cd(),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 Li(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 Li(Oe(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&R0(c)!==R0(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=>DN(g))),this.desktopManaged&&(await Xp(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 g0(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 A0(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 oo(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 Li(o,"utf8"))?.nonce!==this.launcherNonce){let c=Oe(this.agentDir,"pi-web","restart-history");await ns(c,{recursive:!0,mode:448}),await x0(o,Oe(c,`stale-${Cd()}.json`))}}catch{}try{await O0(o,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(a){try{let c=JSON.parse(await Li(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 vk,randomUUID as GP}from"node:crypto";import{randomUUID as bP}from"node:crypto";import{join as Yd}from"node:path";import{randomUUID as C0}from"node:crypto";import{randomUUID as FN}from"node:crypto";function N0(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_${FN().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 P0(){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,f=!1,_=!1;try{let y=(q,F,N)=>({name:q,label:q,description:"Inert host SDK contract check",exposure:F,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:[q=>{q.on("tool_call",F=>{if(F.toolName==="__contract_direct"&&(f=!!F.parentToolCallId),F.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let F of["hidden","model-only"])q.registerTool(y(`__contract_${F.replace("-","_")}`,F,async()=>(g++,S())));q.registerTool(y("__contract_protected","direct",async()=>(g++,S()))),q.registerTool(y("__contract_direct","direct",async()=>(d++,S()))),q.registerTool(y("__contract_driver","direct",async(F,N,w,h,M)=>{let Z=await M.executeTool("__contract_hidden",{}),re=await M.executeTool("__contract_model_only",{}),ae=await M.executeTool("__contract_direct",{}),P=await M.executeTool("__contract_protected",{});return(!Z.isError||!re.isError)&&p.push("nested-tool-exposure"),(ae.isError||d!==1)&&p.push("nested-tool-execution"),(!P.isError||g!==0)&&p.push("nested-tool-permission-guard"),f||p.push("nested-parent-identity"),_=!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 A=c.modelRuntime.getModels("openai")[0];if(!A)return{supported:!1,missing:["sdk-model-contract"]};await c.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await c.setModel(A);let I=0;c.agent.streamFunction=async q=>{let F=I++===0,N={role:"assistant",api:q.api,provider:q.provider,model:q.id,timestamp:Date.now(),content:F?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:F?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},w=r();return w.push({type:"start",partial:N}),w.push({type:"done",reason:F?"toolUse":"stop",message:N}),w.end(N),w};let C;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((q,F)=>{C=setTimeout(()=>F(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(C)}return _||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(a,{recursive:!0,force:!0})}}var po=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??=P0().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=N0(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:C0(),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:GN};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:C0(),scope:t,kind:"action",action:r,input:n},s)}};async function GN(){throw new Error("Hosted tool unavailable")}import{randomBytes as Y1,randomUUID as Q1,timingSafeEqual as J1}from"node:crypto";import{join as kt}from"node:path";var WN=30,D0=/^[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}$/,ss=i=>{throw new b("invalid_package",i)},Dd=(i,e)=>i===void 0?[]:!Array.isArray(i)||i.length>32?ss(`Invalid ${e} declaration`):i;function zr(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")?Dd(e.secrets,"secrets").map(l=>{let a=l?.name;return typeof a=="string"&&D0.test(a)?a:ss("Invalid secret name")}):[],n=e.network,s=t.has("network")?Dd(n?.hosts,"network").map(l=>typeof l=="string"&&$N.test(l)?l:ss("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Dd(e.schedules,"schedules").map(l=>{let a=l;return!a||typeof a.id!="string"||!D0.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<WN||a.intervalSec>86400?ss("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(l=>l.id)).size!==o.length&&ss("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:o,sessions:t.has("sessions")}}import{lookup as VN}from"node:dns/promises";import{isIP as zN}from"node:net";var KN=new Set(["GET","POST","PATCH","PUT","DELETE"]),YN=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),QN=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),uo=(i,e)=>{throw new b("network_denied",i,{status:403,reason:e})};function JN(i){let e=i.toLowerCase().replace(/^::ffff:/,"");if(zN(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 M0(i,e,t,r,n){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new b("invalid_input","Invalid network request");let o;try{o=new URL(s.url)}catch{throw new b("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&uo("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||uo("Host is not declared by the plugin","host");let l=(s.method??"GET").toUpperCase();if(!KN.has(l))throw new b("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new b("invalid_input","Invalid body");let a={};for(let[A,I]of Object.entries(s.headers??{})){if(typeof I!="string"||YN.has(A.toLowerCase())||!/^[\w-]{1,64}$/.test(A)||/[\r\n]/.test(I))throw new b("invalid_input",`Header not allowed: ${A.slice(0,64)}`);a[A]=I}let c=null;if(s.secret!==void 0){if(t.includes(s.secret)||uo("Secret is not declared by the plugin","secret"),c=await n.secrets.get(i,s.secret),!c)throw new b("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${c}`}let p=await(n.resolve??(async A=>(await VN(A,{all:!0})).map(I=>I.address)))(o.hostname);(!p.length||p.some(JN))&&uo("Host resolves to a non-public address","address");let d=n.timeoutMs??2e4,g=n.maxResponseBytes??2*1024*1024,f=await(n.fetch??fetch)(o,{method:l,headers:a,body:s.body,redirect:"manual",signal:AbortSignal.timeout(d)}),_=[],y=0;if(f.body)for await(let A of f.body){if(y+=A.byteLength,y>g)throw new b("response_too_large","Network response exceeds limit",{status:502});_.push(Buffer.from(A))}let S=Buffer.concat(_).toString("utf8"),T={};return f.headers.forEach((A,I)=>{QN.has(I.toLowerCase())&&(T[I.toLowerCase()]=A)}),c&&(S=S.split(c).join("[redacted]")),{status:f.status,headers:T,body:S}}var mo=(i,e,t)=>{if(typeof i!="string"||!i||i.length>e)throw new b("invalid_input",`Invalid ${t}`);return i};async function L0(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 b("invalid_input","Plugin sessions must start in plan mode");if(i.activeCount(e)>=s)throw new b("quota_exceeded","Too many active plugin sessions",{status:429});return i.create({pluginId:e,cwd:t,title:mo(o.title,200,"title"),prompt:mo(o.prompt,64*1024,"prompt"),mode:"plan"})}let l=mo(o.sessionId,200,"sessionId");if(i.ownerOf(l)!==e)throw new b("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 b("invalid_input","Invalid mode");return await i.send(l,mo(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 b("method_denied","Unknown sessions method")}}var XN=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),go=class{options;constructor(e){this.options=e}handles(e){return XN.has(e)}async call(e,t,r,n,s){let o=zr(t);if(n==="network.fetch"){if(!o.networkHosts.length)throw new b("capability_denied","Plugin did not declare network access",{status:403});return M0(e,o.networkHosts,o.secrets,s,this.options)}if(!o.sessions||!this.options.sessions)throw new b("capability_denied","Sessions capability is unavailable",{status:403});return L0(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var fo=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 Bd,timingSafeEqual as v1}from"node:crypto";import{lstat as z0,mkdtemp as Fd,readdir as w1,readFile as k1,realpath as S1,rename as E1,rm as Ui,writeFile as T1}from"node:fs/promises";import{tmpdir as I1}from"node:os";import{join as Ie}from"node:path";import{gunzipSync as s1}from"node:zlib";import{mkdir as a1,writeFile as o1}from"node:fs/promises";import{dirname as l1,join as c1}from"node:path";import{constants as Md}from"node:fs";import{lstat as j0,open as ZN,readdir as U0,realpath as F0}from"node:fs/promises";import{createHash as e1}from"node:crypto";import{join as B0,relative as t1,resolve as i1,sep as r1}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},n1={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=>e1("sha256").update(i).digest("hex");function Ee(i){throw new b("invalid_package",i)}async function lr(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=B0(n,r[l]);let a=await j0(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 F0(n);(s!==i1(i,e)||t1(i,s).startsWith(`..${r1}`))&&Ee("Resource escapes package root");let o=await ZN(n,Md.O_RDONLY|Md.O_NONBLOCK|(Md.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 q0(i){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{return Ee("Invalid package JSON")}}async function cr(i,e){let t=await F0(i);(await j0(i)).isSymbolicLink()&&Ee("Package root cannot be a symlink");let r=q0(await lr(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"),Ci(r.piWebapp)||Ee("Unsupported hosted manifest"),r.type!=="module"&&Ee("Hosted package must declare ESM module type");for(let d of await U0(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=q0(await lr(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,f={...g,path:typeof g.path=="string"&&g.path.startsWith("./")?g.path.slice(2):g.path};(!sr(`./${f.path}`)||typeof f.sha256!="string"||!/^[a-f0-9]{64}$/.test(f.sha256)||!Number.isSafeInteger(f.bytes)||f.bytes<0||o.has(f.path))&&Ee("Invalid or duplicate resource");let _=f.path.split(".").at(-1);n1[_]?.includes(f.mime)||Ee("Unsupported resource MIME");let y=_==="js"||_==="mjs"||_==="cjs"?Re.js:_==="css"?Re.css:["woff","woff2","ttf","otf"].includes(_)?Re.font:_==="wasm"?Re.wasm:Re.other;(f.bytes>y||(l+=f.bytes)>Re.total)&&Ee("Resource budget exceeded");let S=await lr(t,f.path,y);(S.length!==f.bytes||Te(S)!==f.sha256)&&Ee("Resource integrity mismatch"),o.set(f.path,Object.freeze({...f}))}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 f of await U0(B0(t,d),{withFileTypes:!0})){++a>Re.files*2&&Ee("Too many package entries");let _=`${d}/${f.name}`;(f.isSymbolicLink()||!f.isDirectory()&&!f.isFile())&&Ee("Invalid archive member"),f.isDirectory()?await c(_,g+1):_!==n.resourcesManifest.slice(2)&&!o.has(_)&&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 H0(i,e,t){if(t!==i.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!sr(`./${r}`))return null;let n=i.resources.get(r);if(!n||r===i.manifest.backend.entry.slice(2))return null;let s=await lr(i.root,r,n.bytes);if(s.length!==n.bytes||Te(s)!==n.sha256)throw new b("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:n.mime}}var ho=64*1024*1024,p1=Re.total+Re.files*2048,ke=i=>{throw new b("invalid_archive",i)};function Kr(i){let e=i.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?i:i.subarray(0,e))}catch{return ke("Archive has invalid UTF-8 paths")}}function G0(i){let e=Kr(i).trim();if(!/^[0-7]+$/.test(e))return ke("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:ke("Archive number exceeds limits")}function d1(i){let e=i.endsWith("/")?i.slice(0,-1):i;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return ke("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))?ke("Archive path is not a safe relative package path"):t}function u1(i){let e={},t=0;for(;t<i.length;){let r=i.indexOf(32,t);if(r<0)return ke("Invalid PAX header");let n=i.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(n))return ke("Invalid PAX record length");let s=Number(n),o=t+s;if(o>i.length||o<=r+2||i[o-1]!==10)return ke("Truncated PAX record");let l=Kr(i.subarray(r+1,o-1)),a=l.indexOf("=");if(a<1)return ke("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 ke("Unsupported PAX feature");e[c]=p,t=o}return e}function m1(i){if(!i.length||i.length>ho)return ke("Compressed archive exceeds budget");let e;try{e=s1(i,{maxOutputLength:p1})}catch{return ke("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(C=>C===0)){if(a||e.subarray(n).some(C=>C!==0))return ke("Unexpected archive data after end marker");c=!0;break}if(++l>Re.files*2)return ke("Too many archive headers");let g=0;for(let C=0;C<512;C++)g+=C>=148&&C<156?32:d[C];if(G0(d.subarray(148,156))!==g)return ke("Invalid tar header checksum");let f=Kr(d.subarray(257,263));if(f&&f!=="ustar"&&f!=="ustar ")return ke("Unsupported tar format");let _=d[156],y=Kr(d.subarray(345,500)),S=(y?y+"/":"")+Kr(d.subarray(0,100)),T=G0(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 ke("Invalid PAX size");T=Number(a.size)}if(!Number.isSafeInteger(T)||T<0||T>Re.total||n+T>e.length)return ke("Truncated or oversized tar member");let A=e.subarray(n,n+T);if(n+=Math.ceil(T/512)*512,_===120){if(a||T>8192)return ke("Oversized or chained PAX header");a=u1(A);continue}if(a=null,_!==0&&_!==48&&_!==53)return ke("Links and special archive members are forbidden");let I=_===53;if(I&&T!==0||Kr(d.subarray(157,257)))return ke("Invalid archive link or directory");if(S=d1(S),!S&&!I)return ke("Invalid package root member");if(r.has(S))return ke("Duplicate archive member");if(r.add(S),++s>Re.files||(o+=T)>Re.total)return ke("Unpacked archive exceeds budget");t.push({path:S,data:A,directory:I})}if(!c||!r.has("package.json"))return ke("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 f=1;f<g.length;f++)if(p.has(g.slice(0,f).join("/")))return ke("Archive file/directory collision")}return t}async function Ld(i,e){let t=m1(i);for(let r of t){if(!r.path)continue;let n=c1(e,r.path);await a1(r.directory?n:l1(n),{recursive:!0,mode:448}),r.directory||await o1(n,r.data,{flag:"wx",mode:384})}}import{lstat as g1,mkdir as f1,readdir as h1,realpath as y1,writeFile as b1}from"node:fs/promises";import{dirname as _1,join as Ud}from"node:path";async function W0(i,e){let t=await y1(i),r=await lr(t,"package.json",Re.other),n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new b("invalid_package","package.json is not valid JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new b("invalid_package","package.json must be an object");let s=[],o=0,l=0;async function a(g,f){if(f>16)throw new b("invalid_package","Package directory nesting limit exceeded");for(let _ of await h1(Ud(t,g),{withFileTypes:!0})){let y=`${g}/${_.name}`;if(++o>Re.files)throw new b("invalid_package","Too many package entries");if(_.isDirectory()){await a(y,f+1);continue}if(!_.isFile())throw new b("invalid_package",`Links and non-regular files are forbidden: ${y}`);let S=await lr(t,y,Re.js);if((l+=S.length)>Re.total)throw new b("invalid_package","Resource budget exceeded");let T=Ud(e,y);await f1(_1(T),{recursive:!0,mode:448}),await b1(T,S,{flag:"wx",mode:384}),s.push([y,Te(S)])}}let c;try{c=await g1(Ud(t,"dist"))}catch(g){throw g.code==="ENOENT"?new b("dist_missing","dist/ does not exist yet; build the plugin first"):g}if(!c.isDirectory())throw new b("invalid_package","dist must be a real directory");await a("dist",0);let{version:p,...d}=n;return s.sort((g,f)=>g[0].localeCompare(f[0])),{contentHash:Te(JSON.stringify({package:d,files:s})),packageJson:n}}function vt(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=vt(i),r=vt(e);if(!t||!r)throw new b("invalid_version","Only exact stable semantic versions are supported");return t.major-r.major||t.minor-r.minor||t.patch-r.patch}function $0(i){let e=vt(i);if(e)return e;if(!Wa(i))return null;let[t,r]=i.split("-alpha."),n=vt(t),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function qd(i){return!!$0(i)}function Yr(i,e){if(!qd(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&&$0(a[2]);if(!a||!c)return!1;let p=a[2],d=ct(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&&ct(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&&ct(i,`${g}-0`)<0;break}}}r.push(o)}return r.some(Boolean)}var wt=Object.freeze([Object.freeze({id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"]}),Object.freeze({id:"@chengzhiyi/pi-pencil",name:"Pencil",icon:"drawing",description:{zh:"\u57FA\u4E8E OpenPencil \u7684 UI \u8BBE\u8BA1\uFF1A\u7F16\u8F91\u5DE5\u4F5C\u533A\u91CC\u7684 .fig \u8BBE\u8BA1\u7A3F\uFF0Cagent \u63D0\u51FA\u4FEE\u6539\uFF0C\u7531\u4F60\u786E\u8BA4\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"UI design on OpenPencil: edit .fig designs in your workspace; the agent proposes changes and you accept them. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.0.1",requiredCapabilities:["state","workspace","panels","browser.wasm"]})]);function dt(i,e=wt){let t=e.find(r=>r.id===i);if(!t)throw new b("unknown_plugin","Plugin is not in the trusted official catalog");return t}function jd(i,e,t){let r=i.piWebapp;return i.name===e.id&&!!vt(i.version)&&!i.deprecated&&Ci(r)&&Yr(t,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function V0(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 b("registry_invalid","Invalid registry version catalog");let s=Object.entries(i.versions);if(s.length>1e4)throw new b("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&&jd(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 b("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 b("registry_invalid","Release is missing its immutable tarball integrity");return l}function x1(i,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new b("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(t[1],"base64"),n=Bd("sha512").update(i).digest();if(r.length!==n.length||!v1(r,n))throw new b("integrity_mismatch","Downloaded package failed integrity verification")}var Qr=class{root;hostVersion;catalog;fetcher;constructor(e){if(!qd(e.hostVersion))throw new b("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??wt,this.fetcher=e.fetch??Gw}async index(){let e=await Ue(Ie(this.root,"installed.json"));if(!e){if(await Pe(Ie(this.root,"installed.json"),2*1024*1024))throw new b("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 b("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 b("invalid_storage","Invalid installed version list");for(let n of r)this.validateRecord(t,n)}return e}validateRecord(e,t){if(!t||!vt(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 b("invalid_storage","Invalid installed plugin record")}path(e){return Ie(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await pt(Ie(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(s=>!["schema","pluginId","next"].includes(s)))throw new b("invalid_storage","Invalid install journal");dt(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 b("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 w1(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await z0(Ie(r,n))).isSymbolicLink())throw new b("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 pt(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 b("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");dt(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 b("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 dt(e,this.catalog),qe(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 qe(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 b("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 b("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 b("registry_unreachable",d instanceof Error?d.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new b(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 b("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 b("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 b("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 b?d:new b("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=dt(e,this.catalog);if(r&&!vt(r))throw new b("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 b("registry_invalid","Invalid registry metadata JSON")}return V0(l,s,this.hostVersion,t,r)}async install(e,t,r){let n=dt(e,this.catalog);if(!jd(t,n,this.hostVersion))throw new b("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(t.dist.tarball,n),ho,r);return this.installArchive(e,s,t.dist.integrity,t.version,r)}async installArchive(e,t,r,n,s){let o=dt(e,this.catalog);if(!vt(n))throw new b("invalid_version","Choose an exact stable version");if(t.length>ho)throw new b("download_too_large","Package archive exceeds budget");return x1(t,r),qe(this.root,async()=>{let l=await this.recoverLocked();s?.throwIfAborted();let a=await Fd(Ie(this.root,"staging","stage-"));try{await Ld(t,a),s?.throwIfAborted();let c=await cr(a,e);if(c.version!==n||!Ci(c.manifest)||!Yr(this.hostVersion,c.manifest.hostRange)||!o.requiredCapabilities.every(p=>c.manifest.capabilities.includes(p)))throw new b("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 b("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 b("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 z0(c),p=!0}catch(d){if(!Ni(d))throw d}if(p){if((await cr(c,e)).digest!==n.digest)throw new b("resource_changed","Installed package content was modified")}else await E1(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 S1(c)}}async installDevArchive(e,t,r){dt(e,this.catalog);let n=await k1(t),s="sha512-"+Bd("sha512").update(n).digest("base64"),o=await Fd(Ie(I1(),"pi-dev-archive-"));try{await Ld(n,o);let l=(await cr(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=dt(e,this.catalog);return qe(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let o=await Fd(Ie(this.root,"staging","stage-"));try{let{contentHash:l,packageJson:a}=await W0(t,o);r?.throwIfAborted();let c=Ie(this.root,"dev-sources.json"),p=await Ue(c)??{},d=p[e],g=s.versions[e]??[],f=d?.contentHash===l?g.find(F=>F.version===d.version):void 0;if(f){let F=await cr(this.path(f),e);if(F.digest!==f.digest)throw new b("resource_changed","Installed package integrity changed");return F}let _=typeof a.version=="string"?vt(a.version):null;if(!_)throw new b("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let y=Math.max(-1,...g.map(F=>vt(F.version)).filter(F=>F&&F.major===_.major&&F.minor===_.minor).map(F=>F.patch)),S=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),y+1),T=`${_.major}.${_.minor}.${S}`;await T1(Ie(o,"package.json"),JSON.stringify({...a,version:T},null,2),{flag:"wx",mode:384});let A=await cr(o,e);if(!Yr(this.hostVersion,A.manifest.hostRange))throw new b("incompatible_plugin",`Package hostRange ${A.manifest.hostRange} does not include host ${this.hostVersion}`);let I=n.requiredCapabilities.filter(F=>!A.manifest.capabilities.includes(F));if(I.length)throw new b("incompatible_plugin",`Package lacks required capabilities: ${I.join(", ")}`);let C="sha512-"+Bd("sha512").update(l).digest("base64"),q=await this.commitStaged(e,s,o,A,C,r);return p[e]={contentHash:l,version:T},await ye(c,p),q}finally{await Ui(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let r=dt(e,this.catalog);return qe(this.root,async()=>{let n=await this.recoverLocked(),s=n.versions[e]?.find(l=>l.version===t);if(!s)throw new b("not_installed","Plugin version is not installed");let o=await cr(this.path(s),e);if(o.digest!==s.digest)throw new b("resource_changed","Installed package integrity changed");if(!Yr(this.hostVersion,o.manifest.hostRange)||!r.requiredCapabilities.every(l=>o.manifest.capabilities.includes(l)))throw new b("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){dt(e,this.catalog),await qe(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 yo,mkdir as D1,open as X0,realpath as Z0,readdir as Wd,link as M1,rename as L1,unlink as pr,copyFile as U1,rm as q1}from"node:fs/promises";import{dirname as j1,isAbsolute as ek,join as de,relative as tk,resolve as F1,sep as $d,win32 as B1}from"node:path";import{randomUUID as Vd}from"node:crypto";var K0=64*1024*1024,Hd=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]),A1="@chengzhiyi/pi-excalidraw",O1={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"}}},R1="@chengzhiyi/pi-github",N1={tools:{},readonlyActions:[],actions:["get","configure","pickup","sync","cancel","approve","reject","answer","remove"],checkpointActions:["get"],contribution:{entry:{label:"GitHub",description:{zh:"GitHub \u4EFB\u52A1",en:"GitHub tasks"},kind:"workspace"},panels:["workspace"],artifactTools:[],toolViews:[],panelAlias:{prefix:"github:",kind:"workspace",title:"GitHub"}}},P1="@chengzhiyi/pi-pencil",C1={tools:{pencil_read_me:"reference",pencil_status:"status",pencil_inspect:"inspect",pencil_render:"render",pencil_propose_changes:"propose"},readonlyActions:["reference","status","inspect","render"],actions:["list","get","accept","reject","save","open","create","rename","selection","sync","lock"],checkpointActions:["get","list","sync","create"],contribution:{entry:{label:"Pencil",description:{zh:"UI \u8BBE\u8BA1",en:"UI design"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["pencil_propose_changes"],toolViews:[],panelAlias:{prefix:"pencil:",kind:"editor",title:"Pencil"}},browser:{wasm:!0},workspace:{files:[{extension:".fig",binary:!0,maxBytes:K0,createDirectory:"designs"}]},runtime:{invokeTimeoutMs:12e4}},Y0=new Map([[A1,O1],[R1,N1],[P1,C1]]);function Gd(i,e){let t=i.get(e);if(!t)throw new b("unreviewed_plugin","No trusted tool policy for this package");return t}function Q0(i,e){let t=i.get(e)?.workspace?.files??Hd;for(let r of t)if(!/^\.[a-z0-9]{1,16}$/.test(r.extension)||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0||r.maxBytes>K0||r.createDirectory!==void 0&&!/^[A-Za-z0-9_-]{1,64}$/.test(r.createDirectory))throw new b("invalid_policy","Invalid workspace file rule");return t}function J0(i,e){let t=i.get(e)?.runtime?.invokeTimeoutMs;return t===void 0?void 0:Math.min(Math.max(t,1e3),18e4)}var as=192*1024*1024,D7=512*1024,rk=i=>typeof i=="string"&&/^[a-f0-9-]{36}$/.test(i);function H1(i){if(!i||typeof i!="object"||Array.isArray(i))throw new b("invalid_input","Expected object input");return i}function ik(i){if(typeof i!="string"||!/^[\w.-]{1,160}$/.test(i)||i==="."||i==="..")throw new b("invalid_input","Invalid state key");return i}function os(i){if(i&&(!rk(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 b("invalid_storage","Invalid active plugin record");return i}var dr=class{root;pluginId;legacy;checkpoint;files;constructor(e,t,r,n,s=Hd){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 b("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return t}active(){return Ue(de(this.root,"active.json")).then(os)}async recover(){return qe(this.root,async()=>{let e=await this.active(),t=await pt(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 b("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");os(t.next),os(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 b("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 pt(de(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(l=>["version","stateRef"].includes(l))&&await pr(de(this.root,"fork.json"))}return await pr(de(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,t){return qe(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new b("stale_generation","Plugin activation changed concurrently");let n=await pt(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 b("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=os({...t,generation:e+1,operationId:Vd()});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 pr(de(this.root,"transition.json")),await pr(de(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return qe(this.root,async()=>{let t=await this.assertGeneration(e,!1),r=Vd(),n=de(this.root,"states",r);if(await pt(de(this.root,"fork.json")))throw new b("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 Wd(s)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new b("invalid_storage","Unexpected state file");if(!await Pe(de(s,o),as))throw new b("invalid_storage","Missing state file");await U1(de(s,o),de(n,o))}return await this.checkpoint?.("forked"),r})}async collect(e){return qe(this.root,async()=>{for(let c of["transition.json","fork.json"])if(await Pe(de(this.root,c),2*1024*1024))throw new b("gc_recovery_required",`GC refused: unresolved ${c}; stop all owners and inspect recovery references`);let t=await this.active(),r=os(await pt(de(this.root,"previous.json")));if(!t&&await Pe(de(this.root,"active.json"),2*1024*1024))throw new b("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 Wd(s),l=new Set(n.map(c=>c.stateRef));for(let c of o){if(!rk(c))throw new b("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=de(s,c),d=await yo(p);if(!d.isDirectory()||d.isSymbolicLink())throw new b("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let g of await Wd(p)){let f=await yo(de(p,g));if(!/^[a-f0-9]{64}\.json$/.test(g)||!f.isFile()||f.isSymbolicLink()||f.nlink!==1)throw new b("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!l.has(c)){let _=await Ue(de(p,g),as);if(!_)throw new b("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(_,"committed")){let y=_;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 b("gc_recovery_required",`GC refused: unresolved file intent in states/${c}; reconcile the workspace save before cleanup`)}else{if(Object.keys(_).some(y=>!["revision","schema","value","requestId","inputHash"].includes(y)))throw new b("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(_)}}}}for(let c of l)if(!o.includes(c))throw new b("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 q1(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 b("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 b("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 b("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 b("invalid_lease","Invalid invocation lease");this.scopeKey(e);let n=H1(r);return qe(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await Ue(this.statePath(s,e,ik(n.key),n.scope),as);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(s,e,ik(n.key),n.scope);if(!Number.isSafeInteger(n.expectedRevision)||n.expectedRevision<0||n.schema!==s.schema||!Object.hasOwn(n,"value"))throw new b("invalid_input","Invalid state revision or schema");if(JSON.stringify(n.value)===void 0)throw new b("invalid_input","State value must be JSON serializable");let l=JSON.stringify(n);if(Buffer.byteLength(l)>as)throw new b("state_too_large","Plugin state exceeds limit");let a=await Ue(o,as);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 b("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 b("invalid_input","Invalid workspace read limit");if(n.encoding!==void 0&&n.encoding!==(o.binary?"base64":"utf-8"))throw new b("invalid_input","Encoding does not match the reviewed file rule");let c=await Pe(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 b("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 b("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")||ek(t)||B1.isAbsolute(t))throw new b("invalid_path",`Use a workspace-relative ${n.extension} path`);let s=await Z0(e),o=F1(s,t),l=tk(s,o);if(!l||l===".."||l.startsWith(`..${$d}`)||ek(l))throw new b("invalid_path","Workspace path escapes root");let a=s,c=l.split($d);for(let d=0;d<c.length;d++){a=de(a,c[d]);let g;try{g=await yo(a)}catch(f){if(!Ni(f))throw f;if(d<c.length-1){if(!r||!n.createDirectory||tk(s,a)!==n.createDirectory)throw new b("invalid_path","Workspace directory does not exist");try{await D1(a,{mode:448})}catch(_){if(_.code!=="EEXIST")throw _}g=await yo(a)}}if(g&&(g.isSymbolicLink()||(d<c.length-1?!g.isDirectory():!g.isFile()||g.nlink!==1)))throw new b("invalid_path","Workspace path contains a link or non-regular file")}let p=await Z0(j1(o));if(p!==s&&!p.startsWith(s+$d))throw new b("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 b("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 Ue(a);if(d&&(d.requestId!==t.requestId||d.inputHash!==c||d.nextHash!==p))throw new b("duplicate_request","Request ID was reused with different content");let g;try{g=await X0(`${o}.lock`,"wx",384)}catch(_){throw _.code==="EEXIST"?new b("file_busy","Workspace file is locked; original file preserved"):_}let f;try{await g.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let _=await Pe(o,n.maxBytes),y=_?Te(_):null;if(d&&y===p)return{hash:p};if(d?.committed||y!==r.expectedHash)throw new b("file_conflict","Workspace file already exists or changed externally");await ye(a,{requestId:t.requestId,inputHash:c,nextHash:p,committed:!1}),f=de(l,`.plugin-${Vd()}.tmp`);let S=await X0(f,"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 b("file_conflict","Workspace directory changed during save");let A=await Pe(o,n.maxBytes);if((A?Te(A):null)!==r.expectedHash)throw new b("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),r.expectedHash===null){try{await M1(f,o)}catch(I){throw I.code==="EEXIST"?new b("file_conflict","Workspace file was created concurrently"):I}await pr(f),f=void 0}else await L1(f,o),f=void 0;return await ye(a,{requestId:t.requestId,inputHash:c,nextHash:p,committed:!0}),{hash:p}}finally{f&&await pr(f).catch(()=>{}),await g.close(),await pr(`${o}.lock`)}}};import{randomUUID as z1}from"node:crypto";import{fork as G1}from"node:child_process";import{randomUUID as W1}from"node:crypto";import{join as $1}from"node:path";import{EventEmitter as V1}from"node:events";var nk=192*1024*1024,ls=class i{child;pending=new Map;events=new V1;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=G1(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 b("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:$1(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 b("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 b("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>nk){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 b(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 b("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 b("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new b("worker_busy","Too many plugin requests"));let s=n?.requestId??W1();if(this.pending.has(s))return Promise.reject(new b("duplicate_request","An identical request is still running"));let o={type:"request",id:s,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>nk?Promise.reject(new b("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 b("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 b("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 b("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 K1={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},bo=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,r=K1,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 yd(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 b("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 b("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 b("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 b("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 b("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 ls.start(e,n+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(t))throw new b("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 b("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new b("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):z1(),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 b("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await ls.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 b("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 b("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 b("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 b("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new b("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 b("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new b("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 sk}from"node:fs/promises";var _o=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 Qr({root:kt(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new go(e.capabilities):void 0;this.scheduler=new fo({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:Q1(),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 dr(kt(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 bo(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,Y1(24).toString("base64url"));try{this.scheduler.start(r.id,zr(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){dt(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new b("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new b("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 Ue(kt(this.options.root,"policies","policies.json"));if(!e){if(await Pe(kt(this.options.root,"policies","policies.json"),2*1024*1024))throw new b("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 b("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await Ue(kt(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await qe(kt(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await ye(kt(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 b("invalid_input","Invalid plugin update policy");await qe(kt(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await ye(kt(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return qe(ro(this.options.root),async()=>{let e=await vd(this.options.root);if(!e)return{intent:e,admitted:!1};if(!wd(e))return e.phase==="required-action"&&await so(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await _d(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await _d(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await sk(this.options.workerEntry)).equals(await sk(kt(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(t){return await so(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 so(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 qe(kt(this.options.root,"policies"),async()=>{let t=await this.policies();await ye(kt(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:!0,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 b("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 b("not_installed","Only installed plugins can be updated");let c=this.devSource(e);if(c){let _=await c(n),y=await s.broker.active();if(await this.recordDevSync(e,_.version),!y?.enabled)return{installed:!0,enabled:!1,version:_.version};if(y.version===_.version&&!s.pendingVersion)return{unchanged:!0,version:_.version};let S=await this.lifecycle(e,()=>s.replace(_));return S.pending||this.packages.set(e,_),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 f=await this.lifecycle(e,()=>s.replace(g));return f.pending||this.packages.set(e,g),f}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 b("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 b("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 b("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 H0(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)||!J1(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(r0(await vd(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 Qr({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 Qr({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 X1}from"node:crypto";var oe=i=>Object.assign(new Error(i),{status:409,code:"view_barrier"}),cs=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)));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??X1();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(r=>r.activeActions||r.kind!=="controller"&&!r.frozen&&(r.busy||!this.immediate&&["editor","workspace"].includes(r.kind)));throw oe(`Close editors before updating; old version retained. Pending views: ${t.map(r=>`${r.kind}:${r.identity.mountId}${r.activeActions?` (action in flight x${r.activeActions})`:r.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,r)=>{let 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 ak={"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 ok(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"&&ak[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&&ak[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 Z1}from"node:crypto";var eP="https://github.com/settings/personal-access-tokens/new?"+new URLSearchParams({name:"pi-webapp",description:"pi-webapp GitHub plugin",issues:"write",pull_requests:"write",contents:"write"}),tP="Ov23limJmKiuu8cOP83E";function zd(i,e,t=process.env){if(i==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||tP,scope:"repo",createUrl:eP}}var iP="https://github.com/login/device/code",rP="https://github.com/login/oauth/access_token",nP=8,vo=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 b("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 b("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return n}async start(e,t,r){if(!r.clientId)throw new b("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>=nP)throw new b("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(iP,{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 b("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=Z1();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(rP,{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 ck,readFileSync as pk,statSync as sP}from"node:fs";import{lstat as aP,readdir as oP,writeFile as lP,mkdir as cP,rename as pP}from"node:fs/promises";import{delimiter as dP,dirname as uP,isAbsolute as mP,join as ur,resolve as ps}from"node:path";var lk="@chengzhiyi/pi-github",So={[lk]:{id:lk,name:"GitHub",icon:"github",description:{zh:"\u628A GitHub issue \u4EA4\u7ED9 agent\uFF1A\u5148\u51FA\u65B9\u6848\uFF0C\u7ECF\u4F60\u6279\u51C6\u540E\u5B9E\u73B0\u5E76\u63D0\u4EA4\u8349\u7A3F PR\u3002",en:"Hand GitHub issues to an agent: it plans, you approve, then it implements and opens a draft PR."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","panels","scheduler","network","secrets","sessions"]}},dk=i=>wt.some(e=>e.id===i),Kd=i=>!!So[i]||dk(i),uk=()=>[...Object.keys(So),...wt.map(i=>i.id)].join(", ");function gP(i=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,r=[],n="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let s of(i??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=s.lastIndexOf("="),l=s.slice(0,o),a=s.slice(o+1),c=So[l],p=o<1?`entry "${s}" is not <id>=<path.tgz>`:Kd(l)?a.endsWith(".tgz")?ck(ps(a))?null:`archive not found: ${ps(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${l}" (known: ${uk()})`;if(p){r.push({level:"error",source:n,...Kd(l)?{pluginId:l}:{},message:p});continue}c&&e.push(c),t.set(l,ps(a))}return{catalog:e,archives:t,notices:r}}var mk=i=>ur(i,"pi-web","hosted-dev.json"),gk=i=>ur(i,"pi-web","hosted-dev-status.json");function fP(i,e,t=process.cwd()){let r=[],n=[],s=(i.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(dP).map(l=>l.trim()).filter(Boolean);for(let l of s)r.push({path:ps(t,l),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=s.length>0;if(e&&ck(e)){o=!0;try{let l=JSON.parse(pk(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"||!mP(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:ps(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 hP(i){let e=(n,s)=>({notice:{level:"error",source:i.source,...s?{pluginId:s}:{},message:`${i.path}: ${n}`}}),t;try{t=sP(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(pk(ur(i.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof r.name!="string"?e("package.json has no name"):Kd(r.name)?Ci(r.piWebapp)?{pluginId:r.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name):e(`unknown plugin id "${r.name}" (known: ${uk()})`)}var wo=class{catalog;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let t=gP(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.catalog=[...t.catalog],this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let t=fP(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let o of t.specs){let l=hP(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`}),!dk(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}this.catalog.push(So[a])}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]}},ko=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 yP(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}s===n.applied||this.stopped||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){this.set(e,t,"switching");try{let s=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=r,s?.installed?s.pendingVersion?this.set(e,t,"pending",{version:s.version,message:`Waiting for editors to close before switching to ${s.pendingVersion}`}):this.set(e,t,"synced",{version:s.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(n){let s=Ne(n);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(s.code)||(t.applied=r),s.code==="not_installed"?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:s.code,message:`${s.message} (${s.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let 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 cP(uP(r),{recursive:!0}),await lP(o,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await pP(o,r)}catch{}}};async function yP(i){let e=[],t=async(r,n)=>{let s=await aP(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await t(ur(i,"package.json"),"package.json");let r=async(n,s,o)=>{if(!(o>16||e.length>8192))for(let l of(await oP(n,{withFileTypes:!0})).sort((a,c)=>a.name.localeCompare(c.name)))l.isDirectory()?await r(ur(n,l.name),`${s}/${l.name}`,o+1):await t(ur(n,l.name),`${s}/${l.name}`)};if(await r(ur(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 _P(i){try{return[...zr(i).secrets]}catch{return[]}}var Eo=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new vo;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Y0,e.dev?.enabled&&(this.devWatcher=new ko({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}}})),this.adapter=new po({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 b("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,s.generation,r);return ok(o)}}),this.manager=new _o({...e,workspaceRules:t=>Q0(this.trusted,t),invokeTimeoutMs:t=>J0(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(Gd(this.trusted,t).tools).length)throw new b("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:_P(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 b("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(r))throw new b("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 b("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)?zd(t.pluginId,t.name):void 0;if(!s)throw new b("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 b("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 b("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&&uw(this.manager.servedManifest(r.pluginId));return{bytes:r.bytes,mime:r.mime,csp:dw({wasm:n})}}}}verifyTools(e,t){let r=Gd(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 b("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new b("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 b("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 b("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 b("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 b("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 dr(Yd(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new b("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??wt)try{let t=await new dr(Yd(this.options.root,"data"),e.id).active();this.views.set(e.id,new cs(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new cs(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Yd(this.options.root,"host-version.json");(await Ue(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??wt)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=zd(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??wt).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 b("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new b("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 b("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 b("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 b("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 b("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:bP(),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 b("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new b("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 vP,readdir as wP,unlink as kP}from"node:fs/promises";import{join as Jr}from"node:path";import{randomUUID as SP}from"node:crypto";var Qd="hosted-migration.json";function fk(i,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:n}=t.scope,s=Jr(i,Te(JSON.stringify([r,n])));await Le(i),await Le(s);let o=Jr(s,"scope.lock"),l;try{l=await vP(o,"wx",384)}catch(a){throw a.code==="EEXIST"?new b("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:SP()}));let a=await Ue(Jr(s,Qd));if(a&&(a.version!==1||a.pluginId!==e))throw new b("invalid_storage","Legacy scope belongs to another migration");let c=await wP(s),p=[];for(let g of c){if(g==="scope.lock"||g==="focus.json"||g===Qd||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(g))continue;if(!/^[\w-]{1,80}\.json$/.test(g))throw new b("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new b("invalid_storage","Too many legacy checkpoints");let f=await Ue(Jr(s,g),3*512*1024);if(!f||f.version!==1||f.cwd!==r||f.sessionId!==n||!f.draft||g!==`${f.draft.id}.json`)throw new b("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(f.draft)}let d=await Ue(Jr(s,"focus.json"),1024);if(d!==null&&(typeof d!="string"||!p.some(g=>g.id===d)))throw new b("invalid_storage","Invalid legacy focused drawing");return a||await ye(Jr(s,Qd),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:d}}finally{await l.close(),await kP(o)}}}import{join as PP}from"node:path";import{randomUUID as EP}from"node:crypto";var TP=6e4,To=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 b("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new b("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<TP?new b("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:EP(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new b("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 b("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 IP,readFile as xP,rename as AP,writeFile as OP}from"node:fs/promises";import{randomUUID as RP,createHash as NP}from"node:crypto";import{join as hk}from"node:path";var Io=class{dir;queue=Promise.resolve();constructor(e){this.dir=hk(e,"secrets")}file=e=>hk(this.dir,`${NP("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await xP(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!Ni(t))throw new b("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 IP(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${RP()}.tmp`;await OP(n,JSON.stringify(r),{mode:384}),await AP(n,this.file(e))})}};function yk(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 CP="scheduler";function bk(i){let e=new To({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 Io(PP(i.root,"capability-secrets")),sessions:yk(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=i.activeWorkspace();if(!n)return null;try{return i.trustedScope(n,CP)}catch{return null}}}}async function DP(){for(let i of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=Ha(i),t=new zt({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:ln,buildId:It,browser:Ha({}).browser}}async function _k(){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 zt({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:ln,buildId:It}}finally{await i.close()}}var ds=en(LP(jP(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),WP=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),m=globalThis[WP]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new Ri(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:ui()}),Ge()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new or,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};m.lifecycle??=new or;m.tuiGeneration??=0;m.stopChanged??=null;m.tuiWaitController??=new AbortController;m.tuiStreaming??=null;m.tuiPrompts??=new Ri(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:ui()}),Ge()});m.tuiPromptSessionId??=null;m.tuiAgentError??=!1;var wk=!1;function $P(i){return wk||(wk=!0,setTimeout(()=>{i.pruneReleases().catch(()=>{})},6e4).unref()),i}function xo(){return m.selected==="sdk"?m.workspaceSessions?.catalog??null:m.tuiCatalog}var VP=null;function zP(){return VP??=FP.create({refreshOnCreate:!1})}var Ao=new Map;async function Zr(){let i=await zP(),e=m.selected==="tui"?m.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Ao.keys())t.has(r)||(i.unregisterProvider(r),Ao.delete(r));for(let r of t){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),o=n??s;!o||Ao.get(r)===o||(n?i.registerNativeProvider(n):s&&i.registerProvider(r,s),Ao.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")})():ui()}function ui(){if(m.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...hw(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 iu(i,e,t,r,n){let s=nt(i);Oi({...ui(),idle:s.isIdle()},e,n);let o=s.isIdle();o&&Wr(()=>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:ui()})}catch(l){throw o&&(m.operation=void 0),l}}function Zd(){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=ui();return!m.hosted?.adapter.isFrozen&&m.current.isIdle()&&!r.paused&&!r.interactions.length};m.tuiPrompts.schedule(t,(r,n,s)=>iu(i,r,n,s))}function Ye(i){if(We().sessionId!==i)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function Tk(){let i=(m.workspaces?.list()??[]).map(p=>({...p})),e=m.activeWorkspaceId,t=We(),n=m.current?ui():null,s=await nr(t.cwd).catch(p=>(m.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=n?await nr(n.cwd).catch(p=>(m.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,l=await tu.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 Hr(p.path,l).catch(f=>(f instanceof Jn?p.available=!1:m.bridge?.reportError?.(f,{stage:"workspace_sessions"}),[]))).map(f=>({id:f.id,workspaceId:p.id,path:f.path,name:f.name||f.firstMessage?.slice(0,50)||"",modified:f.modified.toISOString(),idle:!0}));for(let f of a.filter(_=>_.cwd===p.path)){if(f.blank&&f.sessionId!==t.sessionId)continue;let _=g.findIndex(S=>S.id===f.sessionId),y={id:f.sessionId,workspaceId:p.id,path:f.path??g[_]?.path??null,name:f.name,modified:f.modified,idle:f.idle};_<0?g.unshift(y):g[_]=y}return p.path===s&&!g.some(f=>f.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 kk=0;async function Ge(){if(!m.bridge)return;let i=++kk;try{let e=await Tk();i===kk&&m.bridge?.publish({type:"workspaces",value:e})}catch(e){m.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function eu(i,e=!1){let t=m.workspaces?.get(i);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Yt(t.path),!e&&m.current&&t.path===await nr(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 Ge()}async function Sk(i,e,t){let r=m.workspaces?.get(i);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await Yt(r.path);if(m.workspaceSessions?.hasSession(n,e)||m.current?.sessionManager.getSessionId()===e&&await nr(m.current.cwd)===n)return r;if(!(await Hr(n)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function nt(i){let e=m.current;if(e===null||e.sessionManager.getSessionId()!==i)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function tt(i){m.current=i,m.selected==="tui"&&m.bridge?.publish({type:"snapshot",session:We()})}function Ik(){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 BP.create(i,void 0,{projectTrusted:e})}async function xk(){let i=Ik(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),t=new Ek({cwd:We().cwd,agentDir:ut(),settingsManager:i}),r=Qw(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:i.isProjectTrusted(),global:e(i.getGlobalSettings()),project:e(i.getProjectSettings()),installed:r}}async function KP(i){Ye(i.sessionId);let e=m.selected==="tui"?nt(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=Ik();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 Ek({cwd:We().cwd,agentDir:ut(),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&&tt(m.current)):(await m.workspaceSessions?.reload(),m.bridge?.publish({type:"plugins_changed"})),await xk()}function Oo(i,e=fd){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=Jd(c);return{cwd:d,sessionId:p,workspaceId:vk("sha256").update(d).digest("hex")}},r=Xr(ut(),"pi-web","hosted"),n=new wo({configPath:mk(ut())});m.hosted??=new Eo({root:r,...n.enabled?{dev:n,devStatusPath:gk(ut())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...wt,...n.catalog]}:{},...bk({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(UP(en(ds,"../../package.json"),"utf8")).version,packageRoot:en(ds,"../.."),workerEntry:en(ds,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${vk("sha256").update(ut()).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:()=>fk(Xr(ut(),"pi-web","diagrams")),changed:()=>m.bridge?.publish({type:"hosted_plugins_changed"})}),m.offHostedThaw?.(),m.offHostedThaw=m.hosted?.adapter.onThaw(Zd),m.pi=i;let s=Pm({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 Qa(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 Gr({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:Xd,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});m.interactions?.dispose(),m.interactions=new Br(i.events,c=>!!m.bridge&&c.sessionId===m.current?.sessionManager.getSessionId()&&Xn(m.tuiCatalog,c.pluginId),()=>{m.current&&m.selected==="tui"&&tt(m.current)});let l=()=>{m.stopChanged?.(),m.stopChanged=i.events.on(Ja,()=>{m.selected==="tui"&&m.current&&tt(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 Ri(()=>{m.selected==="tui"&&m.current&&m.bridge?.publish({type:"snapshot",session:ui()}),Ge()}),m.tuiPromptSessionId=p.sessionManager.getSessionId()),m.tuiAgentError=!1,m.bridge){let d=await ar.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),tt(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 Ge())}).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)),tt(p),Ge()}),i.on("agent_end",(c,p)=>tt(p)),i.on("agent_settled",(c,p)=>{m.bridge?.breadcrumb?.("agent_end",o(p)),m.tools?.clear(),m.operation=void 0,m.tuiStreaming=null,Zd(),tt(p),Ge()}),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)=>tt(p)),i.on("thinking_level_select",(c,p)=>tt(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:Xd});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}),tt(p),Ge()}),i.on("session_info_changed",(c,p)=>tt(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:rr(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 zt;try{m.current=c,m.commandContext="newSession"in c?c:null,m.pi=i,m.tuiCatalog=await ar.discover(c.cwd,c.isProjectTrusted?.()??!1),m.workspaces===null&&(m.workspaces=new Ya(vw(ut())),await m.workspaces.load());try{await m.workspaces.discover((await tu.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 zt}if(m.bridge===null){let g=m.workspaceSessions&&(m.workspaceSessions.telemetryVersion!==2||m.workspaceSessions.runtimeVersion!==4)?m.workspaceSessions:null,f=g?.session&&g.path?{path:g.path,sessionManager:g.session.sessionManager}:null;g&&(await g.dispose(),m.workspaceSessions=null),m.workspaceSessions??=new to(y=>{m.selected==="sdk"&&m.bridge?.publish(y)},()=>m.current?.model,y=>{try{return!!m.current&&Jd(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"},()=>{Ge()},s,{adapter:m.hosted.adapter,scope:t}),f&&await m.workspaceSessions.open(f.path,{sessionManager:f.sessionManager});let _={hosted:m.hosted?.handlers,selfUpdate:$P(new co({agentDir:ut(),packageRoot:en(ds,"../.."),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(Jd(m.current.cwd))}catch{y.push(m.current.cwd)}return y},plugins:async()=>{let y=xo();return await y?.refreshAssets(),y?.view()??{plugins:[],errors:[]}},pluginAsset:async y=>xo()?.asset(y)??null,async invokePluginAction(y,S,T,A){if(Ye(y),!xo()?.has(S))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let I=m.selected,C=m.tuiGeneration,q=m.workspaceSessions?.session,F={requestId:GP(),sessionId:y,pluginId:S,action:T,input:A},N=m.selected==="sdk"?await m.workspaceSessions.invokePluginAction(F):await Xa(m.pi.events,F,15e3,m.tuiWaitController.signal);if(Ye(y),I!==m.selected||(I==="tui"?C!==m.tuiGeneration:q!==m.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return m.selected==="tui"&&m.current&&tt(m.current),N},async resolvePluginInteraction(y,S,T,A){if(Ye(y),!Xn(xo(),S))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");m.selected==="sdk"?m.workspaceSessions.resolveInteraction(y,S,T,A):m.interactions.resolve(y,S,T,A)},image(y,S,T){Ye(y);let I=(m.selected==="sdk"?m.workspaceSessions?.session?.sessionManager.getBranch():m.current?.sessionManager.getBranch())?.find(q=>q.id===S);if(I?.type!=="message"||I.message.role!=="user"||!Array.isArray(I.message.content))return null;let C=I.message.content[T];return C?.type!=="image"?null:{data:Buffer.from(C.data,"base64"),mimeType:C.mimeType}},async workspaces(){return Tk()},async addWorkspace(y,S){let T=await m.workspaces.add(y,S);try{await eu(T.id,!0)}catch(A){throw await Ge(),A}},async selectWorkspace(y){await eu(y)},async newSessionInWorkspace(y){await eu(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 Ge()},async selectSession(y,S,T){let A=m.workspaces?.get(y);if(!A)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Yt(A.path),S===m.current?.sessionManager.getSessionId()&&A.path===await nr(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===A.path)return;if(m.workspaceSessions?.hasSession(A.path,S))await m.workspaceSessions.open(A.path,{sessionId:S});else{if(!(await Hr(A.path)).some(C=>C.id===S&&C.path===T))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await m.workspaceSessions.open(A.path,{sessionFile:T})}m.selected="sdk",m.activeWorkspaceId=y,m.bridge?.publish({type:"snapshot",session:We()})}await Ge()},async renameSession(y,S,T,A){let I=A.replace(/\s+/g," ").trim();if(I.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await Sk(y,S,T),m.current?.sessionManager.getSessionId()===S&&m.pi?m.pi.setSessionName(I):m.workspaceSessions?.rename(S,I)||tu.open(T).appendSessionInfo(I),m.selected==="tui"&&m.current?.sessionManager.getSessionId()===S&&m.bridge?.publish({type:"snapshot",session:We()}),await Ge()},async deleteSession(y,S,T){let A=await Sk(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 I=await m.workspaceSessions?.discard(S)??null,C=I?.path??(T||null);C&&await Yw(C,ut()),I?.wasActive&&m.selected==="sdk"&&(await m.workspaceSessions.open(A.path,"new"),m.selected="sdk",m.activeWorkspaceId=y,m.bridge?.publish({type:"snapshot",session:We()})),await Ge()},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 Zr(),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(A=>A!==null)}))},async providerModels(y){let S=await Zr();return Zm(Xr(ut(),"models.json"),y,S)},async updateProviderModel(y,S,T){if(Ye(y),m.selected==="tui"?!nt(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 A=We().model;if(T.action==="remove"&&A===`${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&&A===`${S}/${T.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let I=await Zr();await eg(Xr(ut(),"models.json"),S,T,I),await I.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 C=T.action==="save"?T.model.id:T.action==="base_url"&&A?.startsWith(`${S}/`)?A.slice(S.length+1):null;if(C&&A===`${S}/${C}`)if(m.selected==="sdk")try{await m.workspaceSessions.setModel(S,C)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let q=nt(y),F=q.modelRegistry.find(S,C);if(!F||!m.pi||!await m.pi.setModel(F))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");tt(q)}},async logoutProvider(y,S){if(Ye(y),m.selected==="tui"?!nt(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 Zr();if(!(await T.listCredentials()).some(A=>A.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 A=await Zr();await A.login(y,S,zm(y,S,T)),await A.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(Ye(y),m.selected==="tui"?!nt(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 Zr();if(T.getProvider(S.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await Km(Xr(ut(),"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(Ye(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=nt(y);if(!S.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");S.compact()},async setModel(y,S,T){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.setModel(S,T);return}let A=nt(y);if(!A.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let I=A.modelRegistry.find(S,T);if(!I||!A.modelRegistry.getAvailable().some(C=>C.provider===S&&C.id===T))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!m.pi||!await m.pi.setModel(I))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");tt(A)},async setThinkingLevel(y,S){if(Ye(y),!["off","minimal","low","medium","high","xhigh"].includes(S))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(m.selected==="sdk"){let I=m.workspaceSessions?.session;if(!I||!I.isIdle||!I.getAvailableThinkingLevels().includes(S))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");I.setThinkingLevel(S),m.bridge?.publish({type:"snapshot",session:We()});return}let A=nt(y);if(!A.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!A.model||!HP(A.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),tt(A)},config:xk,updateConfig:KP,async send(y,S,T=[],A,I){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.send(S,T,A,I);return}let C=nt(y);if(Oi(ui(),S,I),I==="followUp"&&(!C.isIdle()||m.tuiPrompts.length>0)){m.tuiPrompts.enqueue(S,T,A),Zd();return}if(C.isIdle()&&m.tuiPrompts.sending)throw new et("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await iu(y,S,T,A,I)},async updateQueuedPrompt(y,S,T,A){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.updateQueuedPrompt(S,T,A);return}if(A.kind==="steer"&&nt(y).isIdle())throw new et("\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,A,(I,C,q)=>iu(y,I,C,q,"steer"))},async abort(y){if(Ye(y),m.selected==="sdk")await m.workspaceSessions.stop();else{let S=nt(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(Yn),S.abort()}},async resume(y,S){if(Ye(y),m.selected==="sdk"){await m.workspaceSessions.resume(S);return}let T=nt(y);if(Wr(()=>m.hosted?.adapter.assertAdmission(),S,(A,I)=>m.bridge?.reportError?.(A,I)),!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(Za(We().messages),{triggerTurn:!0})}catch(A){throw m.operation=void 0,A}},async newSession(y){if(Ye(y),m.selected==="sdk"){let A=m.workspaces?.get(m.activeWorkspaceId??"");if(!A)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await m.workspaceSessions.reuseBlank(A.path)||await m.workspaceSessions.open(A.path,"new"),await Ge();return}let S=nt(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 Ge();return}if((await m.commandContext.newSession({withSession:async A=>{m.commandContext=A,m.replacementContext=A,m.replacementSessionId=A.sessionManager.getSessionId(),m.current=A}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await Ge()}};_.addWorkspace=m.lifecycle.wrap(_.addWorkspace),_.selectWorkspace=m.lifecycle.wrap(_.selectWorkspace),_.newSessionInWorkspace=m.lifecycle.wrap(_.newSessionInWorkspace),_.removeWorkspace=m.lifecycle.wrap(_.removeWorkspace),_.selectSession=m.lifecycle.wrap(_.selectSession),_.renameSession=m.lifecycle.wrap(_.renameSession),_.deleteSession=m.lifecycle.wrap(_.deleteSession),_.newSession=m.lifecycle.wrap(_.newSession),_.updateConfig=m.lifecycle.wrap(_.updateConfig),m.bridge=await fw(_,ds,m.telemetry)}if(m.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let g=[],f=null;for(let _ of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(MP).filter(Boolean))try{g.push(qP(Xr(en(_),"dist"),(y,S)=>{let T=String(S??"");["client.js","client.css"].includes(T)&&(f&&clearTimeout(f),f=setTimeout(()=>m.bridge?.publish({type:"plugins_changed"}),180))}))}catch(y){m.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${_}: ${String(y)}`})}m.stopPluginWatch=()=>{for(let _ of g)_.close();f&&clearTimeout(f)}}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:Xd}),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 K9=Oo;export{K9 as default,DP as verifySentryDisabledRelease,_k as verifySentryNodeRelease};
247
247
 
248
- //# debugId=85b9f08e-ec7c-4ef5-8ddd-adbb8d36ec1a
248
+ //# debugId=0115f7b2-180a-4125-81f5-772406ddc1bd