@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
29 lines • 280 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{DEFAULT_HTTP_IDLE_TIMEOUT_MS,parseHttpIdleTimeoutMs}from"./chunk-DEUEMEV3.js";import{base64ByteLength}from"./chunk-XI6THO4F.js";import{assertValidSessionId,sessionFileNameId}from"./chunk-WZ4IZIR2.js";import{projectAgentsSkillDirs}from"./chunk-7AEFFKBD.js";import{DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SYSTEM_THEME_NAME,getTerminalTheme,initTheme,isStdoutTakenOver,keyHint,keyText,loadThemeFromPath,markTerminalColorsPending,parseAutoThemeSetting,rawKeyHint,resolveThemeSetting,setRegisteredThemes,setTerminalColorScheme,setTerminalColors,setTheme,setThemeInstance,theme}from"./chunk-KAQBXCAT.js";import{isBillingErrorMessage,usageLimitScope}from"./chunk-5QZIEDOI.js";import{KeybindingsManager}from"./chunk-3MCOVENJ.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{lockWithLossHandling}from"./chunk-ZZU4J6QP.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import{CredentialStoreBusyError,FILE_STORAGE_LOCK_OPTIONS,FILE_STORAGE_LOCK_RETRY_BUDGET_MS,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,FILE_STORAGE_SYNC_LOCK_BUDGET_MS,isLockError}from"./chunk-7X72IACK.js";import{appendDebugLogEntry,appendHiddenTuiStdout}from"./chunk-WHTAR5IS.js";import{usageLimitReset}from"./chunk-WB4BUHOH.js";import{parseRetryAfterMsMarker}from"./chunk-RQFD6LG2.js";import{Container,Input,ProcessTerminal,Spacer,TUI,Text,fuzzyMatchLower,getKeybindings,setCapabilityOverrides,setKeybindings,truncateToWidth,visibleWidth}from"./chunk-4PMRUR4L.js";import{require_ignore}from"./chunk-DPNC7S74.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,LEGACY_PROVIDER_IDS,USAGE_LIMIT_EXHAUSTION,classifyErrorMessage,isQuotaExhaustionMessage,normalizeModelRef,normalizeProviderId,readByProviderId}from"./chunk-AFDUWYAX.js";import{require_semver}from"./chunk-ZOFZRJSL.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,PACKAGE_NAME,canonicalizePath,envValue,findNearestParentConfigDir,getAgentDir,getSettingsPath,isLocalPath,markPathIgnoredByCloudSync,normalizePath,resolvePath,spawnProcess,spawnProcessSync,stripBom}from"./chunk-QJTWAOBX.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_index_min=__commonJS({"node_modules/lru-cache/dist/commonjs/node/index.min.js"(exports){"use strict";var j=(u,t)=>()=>(t||u((t={exports:{}}).exports,t),t.exports),I=j(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0}),O.tracing=O.metrics=void 0;var U=__require("node:diagnostics_channel");O.metrics=(0,U.channel)("lru-cache:metrics"),O.tracing=(0,U.tracingChannel)("lru-cache")}),P=j(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0}),R.defaultPerf=void 0,R.defaultPerf=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date});Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var g=I(),N=P(),C=()=>g.metrics.hasSubscribers||g.tracing.hasSubscribers,k=new Set,G=typeof process=="object"&&process?process:{},V=(u,t,e,i)=>{typeof G.emitWarning=="function"?G.emitWarning(u,t,e,i):console.error(`[${e}] ${t}: ${u}`)},q=u=>!k.has(u),T=u=>!!u&&u===Math.floor(u)&&u>0&&isFinite(u),H=u=>T(u)?u<=Math.pow(2,8)?Uint8Array:u<=Math.pow(2,16)?Uint16Array:u<=Math.pow(2,32)?Uint32Array:u<=Number.MAX_SAFE_INTEGER?W:null:null,W=class extends Array{constructor(t){super(t),this.fill(0)}},L=class u{heap;length;static#o=!1;static create(t){let e=H(t);if(!e)return[];u.#o=!0;let i=new u(t,e);return u.#o=!1,i}constructor(t,e){if(!u.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},M=class u{#o;#c;#m;#W;#S;#x;#j;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#_;#r;#y;#F;#d;#g;#T;#U;#f;#R;static unsafeExposeInternals(t){return{starts:t.#F,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#u,get head(){return t.#a},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#G(e,i,s,n),moveToTail:e=>t.#M(e),indexes:e=>t.#A(e),rindexes:e=>t.#z(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#x}get memoMethod(){return this.#j}get dispose(){return this.#m}get onInsert(){return this.#W}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:l,allowStale:h,dispose:r,onInsert:c,disposeAfter:w,noDisposeOnSet:y,noUpdateTTL:d,maxSize:p=0,maxEntrySize:f=0,sizeCalculation:_,fetchMethod:a,memoMethod:S,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:x=1,perf:v}=t;if(this.backgroundFetchSize=x,v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#w=v??N.defaultPerf,e!==0&&!T(e))throw new TypeError("max option must be a nonnegative integer");let E=e?H(e):Array;if(!E)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=p,this.maxEntrySize=f||this.#c,this.sizeCalculation=_,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#j=S,a!==void 0&&typeof a!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#x=a,this.#U=!!a,this.#s=new Map,this.#i=Array.from({length:e}).fill(void 0),this.#t=Array.from({length:e}).fill(void 0),this.#l=new E(e),this.#u=new E(e),this.#a=0,this.#h=0,this.#_=L.create(e),this.#n=0,this.#b=0,typeof r=="function"&&(this.#m=r),typeof c=="function"&&(this.#W=c),typeof w=="function"?(this.#S=w,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#m,this.#R=!!this.#W,this.#f=!!this.#S,this.noDisposeOnSet=!!y,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!m,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#X()}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!l,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let D="LRU_CACHE_UNBOUNDED";q(D)&&(k.add(D),V("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",D,u))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#k(){let t=new W(this.#o),e=new W(this.#o);this.#d=t,this.#F=e;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,r,c=this.#w.now())=>{e[h]=r!==0?c:0,t[h]=r,s(h,r)},this.#D=h=>{e[h]=t[h]!==0?this.#w.now():0,s(h,t[h])};let s=this.ttlAutopurge?(h,r)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),r&&r!==0&&i){let c=setTimeout(()=>{this.#p(h)?(this.#v(this.#i[h],"expire"),i[h]=void 0):s(h,l(h))},r+1);c.unref&&c.unref(),i[h]=c}}:()=>{};this.#E=(h,r)=>{if(t[r]){let c=t[r],w=e[r];if(!c||!w)return;h.ttl=c,h.start=w,h.now=n||o();let y=h.now-w;h.remainingTTL=c-y}};let n=0,o=()=>{let h=this.#w.now();if(this.ttlResolution>0){n=h;let r=setTimeout(()=>n=0,this.ttlResolution);r.unref&&r.unref()}return h};this.getRemainingTTL=h=>{let r=this.#s.get(h);return r===void 0?0:l(r)};let l=h=>{let r=t[h],c=e[h];if(!r||!c)return 1/0;let w=(n||o())-c;return r-w};this.#p=h=>{let r=e[h],c=t[h];return!!c&&!!r&&(n||o())-r>c}}#D=()=>{};#E=()=>{};#H=()=>{};#p=()=>!1;#X(){let t=new W(this.#o);this.#b=0,this.#y=t,this.#C=e=>{this.#b-=t[e],t[e]=0},this.#N=(e,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!T(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return s},this.#I=(e,i,s)=>{if(t[e]=i,this.#c){let n=this.#c-t[e];for(;this.#b>n;)this.#P(!0)}this.#b+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#C=t=>{};#I=(t,e,i)=>{};#N=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#a);)e=this.#u[e]}*#z({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#a;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#h);)e=this.#l[e]}#V(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#z())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#z()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#z())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.#L(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#z()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#z({allowStale:!0}))this.#p(e)&&(this.#v(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#d&&this.#F){let o=this.#d[e],l=this.#F[e];if(o&&l){let h=o-(this.#w.now()-l);n.ttl=h,n.start=Date.now()}}return this.#y&&(n.size=this.#y[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let o={value:n};if(this.#d&&this.#F){o.ttl=this.#d[e];let l=this.#w.now()-this.#F[e];o.start=Math.floor(Date.now()-l)}this.#y&&(o.size=this.#y[e]),t.unshift([i,o])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#w.now()-s}this.#O(e,i.value,i)}}set(t,e,i={}){let{status:s=g.metrics.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op="set",s.key=t,e!==void 0&&(s.value=e),s.cache=this);let n=this.#O(t,e,i);return s&&g.metrics.hasSubscribers&&g.metrics.publish(s),n}#O(t,e,i,s){let{ttl:n=this.ttl,start:o,noDisposeOnSet:l=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:r}=i,c=this.#e(e);if(e===void 0)return r&&(r.set="deleted"),this.delete(t),this;let{noUpdateTTL:w=this.noUpdateTTL}=i;r&&!c&&(r.value=e);let y=this.#N(t,e,i.size||0,h,r);if(this.maxEntrySize&&y>this.maxEntrySize)return this.#v(t,"set"),r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this;let d=this.#n===0?void 0:this.#s.get(t);if(d===void 0)d=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#o?this.#P(!1):this.#n,this.#i[d]=t,this.#t[d]=e,this.#s.set(t,d),this.#l[this.#h]=d,this.#u[d]=this.#h,this.#h=d,this.#n++,this.#I(d,y,r),r&&(r.set="add"),w=!1,this.#R&&!c&&this.#W?.(e,t,"add");else{this.#M(d);let p=this.#t[d];if(e!==p){if(!l)if(this.#e(p)){p!==s&&p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&f!==e&&(this.#T&&this.#m?.(f,t,"set"),this.#f&&this.#r?.push([f,t,"set"]))}else this.#T&&this.#m?.(p,t,"set"),this.#f&&this.#r?.push([p,t,"set"]);if(this.#C(d),this.#I(d,y,r),this.#t[d]=e,!c){let f=p&&this.#e(p)?p.__staleWhileFetching:p,_=f===void 0?"add":e!==f?"replace":"update";r&&(r.set=_,f!==void 0&&(r.oldValue=f)),this.#R&&this.onInsert?.(e,t,_)}}else c||(r&&(r.set="update"),this.#R&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(w||this.#H(d,n,o),r&&this.#E(r,d)),!l&&this.#f&&this.#r){let p=this.#r,f;for(;f=p?.shift();)this.#S?.(...f)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#a];if(this.#P(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#P(t){let e=this.#a,i=this.#i[e],s=this.#t[e],n=this.#e(s);n&&s.__abortController.abort(new Error("evicted"));let o=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&o!==void 0&&(this.#T&&this.#m?.(o,i,"evict"),this.#f&&this.#r?.push([o,i,"evict"])),this.#C(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#a=this.#h=0,this.#_.length=0):this.#a=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="has",i.key=t,i.cache=this);let s=this.#Y(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Y(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let o=this.#t[n];if(this.#e(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#D(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{status:i=C()?{}:void 0}=e;i&&(i.op="peek",i.key=t,i.cache=this),e.status=i;let s=this.#J(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#J(t,e){let{status:i,allowStale:s=this.allowStale}=e,n=this.#s.get(t);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?"miss":"stale");return}let o=this.#t[n],l=this.#e(o)?o.__staleWhileFetching:o;return i&&(l!==void 0?(i.peek="hit",i.value=l):i.peek="miss"),l}#G(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let o=new AbortController,{signal:l}=i;l?.addEventListener("abort",()=>o.abort(l.reason),{signal:o.signal});let h={signal:o.signal,options:i,context:s},r=(f,_=!1)=>{let{aborted:a}=o.signal,S=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(a&&!_?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,S&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!S&&!_)return w(o.signal.reason,F);let b=d,m=this.#t[e];return(m===d||m===void 0&&S&&_)&&(f===void 0?b.__staleWhileFetching!==void 0?this.#t[e]=b.__staleWhileFetching:this.#v(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.#O(t,f,h.options,b))),f},c=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),w(f,!1)),w=(f,_)=>{let{aborted:a}=o.signal,S=a&&i.allowStaleOnFetchAbort,F=S||i.allowStaleOnFetchRejection,b=F||i.noDeleteOnFetchRejection,m=d;if(this.#t[e]===d&&(!b||!_&&m.__staleWhileFetching===void 0?this.#v(t,"fetch"):S||(this.#t[e]=m.__staleWhileFetching)),F)return i.status&&m.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),m.__staleWhileFetching;if(m.__returned===m)throw f},y=(f,_)=>{let a=this.#x?.(t,n,h);o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=S=>r(S,!0)))}),a&&a instanceof Promise?a.then(S=>f(S===void 0?void 0:S),_):a!==void 0&&f(a)};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(y).then(r,c),p=Object.assign(d,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#O(t,p,{...h.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=p,p}#e(t){if(!this.#U)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#q(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#q(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:h=0,sizeCalculation:r=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:y=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:_=!1,status:a,signal:S}=e;if(a&&(a.op="fetch",a.key=t,_&&(a.forceRefresh=!0),a.cache=this),!this.#U)return a&&(a.fetch="get"),this.#L(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:l,size:h,sizeCalculation:r,noUpdateTTL:c,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:p,ignoreFetchAbort:d,status:a,signal:S},b=this.#s.get(t);if(b===void 0){a&&(a.fetch="miss");let m=this.#G(t,b,F,f);return m.__returned=m}else{let m=this.#t[b];if(this.#e(m)){let E=i&&m.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",E&&(a.returnedStale=!0)),E?m.__staleWhileFetching:m.__returned=m}let A=this.#p(b);if(!_&&!A)return a&&(a.fetch="hit"),this.#M(b),s&&this.#D(b),a&&this.#E(a,b),m;let z=this.#G(t,b,F,f),v=z.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=A?"stale":"refresh",v&&A&&(a.returnedStale=!0)),v?z.__staleWhileFetching:z.__returned=z}}forceFetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#K(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#K(t,e={}){let i=await this.#q(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="memo",i.key=t,e.context&&(i.context=e.context),i.cache=this);let s=this.#Q(t,e);return i&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Q(t,e={}){let i=this.#j;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,status:n,forceRefresh:o,...l}=e;n&&o&&(n.forceRefresh=!0);let h=this.#L(t,l),r=o||h===void 0;if(n&&(n.memo=r?"miss":"hit",r||(n.value=h)),!r)return h;let c=i(t,h,{options:l,context:s});return n&&(n.value=c),this.#O(t,c,l),c}get(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op="get",i.key=t,i.cache=this);let s=this.#L(t,e);return i&&(s!==void 0&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i)),s}#L(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=e,l=this.#s.get(t);if(l===void 0){o&&(o.get="miss");return}let h=this.#t[l],r=this.#e(h);return o&&this.#E(o,l),this.#p(l)?r?(o&&(o.get="stale-fetching"),i&&h.__staleWhileFetching!==void 0?(o&&(o.returnedStale=!0),h.__staleWhileFetching):void 0):(n||this.#v(t,"expire"),o&&(o.get="stale"),i?(o&&(o.returnedStale=!0),h):void 0):(o&&(o.get=r?"fetching":"hit"),this.#M(l),s&&this.#D(l),r?h.__staleWhileFetching:h)}#B(t,e){this.#u[e]=t,this.#l[t]=e}#M(t){t!==this.#h&&(t===this.#a?this.#a=this.#l[t]:this.#B(this.#u[t],this.#l[t]),this.#B(this.#h,t),this.#h=t)}delete(t){return this.#v(t,"delete")}#v(t,e){g.metrics.hasSubscribers&&g.metrics.publish({op:"delete",delete:e,key:t,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#$(e);else{this.#C(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#m?.(n,t,e),this.#f&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let o=this.#u[s];this.#l[o]=this.#l[s];let l=this.#l[s];this.#u[l]=this.#u[s]}this.#n--,this.#_.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#S?.(...n)}return i}clear(){return this.#$("delete")}#$(t){for(let e of this.#z({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#m?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#a=0,this.#h=0,this.#_.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=M}});var require_hosts=__commonJS({"node_modules/hosted-git-info/lib/hosts.js"(exports,module){"use strict";var maybeJoin=(...args)=>args.every(arg=>arg)?args.join(""):"",maybeEncode=arg=>arg?encodeURIComponent(arg):"",formatHashFragment=f=>f.toLowerCase().replace(/^\W+/g,"").replace(/(?<!\W)\W+$/,"").replace(/\//g,"").replace(/\W+/g,"-"),defaults2={sshtemplate:({domain,user,project,committish})=>`git@${domain}:${user}/${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,user,project,committish})=>`git+ssh://git@${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath,path:path2})=>`https://${domain}/${user}/${project}${maybeJoin("/",editpath,"/",maybeEncode(committish||"HEAD"),"/",path2)}`,browsetemplate:({domain,user,project,committish,treepath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}`,browsetreetemplate:({domain,user,project,committish,treepath,path:path2,fragment,hashformat})=>`https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish||"HEAD")}/${path2}${maybeJoin("#",hashformat(fragment||""))}`,browseblobtemplate:({domain,user,project,committish,blobpath,path:path2,fragment,hashformat})=>`https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish||"HEAD")}/${path2}${maybeJoin("#",hashformat(fragment||""))}`,docstemplate:({domain,user,project,treepath,committish})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}#readme`,httpstemplate:({auth,domain,user,project,committish})=>`git+https://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({domain,user,project,committish,path:path2})=>`https://${domain}/${user}/${project}/raw/${maybeEncode(committish||"HEAD")}/${path2}`,shortcuttemplate:({type,user,project,committish})=>`${type}:${user}/${project}${maybeJoin("#",committish)}`,pathtemplate:({user,project,committish})=>`${user}/${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,user,project})=>`https://${domain}/${user}/${project}/issues`,hashformat:formatHashFragment},hosts={};hosts.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth,user,project,committish,path:path2})=>`https://${maybeJoin(auth,"@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish||"HEAD")}/${path2}`,gittemplate:({auth,domain,user,project,committish})=>`git://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,type,committish]=url.pathname.split("/",5);if(!(type&&type!=="tree")&&(type||(committish=url.hash.slice(1)),project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish}}};hosts.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain,user,project,committish,treepath,path:path2,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish||"HEAD"),"/",path2,editpath)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/get/${maybeEncode(committish||"HEAD")}.tar.gz`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["get"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};hosts.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",tarballtemplate:({domain,user,project,committish})=>`https://${domain}/api/v4/projects/${maybeEncode(user+"/"+project)}/repository/archive.tar.gz?sha=${maybeEncode(committish||"HEAD")}`,extract:url=>{let path2=url.pathname.slice(1);if(path2.includes("/-/")||path2.includes("/archive.tar.gz"))return;let segments=path2.split("/"),project=segments.pop();project.endsWith(".git")&&(project=project.slice(0,-4));let user=segments.join("/");if(!(!user||!project))return{user,project,committish:url.hash.slice(1)}}};hosts.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain,project,committish})=>`git@${domain}:${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,project,committish})=>`git+ssh://git@${domain}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",maybeEncode(committish))}/${editpath}`,browsetemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,browsetreetemplate:({domain,project,committish,path:path2,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path2))}`,browseblobtemplate:({domain,project,committish,path:path2,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path2))}`,docstemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,httpstemplate:({domain,project,committish})=>`git+https://${domain}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({user,project,committish,path:path2})=>`https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/",maybeEncode(committish))}/${path2}`,shortcuttemplate:({type,project,committish})=>`${type}:${project}${maybeJoin("#",committish)}`,pathtemplate:({project,committish})=>`${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,project})=>`https://${domain}/${project}`,gittemplate:({domain,project,committish})=>`git://${domain}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({project,committish})=>`https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(aux!=="raw"){if(!project){if(!user)return;project=user,user=null}return project.endsWith(".git")&&(project=project.slice(0,-4)),{user,project,committish:url.hash.slice(1)}}},hashformat:function(fragment){return fragment&&"file-"+formatHashFragment(fragment)}};hosts.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain,user,project,committish,path:path2})=>`https://${domain}/${user}/${project}/blob/${maybeEncode(committish)||"HEAD"}/${path2}`,httpstemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/archive/${maybeEncode(committish)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["archive"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};for(let[name,host]of Object.entries(hosts))hosts[name]=Object.assign({},defaults2,host);module.exports=hosts}});var require_parse_url=__commonJS({"node_modules/hosted-git-info/lib/parse-url.js"(exports,module){var lastIndexOfBefore=(str,char,beforeChar)=>{let startPosition=str.indexOf(beforeChar);return str.lastIndexOf(char,startPosition>-1?startPosition:1/0)},safeUrl=u=>{try{return new URL(u)}catch{}},correctProtocol=(arg,protocols)=>{let firstColon=arg.indexOf(":"),proto=arg.slice(0,firstColon+1);if(Object.prototype.hasOwnProperty.call(protocols,proto)||arg.substr(firstColon,3)==="://")return arg;let firstAt=arg.indexOf("@");return firstAt>-1?firstAt>firstColon?`git+ssh://${arg}`:arg:`${arg.slice(0,firstColon+1)}//${arg.slice(firstColon+1)}`},correctUrl=giturl=>{let firstAt=lastIndexOfBefore(giturl,"@","#"),lastColonBeforeHash=lastIndexOfBefore(giturl,":","#");return lastColonBeforeHash>firstAt&&(giturl=giturl.slice(0,lastColonBeforeHash)+"/"+giturl.slice(lastColonBeforeHash+1)),lastIndexOfBefore(giturl,":","#")===-1&&giturl.indexOf("//")===-1&&(giturl=`git+ssh://${giturl}`),giturl};module.exports=(giturl,protocols)=>{let withProtocol=protocols?correctProtocol(giturl,protocols):giturl;return safeUrl(withProtocol)||safeUrl(correctUrl(withProtocol))}}});var require_from_url=__commonJS({"node_modules/hosted-git-info/lib/from-url.js"(exports,module){"use strict";var parseUrl=require_parse_url(),isGitHubShorthand=arg=>{let firstHash=arg.indexOf("#"),firstSlash=arg.indexOf("/"),secondSlash=arg.indexOf("/",firstSlash+1),firstColon=arg.indexOf(":"),firstSpace=/\s/.exec(arg),firstAt=arg.indexOf("@"),spaceOnlyAfterHash=!firstSpace||firstHash>-1&&firstSpace.index>firstHash,atOnlyAfterHash=firstAt===-1||firstHash>-1&&firstAt>firstHash,colonOnlyAfterHash=firstColon===-1||firstHash>-1&&firstColon>firstHash,secondSlashOnlyAfterHash=secondSlash===-1||firstHash>-1&&secondSlash>firstHash,hasSlash=firstSlash>0,doesNotEndWithSlash=firstHash>-1?arg[firstHash-1]!=="/":!arg.endsWith("/"),doesNotStartWithDot=!arg.startsWith(".");return spaceOnlyAfterHash&&hasSlash&&doesNotEndWithSlash&&doesNotStartWithDot&&atOnlyAfterHash&&colonOnlyAfterHash&&secondSlashOnlyAfterHash};module.exports=(giturl,opts,{gitHosts,protocols})=>{if(!giturl)return;let correctedUrl=isGitHubShorthand(giturl)?`github:${giturl}`:giturl,parsed=parseUrl(correctedUrl,protocols);if(!parsed)return;let gitHostShortcut=gitHosts.byShortcut[parsed.protocol],gitHostDomain=gitHosts.byDomain[parsed.hostname.startsWith("www.")?parsed.hostname.slice(4):parsed.hostname],gitHostName=gitHostShortcut||gitHostDomain;if(!gitHostName)return;let gitHostInfo=gitHosts[gitHostShortcut||gitHostDomain],auth=null;protocols[parsed.protocol]?.auth&&(parsed.username||parsed.password)&&(auth=`${parsed.username}${parsed.password?":"+parsed.password:""}`);let committish=null,user=null,project=null,defaultRepresentation=null;try{if(gitHostShortcut){let pathname=parsed.pathname.startsWith("/")?parsed.pathname.slice(1):parsed.pathname,firstAt=pathname.indexOf("@");firstAt>-1&&(pathname=pathname.slice(firstAt+1));let lastSlash=pathname.lastIndexOf("/");lastSlash>-1?(user=decodeURIComponent(pathname.slice(0,lastSlash)),user||(user=null),project=decodeURIComponent(pathname.slice(lastSlash+1))):project=decodeURIComponent(pathname),project.endsWith(".git")&&(project=project.slice(0,-4)),parsed.hash&&(committish=decodeURIComponent(parsed.hash.slice(1))),defaultRepresentation="shortcut"}else{if(!gitHostInfo.protocols.includes(parsed.protocol))return;let segments=gitHostInfo.extract(parsed);if(!segments)return;user=segments.user&&decodeURIComponent(segments.user),project=decodeURIComponent(segments.project),committish=decodeURIComponent(segments.committish),defaultRepresentation=protocols[parsed.protocol]?.name||parsed.protocol.slice(0,-1)}}catch(err){if(err instanceof URIError)return;throw err}return[gitHostName,user,auth,project,committish,defaultRepresentation,opts]}}});var require_lib=__commonJS({"node_modules/hosted-git-info/lib/index.js"(exports,module){"use strict";var{LRUCache}=require_index_min(),hosts=require_hosts(),fromUrl=require_from_url(),parseUrl=require_parse_url(),cache2=new LRUCache({max:1e3});function unknownHostedUrl(url){try{let{protocol,hostname,pathname}=new URL(url);if(!hostname)return null;let proto=/(?:git\+)http:$/.test(protocol)?"http:":"https:",path2=pathname.replace(/\.git$/,"");return`${proto}//${hostname}${path2}`}catch{return null}}var GitHost=class _GitHost{constructor(type,user,auth,project,committish,defaultRepresentation,opts={}){Object.assign(this,_GitHost.#gitHosts[type],{type,user,auth,project,committish,default:defaultRepresentation,opts})}static#gitHosts={byShortcut:{},byDomain:{}};static#protocols={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(name,host){_GitHost.#gitHosts[name]=host,_GitHost.#gitHosts.byDomain[host.domain]=name,_GitHost.#gitHosts.byShortcut[`${name}:`]=name,_GitHost.#protocols[`${name}:`]={name}}static fromUrl(giturl,opts){if(typeof giturl!="string")return;let key=giturl+JSON.stringify(opts||{});if(!cache2.has(key)){let hostArgs=fromUrl(giturl,opts,{gitHosts:_GitHost.#gitHosts,protocols:_GitHost.#protocols});cache2.set(key,hostArgs?new _GitHost(...hostArgs):void 0)}return cache2.get(key)}static fromManifest(manifest,opts={}){if(!manifest||typeof manifest!="object")return;let r=manifest.repository,rurl=r&&(typeof r=="string"?r:typeof r=="object"&&typeof r.url=="string"?r.url:null);if(!rurl)throw new Error("no repository");let info=rurl&&_GitHost.fromUrl(rurl.replace(/^git\+/,""),opts)||null;if(info)return info;let unk=unknownHostedUrl(rurl);return _GitHost.fromUrl(unk,opts)||unk}static parseUrl(url){return parseUrl(url)}#fill(template,opts){if(typeof template!="function")return null;let options={...this,...this.opts,...opts};options.path||(options.path=""),options.path.startsWith("/")&&(options.path=options.path.slice(1)),options.noCommittish&&(options.committish=null);let result=template(options);return options.noGitPlus&&result.startsWith("git+")?result.slice(4):result}hash(){return this.committish?`#${this.committish}`:""}ssh(opts){return this.#fill(this.sshtemplate,opts)}sshurl(opts){return this.#fill(this.sshurltemplate,opts)}browse(path2,...args){return typeof path2!="string"?this.#fill(this.browsetemplate,path2):typeof args[0]!="string"?this.#fill(this.browsetreetemplate,{...args[0],path:path2}):this.#fill(this.browsetreetemplate,{...args[1],fragment:args[0],path:path2})}browseFile(path2,...args){return typeof args[0]!="string"?this.#fill(this.browseblobtemplate,{...args[0],path:path2}):this.#fill(this.browseblobtemplate,{...args[1],fragment:args[0],path:path2})}docs(opts){return this.#fill(this.docstemplate,opts)}bugs(opts){return this.#fill(this.bugstemplate,opts)}https(opts){return this.#fill(this.httpstemplate,opts)}git(opts){return this.#fill(this.gittemplate,opts)}shortcut(opts){return this.#fill(this.shortcuttemplate,opts)}path(opts){return this.#fill(this.pathtemplate,opts)}tarball(opts){return this.#fill(this.tarballtemplate,{...opts,noCommittish:!1})}file(path2,opts){return this.#fill(this.filetemplate,{...opts,path:path2})}edit(path2,opts){return this.#fill(this.edittemplate,{...opts,path:path2})}getDefaultRepresentation(){return this.default}toString(opts){return this.default&&typeof this[this.default]=="function"?this[this.default](opts):this.sshurl(opts)}};for(let[name,host]of Object.entries(hosts))GitHost.addHost(name,host);module.exports=GitHost}});var import_hosted_git_info=__toESM(require_lib(),1);function splitRef(url){let scpLikeMatch=url.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch){let pathWithMaybeRef2=scpLikeMatch[2]??"",refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:{repo:`git@${scpLikeMatch[1]??""}:${repoPath2}`,ref:ref2}}if(url.includes("://"))try{let parsed=new URL(url),pathWithMaybeRef2=parsed.pathname.replace(/^\/+/,""),refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:(parsed.pathname=`/${repoPath2}`,{repo:parsed.toString().replace(/\/$/,""),ref:ref2})}catch{return{repo:url}}let slashIndex=url.indexOf("/");if(slashIndex<0)return{repo:url};let host=url.slice(0,slashIndex),pathWithMaybeRef=url.slice(slashIndex+1),refSeparator=pathWithMaybeRef.indexOf("@");if(refSeparator<0)return{repo:url};let repoPath=pathWithMaybeRef.slice(0,refSeparator),ref=pathWithMaybeRef.slice(refSeparator+1);return!repoPath||!ref?{repo:url}:{repo:`${host}/${repoPath}`,ref}}function decodeForValidation(value){try{return decodeURIComponent(value)}catch{return null}}function hasUnsafeGitInstallPart(value,allowSlash){let decoded=decodeForValidation(value);if(decoded===null)return!0;let candidates=[value,decoded];for(let candidate of candidates)if(candidate.includes("\0")||candidate.includes("\\")||candidate.startsWith("/")||!allowSlash&&candidate.includes("/")||candidate.split("/").includes(".."))return!0;return!1}function buildGitSource(args){if(args.path.startsWith("/"))return null;let normalizedPath=args.path.replace(/\.git$/,"").replace(/^\/+/,"");return!args.host||!normalizedPath||normalizedPath.split("/").length<2||hasUnsafeGitInstallPart(args.host,!1)||hasUnsafeGitInstallPart(normalizedPath,!0)?null:{type:"git",repo:args.repo,host:args.host,path:normalizedPath,ref:args.ref,pinned:!!args.ref}}function parseGenericGitUrl(url){let{repo:repoWithoutRef,ref}=splitRef(url),repo=repoWithoutRef,host="",path2="",scpLikeMatch=repoWithoutRef.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch)host=scpLikeMatch[1]??"",path2=scpLikeMatch[2]??"";else if(repoWithoutRef.startsWith("https://")||repoWithoutRef.startsWith("http://")||repoWithoutRef.startsWith("ssh://")||repoWithoutRef.startsWith("git://"))try{let parsed=new URL(repoWithoutRef);host=parsed.hostname,path2=parsed.pathname.replace(/^\/+/,"")}catch{return null}else{let slashIndex=repoWithoutRef.indexOf("/");if(slashIndex<0||(host=repoWithoutRef.slice(0,slashIndex),path2=repoWithoutRef.slice(slashIndex+1),!host.includes(".")&&host!=="localhost"))return null;repo=`https://${repoWithoutRef}`}return buildGitSource({repo,host,path:path2,ref})}function parseGitUrl(source){let trimmed=source.trim(),hasGitPrefix=trimmed.startsWith("git:"),url=hasGitPrefix?trimmed.slice(4).trim():trimmed;if(!hasGitPrefix&&!/^(https?|ssh|git):\/\//i.test(url))return null;let split=splitRef(url),hostedCandidates=[split.ref?`${split.repo}#${split.ref}`:void 0,url].filter(value=>!!value);for(let candidate of hostedCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;let useHttpsPrefix=!split.repo.startsWith("http://")&&!split.repo.startsWith("https://")&&!split.repo.startsWith("ssh://")&&!split.repo.startsWith("git://")&&!split.repo.startsWith("git@");return buildGitSource({repo:useHttpsPrefix?`https://${split.repo}`:split.repo,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}let httpsCandidates=[split.ref?`https://${split.repo}#${split.ref}`:void 0,`https://${url}`].filter(value=>!!value);for(let candidate of httpsCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;return buildGitSource({repo:`https://${split.repo}`,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}return parseGenericGitUrl(url)}import{createHash as createHash2}from"node:crypto";import{chmodSync,existsSync as existsSync3,globSync,mkdirSync,readdirSync as readdirSync2,readFileSync as readFileSync4,rmSync,statSync as statSync3,writeFileSync}from"node:fs";import{homedir as homedir2}from"node:os";var import_ignore2=__toESM(require_ignore(),1);import{basename,dirname as dirname2,join as join3,relative as relative2,resolve as resolve3,sep as sep4}from"node:path";var balanced=(a,b,str)=>{let ma=a instanceof RegExp?maybeMatch(a,str):a,mb=b instanceof RegExp?maybeMatch(b,str):b,r=ma!==null&&mb!=null&&range(ma,mb,str);return r&&{start:r[0],end:r[1],pre:str.slice(0,r[0]),body:str.slice(r[0]+ma.length,r[1]),post:str.slice(r[1]+mb.length)}},maybeMatch=(reg,str)=>{let m=str.match(reg);return m?m[0]:null},range=(a,b,str)=>{let begs,beg,left,right,result,ai=str.indexOf(a),bi=str.indexOf(b,ai+1),i=ai;if(ai>=0&&bi>0){if(a===b)return[ai,bi];for(begs=[],left=str.length;i>=0&&!result;){if(i===ai)begs.push(i),ai=str.indexOf(a,i+1);else if(begs.length===1){let r=begs.pop();r!==void 0&&(result=[r,bi])}else beg=begs.pop(),beg!==void 0&&beg<left&&(left=beg,right=bi),bi=str.indexOf(b,i+1);i=ai<bi&&ai>=0?ai:bi}begs.length&&right!==void 0&&(result=[left,right])}return result};var escSlash="\0SLASH"+Math.random()+"\0",escOpen="\0OPEN"+Math.random()+"\0",escClose="\0CLOSE"+Math.random()+"\0",escComma="\0COMMA"+Math.random()+"\0",escPeriod="\0PERIOD"+Math.random()+"\0",escSlashPattern=new RegExp(escSlash,"g"),escOpenPattern=new RegExp(escOpen,"g"),escClosePattern=new RegExp(escClose,"g"),escCommaPattern=new RegExp(escComma,"g"),escPeriodPattern=new RegExp(escPeriod,"g"),slashPattern=/\\\\/g,openPattern=/\\{/g,closePattern=/\\}/g,commaPattern=/\\,/g,periodPattern=/\\\./g,EXPANSION_MAX=1e5,EXPANSION_MAX_LENGTH=4e6,EXPANSION_MAX_DEPTH=1e3,EXPANSION_MAX_REWRITES=1e3;function numeric(str){return isNaN(str)?str.charCodeAt(0):parseInt(str,10)}function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function pushAll(target,items){for(let i=0;i<items.length;i++)target.push(items[i])}function parseCommaParts(str){let parts=[],carry="";for(;;){let m=balanced("{","}",str);if(!m){let tail=str.split(",");return tail[0]=carry+tail[0],pushAll(parts,tail),parts}let{pre,body,post}=m,p=pre.split(",");if(p[0]=carry+p[0],p[p.length-1]+="{"+body+"}",!post.length)return pushAll(parts,p),parts;carry=p.pop(),pushAll(parts,p),str=post}}function expand(str,options={}){if(!str)return[];let{max=EXPANSION_MAX,maxLength=EXPANSION_MAX_LENGTH,maxDepth=EXPANSION_MAX_DEPTH,maxRewrites=EXPANSION_MAX_REWRITES}=options;return str.slice(0,2)==="{}"&&(str="\\{\\}"+str.slice(2)),expand_(escapeBraces(str),max,maxLength,maxDepth,0,maxRewrites,!0).map(unescapeBraces)}function embrace(str){return"{"+str+"}"}function isPadded(el){return/^-?0\d/.test(el)}function lte(i,y){return i<=y}function gte(i,y){return i>=y}function combine(acc,pre,values,max,maxLength,dropEmpties){let out=[],length=0;for(let a=0;a<acc.length;a++)for(let v=0;v<values.length;v++){if(out.length>=max)return out;let expansion=acc[a]+pre+values[v];if(!(dropEmpties&&!expansion)){if(length+expansion.length>maxLength)return out;out.push(expansion),length+=expansion.length}}return out}function expandSequence(body,isAlphaSequence,max,maxLength){let n=body.split(/\.\./),N=[];if(n[0]===void 0||n[1]===void 0)return N;let x=numeric(n[0]),y=numeric(n[1]),width=Math.max(n[0].length,n[1].length),incr=n.length===3&&n[2]!==void 0?Math.max(Math.abs(numeric(n[2])),1):1,test=lte;y<x&&(incr*=-1,test=gte);let pad=n.some(isPadded),length=0;for(let i=x;test(i,y)&&N.length<max;i+=incr){let c;if(isAlphaSequence)c=String.fromCharCode(i),c==="\\"&&(c="");else if(c=String(i),pad){let need=width-c.length;if(need>0){let z=new Array(need+1).join("0");i<0?c="-"+z+c.slice(1):c=z+c}}if(length+c.length>maxLength)break;N.push(c),length+=c.length}return N}function expand_(str,max,maxLength,maxDepth,depth,maxRewrites,isTop){if(depth>maxDepth)return[str];let acc=[""],rewrites=0,dropEmpties=!1,firstGroup=!0;for(;;){let m=balanced("{","}",str);if(!m)return combine(acc,str,[""],max,maxLength,dropEmpties);let pre=m.pre;if(/\$$/.test(pre)){if(acc=combine(acc,pre+"{"+m.body+"}",[""],max,maxLength,dropEmpties&&!m.post.length),firstGroup=!1,!m.post.length)break;str=m.post;continue}let isNumericSequence=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body),isAlphaSequence=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body),isSequence=isNumericSequence||isAlphaSequence,isOptions=m.body.indexOf(",")>=0;if(!isSequence&&!isOptions){if(rewrites<maxRewrites&&m.post.match(/,(?!,).*\}/)){rewrites++,str=m.pre+"{"+m.body+escClose+m.post,isTop=!0;continue}return combine(acc,pre+"{"+m.body+"}"+m.post,[""],max,maxLength,dropEmpties)}firstGroup&&(dropEmpties=isTop&&!isSequence,firstGroup=!1);let values;if(isSequence)values=expandSequence(m.body,isAlphaSequence,max,maxLength);else{let n=parseCommaParts(m.body);if(n.length===1&&n[0]!==void 0&&(n=expand_(n[0],max,maxLength,maxDepth,depth+1,maxRewrites,!1).map(embrace),n.length===1)){if(acc=combine(acc,pre+n[0],[""],max,maxLength,dropEmpties&&!m.post.length),!m.post.length)break;str=m.post;continue}let dropsEmpties=dropEmpties&&!m.post.length&&!pre;for(let d=0;dropsEmpties&&d<acc.length;d++)acc[d]&&(dropsEmpties=!1);values=[];let valuesLength=0;outer:for(let j=0;j<n.length;j++){let expanded=expand_(n[j],max,maxLength,maxDepth,depth+1,maxRewrites,!1);for(let k=0;k<expanded.length;k++){let v=expanded[k];if(!(dropsEmpties&&!v)){if(values.length>=max||valuesLength+v.length>maxLength)break outer;values.push(v),valuesLength+=v.length}}}}if(acc=combine(acc,pre,values,max,maxLength,dropEmpties&&!m.post.length),!m.post.length)break;str=m.post}return acc}var digit=(a,b)=>a===b?{t:"lit",ch:String(a)}:{t:"class",re:new RegExp(`^[${a}-${b}]$`)},prefix=(d,alts)=>alts.map(s=>[digit(d,d),...s]),fixed=(a,b)=>{if(!a)return[[]];let lo=+a[0],hi=+b[0],ra=a.slice(1),rb=b.slice(1);if(lo===hi)return prefix(lo,fixed(ra,rb));let zeros="0".repeat(ra.length),nines="9".repeat(ra.length),out=[];ra!==zeros&&out.push(...prefix(lo++,fixed(ra,nines)));let last=rb===nines?[]:prefix(hi--,fixed(zeros,rb));return lo<=hi&&out.push([digit(lo,hi),...Array.from(ra,()=>digit(0,9))]),out.push(...last),out},nonneg=(a,b,width)=>{if(width)return fixed(String(a).padStart(width,"0"),String(b).padStart(width,"0"));let out=[];for(let len=String(a).length;len<=String(b).length;len++){let lo=Math.max(a,len===1?0:10**(len-1)),hi=Math.min(b,10**len-1);out.push(...fixed(String(lo),String(hi)))}return out},numericRange=(loStr,hiStr)=>{let lo=Number(loStr),hi=Number(hiStr);if(!Number.isSafeInteger(lo)||!Number.isSafeInteger(hi))return;lo>hi&&([lo,hi]=[hi,lo]);let width=/^-?0\d/.test(loStr)||/^-?0\d/.test(hiStr)?Math.max(loStr.length,hiStr.length):0,out=[];if(lo<0){let neg=nonneg(Math.max(-hi,1),-lo,width&&width-1);out.push(...neg.map(s=>[{t:"lit",ch:"-"},...s]))}return hi>=0&&out.push(...nonneg(Math.max(lo,0),hi,width)),out};var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},braceEscape=s=>s.replace(/[[\]\\-]/g,"\\$&"),noMatch=/$./,parseClass=(glob,position,nocase=!1,form)=>{let norm=c=>{let n=form?c.normalize(form):c;return[...n].length===1?n:c},pos=position;if(glob.charAt(pos)!=="[")throw new Error("not in a brace expression");let ranges=[],negs=[],i=pos+1,sawStart=!1,escaping=!1,negate=!1,endPos=pos,rangeStart="";WHILE:for(;i<glob.length;){let c=String.fromCodePoint(glob.codePointAt(i));if((c==="!"||c==="^")&&i===pos+1){negate=!0,i++;continue}if(c==="]"&&sawStart&&!escaping){endPos=i+1;break}if(sawStart=!0,c==="\\"&&!escaping){escaping=!0,i++;continue}if(c==="["&&!escaping){for(let[cls,[unip,neg]]of Object.entries(posixClasses))if(glob.startsWith(cls,i)){if(rangeStart)return[noMatch,glob.length-pos];i+=cls.length,neg?negs.push(unip):ranges.push(unip);continue WHILE}}escaping=!1;let n=norm(c);if(rangeStart){n.codePointAt(0)>rangeStart.codePointAt(0)?ranges.push(braceEscape(rangeStart)+"-"+braceEscape(n)):n===rangeStart&&ranges.push(braceEscape(n)),rangeStart="",i+=c.length;continue}if(glob.startsWith("-]",i+c.length)){ranges.push(braceEscape(n+"-")),i+=c.length+1;continue}if(glob.startsWith("-",i+c.length)){rangeStart=n,i+=c.length+1;continue}ranges.push(braceEscape(n)),i+=c.length}if(endPos<i)return[noMatch,0];if(!ranges.length&&!negs.length)return[noMatch,glob.length-pos];let sranges="["+(negate?"^":"")+ranges.join("")+"]",snegs="["+(negate?"":"^")+negs.join("")+"]",comb="^"+(ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs);return[new RegExp(comb,nocase?"iu":"u"),endPos-pos]};var MATCH={t:"match",id:0},extTypes="!?+*@",lit=ch=>({t:"lit",ch}),reEscape=s=>s.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),newFoldRe=s=>new RegExp(`^${reEscape(s)}$`,"iu"),foldCache=new Map,foldRe=ch=>{let re=foldCache.get(ch);return re||(re=newFoldRe(ch),foldCache.size>=1e3&&foldCache.clear(),foldCache.set(ch,re)),re},litMatch=(l,c)=>{if(c===l.ch)return!0;if(!l.re)return!1;let code=c.charCodeAt(0);if(code>=128)return l.re.test(c);let ascii=l.ascii??=new Uint8Array(128);return ascii[code]||=l.re.test(c)?1:2,ascii[code]===1},tokenize=(p,nocase,noext,form,mark)=>{let toks=[];for(let i=0;i<p.length;){let c=String.fromCodePoint(p.codePointAt(i));if(mark){let m=c==="\\"&&p.startsWith(mark,i+1)?1:0;if(m||c===mark){let start=i+m+mark.length,end=p.indexOf(mark,start),r=/^(-?\d+)\.\.(-?\d+)$/.exec(p.slice(start,end)),alts=end!==-1&&r&&numericRange(r[1],r[2]);if(alts){toks.push({t:"ext",type:"@",alts}),i=end+mark.length;continue}}}if(c==="\\"){let e=p.codePointAt(i+1),ch=e===void 0?c:String.fromCodePoint(e);toks.push(lit(ch)),i+=1+ch.length;continue}if(c==="["){let[re,consumed]=parseClass(p,i,nocase,form);if(consumed){toks.push({t:"class",re}),i+=consumed;continue}}if(!noext&&extTypes.includes(c)&&p[i+1]==="("){toks.push({t:"open",type:c}),i+=2;continue}toks.push(!noext&&c==="|"?{t:"bar"}:!noext&&c===")"?{t:"close"}:c==="*"?{t:"star"}:c==="?"?{t:"any"}:lit(c)),i+=c.length}return toks},pair=toks=>{let pairs=new Map,stack=[];return toks.forEach((tok,i)=>{tok.t==="open"?stack.push(i):tok.t==="close"&&stack.length&&pairs.set(stack.pop(),i)}),pairs},build=(toks,pairs,start,end,top)=>{let seq=[],alts=[seq];for(let i=start;i<end;i++){let tok=toks[i],close=pairs.get(i);if(tok.t==="open"&&close!==void 0){let sub=build(toks,pairs,i+1,close,!1);seq.push({t:"ext",type:tok.type,alts:sub}),i=close}else tok.t==="bar"&&!top?alts.push(seq=[]):tok.t==="open"?seq.push(lit(tok.type),lit("(")):tok.t==="bar"?seq.push(lit("|")):tok.t==="close"?seq.push(lit(")")):seq.push(tok)}return alts},normalize=(items,form)=>{let out=[],run="",flush=()=>{for(let ch of run.normalize(form))out.push(lit(ch));run=""};for(let it of items){if(it.t==="lit"){run+=it.ch;continue}flush(),out.push(it.t==="ext"?{...it,alts:it.alts.map(a=>normalize(a,form))}:it)}return flush(),out},compile=(items,nocase)=>{let id=1,split=out=>({t:"split",id:id++,out}),seq=(items2,next)=>items2.reduceRight((next2,it)=>item(it,next2),next),item=(it,next)=>{switch(it.t){case"lit":let re=nocase?foldRe(it.ch):void 0;return{t:"lit",id:id++,ch:it.ch,re,next};case"any":case"star":return{t:it.t,id:id++,next};case"class":return{t:"class",id:id++,re:it.re,next}}let alts=next2=>it.alts.map(a=>seq(a,next2));switch(it.type){case"@":return split(alts(next));case"?":return split([next,...alts(next)]);case"!":return{t:"neg",id:id++,sub:split(alts(MATCH)),next}}let after=split([]),entry=split(alts(after));return after.out.push(next,entry),it.type==="*"?after:entry};return[seq(items,MATCH),id]},show=start=>{let lines=[],seen=new Set,ref=n=>n.t==="match"?"match":String(n.id),walk=(n,indent)=>{if(n.t==="match"||seen.has(n))return;seen.add(n);let line=desc=>lines.push(`${indent}${n.id}: ${desc}`);switch(n.t){case"split":line(`split -> ${n.out.map(ref).join(", ")}`);for(let o of n.out)walk(o,indent);return;case"neg":return line(`!(${ref(n.sub)}) -> ${ref(n.next)}`),walk(n.sub,indent+" "),walk(n.next,indent);case"lit":line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`);break;case"class":line(`${n.re} -> ${ref(n.next)}`);break;default:line(`${n.t==="any"?"?":"*"} -> ${ref(n.next)}`)}walk(n.next,indent)};return walk(start,""),[`start -> ${ref(start)}`,...lines].join(`
`)},State=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(gen){this.gen=gen}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},sameState=(a,b)=>a.ids.length!==b.ids.length||a.runs.length!==b.runs.length||a.ids.some((id,i)=>id!==b.ids[i])?!1:a.runs.every(r=>b.runs.some(o=>o.neg===r.neg&&sameState(o.state,r.state))),marks=size=>({has:new Float64Array(size),seen:new Float64Array(size),gen:0}),Sim=class{dots;dotStart;#marks;constructor(dots,dotStart,marks2){this.dots=dots,this.dotStart=dotStart,this.#marks=marks2}state(){return new State(++this.#marks.gen)}done(state){return state.ids=state.threads.map(n=>n.id).sort((a,b)=>a-b),state.match&&state.ids.unshift(MATCH.id),state}#visit(state,node){let{seen}=this.#marks;return seen[node.id]===state.gen?!1:(seen[node.id]=state.gen,!0)}#addThread(state,node){let{has}=this.#marks;return has[node.id]===state.gen?!1:(has[node.id]=state.gen,state.threads.push(node),!0)}restricted(i,top){return top&&(this.dots||this.dotStart&&i===0)}add(state,node,i,top){switch(node.t){case"split":if(!this.#visit(state,node))return;for(let o of node.out)this.add(state,o,i,top);return;case"neg":if(!this.#visit(state,node))return;let sub=this.state();return this.add(sub,node.sub,i,!1),this.done(sub),this.addRun(state,{t:"run",neg:node,state:sub},i,top);case"star":if(this.restricted(i,top))return;this.#addThread(state,node)&&this.add(state,node.next,i,top);return;case"match":state.match=!0;return;default:this.#addThread(state,node)}}addRun(state,run,i,top){for(let r of state.runs)if(r.neg===run.neg&&sameState(r.state,run.state))return;state.runs.push(run),run.state.match||this.add(state,run.neg.next,i,top)}step(state,c,i,top){let next=this.state();for(let th of state.threads)switch(th.t){case"lit":litMatch(th,c)&&this.add(next,th.next,i+1,top);break;case"any":this.restricted(i,top)||this.add(next,th.next,i+1,top);break;case"class":!this.restricted(i,top)&&th.re.test(c)&&this.add(next,th.next,i+1,top);break;case"star":this.restricted(i,top)||this.add(next,th,i+1,top)}if(!this.restricted(i,top))for(let run of state.runs){if(run.state.dead){this.addRun(next,run,i+1,top);continue}let sub=this.step(run.state,c,i,!1);this.addRun(next,{t:"run",neg:run.neg,state:sub},i+1,top)}return this.done(next)}},stateKey=state=>{let ids=state.ids.join();if(!state.runs.length)return ids;let runs=state.runs.map(r=>`${r.neg.id}(${stateKey(r.state)})`);return`${ids}|${runs.sort().join("|")}`},DFA_BUDGET=1<<18,Dfa=class{#start;#states=new Map;#size=0;#plain;#dotStart;#sim;#dotSim;constructor(start,marks2){this.#start=start,this.#sim=new Sim(!1,!1,marks2),this.#dotSim=new Sim(!1,!0,marks2)}#make(state){return{state,match:state.match,dead:state.dead,next:new Map}}#intern(state){let key=stateKey(state),found=this.#states.get(key);if(found)return found;this.#size>DFA_BUDGET&&this.#clear();let d=this.#make(state);return this.#states.set(key,d),this.#size+=key.length+1,d}#clear(){this.#states.clear(),this.#size=0,this.#plain=void 0,this.#dotStart=void 0}start(dotStart){if(dotStart){if(this.#dotStart)return this.#dotStart;let state2=this.#dotSim.state();return this.#dotSim.add(state2,this.#start,0,!0),this.#dotStart=this.#make(this.#dotSim.done(state2))}if(this.#plain)return this.#plain;let state=this.#sim.state();return this.#sim.add(state,this.#start,0,!0),this.#plain=this.#intern(this.#sim.done(state))}next(d,c){let code=c.charCodeAt(0),found=code<128?void 0:d.next.get(c);if(found)return found;let n=d===this.#dotStart?this.#intern(this.#dotSim.step(d.state,c,0,!0)):this.#intern(this.#sim.step(d.state,c,1,!0));return code<128?(d.ascii||(d.ascii=new Array(128),this.#size+=128),d.ascii[code]=n):d.next.set(c,n),this.#size++,n}},linear=start=>{let nodes=[];for(let n=start;n.t!=="match";n=n.next){if(n.t==="split"||n.t==="neg")return;nodes.push(n)}return nodes},testLinear=(nodes,chars,start,end)=>{let ni=0,ci=start,starNi=-1,starCi=0;for(;ci<end;){let n=nodes[ni];if(n?.t==="star"){starNi=ni++,starCi=ci;continue}let c=chars[ci];if(n&&(n.t==="any"||n.t==="lit"&&litMatch(n,c)||n.t==="class"&&n.re.test(c))){ni++,ci++;continue}if(starNi===-1)return!1;ni=starNi+1,ci=++starCi}for(;nodes[ni]?.t==="star";)ni++;return ni===nodes.length},lengths=items=>{let min=0,max=0;for(let it of items){let[lo,hi]=itemLengths(it);min+=lo,max+=hi}return[min,max]},itemLengths=it=>{if(it.t==="star")return[0,1/0];if(it.t!=="ext")return[1,1];if(it.type==="!")return[0,1/0];let alts=it.alts.map(lengths),min=Math.min(...alts.map(a=>a[0])),max=Math.max(...alts.map(a=>a[1])),loop=max===0?0:1/0;return it.type==="@"?[min,max]:it.type==="?"?[0,max]:it.type==="*"?[0,loop]:[min,loop]},hasAffix=(lits,chars,start)=>{for(let j=0;j<lits.length;j++)if(!litMatch(lits[j],chars[start+j]))return!1;return!0},slashOrSurrogate=/[/\ud800-\udfff]/,surrogate=/[\ud800-\udfff]/,codePoints=s=>surrogate.test(s)?[...s]:s,noSlash=s=>{if(s.includes("/"))throw new Error("can only match a single path portion, got: "+s)},Matcher=class{pattern;options;#start;#size;#marks;#dotsSim;#literal;#literalFold=!1;#literalRe;#linear;#wild=!1;#min=0;#max=1/0;#prefix=[];#suffix=[];#prefixStr;#suffixStr;#affix=!1;#dfa;#form;constructor(pattern,options={}){if(pattern.includes("/"))throw new Error("can only match a single path portion, got pattern: "+pattern);this.pattern=pattern,this.options=options;let{nocase=!1,noext=!1,normalize:n}=options;this.#form=n===!0?"NFC":n||void 0;let literal2=/^[?*+@]\(\)$/.test(pattern),toks=tokenize(pattern,nocase,noext||literal2,this.#form,options.rangeMark),[items]=build(toks,pair(toks),0,toks.length,!0);this.#form&&(items=normalize(items,this.#form));let[start,size]=compile(items,nocase);if(this.#start=start,this.#size=size,items.every(it=>it.t==="lit"))this.#literal=items.map(it=>it.ch).join(""),this.#literalFold=nocase;else{let lit2=it=>it.t!=="lit"?void 0:nocase?{ch:it.ch,re:foldRe(it.ch)}:{ch:it.ch};for(let it of items){let l=lit2(it);if(!l)break;this.#prefix.push(l)}for(let j=items.length-1;j>=0;j--){let l=lit2(items[j]);if(!l)break;this.#suffix.unshift(l)}this.#affix=!!(this.#prefix.length||this.#suffix.length),nocase||(this.#prefixStr=this.#prefix.map(l=>l.ch).join(""),this.#suffixStr=this.#suffix.map(l=>l.ch).join("")),this.#linear=linear(this.#start)?.slice(this.#prefix.length,-this.#suffix.length||void 0),this.#wild=!!this.#linear?.every(n2=>n2.t==="star"||n2.t==="any");let[min,max]=lengths(items);this.#min=min,this.#max=max}}test(s){return this.#form?(noSlash(s),this.#test(s.normalize(this.#form))):slashOrSurrogate.test(s)?(noSlash(s),this.#test(s,[...s])):this.#test(s,s)}testUnchecked(s){return this.#test(this.#form?s.normalize(this.#form):s)}#test(s,chars){if(this.#literal!==void 0)return this.#literalFold?(this.#literalRe??=newFoldRe(this.#literal)).test(s):s===this.#literal;let min=this.#min,max=this.#max;if(chars===void 0){let most=s.length,least=most+1>>1;if(most<min||least>max)return!1;(least<min||most>max)&&(chars=codePoints(s))}if(chars!==void 0&&(chars.length<min||chars.length>max))return!1;let prefix2=this.#prefix.length;if(this.#affix)if(this.#prefixStr!==void 0&&this.#suffixStr!==void 0){if(!s.startsWith(this.#prefixStr)||!s.endsWith(this.#suffixStr))return!1}else{chars??=codePoints(s);let end=chars.length-this.#suffix.length;if(!hasAffix(this.#prefix,chars,0)||!hasAffix(this.#suffix,chars,end))return!1}let dotStart=!this.options.dot&&s.startsWith(".");if(this.#linear){if(s==="."||s===".."||dotStart&&!prefix2)return!1;if(this.#wild)return!0;chars??=codePoints(s);let end=chars.length-this.#suffix.length;return testLinear(this.#linear,chars,prefix2,end)}if(chars??=codePoints(s),s==="."||s===".."){this.#marks??=marks(this.#size);let sim=this.#dotsSim??=new Sim(!0,!1,this.#marks),start=sim.state();sim.add(start,this.#start,0,!0);let state=sim.done(start);for(let i=0;i<chars.length;i++)state=sim.step(state,chars[i],i,!0);return state.match}this.#marks??=marks(this.#size);let dfa=this.#dfa??=new Dfa(this.#start,this.#marks),d=dfa.start(dotStart),str=chars===s;for(let i=0;i<chars.length;i++){if(d.dead)return!1;let code=str?s.charCodeAt(i):chars[i].charCodeAt(0);d=d.ascii?.[code]??dfa.next(d,chars[i])}return d.match}toString(){return show(this.#start)}};var assertValidPattern=pattern=>{if(typeof pattern!="string")throw new TypeError("invalid pattern");if(pattern.length>65536)throw new TypeError("pattern is too long")};var escape=(s,{windowsPathsNoEscape=!1,magicalBraces=!1}={})=>magicalBraces?windowsPathsNoEscape?s.replace(/[?*()[\]{}]/g,"[$&]"):s.replace(/[?*()[\]\\{}]/g,"\\$&"):windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");var unescape=(s,{windowsPathsNoEscape=!1,magicalBraces=!0}={})=>magicalBraces?windowsPathsNoEscape?s.replace(/\[([^/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):windowsPathsNoEscape?s.replace(/\[([^/\\{}])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var minimatch=(p,pattern,options={})=>(assertValidPattern(pattern),!options.nocomment&&pattern.charAt(0)==="#"?!1:cachedMinimatch(pattern,options).match(p)),cache=new Map,cacheMax=256,cachedMinimatch=(pattern,options)=>{let key=pattern+"\0"+JSON.stringify(options),mm=cache.get(key);return mm?cache.delete(key):(mm=new Minimatch(pattern,{...options}),cache.size>=cacheMax&&cache.delete(cache.keys().next().value)),cache.set(key,mm),mm},defaultPlatform=typeof process=="object"&&process?process.env?.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",path={win32:{sep:"\\"},posix:{sep:"/"}},sep=defaultPlatform==="win32"?path.win32.sep:path.posix.sep;minimatch.sep=sep;var GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;var filter=(pattern,options={})=>p=>minimatch(p,pattern,options);minimatch.filter=filter;var ext=(a,b={})=>Object.assign({},a,b),defaults=def=>{if(!def||typeof def!="object"||!Object.keys(def).length)return minimatch;let orig=minimatch;return Object.assign((p,pattern,options={})=>orig(p,pattern,ext(def,options)),{Minimatch:class extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},unescape:(s,options={})=>orig.unescape(s,ext(def,options)),escape:(s,options={})=>orig.escape(s,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list,pattern,options={})=>orig.match(list,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;var braceExpand=(pattern,options={})=>(assertValidPattern(pattern),options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)?[pattern]:expand(pattern,{max:options.braceExpandMax}));minimatch.braceExpand=braceExpand;var RANGE_MIN=100,rangeRe=/(?<![\\$])\{(-?\d+)\.\.(-?\d+)\}/g,match=(list,pattern,options={})=>{let mm=new Minimatch(pattern,options);return list=list.filter(f=>mm.match(f)),mm.options.nonull&&!list.length&&list.push(pattern),list};minimatch.match=match;var globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/,classEnd=(pattern,start)=>{let i=start+1;(pattern.charAt(i)==="!"||pattern.charAt(i)==="^")&&i++;let sawStart=!1;for(;i<pattern.length;i++){let c=pattern.charAt(i);if(c==="]"&&sawStart)return i;sawStart=!0,c==="\\"&&i++}return-1},literal=(pattern,noext)=>{if(!noext&&(pattern==="+()"||pattern==="@()"))return pattern;let lit2="";for(let i=0;i<pattern.length;i++){let c=pattern.charAt(i);if(c==="\\")lit2+=pattern.charAt(++i)||c;else{if(c==="*"||c==="?")return;if(c==="["){let close=classEnd(pattern,i);if(close===-1){lit2+=c;continue}let body=pattern.slice(i+1,close);if(body.startsWith("\\")&&(body=body.slice(1)),[...body].length!==1||"!^".includes(pattern.charAt(i+1)))return;lit2+=body,i=close}else{if(!noext&&"+@!".includes(c)&&pattern.charAt(i+1)==="("&&pattern.includes(")",i+2))return;lit2+=c}}}return lit2},extSafe=pattern=>{if(/^[?*+@]\(\)$/.test(pattern)||pattern.includes("[:"))return!1;let depth=0;for(let i=0;i<pattern.length;i++){let c=pattern.charAt(i);if(c==="\\"){if(++i===pattern.length)return!1}else if(c==="["){let close=classEnd(pattern,i);close!==-1&&(i=close)}else if("+@!?*".includes(c)&&pattern.charAt(i+1)==="(")depth++,i++;else if(c===")"){if(!depth--)return!1}else if(c==="|"&&!depth)return!1}return!depth},lastSplit,lastChecked,portionMatch=(p,f)=>typeof p=="string"?f===p:f!==""&&p.testUnchecked(f),endIndex=(p,last,lastStart,prev,prevStart)=>portionMatch(p,last)?lastStart:prev!==void 0&&portionMatch(p,prev)?prevStart:-1,isDots=p=>p==="."||p==="..",isDrive=p=>typeof p=="string"&&/^[a-z]:$/i.test(p),isLongUNC=p=>typeof p=="string"&&/^unc$/i.test(p),uncHost=p=>{if(p[0]!==""||p[1]!=="")return-1;let h=p[2]!=="?"?2:isLongUNC(p[3])?4:-1,host=p[h],share=p[h+1];return h!==-1&&host!==void 0&&host!==""&&host!==GLOBSTAR&&share!==void 0&&share!==""&&share!==GLOBSTAR?h:-1},walkable=(p,dot)=>!isDots(p)&&(dot||!p.startsWith(".")),dotPortion=(f,start,end,dot,sep5)=>{for(let k=start;k<end;){if(f.charCodeAt(k)===46){if(!dot)return!0;let n=f.charCodeAt(k+1)===46?k+2:k+1;if(n>=end||isSep(f.charCodeAt(n),sep5))return!0}let s=nextSep(f,k,sep5);if(s===-1)return!1;for(k=s+1;k<end&&isSep(f.charCodeAt(k),sep5);)k++}return!1},isSep=(c,sep5)=>sep5==="/"?c===47:sep5==="\\"?c===92:c===47||c===92,nextSep=(f,from,sep5)=>{if(sep5!=="both")return f.indexOf(sep5,from);let s=f.indexOf("/",from),b=f.indexOf("\\",from);return s===-1?b:b===-1?s:Math.min(s,b)},lastSep=(f,from,sep5)=>sep5!=="both"?f.lastIndexOf(sep5,from):Math.max(f.lastIndexOf("/",from),f.lastIndexOf("\\",from)),PENDING={},Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;#endCheck;#literalCheck;#level2;#form;#literals=[];#shapes=[];#endRows=[];#matchers=new Map;#pending=!1;#rangeMark;#globstarParts=new WeakMap;constructor(pattern,options={}){assertValidPattern(pattern),options=options||{},this.options=options,this.maxGlobstarRecursion=options.maxGlobstarRecursion??200,this.pattern=pattern,this.platform=options.platform||defaultPlatform,this.isWindows=this.platform==="win32";let awe="allowWindowsEscape";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options[awe]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!options.preserveMultipleSlashes,this.negate=!1,this.nonegate=!!options.nonegate,this.comment=!1,this.empty=!1,this.partial=!!options.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=options.windowsNoMagicRoot!==void 0?options.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.#endCheck=!this.preserveMultipleSlashes,this.#level2=(options.optimizationLevel??1)>=2;let n=options.normalize;this.#form=n===!0?"NFC":n||void 0,this.make();let drives=this.set.map(row=>this.#rootIndex(row));this.#endRows=this.set.map((row,r)=>this.#endCheck&&row.length-1>drives[r]),this.#literals=this.set.map((row,r)=>{let end=this.#endRows[r]?row.length-1:row.length,lits=row.slice(drives[r]+1,end).filter(p=>typeof p=="string"&&!!p);return[...new Set(lits)]}),this.#literalCheck=this.#literals.some(l=>l.length),this.#shapes=this.set.map((row,r)=>{let[p0,p1,p2]=row;if(this.#endRows[r]&&row.length===2&&p0===GLOBSTAR&&p1!==GLOBSTAR)return"tail";if(this.#endRows[r]&&options.matchBase&&row.length===1&&p0!==GLOBSTAR&&p0!=="")return"base";if(!(!this.#endCheck||drives[r]!==-1)){if(row.length===3&&p0===GLOBSTAR&&p2===GLOBSTAR&&p1!==GLOBSTAR&&p1!==""&&this.maxGlobstarRecursion>0)return"mid";if(row.length===2&&p1===GLOBSTAR&&p0!==GLOBSTAR&&p0!=="")return"head"}})}#norm(p){return this.#form?p.normalize(this.#form):p}#rootIndex(row){if(!this.isWindows)return-1;if(isDrive(row[0]))return 0;if(row[0]===""&&row[1]===""&&row[2]==="?"&&isDrive(row[3]))return 3;let h=uncHost(row);return h===-1?-1:h+1}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let pattern of this.set)for(let part of pattern)if(typeof part!="string")return!0;return!1}make(){let pattern=this.pattern,options=this.options;if(!options.nocomment&&pattern.charAt(0)==="#"){this.comment=!0;return}if(!pattern){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.#expandBraces())];let rawGlobParts=this.globSet.map(s=>this.#slashSplit(s));this.globParts=this.preprocess(rawGlobParts),this.#pending=!0;let set=this.globParts.map((s,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){let n=s[2]==="?"&&isLongUNC(s[3])?6:4,isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&s.slice(3,n).every(p=>!globMagic.test(p)),isDrive2=/^[a-z]:/i.test(s[0]);if(isUNC)return[...s.slice(0,n).map(p=>this.#norm(p)),...s.slice(n).map(ss=>this.parse(ss))];if(isDrive2)return[this.#norm(s[0]),...s.slice(1).map(ss=>this.parse(ss))]}return s.map(ss=>this.parse(ss))});if(this.set=set.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let p=this.set[i];p[0]===""&&p[1]===""&&this.globParts[i][2]==="?"&&(isDrive(p[3])||isLongUNC(this.globParts[i][3]))&&(isLongUNC(this.globParts[i][3])&&(p[3]="UNC"),p[2]="?")}options.noext||this.mergeRows(),this.#pending=!1,this.set.forEach((row,i)=>{for(let k=0;k<row.length;k++)row[k]===PENDING&&(row[k]=this.parse(this.globParts[i][k]))})}mergeRows(){let merged=!0;for(;merged;){merged=!1;let len=Math.max(0,...this.set.map(r=>r.length));for(let k=0;k<len;k++){let groups=new Map;this.set.forEach((row,i)=>{if(!(row[k]instanceof Matcher||row[k]===PENDING)||!extSafe(this.globParts[i][k]))return;let parts=[...this.globParts[i]];parts[k]="";let key=`${row.length}/${parts.join("/")}`,g=groups.get(key);g?g.push(i):groups.set(key,[i])});let drop=new Set;for(let g of groups.values()){if(g.length<2)continue;let[first,...rest]=g,glob=`@(${g.map(i=>this.globParts[i][k]).join("|")})`;this.globParts[first][k]=glob,this.set[first][k]=this.parse(glob);for(let i of rest)drop.add(i)}drop.size&&(merged=!0,this.set=this.set.filter((_,i)=>!drop.has(i)),this.globParts=this.globParts.filter((_,i)=>!drop.has(i)))}}}preprocess(globParts){if(this.options.noglobstar)for(let partset of globParts)for(let j=0;j<partset.length;j++)partset[j]==="**"&&(partset[j]="*");let{optimizationLevel=1}=this.options;return optimizationLevel>=2?(globParts=this.firstPhasePreProcess(globParts),globParts=this.secondPhasePreProcess(globParts)):optimizationLevel>=1?globParts=this.levelOneOptimize(globParts):globParts=this.adjascentGlobstarOptimize(globParts),globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs=-1;for(;(gs=parts.indexOf("**",gs+1))!==-1;){let i=gs;for(;parts[i+1]==="**";)i++;i!==gs&&parts.splice(gs,i-gs)}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>{let root=this.#rootIndex(parts)+1;return parts=parts.reduce((set,part)=>{let prev=set[set.length-1];return part==="**"&&prev==="**"?set:part===".."&&set.length>root&&prev&&prev!==".."&&prev!=="."&&prev!=="**"?(set.pop(),set):(set.push(part),set)},[]),parts.length===0?[""]:parts})}#canMatch(f){let sep5=!this.isWindows||!f.includes("\\")?"/":f.includes("/")?"both":"\\",ends=this.#endCheck?0:-1,last="",lastStart=0,prev,prevStart=0,dot=!!this.options.dot;ROWS:for(let r=0;r<this.set.length;r++){let row=this.set[r],p=row[row.length-1],end=ends!==-1&&this.#endRows[r]&&p!==GLOBSTAR;if(end&&ends===0){let i=lastSep(f,f.length,sep5);if(lastStart=i+1,last=f.slice(lastStart),last===""&&i>=0){let j=i;for(;j>0&&isSep(f.charCodeAt(j-1),sep5);)j--;prevStart=j===0?0:lastSep(f,j-1,sep5)+1,prev=f.slice(prevStart,j)}let resolves=this.#level2&&(isDots(last)||last===""&&prev!==void 0&&isDots(prev));ends=resolves?-1:1,end=!resolves}let tailStart=-1;if(end&&typeof p=="string"&&(tailStart=endIndex(p,last,lastStart,prev,prevStart),tailStart===-1))continue;if(this.#literalCheck){for(let l of this.#literals[r])if(!f.includes(l))continue ROWS}if(end&&typeof p=="object"&&(tailStart=endIndex(p,last,lastStart,prev,prevStart),tailStart===-1))continue;let shape=this.#shapes[r];if(shape==="base"&&end)return"yes";if(shape==="tail"&&end){if(this.#level2&&dotPortion(f,0,tailStart,!0,sep5))return"maybe";if(!dotPortion(f,0,tailStart,dot,sep5))return"yes";continue}if(shape==="mid"||shape==="head"){let m=this.#walk(f,row,shape==="head",dot,sep5);if(m!=="no")return m;continue}return"maybe"}return"no"}#matchShape(file,row,shape){let dot=!!this.options.dot,n=file.length;if(shape==="head"){if(n<2||!portionMatch(row[0],file[0]))return!1;for(let i=1;i<n;i++)if(!walkable(file[i],dot))return!1;return!0}let x=row[1];if(shape==="tail"){let t=n-1;if(!portionMatch(x,file[t])&&(file[t]!==""||n===1||!portionMatch(x,file[--t])))return!1;for(let i=0;i<t;i++)if(!walkable(file[i],dot))return!1;return!0}for(let k=0;k<n;k++){if(portionMatch(x,file[k])&&k+1<n){let i=k+1;for(;i<n&&walkable(file[i],dot);)i++;if(i===n)return!0}if(!walkable(file[k],dot))return!1}return!1}#walk(f,row,head,dot,sep5){if(this.#level2&&dotPortion(f,0,f.length,!0,sep5))return"maybe";let x=row[head?0:1],s=0;for(let e=nextSep(f,s,sep5);e!==-1;e=nextSep(f,s,sep5)){let next=e+1;for(;next<f.length&&isSep(f.charCodeAt(next),sep5);)next++;if((typeof x=="string"?e-s===x.length&&f.startsWith(x,s):e>s&&x.testUnchecked(f.slice(s,e)))&&!dotPortion(f,next,f.length,dot,sep5))return"yes";if(head||dotPortion(f,s,next,dot,sep5))return"no";s=next}return"no"}#cachedSplit(f){let last=lastSplit;return last?.f===f&&last.isWindows===this.isWindows&&last.preserveMultipleSlashes===this.preserveMultipleSlashes&&last.normalize===this.#form?last:void 0}#split(f){let{isWindows,preserveMultipleSlashes}=this,parts=this.#slashSplit(isWindows?f.split("\\").join("/"):f),normalize2=this.#form;return normalize2&&(parts=parts.map(p=>p.normalize(normalize2))),lastSplit={f,isWindows,preserveMultipleSlashes,normalize:normalize2,parts},lastSplit}#levelTwoFileOptimize(file){let parts=[...file],didSomething=!1;do{if(didSomething=!1,!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){let p=parts[i];i===1&&p===""&&parts[0]===""||(p==="."||p==="")&&(didSomething=!0,parts.splice(i,1),i--)}parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")&&(didSomething=!0,parts.pop())}let root=this.#rootIndex(parts)+1,dd=root;for(;(dd=parts.indexOf("..",dd+1))!==-1;){let p=parts[dd-1];p&&p!=="."&&p!==".."&&p!=="**"&&(didSomething=!0,parts.splice(dd-1,2),dd=Math.max(dd-2,root))}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let{braceExpandMax=1e5}=this.options,splitCells=0,maxSplitCells=1e6,didSomething=!1;do{didSomething=!1;for(let parts of globParts){let gs=-1;for(;(gs=parts.indexOf("**",gs+1))!==-1;){let gss=gs;for(;parts[gss+1]==="**";)gss++;gss>gs&&parts.splice(gs+1,gss-gs);let next=parts[gs+1],p=parts[gs+2],p2=parts[gs+3];if(next!==".."||!p||p==="."||p===".."||!p2||p2==="."||p2==="..")continue;let addedCells=parts.length-1;if(globParts.length>=braceExpandMax||splitCells+addedCells>maxSplitCells)throw new RangeError("optimizationLevel 2: too many patterns from '**/..'");didSomething=!0,parts.splice(gs,1);let other=parts.slice(0);other[gs]="**",splitCells+=addedCells,globParts.push(other),gs--}if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){let p=parts[i];i===1&&p===""&&parts[0]===""||(p==="."||p==="")&&(didSomething=!0,parts.splice(i,1),i--)}parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")&&(didSomething=!0,parts.pop())}let root=this.#rootIndex(parts)+1,dd=root;for(;(dd=parts.indexOf("..",dd+1))!==-1;){let p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=!0;let splin=dd===1&&parts[dd+1]==="**"?["."]:[];parts.splice(dd-1,2,...splin),parts.length===0&&parts.push(""),dd=Math.max(dd-2,root)}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){let keys=new Set,rows=globParts.filter(parts=>{let key=parts.join("/");return keys.has(key)?!1:(keys.add(key),!0)}),stars=new Map;for(let parts of rows){let s=[];for(let i=0;i<parts.length;i++)parts[i]==="*"&&s.push(i);s.length&&stars.set(s.join(","),s)}if(!stars.size||rows.length*stars.size>1e5)return rows;let{dot}=this.options;return rows.filter(parts=>{for(let s of stars.values()){if(s[s.length-1]>=parts.length)continue;let c=[...parts],ok=!0,changed=!1;for(let i of s){let p=parts[i];if(p!=="*"){if(!p||p==="**"||!dot&&p.startsWith(".")){ok=!1;break}c[i]="*",changed=!0}}if(ok&&changed&&keys.has(c.join("/")))return!1}return!0})}parseNegate(){if(this.nonegate)return;let pattern=this.pattern,negate=!1,negateOffset=0;for(let i=0;i<pattern.length&&pattern.charAt(i)==="!";i++)negate=!negate,negateOffset++;negateOffset&&(this.pattern=pattern.slice(negateOffset)),this.negate=negate}#matchRow(file,resolved,pattern,partial){let fileStartIndex=0,patternStartIndex=0,fh=this.isWindows?uncHost(resolved):-1,ph=fh===-1?-1:uncHost(pattern);if(ph!==-1){let host=pattern[ph],share=pattern[ph+1];typeof host!="string"||typeof share!="string"?(fileStartIndex=fh,patternStartIndex=ph):resolved[fh].toLowerCase()===host.toLowerCase()&&resolved[fh+1].toLowerCase()===share.toLowerCase()&&(fileStartIndex=fh+2,patternStartIndex=ph+2)}else if(this.isWindows){let fileDrive=typeof file[0]=="string"&&/^[a-z]:$/i.test(file[0]),fileUNC=!fileDrive&&file[0]===""&&file[1]===""&&file[2]==="?"&&/^[a-z]:$/i.test(file[3]),patternDrive=typeof pattern[0]=="string"&&/^[a-z]:$/i.test(pattern[0]),patternUNC=!patternDrive&&pattern[0]===""&&pattern[1]===""&&pattern[2]==="?"&&typeof pattern[3]=="string"&&/^[a-z]:$/i.test(pattern[3]),fdi=fileUNC?3:fileDrive?0:void 0,pdi=patternUNC?3:patternDrive?0:void 0;if(typeof fdi=="number"&&typeof pdi=="number"){let[fd,pd]=[file[fdi],pattern[pdi]];fd.toLowerCase()===pd.toLowerCase()&&(patternStartIndex=pdi+1,fileStartIndex=fdi+1)}}return file=resolved,pattern.includes(GLOBSTAR)?this.#matchGlobstar(file,pattern,partial,fileStartIndex,patternStartIndex):this.#matchOne(file,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file,pattern,partial,fileIndex,patternIndex){let{head,body,tail,segments}=this.#getGlobstarParts(pattern,partial,patternIndex);if(head.length){let headEnd=fileIndex+head.length;if(!this.#matchOne(file,head,partial,fileIndex,0,headEnd))return!1;fileIndex+=head.length,patternIndex+=head.length}let fileTailMatch=0;if(tail.length){if(tail.length+fileIndex>file.length)return!1;let tailStart=file.length-tail.length;if(this.#matchOne(file,tail,partial,tailStart,0))fileTailMatch=tail.length;else{if(file[file.length-1]!==""||fileIndex+tail.length===file.length||(tailStart--,!this.#matchOne(file,tail,partial,tailStart,0)))return!1;fileTailMatch=tail.length+1}}if(!body.length){let sawSome=!!fileTailMatch;for(let i=fileIndex;i<file.length-fileTailMatch;i++){let f=String(file[i]);if(sawSome=!0,f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return partial||sawSome}return!!this.#matchGlobStarBodySections(file,segments,file.length-fileTailMatch,fileIndex,0,partial,0,!!fileTailMatch,new Set)}#getGlobstarParts(pattern,partial,patternIndex){let byStart=this.#globstarParts.get(pattern);byStart||(byStart=[],this.#globstarParts.set(pattern,byStart));let key=patternIndex*2+(partial?1:0),found=byStart[key];if(found)return found;let firstgs=pattern.indexOf(GLOBSTAR,patternIndex),lastgs=pattern.lastIndexOf(GLOBSTAR),head=pattern.slice(patternIndex,firstgs),body=pattern.slice(firstgs+1,partial?void 0:lastgs),tail=partial?[]:pattern.slice(lastgs+1),segments=[[[],0]],current=segments[0],nonGsParts=0,nonGsPartsSums=[0];for(let b of body)b===GLOBSTAR?(nonGsPartsSums.push(nonGsParts),current=[[],0],segments.push(current)):(current[0].push(b),nonGsParts++);segments.forEach((b,i)=>{b[1]=nonGsParts-nonGsPartsSums[i]});let parts={head,body,tail,segments};return byStart[key]=parts,parts}#matchGlobStarBodySections(file,bodySegments,fileLength,fileIndex,bodyIndex,partial,globStarDepth,sawTail,tried){let bs=bodySegments[bodyIndex];if(!bs){if(partial)return fileIndex>=fileLength||fileIndex===fileLength-1&&file[fileIndex]==="";for(let i=fileIndex;i<fileLength;i++){sawTail=!0;let f=file[i];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return sawTail}let[body,need]=bs,after=partial?fileLength:fileLength-need;for(;fileIndex<=after;){let key=bodyIndex*(file.length+1)+fileIndex;if(tried.has(key))return!1;if(tried.add(key),this.#matchOne(file,body,partial,fileIndex,0,fileIndex+body.length)&&globStarDepth<this.maxGlobstarRecursion){let sub=this.#matchGlobStarBodySections(file,bodySegments,fileLength,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail,tried);if(sub!==!1)return sub}if(fileIndex===after)break;let f=file[fileIndex];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;fileIndex++}return partial||null}#matchOne(file,pattern,partial,fileIndex,patternIndex,fileEnd=file.length){let fi,pi,pl,fl;for(fi=fileIndex,pi=patternIndex,fl=Math.min(fileEnd,file.length),pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){let p=pattern[pi],f=file[fi];if(p===!1||p===GLOBSTAR||!portionMatch(p,f))return!1}if(fi===fl&&pi===pl)return!0;if(fi===fl)return partial;if(pi===pl)return fi===fl-1&&file[fi]==="";throw new Error("wtf?")}braceExpand(){return braceExpand(this.pattern,this.options)}#expandBraces(){let{pattern}=this;if(this.options.nobrace)return this.braceExpand();let code=57344;for(;pattern.includes(String.fromCharCode(code));)if(++code>63743)return this.braceExpand();let mark=String.fromCharCode(code),found=!1,marked=pattern.replace(rangeRe,(m,lo,hi)=>{let a=Number(lo),b=Number(hi);return!Number.isSafeInteger(a)||!Number.isSafeInteger(b)||Math.abs(a-b)+1<RANGE_MIN?m:(found=!0,`${mark}${lo}..${hi}${mark}`)});if(!found)return this.braceExpand();let set=braceExpand(marked,this.options);for(let p of set)for(let portion of p.split("/")){let c=portion.indexOf("[");if(c!==-1&&c<portion.lastIndexOf(mark))return this.braceExpand()}return this.#rangeMark=mark,set}parse(pattern){assertValidPattern(pattern);let options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let{nocase,nocaseMagicOnly,noext=!1,dot,normalize:normalize2}=options,rangeMark=this.#rangeMark,lit2=rangeMark&&pattern.includes(rangeMark)?void 0:literal(pattern,noext);if(lit2!==void 0&&!(nocase&&!nocaseMagicOnly&&pattern.toUpperCase()!==pattern.toLowerCase()))return this.#norm(lit2);if(this.#pending)return PENDING;let m=this.#matchers.get(pattern);return m||(m=new Matcher(pattern,{nocase,noext,dot,normalize:normalize2,...rangeMark&&{rangeMark}}),this.#matchers.set(pattern,m)),m}#slashSplit(p){return this.preserveMultipleSlashes?p.split("/"):this.isWindows&&/^\/\/[^/]+/.test(p)?["",...p.split(/\/+/)]:p.split(/\/+/)}match(f,partial=this.partial){if(this.comment)return!1;if(this.empty)return f==="";if(f==="/"&&partial)return!0;let options=this.options,split=this.#cachedSplit(f);if(!split){if(!partial&&!this.#form&&(this.#endCheck||this.#literalCheck)&&lastChecked!==f){lastChecked=f;let can=this.#canMatch(f);if(can==="no")return options.flipNegate?!1:this.negate;if(can==="yes")return options.flipNegate?!0:!this.negate}split=this.#split(f)}let ff=split.parts,resolved=this.#level2?split.resolved??=this.#levelTwoFileOptimize(ff):ff,set=this.set,filename=ff[ff.length-1];if(!filename)for(let i=ff.length-2;!filename&&i>=0;i--)filename=ff[i];for(let r=0;r<set.length;r++){let pattern=set[r],shape=partial?void 0:this.#shapes[r];if(shape==="base"?portionMatch(pattern[0],filename):shape?this.#matchShape(resolved,pattern,shape):options.matchBase&&pattern.length===1?this.#matchRow([filename],[filename],pattern,partial):this.#matchRow(ff,resolved,pattern,partial))return options.flipNegate?!0:!this.negate}return options.flipNegate?!1:this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;var import_semver=__toESM(require_semver(),1);import{readFileSync}from"node:fs";var RESOURCE_FIELDS=["extensions","skills","prompts","themes","hooks"];function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg=JSON.parse(stripBom(readFileSync(packageJsonPath,"utf-8")));if(!isObject(pkg)||!isObject(pkg.pi))return null;let manifest={};typeof pkg.pi.system=="boolean"&&(manifest.system=pkg.pi.system);for(let field of RESOURCE_FIELDS){let entries=pkg.pi[field];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field]=entries)}return manifest}catch{return null}}import{createHash}from"node:crypto";import{closeSync as closeSync2,constants,existsSync as existsSync2,fstatSync as fstatSync2,lstatSync,openSync as openSync2,readFileSync as readFileSync3,realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{lstat,open,readFile,realpath}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join as join2,resolve as resolve2,sep as sep3}from"node:path";var import_ignore=__toESM(require_ignore(),1);import{closeSync,existsSync,fstatSync,openSync,readdirSync,readFileSync as readFileSync2,readSync,realpathSync,statSync}from"node:fs";import{join,relative,resolve,sep as sep2}from"node:path";var SKILL_FRONTMATTER_PREFIX_BYTES=8192,IGNORE_FILE_NAMES=[".gitignore",".ignore",".fdignore"],SKIP_SKILL_WALK_DIRECTORY_NAMES=new Set(["node_modules",".git"]),FRONTMATTER_CLOSE_LF=Buffer.from(`
---`),FRONTMATTER_CLOSE_CR=Buffer.from("\r---");function toPosixPath(p){return p.split(sep2).join("/")}function shouldSkipSkillWalkDirectoryName(name){return name.startsWith(".")||SKIP_SKILL_WALK_DIRECTORY_NAMES.has(name)}function prefixIgnorePattern(line,prefix2){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")&&!trimmed.startsWith("\\#"))return null;let pattern=line,negated=!1;pattern.startsWith("!")?(negated=!0,pattern=pattern.slice(1)):pattern.startsWith("\\!")&&(pattern=pattern.slice(1)),pattern.startsWith("/")&&(pattern=pattern.slice(1));let prefixed=prefix2?`${prefix2}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules(ig,dir,rootDir,entries){let relativeDir=relative(rootDir,dir),prefix2=relativeDir?`${toPosixPath(relativeDir)}/`:"",names=new Set(entries.map(entry=>entry.name.toLowerCase()));for(let filename of IGNORE_FILE_NAMES){if(!names.has(filename))continue;let ignorePath=join(dir,filename);try{let patterns=readFileSync2(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern(line,prefix2)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function frontmatterPrefixEnd(buf){let offset=0;if(buf.length>=3&&buf[0]===239&&buf[1]===187&&buf[2]===191&&(offset=3),buf.length-offset<3||buf[offset]!==45||buf[offset+1]!==45||buf[offset+2]!==45)return buf.length;let lf=buf.indexOf(FRONTMATTER_CLOSE_LF,offset+3),cr=buf.indexOf(FRONTMATTER_CLOSE_CR,offset+3),closeAt=lf>=0&&cr>=0?Math.min(lf,cr):lf>=0?lf:cr;if(!(closeAt<0))return closeAt+FRONTMATTER_CLOSE_LF.length}function decodeFrontmatterSource(buf){let end=frontmatterPrefixEnd(buf);return(end===void 0?buf:buf.subarray(0,end)).toString("utf8")}function readSkillMarkdownSource(filePath){let fd;try{fd=openSync(filePath,"r")}catch{return decodeFrontmatterSource(readFileSync2(filePath))}try{let prefix2=Buffer.allocUnsafe(SKILL_FRONTMATTER_PREFIX_BYTES),bytesRead=readSync(fd,prefix2,0,SKILL_FRONTMATTER_PREFIX_BYTES,0),prefixBuf=prefix2.subarray(0,bytesRead);if(bytesRead<SKILL_FRONTMATTER_PREFIX_BYTES||frontmatterPrefixEnd(prefixBuf)!==void 0)return decodeFrontmatterSource(prefixBuf);let restSize=fstatSync(fd).size-bytesRead;if(restSize<=0)return decodeFrontmatterSource(prefixBuf);let rest=Buffer.allocUnsafe(restSize);return readSync(fd,rest,0,restSize,bytesRead),decodeFrontmatterSource(Buffer.concat([prefixBuf,rest]))}finally{closeSync(fd)}}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir,options={}){let entries=[];if(!existsSync(dir))return entries;let canonical;try{authorizeSkillPath(dir,options.provenance,options.allowedSet,!0),canonical=(options.realpath??realpathSync.native)(dir)}catch(error){if(error instanceof BlockedSkillLinkError)return[dir];canonical=resolve(dir)}if(options.ancestry?.has(canonical))return entries;let ancestry=new Set(options.ancestry);ancestry.add(canonical),options.onDirectory?.(dir);let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore.default)();try{let dirEntries=readdirSync(dir,{withFileTypes:!0});addIgnoreRules(ig,dir,root,dirEntries);for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync(fullPath).isFile()}catch{continue}let relPath=toPosixPath(relative(root,fullPath));if(isFile&&!ig.ignores(relPath))return entries.push(fullPath),entries}for(let entry of dirEntries){if(shouldSkipSkillWalkDirectoryName(entry.name))continue;let fullPath=join(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile(),isLink=entry.isSymbolicLink();if(isLink)try{let stats=statSync(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath(relative(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&(isLink||!ig.ignores(relPath))&&(mode==="pi"&&dir===root||mode==="agents"&&dir!==root)){entries.push(fullPath);continue}if(isDir){if(isLink){entries.push(...collectSkillEntries(fullPath,mode,(0,import_ignore.default)(),root,{...options,ancestry}));continue}if(ig.ignores(`${relPath}/`)){let skillFile=join(fullPath,"SKILL.md");options.onIgnoredSkill&&existsSync(skillFile)&&options.onIgnoredSkill(skillFile);continue}entries.push(...collectSkillEntries(fullPath,mode,ig,root,{...options,ancestry}))}}}catch{}return entries}function collectAutoSkillEntries(dir,mode,options){return collectSkillEntries(dir,mode,void 0,void 0,options)}var EMPTY_SKILL_ALLOWED_SET={roots:[],files:[],digest:""};function skillProjectRoot(cwd){let current=resolve2(cwd);for(;;){if(existsSync2(join2(current,".git")))return current;let parent=dirname(current);if(parent===current)return resolve2(cwd);current=parent}}function insideSkillRoot(path2,root){return path2===root||path2.startsWith(root.endsWith(sep3)?root:`${root}${sep3}`)}function buildSkillAllowedSet(sources){let roots=new Set,files=new Set,realpaths=new Map,realpath2=path2=>{let canonical=realpaths.get(path2);return canonical===void 0&&(canonical=realpathSync2.native(path2),realpaths.set(path2,canonical)),canonical};for(let source of new Set(sources))try{let canonical=realpath2(source);if(statSync2(canonical).isFile()){files.add(canonical);continue}collectSkillEntries(source,"pi",void 0,void 0,{realpath:realpath2,onDirectory:path2=>roots.add(realpath2(path2))})}catch{}let allowedRoots=[...roots].sort(),allowedFiles=[...files].sort();return{roots:allowedRoots,files:allowedFiles,digest:createHash("sha256").update(JSON.stringify([allowedRoots,allowedFiles])).digest("hex")}}var BlockedSkillLinkError=class extends Error{constructor(path2,target){let display=value=>{let home=homedir();return insideSkillRoot(value,home)?`~${value.slice(home.length)}`:value};super(`Blocked skill link outside the project: ${display(path2)} -> ${display(target)}. Add the target folder to your user skills settings to allow it.`),this.name="BlockedSkillLinkError",this.diagnostic={type:"warning",category:"skill-link-blocked",path:path2,message:this.message}}};function projectRoots(provenance){return[...provenance.projectRoot===void 0?[]:[provenance.projectRoot],...provenance.kind==="project-selected"?[provenance.selectedRoot]:[]]}function contained(canonical,roots,allowed,directory){return[...roots,...allowed.roots].some(root=>insideSkillRoot(canonical,root))||allowed.files.includes(canonical)||directory&&allowed.files.some(file=>insideSkillRoot(file,canonical))}function authorizeSkillPath(path2,provenance,allowed=EMPTY_SKILL_ALLOWED_SET,directory=!1){if(provenance===void 0||provenance.kind==="user")return path2;let canonical;try{canonical=realpathSync2.native(path2);let roots=projectRoots(provenance).map(root=>realpathSync2.native(root));if(contained(canonical,roots,allowed,directory))return canonical}catch{throw new BlockedSkillLinkError(path2,"unresolvable target")}throw new BlockedSkillLinkError(path2,canonical)}async function authorizeSkillPathAsync(path2,provenance,allowed){let canonical;try{canonical=await realpath(path2);let roots=await Promise.all(projectRoots(provenance).map(root=>realpath(root)));if(contained(canonical,roots,allowed,!1))return canonical}catch{throw new BlockedSkillLinkError(path2,"unresolvable target")}throw new BlockedSkillLinkError(path2,canonical)}function readSkillFileCheckedSync(path2,provenance,allowed){if(provenance===void 0||provenance.kind==="user")return readFileSync3(path2,"utf8");let canonical=authorizeSkillPath(path2,provenance,allowed),expected,descriptor;try{if(expected=lstatSync(canonical),!expected.isFile())throw new BlockedSkillLinkError(path2,canonical);descriptor=openSync2(canonical,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch{throw new BlockedSkillLinkError(path2,canonical)}try{let opened=fstatSync2(descriptor);if(!opened.isFile()||opened.dev!==expected.dev||opened.ino!==expected.ino||lstatSync(canonical).isSymbolicLink())throw new BlockedSkillLinkError(path2,canonical);return readFileSync3(descriptor,"utf8")}finally{closeSync2(descriptor)}}async function readSkillFileChecked(path2,provenance,allowed=EMPTY_SKILL_ALLOWED_SET){if(provenance===void 0||provenance.kind==="user")return await readFile(path2,"utf8");let canonical=await authorizeSkillPathAsync(path2,provenance,allowed),expected,handle;try{if(expected=await lstat(canonical),!expected.isFile())throw new BlockedSkillLinkError(path2,canonical);handle=await open(canonical,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch{throw new BlockedSkillLinkError(path2,canonical)}try{let opened=await handle.stat();if(!opened.isFile()||opened.dev!==expected.dev||opened.ino!==expected.ino||(await lstat(canonical)).isSymbolicLink())throw new BlockedSkillLinkError(path2,canonical);return await handle.readFile("utf8")}finally{await handle.close()}}function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync4("/proc/self/environ","utf-8"),env={};for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&(env[entry.slice(0,idx)]=entry.slice(idx+1))}return env}catch{return process.env}}var NETWORK_TIMEOUT_MS=1e4,UPDATE_CHECK_CONCURRENCY=4,GIT_UPDATE_CONCURRENCY=4;function isOfflineModeEnabled(){let value=envValue("OFFLINE");return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}function isExactNpmVersion(version){return(0,import_semver.valid)(version??"")!==null}function getNpmVersionRange(version){return version?(0,import_semver.validRange)(version)??void 0:void 0}function resourcePrecedenceRank(m){return m.source==="builtin"?5:m.origin==="package"?4:(m.scope==="project"?0:2)+(m.source==="local"?0:1)}var RESOURCE_TYPES=["extensions","skills","prompts","themes","hooks"],FILE_PATTERNS={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/,hooks:/\.json$/},IGNORE_FILE_NAMES2=[".gitignore",".ignore",".fdignore"];function toPosixPath2(p){return p.split(sep4).join("/")}function getHomeDir(){return process.env.HOME||homedir2()}function getExtensionTempFolder(agentDir){let tempFolder=join3(agentDir,"tmp","extensions");return mkdirSync(tempFolder,{recursive:!0,mode:448}),chmodSync(tempFolder,448),tempFolder}function prefixIgnorePattern2(line,prefix2){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")&&!trimmed.startsWith("\\#"))return null;let pattern=line,negated=!1;pattern.startsWith("!")?(negated=!0,pattern=pattern.slice(1)):pattern.startsWith("\\!")&&(pattern=pattern.slice(1)),pattern.startsWith("/")&&(pattern=pattern.slice(1));let prefixed=prefix2?`${prefix2}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules2(ig,dir,rootDir){let relativeDir=relative2(rootDir,dir),prefix2=relativeDir?`${toPosixPath2(relativeDir)}/`:"";for(let filename of IGNORE_FILE_NAMES2){let ignorePath=join3(dir,filename);if(existsSync3(ignorePath))try{let patterns=readFileSync4(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix2)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function isPattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")||s.includes("*")||s.includes("?")}function isOverridePattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")}function hasGlobPattern(s){return s.includes("*")||s.includes("?")}function expandPackageGlob(pattern,root){return globSync(pattern,{cwd:root}).map(match2=>resolve3(root,match2)).filter(path2=>relative2(root,path2).split(sep4).every(segment=>segment===".."||!segment.startsWith("."))).sort((a,b)=>a<b?-1:a>b?1:0)}function splitPatterns(entries){let plain=[],patterns=[];for(let entry of entries)isPattern(entry)?patterns.push(entry):plain.push(entry);return{plain,patterns}}function collectFiles(dir,filePattern,skipNodeModules=!0,ignoreMatcher,rootDir){let files=[];if(!existsSync3(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore2.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync2(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync3(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath2(relative2(root,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;ig.ignores(ignorePath)||(isDir?files.push(...collectFiles(fullPath,filePattern,skipNodeModules,ig,root)):isFile&&filePattern.test(entry.name)&&files.push(fullPath))}}catch{}return files}function collectAncestorAgentsSkillDirs(startDir){return projectAgentsSkillDirs(startDir)}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync3(fullPath).isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".md")&&entries.push(fullPath)}}catch{}return entries}function collectAutoThemeEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync3(fullPath).isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".json")&&entries.push(fullPath)}}catch{}return entries}function resolveExtensionEntries(dir){let packageJsonPath=join3(dir,"package.json");if(existsSync3(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=resolve3(dir,extPath);existsSync3(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=join3(dir,"index.ts"),indexJs=join3(dir,"index.js");return existsSync3(indexTs)?[indexTs]:existsSync3(indexJs)?[indexJs]:null}function collectAutoExtensionEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let rootEntries=resolveExtensionEntries(dir);if(rootEntries)return rootEntries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync3(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;if(!ig.ignores(ignorePath)){if(isFile&&(entry.name.endsWith(".ts")||entry.name.endsWith(".js")))entries.push(fullPath);else if(isDir){let resolvedEntries=resolveExtensionEntries(fullPath);resolvedEntries&&entries.push(...resolvedEntries)}}}}catch{}return entries}function collectResourceFiles(dir,resourceType,provenance){return resourceType==="skills"?collectSkillEntries(dir,"pi",void 0,void 0,{provenance}):resourceType==="extensions"?collectAutoExtensionEntries(dir):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentName=isSkillFile?basename(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath2(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath2(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var DefaultPackageManager=class{constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager,this.builtinExtensions=options.builtinExtensions??[]}setProgressCallback(callback){this.progressCallback=callback}addSourceToSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],normalizedSource=this.normalizePackageSourceForSettings(source,scope),matchIndex=currentPackages.findIndex(existing=>this.packageSourcesMatch(existing,source,scope));if(matchIndex!==-1){let existing=currentPackages[matchIndex];if(this.getPackageSourceString(existing)===normalizedSource)return!1;let nextPackages2=[...currentPackages];return nextPackages2[matchIndex]=typeof existing=="string"?normalizedSource:{...existing,source:normalizedSource},scope==="project"?this.settingsManager.setProjectPackages(nextPackages2):this.settingsManager.setPackages(nextPackages2),!0}let nextPackages=[...currentPackages,normalizedSource];return scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0}removeSourceFromSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],nextPackages=currentPackages.filter(existing=>!this.packageSourcesMatch(existing,source,scope));return nextPackages.length!==currentPackages.length?(scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0):!1}getInstalledPath(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm"){let path2=this.getNpmInstallPath(parsed,scope);return existsSync3(path2)?path2:void 0}if(parsed.type==="git"){let path2=this.getGitInstallPath(parsed,scope);return existsSync3(path2)?path2:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path2=this.resolvePathFromBase(parsed.path,baseDir);return existsSync3(path2)?path2:void 0}}emitProgress(event){this.progressCallback?.(event)}async withProgress(action,source,message,operation){this.emitProgress({type:"start",action,source,message});try{await operation(),this.emitProgress({type:"complete",action,source})}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw this.emitProgress({type:"error",action,source,message:errorMessage}),error}}async resolve(onMissing){let accumulator=this.createAccumulator(),globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg of projectSettings.packages??[])allPackages.push({pkg,scope:"project"});for(let pkg of globalSettings.packages??[])allPackages.push({pkg,scope:"user"});let packageSources=this.dedupePackages(allPackages);await this.resolvePackageSources(packageSources,accumulator,onMissing);let globalBaseDir=this.agentDir,projectBaseDir=join3(this.cwd,CONFIG_DIR_NAME);for(let resourceType of RESOURCE_TYPES){let target=this.getTargetMap(accumulator,resourceType),globalEntries=globalSettings[resourceType]??[],projectEntries=projectSettings[resourceType]??[];this.resolveLocalEntries(projectEntries,resourceType,target,{source:"local",scope:"project",origin:"top-level"},projectBaseDir),this.resolveLocalEntries(globalEntries,resourceType,target,{source:"local",scope:"user",origin:"top-level"},globalBaseDir)}this.addAutoDiscoveredResources(accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir);for(let name of this.builtinExtensions){let path2=`${BUILTIN_PATH_PREFIX}${name}`,projectEnabled=applyAutoloadDisabledPatterns([path2],getOverridePatterns(projectSettings.extensions??[]),projectBaseDir).get(path2);this.addResource(accumulator.extensions,path2,{source:"builtin",scope:projectEnabled===void 0?"user":"project",origin:"top-level"},projectEnabled??isEnabledByOverrides(path2,globalSettings.extensions??[],globalBaseDir))}return this.toResolvedPaths(accumulator)}async resolveExtensionSources(sources,options){let accumulator=this.createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user";for(let source of sources.filter(source2=>source2.startsWith(BUILTIN_PATH_PREFIX)))this.addResource(accumulator.extensions,source,{source:"builtin",scope,origin:"top-level"},!0);let packageSources=sources.filter(source=>!source.startsWith(BUILTIN_PATH_PREFIX)).map(source=>({pkg:source,scope}));return await this.resolvePackageSources(packageSources,accumulator),this.toResolvedPaths(accumulator)}listConfiguredPackages(){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),configuredPackages=[];for(let pkg of globalSettings.packages??[]){let source=typeof pkg=="string"?pkg:pkg.source;configuredPackages.push({source,scope:"user",filtered:typeof pkg=="object",installedPath:this.getInstalledPath(source,"user")})}for(let pkg of projectSettings.packages??[]){let source=typeof pkg=="string"?pkg:pkg.source;configuredPackages.push({source,scope:"project",filtered:typeof pkg=="object",installedPath:this.getInstalledPath(source,"project")})}return configuredPackages}async install(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";this.assertProjectTrustedForScope(scope),await this.withProgress("install",source,`Installing ${source}...`,async()=>{if(parsed.type==="npm"){await this.installNpm(parsed,scope,!1);return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}if(parsed.type==="local"){let resolved=this.resolvePath(parsed.path);if(!existsSync3(resolved))throw new Error(`Path does not exist: ${resolved}`);return}throw new Error(`Unsupported install source: ${source}`)})}async installAndPersist(source,options){await this.install(source,options),this.addSourceToSettings(source,options)}async remove(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";this.assertProjectTrustedForScope(scope),await this.withProgress("remove",source,`Removing ${source}...`,async()=>{if(parsed.type==="npm"){await this.uninstallNpm(parsed,scope);return}if(parsed.type==="git"){await this.removeGit(parsed,scope);return}if(parsed.type!=="local")throw new Error(`Unsupported remove source: ${source}`)})}async removeAndPersist(source,options){return await this.remove(source,options),this.removeSourceFromSettings(source,options)}async update(source){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),identity=source?this.getPackageIdentity(source):void 0,matched=!1,updateSources=[];for(let pkg of globalSettings.packages??[]){let sourceStr=typeof pkg=="string"?pkg:pkg.source;identity&&this.getPackageIdentity(sourceStr,"user")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"user"}))}for(let pkg of projectSettings.packages??[]){let sourceStr=typeof pkg=="string"?pkg:pkg.source;identity&&this.getPackageIdentity(sourceStr,"project")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"project"}))}if(source&&!matched)throw new Error(this.buildNoMatchingPackageMessage(source,[...globalSettings.packages??[],...projectSettings.packages??[]]));await this.updateConfiguredSources(updateSources)}async updateConfiguredSources(sources){if(isOfflineModeEnabled()||sources.length===0)return;let npmCandidates=[],gitCandidates=[];for(let entry of sources){let parsed=this.parseSource(entry.source);parsed.type==="npm"?parsed.pinned||npmCandidates.push({...entry,parsed}):parsed.type==="git"&&gitCandidates.push({...entry,parsed})}let npmCheckTasks=npmCandidates.map(entry=>async()=>({entry,shouldUpdate:await this.shouldUpdateNpmSource(entry.parsed,entry.scope)})),npmCheckResults=await this.runWithConcurrency(npmCheckTasks,UPDATE_CHECK_CONCURRENCY),userNpmUpdates=[],projectNpmUpdates=[];for(let result of npmCheckResults)result.shouldUpdate&&(result.entry.scope==="user"?userNpmUpdates.push(result.entry):projectNpmUpdates.push(result.entry));let tasks=[];if(userNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(userNpmUpdates,"user")),projectNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(projectNpmUpdates,"project")),gitCandidates.length>0){let gitTasks=gitCandidates.map(entry=>async()=>this.withProgress("update",entry.source,`Updating ${entry.source}...`,async()=>{await this.updateGit(entry.parsed,entry.scope)}));tasks.push(this.runWithConcurrency(gitTasks,GIT_UPDATE_CONCURRENCY).then(()=>{}))}await Promise.all(tasks)}async shouldUpdateNpmSource(source,scope){let installedPath=this.getManagedNpmInstallPath(source,scope),installedVersion=existsSync3(installedPath)?this.getInstalledNpmVersion(installedPath):void 0;if(!installedVersion)return!0;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver.gt)(targetVersion,installedVersion)}catch{return!0}}async updateNpmBatch(sources,scope){if(sources.length===0)return;let sourceLabel=sources.length===1?sources[0].source:`${scope} npm packages`,message=sources.length===1?`Updating ${sources[0].source}...`:`Updating ${scope} npm packages...`,specs=sources.map(entry=>entry.parsed.version?entry.parsed.spec:`${entry.parsed.name}@latest`);await this.withProgress("update",sourceLabel,message,async()=>{await this.installNpmBatch(specs,scope)})}async installNpmBatch(specs,scope){let installRoot=this.getNpmInstallRoot(scope,!1);this.ensureNpmProject(installRoot),await this.runNpmCommand(this.getNpmInstallArgs(specs,installRoot))}async checkForAvailableUpdates(){if(isOfflineModeEnabled())return[];let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg of projectSettings.packages??[])allPackages.push({pkg,scope:"project"});for(let pkg of globalSettings.packages??[])allPackages.push({pkg,scope:"user"});let checks=this.dedupePackages(allPackages).filter(entry=>entry.scope!=="temporary"&&entry.scope!=="system").map(entry=>async()=>{let source=typeof entry.pkg=="string"?entry.pkg:entry.pkg.source,parsed=this.parseSource(source);if(parsed.type==="local"||parsed.pinned)return;if(parsed.type==="npm"){let installedPath2=this.getNpmInstallPath(parsed,entry.scope);return!existsSync3(installedPath2)||!await this.npmHasAvailableUpdate(parsed,installedPath2)?void 0:{source,displayName:parsed.name,type:"npm",scope:entry.scope}}let installedPath=this.getGitInstallPath(parsed,entry.scope);if(!(!existsSync3(installedPath)||!await this.gitHasAvailableUpdate(installedPath)))return{source,displayName:`${parsed.host}/${parsed.path}`,type:"git",scope:entry.scope}});return(await this.runWithConcurrency(checks,UPDATE_CHECK_CONCURRENCY)).filter(result=>result!==void 0)}async resolvePackageSources(sources,accumulator,onMissing){for(let{pkg,scope}of sources){let sourceStr=typeof pkg=="string"?pkg:pkg.source,filter2=typeof pkg=="object"?pkg:void 0,deltaBase=this.findAutoloadDeltaBase(pkg,scope,sources),resolvedSource=deltaBase?.source??sourceStr,resolvedScope=deltaBase?.scope??scope,parsed=this.parseSource(resolvedSource),metadata={source:sourceStr,scope,origin:"package"};if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(resolvedScope);this.resolveLocalExtensionSource(parsed,accumulator,filter2,metadata,baseDir);continue}let installMissing=async()=>{if(isOfflineModeEnabled())return!1;if(!onMissing)return await this.installParsedSource(parsed,resolvedScope),!0;let action=await onMissing(resolvedSource);if(action==="skip")return!1;if(action==="error")throw new Error(`Missing source: ${resolvedSource}`);return await this.installParsedSource(parsed,resolvedScope),!0};if(parsed.type==="npm"){let installedPath=this.getNpmInstallPath(parsed,resolvedScope);if(!existsSync3(installedPath)||!await this.installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,metadata.packageRoot=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync3(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=installedPath,metadata.packageRoot=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata)}}}findAutoloadDeltaBase(pkg,scope,sources){if(scope!=="project"||typeof pkg!="object"||pkg.autoload!==!1)return;let identity=this.getPackageIdentity(pkg.source,scope),userEntry=sources.find(entry=>entry.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(entry.pkg),"user")===identity);return userEntry?{source:this.getPackageSourceString(userEntry.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(source,accumulator,filter2,metadata,baseDir){let resolved=this.resolvePathFromBase(source.path,baseDir);if(existsSync3(resolved))try{let stats=statSync3(resolved);if(stats.isFile()){metadata.baseDir=dirname2(resolved),this.addResource(accumulator.extensions,resolved,metadata,!0);return}stats.isDirectory()&&(metadata.baseDir=resolved,metadata.packageRoot=resolved,this.collectPackageResources(resolved,accumulator,filter2,metadata)||this.addResource(accumulator.extensions,resolved,metadata,!0))}catch{return}}async installParsedSource(parsed,scope){if(parsed.type==="npm"){await this.installNpm(parsed,scope,scope==="temporary");return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}}getPackageSourceString(pkg){return typeof pkg=="string"?pkg:pkg.source}getSourceMatchKeyForInput(source){let parsed=this.parseSource(source);return parsed.type==="npm"?`npm:${parsed.name}`:parsed.type==="git"?`git:${parsed.host}/${parsed.path}`:`local:${this.resolvePath(parsed.path)}`}getSourceMatchKeyForSettings(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;let baseDir=this.getBaseDirForScope(scope);return`local:${this.resolvePathFromBase(parsed.path,baseDir)}`}buildNoMatchingPackageMessage(source,configuredPackages){let suggestion=this.findSuggestedConfiguredSource(source,configuredPackages);return suggestion?`No matching package found for ${source}. Did you mean ${suggestion}?`:`No matching package found for ${source}`}findSuggestedConfiguredSource(source,configuredPackages){let trimmedSource=source.trim(),suggestions=new Set;for(let pkg of configuredPackages){let sourceStr=this.getPackageSourceString(pkg),parsed=this.parseSource(sourceStr);if(parsed.type==="npm"){(trimmedSource===parsed.name||trimmedSource===parsed.spec)&&suggestions.add(sourceStr);continue}if(parsed.type==="git"){let shorthand=`${parsed.host}/${parsed.path}`,shorthandWithRef=parsed.ref?`${shorthand}@${parsed.ref}`:void 0;(trimmedSource===shorthand||shorthandWithRef&&trimmedSource===shorthandWithRef)&&suggestions.add(sourceStr)}}return suggestions.values().next().value}packageSourcesMatch(existing,inputSource,scope){let left=this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing),scope),right=this.getSourceMatchKeyForInput(inputSource);return left===right}normalizePackageSourceForSettings(source,scope){let parsed=this.parseSource(source);if(parsed.type!=="local")return source;let baseDir=this.getBaseDirForScope(scope),resolved=this.resolvePath(parsed.path);return relative2(baseDir,resolved)||"."}parseSource(source){if(source.startsWith("npm:")){let spec=source.slice(4).trim(),{name,version}=this.parseNpmSpec(spec);return{type:"npm",spec,name,version,range:getNpmVersionRange(version),pinned:isExactNpmVersion(version)}}if(isLocalPath(source))return{type:"local",path:source};let gitParsed=parseGitUrl(source);return gitParsed||{type:"local",path:source}}async installedNpmMatchesConfiguredVersion(source,installedPath){let installedVersion=this.getInstalledNpmVersion(installedPath);return installedVersion?source.range?(0,import_semver.satisfies)(installedVersion,source.range):!0:!1}async npmHasAvailableUpdate(source,installedPath){if(isOfflineModeEnabled())return!1;let installedVersion=this.getInstalledNpmVersion(installedPath);if(!installedVersion)return!1;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver.gt)(targetVersion,installedVersion)}catch{return!1}}getInstalledNpmVersion(installedPath){let packageJsonPath=join3(installedPath,"package.json");if(existsSync3(packageJsonPath))try{let content=readFileSync4(packageJsonPath,"utf-8");return JSON.parse(stripBom(content)).version}catch{return}}async getLatestNpmVersion(packageSpec,range2){let npmCommand=this.getNpmCommand(),raw=(await this.runCommandCapture(npmCommand.command,[...npmCommand.args,"view",packageSpec,"version","--json"],{cwd:this.cwd,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!raw)throw new Error("Empty response from npm view");let parsed=JSON.parse(raw);if(typeof parsed=="string")return parsed;if(Array.isArray(parsed)){let versions=parsed.filter(value=>typeof value=="string"&&value.length>0),latest=range2?(0,import_semver.maxSatisfying)(versions,range2):[...versions].sort(import_semver.rcompare)[0];if(latest)return latest}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(installedPath){if(isOfflineModeEnabled())return!1;try{let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),remoteHead=await this.getRemoteGitHead(installedPath);return localHead.trim()!==remoteHead.trim()}catch{return!1}}async getRemoteGitHead(installedPath){let upstreamRef=await this.getGitUpstreamRef(installedPath);if(upstreamRef){let match3=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin",upstreamRef])).match(/^([0-9a-f]{40})\s+/m);if(match3?.[1])return match3[1]}let match2=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!match2?.[1])throw new Error("Failed to determine remote HEAD");return match2[1]}async getLocalGitUpdateTarget(installedPath){try{let trimmedUpstream=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!trimmedUpstream.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`);let branch=trimmedUpstream.slice(7);if(!branch)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:installedPath}).catch(()=>{});let head=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),branch=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return branch?{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}:{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(installedPath){try{let trimmed=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!trimmed.startsWith("origin/"))return;let branch=trimmed.slice(7);return branch?`refs/heads/${branch}`:void 0}catch{return}}runGitRemoteCommand(installedPath,args){return this.runCommandCapture("git",args,{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(tasks,limit){if(tasks.length===0)return[];let results=new Array(tasks.length),nextIndex=0,workerCount=Math.max(1,Math.min(limit,tasks.length)),worker=async()=>{for(;;){let index=nextIndex;if(nextIndex+=1,index>=tasks.length)return;results[index]=await tasks[index]()}};return await Promise.all(Array.from({length:workerCount},()=>worker())),results}getPackageIdentity(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;if(scope){let baseDir=this.getBaseDirForScope(scope);return`local:${this.resolvePathFromBase(parsed.path,baseDir)}`}return`local:${this.resolvePath(parsed.path)}`}dedupePackages(packages){let result=[],seen=new Map;for(let entry of packages){let identity=this.getPackageIdentity(this.getPackageSourceString(entry.pkg),entry.scope),index=seen.get(identity);if(index===void 0){seen.set(identity,result.length),result.push(entry);continue}let existing=result[index];existing?.scope==="project"&&entry.scope==="user"?typeof existing.pkg=="object"&&existing.pkg.autoload===!1&&result.push(entry):entry.scope==="project"&&(result[index]=entry)}return result}parseNpmSpec(spec){let match2=spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!match2)return{name:spec};let name=match2[1]??spec,version=match2[2];return{name,version}}assertProjectTrustedForScope(scope){if(scope==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){let configuredCommand=this.settingsManager.getNpmCommand();if(!configuredCommand||configuredCommand.length===0)return{command:"npm",args:[]};let[command,...args]=configuredCommand;if(!command)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command,args}}getPackageManagerName(){let npmCommand=this.getNpmCommand(),normalizeCommandName=command=>basename(command).replace(/\.(cmd|exe)$/i,""),supportedPackageManagers=new Set(["npm","pnpm","bun"]),directCommand=normalizeCommandName(npmCommand.command),separatorIndex=npmCommand.args.lastIndexOf("--");if(separatorIndex>=0){let wrappedCommand=npmCommand.args[separatorIndex+1];return wrappedCommand?normalizeCommandName(wrappedCommand):directCommand}if(supportedPackageManagers.has(directCommand))return directCommand;let wrappedPackageManagers=[...new Set(npmCommand.args.map(normalizeCommandName).filter(command=>supportedPackageManagers.has(command)))];if(wrappedPackageManagers.length>1)throw new Error(`Ambiguous npmCommand package managers: ${wrappedPackageManagers.join(", ")}`);return wrappedPackageManagers[0]??directCommand}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(args){let npmCommand=this.getNpmCommand();return this.runCommandSync(npmCommand.command,[...npmCommand.args,...args])}getNpmInstallArgs(specs,installRoot){let packageManagerName=this.getPackageManagerName();return packageManagerName==="bun"?["install",...specs,"--cwd",installRoot,"--omit=peer"]:packageManagerName==="pnpm"?["install",...specs,"--prefix",installRoot,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...specs,"--prefix",installRoot,"--legacy-peer-deps"]}async installNpm(source,scope,temporary){let installRoot=this.getNpmInstallRoot(scope,temporary);this.ensureNpmProject(installRoot),await this.runNpmCommand(this.getNpmInstallArgs([source.spec],installRoot))}async uninstallNpm(source,scope){let installRoot=this.getNpmInstallRoot(scope,!1);if(!existsSync3(installRoot))return;let packageManagerName=this.getPackageManagerName();if(packageManagerName==="bun"){await this.runNpmCommand(["uninstall",source.name,"--cwd",installRoot]);return}let args=["uninstall",source.name,"--prefix",installRoot];packageManagerName!=="pnpm"&&args.push("--legacy-peer-deps"),await this.runNpmCommand(args)}async installGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(existsSync3(targetDir)){if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref);return}let gitRoot=this.getGitInstallRoot(scope);gitRoot&&this.ensureGitIgnore(gitRoot),mkdirSync(dirname2(targetDir),{recursive:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join3(targetDir,"package.json");existsSync3(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}catch(error){throw rmSync(targetDir,{recursive:!0,force:!0}),this.pruneEmptyGitParents(targetDir,gitRoot),error}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync3(targetDir)){await this.installGit(source,scope);return}if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref)}hasMissingGitDependencies(targetDir){let packageJsonPath=join3(targetDir,"package.json");if(!existsSync3(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync4(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve3(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve3(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep4}`)?!existsSync3(dependencyPath):!1})}catch{return!1}}async repairMissingGitDependencies(targetDir){this.hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}getGitUpdateMarkerPath(targetDir){return join3(dirname2(targetDir),`.${basename(targetDir)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error}let packageJsonPath=join3(targetDir,"package.json");existsSync3(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir}),rmSync(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),markerPath=this.getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync3(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync(targetDir,{recursive:!0,force:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0}),this.pruneEmptyGitParents(targetDir,this.getGitInstallRoot(scope))}pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve3(installRoot),current=dirname2(targetDir);for(;current.startsWith(resolvedRoot)&¤t!==resolvedRoot;){if(!existsSync3(current)){current=dirname2(current);continue}if(readdirSync2(current).length>0)break;try{rmSync(current,{recursive:!0,force:!0})}catch{break}current=dirname2(current)}}ensureNpmProject(installRoot){existsSync3(installRoot)||mkdirSync(installRoot,{recursive:!0}),markPathIgnoredByCloudSync(installRoot),this.ensureGitIgnore(installRoot);let packageJsonPath=join3(installRoot,"package.json");existsSync3(packageJsonPath)||writeFileSync(packageJsonPath,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(dir){existsSync3(dir)||mkdirSync(dir,{recursive:!0});let ignorePath=join3(dir,".gitignore");existsSync3(ignorePath)||writeFileSync(ignorePath,`*
!.gitignore
`,"utf-8")}getNpmInstallRoot(scope,temporary){return temporary?this.getTemporaryDir("npm"):scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME,"npm")):join3(this.agentDir,"npm")}getGlobalNpmRoot(){let npmCommand=this.getNpmCommand(),commandKey=[npmCommand.command,...npmCommand.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===commandKey)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){let binDir=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=join3(dirname2(binDir),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=commandKey,this.globalNpmRoot}getPnpmGlobalPackagePath(packageName){if(this.getPackageManagerName()!=="pnpm")return;let output=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),entries=JSON.parse(output);for(let entry of entries){let path2=entry.dependencies?.[packageName]?.path;if(path2)return path2}}getManagedNpmInstallPath(source,scope){return scope==="temporary"?join3(this.getTemporaryDir("npm"),"node_modules",source.name):scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME,"npm","node_modules",source.name)):join3(this.agentDir,"npm","node_modules",source.name)}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join3(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=this.getManagedNpmInstallPath(source,scope);if(scope!=="user"||existsSync3(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync3(legacyPath)?legacyPath:managedPath}getGitInstallPath(source,scope){if(scope==="temporary")return this.getTemporaryDir(`git-${source.host}`,source.path,source.ref);let installRoot=this.getGitInstallRoot(scope);if(!installRoot)throw new Error("Missing git install root");return this.resolveManagedPath(installRoot,source.host,source.path)}getGitInstallRoot(scope){if(scope!=="temporary")return scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME,"git")):join3(this.agentDir,"git")}getTemporaryDir(prefix2,suffix,ref){let root=this.resolveManagedPath(getExtensionTempFolder(this.agentDir),prefix2),hash=createHash2("sha256").update(`${prefix2}-${suffix??""}${ref?`@${ref}`:""}`).digest("hex").slice(0,8);return this.resolveManagedPath(root,hash,suffix??"")}resolveManagedPath(root,...parts){let resolvedRoot=resolve3(root),resolvedPath=resolve3(resolvedRoot,...parts);if(resolvedPath!==resolvedRoot&&!resolvedPath.startsWith(`${resolvedRoot}${sep4}`))throw new Error(`Refusing to use path outside package install root: ${resolvedPath}`);return resolvedPath}getBaseDirForScope(scope){return scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME)):scope==="user"?this.agentDir:this.cwd}resolvePath(input){return resolvePath(input,this.cwd,{homeDir:getHomeDir(),trim:!0})}resolvePathFromBase(input,baseDir){return resolvePath(input,baseDir,{homeDir:getHomeDir(),trim:!0})}collectPackageResources(packageRoot,accumulator,filter2,metadata){metadata=this.selectSkillRoot(packageRoot,metadata,"project-auto");let manifest=readPiManifest(join3(packageRoot,"package.json"));if(manifest?.system===!0&&metadata.scope==="temporary"&&(metadata.scope="system"),filter2){for(let resourceType of RESOURCE_TYPES){let patterns=filter2[resourceType],target=this.getTargetMap(accumulator,resourceType);filter2.autoload===!1?this.applyPackageDeltaFilter(packageRoot,patterns??[],resourceType,target,metadata):patterns!==void 0?this.applyPackageFilter(packageRoot,patterns,resourceType,target,metadata):this.collectDefaultResources(packageRoot,resourceType,target,metadata)}return!0}if(manifest){for(let resourceType of RESOURCE_TYPES){let entries=manifest[resourceType];this.addManifestEntries(entries,packageRoot,resourceType,this.getTargetMap(accumulator,resourceType),metadata)}return!0}let hasAnyDir=!1;for(let resourceType of RESOURCE_TYPES){let dir=join3(packageRoot,resourceType);if(existsSync3(dir)){let files=collectResourceFiles(dir,resourceType,metadata.skillProvenance);for(let f of files)this.addResource(this.getTargetMap(accumulator,resourceType),f,metadata,!0);hasAnyDir=!0}}return hasAnyDir}collectDefaultResources(packageRoot,resourceType,target,metadata){let entries=readPiManifest(join3(packageRoot,"package.json"))?.[resourceType];if(entries){this.addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join3(packageRoot,resourceType);if(existsSync3(dir)){let files=collectResourceFiles(dir,resourceType,metadata.skillProvenance);for(let f of files)this.addResource(target,f,metadata,!0)}}applyPackageFilter(packageRoot,userPatterns,resourceType,target,metadata){let{allFiles}=this.collectManifestFiles(packageRoot,resourceType,metadata.skillProvenance);if(userPatterns.length===0){for(let f of allFiles)this.addResource(target,f,metadata,!1);return}let enabledByUser=applyPatterns(allFiles,userPatterns,packageRoot);for(let f of allFiles){let enabled=enabledByUser.has(f);this.addResource(target,f,metadata,enabled)}}applyPackageDeltaFilter(packageRoot,userPatterns,resourceType,target,metadata){if(userPatterns.length===0)return;let{allFiles}=this.collectManifestFiles(packageRoot,resourceType,metadata.skillProvenance),enabledByUser=applyAutoloadDisabledPatterns(allFiles,userPatterns,packageRoot);for(let[filePath,enabled]of enabledByUser)this.addResource(target,filePath,metadata,enabled)}collectManifestFiles(packageRoot,resourceType,provenance){let entries=readPiManifest(join3(packageRoot,"package.json"))?.[resourceType];if(entries&&entries.length>0){let allFiles2=this.collectFilesFromManifestEntries(entries,packageRoot,resourceType,provenance),manifestPatterns=entries.filter(isOverridePattern),enabledByManifest=manifestPatterns.length>0?applyPatterns(allFiles2,manifestPatterns,packageRoot):new Set(allFiles2);return{allFiles:Array.from(enabledByManifest),enabledByManifest}}let conventionDir=join3(packageRoot,resourceType);if(!existsSync3(conventionDir))return{allFiles:[],enabledByManifest:new Set};let allFiles=collectResourceFiles(conventionDir,resourceType,provenance);return{allFiles,enabledByManifest:new Set(allFiles)}}addManifestEntries(entries,root,resourceType,target,metadata){if(!entries)return;let allFiles=this.collectFilesFromManifestEntries(entries,root,resourceType,metadata.skillProvenance),patterns=entries.filter(isOverridePattern),enabledPaths=applyPatterns(allFiles,patterns,root);for(let f of allFiles)enabledPaths.has(f)&&this.addResource(target,f,metadata,!0)}collectFilesFromManifestEntries(entries,root,resourceType,provenance){let resolved=entries.filter(entry=>!isOverridePattern(entry)).flatMap(entry=>hasGlobPattern(entry)?expandPackageGlob(entry,root):[resolve3(root,entry)]);return this.collectFilesFromPaths(resolved,resourceType,provenance)}resolveLocalEntries(entries,resourceType,target,metadata,baseDir){if(entries.length===0)return;let{plain,patterns}=splitPatterns(entries),resolvedPlain=plain.map(p=>this.resolvePathFromBase(p,baseDir)),metadataByFile=new Map,allFiles=resolvedPlain.flatMap(path2=>{let selected=resourceType==="skills"?this.selectSkillRoot(path2,metadata,"project-selected"):metadata,files=this.collectFilesFromPaths([path2],resourceType,selected.skillProvenance);for(let file of files)metadataByFile.set(file,selected);return files}),enabledPaths=applyPatterns(allFiles,patterns,baseDir);for(let f of allFiles)this.addResource(target,f,metadataByFile.get(f)??metadata,enabledPaths.has(f))}addAutoDiscoveredResources(accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir){let userMetadata={source:"auto",scope:"user",origin:"top-level",baseDir:globalBaseDir},projectMetadata={source:"auto",scope:"project",origin:"top-level",baseDir:projectBaseDir},userOverrides={extensions:globalSettings.extensions??[],skills:globalSettings.skills??[],prompts:globalSettings.prompts??[],themes:globalSettings.themes??[],hooks:globalSettings.hooks??[]},projectOverrides={extensions:projectSettings.extensions??[],skills:projectSettings.skills??[],prompts:projectSettings.prompts??[],themes:projectSettings.themes??[],hooks:projectSettings.hooks??[]},userDirs={extensions:join3(globalBaseDir,"extensions"),skills:join3(globalBaseDir,"skills"),prompts:join3(globalBaseDir,"prompts"),themes:join3(globalBaseDir,"themes"),hooks:join3(globalBaseDir,"hooks")},projectDirs={extensions:join3(projectBaseDir,"extensions"),skills:join3(projectBaseDir,"skills"),prompts:join3(projectBaseDir,"prompts"),themes:join3(projectBaseDir,"themes"),hooks:join3(projectBaseDir,"hooks")},legacyProjectBaseDir=join3(this.cwd,".pi"),legacyProjectDirs={extensions:join3(legacyProjectBaseDir,"extensions"),skills:join3(legacyProjectBaseDir,"skills"),prompts:join3(legacyProjectBaseDir,"prompts"),themes:join3(legacyProjectBaseDir,"themes"),hooks:join3(legacyProjectBaseDir,"hooks")},userAgentsSkillsDir=join3(getHomeDir(),".agents","skills"),projectTrusted=this.settingsManager.isProjectTrusted(),projectAgentsSkillDirs2=projectTrusted?collectAncestorAgentsSkillDirs(this.cwd):[],addResources=(resourceType,paths,metadata,overrides,baseDir)=>{let target=this.getTargetMap(accumulator,resourceType);for(let path2 of paths){let enabled=isEnabledByOverrides(path2,overrides,baseDir);this.addResource(target,path2,metadata,enabled)}},addSkills=(root,mode,metadata,overrides,base)=>{let selected=this.selectSkillRoot(root,metadata,"project-auto");addResources("skills",collectAutoSkillEntries(root,mode,{provenance:selected.skillProvenance,onIgnoredSkill:skillFile=>accumulator.ignoredSkills.add(skillFile)}),selected,overrides,base)};projectTrusted&&(addResources("extensions",collectAutoExtensionEntries(projectDirs.extensions),projectMetadata,projectOverrides.extensions,projectBaseDir),addSkills(projectDirs.skills,"pi",projectMetadata,projectOverrides.skills,projectBaseDir));for(let agentsSkillsDir of projectAgentsSkillDirs2){let agentsBaseDir=dirname2(agentsSkillsDir),agentsMetadata={...projectMetadata,baseDir:agentsBaseDir};addSkills(agentsSkillsDir,"agents",agentsMetadata,projectOverrides.skills,agentsBaseDir)}if(projectTrusted&&(addResources("prompts",collectAutoPromptEntries(projectDirs.prompts),projectMetadata,projectOverrides.prompts,projectBaseDir),addResources("themes",collectAutoThemeEntries(projectDirs.themes),projectMetadata,projectOverrides.themes,projectBaseDir),addResources("hooks",collectFiles(projectDirs.hooks,FILE_PATTERNS.hooks),projectMetadata,projectOverrides.hooks,projectBaseDir)),projectTrusted&&resolve3(legacyProjectBaseDir)!==resolve3(projectBaseDir)){let legacyProjectMetadata={...projectMetadata,baseDir:legacyProjectBaseDir};addResources("extensions",collectAutoExtensionEntries(legacyProjectDirs.extensions),legacyProjectMetadata,projectOverrides.extensions,legacyProjectBaseDir),addSkills(legacyProjectDirs.skills,"pi",legacyProjectMetadata,projectOverrides.skills,legacyProjectBaseDir),addResources("prompts",collectAutoPromptEntries(legacyProjectDirs.prompts),legacyProjectMetadata,projectOverrides.prompts,legacyProjectBaseDir),addResources("themes",collectAutoThemeEntries(legacyProjectDirs.themes),legacyProjectMetadata,projectOverrides.themes,legacyProjectBaseDir),addResources("hooks",collectFiles(legacyProjectDirs.hooks,FILE_PATTERNS.hooks),legacyProjectMetadata,projectOverrides.hooks,legacyProjectBaseDir)}addResources("extensions",collectAutoExtensionEntries(userDirs.extensions),userMetadata,userOverrides.extensions,globalBaseDir),addSkills(userDirs.skills,"pi",userMetadata,userOverrides.skills,globalBaseDir);let userAgentsBaseDir=dirname2(userAgentsSkillsDir),userAgentsMetadata={...userMetadata,baseDir:userAgentsBaseDir};addSkills(userAgentsSkillsDir,"agents",userAgentsMetadata,userOverrides.skills,userAgentsBaseDir),addResources("prompts",collectAutoPromptEntries(userDirs.prompts),userMetadata,userOverrides.prompts,globalBaseDir),addResources("themes",collectAutoThemeEntries(userDirs.themes),userMetadata,userOverrides.themes,globalBaseDir),addResources("hooks",collectFiles(userDirs.hooks,FILE_PATTERNS.hooks),userMetadata,userOverrides.hooks,globalBaseDir)}selectSkillRoot(root,metadata,kind){let repositoryRoot=skillProjectRoot(this.cwd),spelled=resolve3(root),owner=dirname2(dirname2(spelled)),ancestorSkillsDir=basename(spelled)==="skills"&&[".agents",".senpi",".pi"].includes(basename(dirname2(spelled)))&&insideSkillRoot(resolve3(this.cwd),owner),projectRoot=kind==="project-auto"&&ancestorSkillsDir&&!insideSkillRoot(spelled,repositoryRoot)?owner:repositoryRoot;return{...metadata,skillProvenance:{kind:metadata.scope==="project"?kind:"user",selectedRoot:root,projectRoot}}}collectFilesFromPaths(paths,resourceType,provenance){let files=[];for(let p of paths)if(existsSync3(p))try{let stats=statSync3(p);stats.isFile()?files.push(p):stats.isDirectory()&&files.push(...collectResourceFiles(p,resourceType,provenance))}catch{}return files}getTargetMap(accumulator,resourceType){switch(resourceType){case"extensions":return accumulator.extensions;case"skills":return accumulator.skills;case"prompts":return accumulator.prompts;case"themes":return accumulator.themes;case"hooks":return accumulator.hooks;default:throw new Error(`Unknown resource type: ${resourceType}`)}}addResource(map,path2,metadata,enabled){path2&&(map.has(path2)||map.set(path2,{metadata,enabled}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map,hooks:new Map,ignoredSkills:new Set}}toResolvedPaths(accumulator){let mapToResolved=entries=>{let resolved=Array.from(entries.entries()).map(([path2,{metadata,enabled}])=>({path:path2,enabled,metadata}));resolved.sort((a,b)=>resourcePrecedenceRank(a.metadata)-resourcePrecedenceRank(b.metadata));let seen=new Set;return resolved.filter(entry=>{let canonicalPath=canonicalizePath(entry.path);return seen.has(canonicalPath)?!1:(seen.add(canonicalPath),!0)})};return{skillRoots:[...accumulator.skills.values()].filter(entry=>entry.enabled).flatMap(entry=>entry.metadata.skillProvenance===void 0?[]:[entry.metadata.skillProvenance]),extensions:mapToResolved(accumulator.extensions),skills:mapToResolved(accumulator.skills),prompts:mapToResolved(accumulator.prompts),themes:mapToResolved(accumulator.themes),hooks:mapToResolved(accumulator.hooks),ignoredSkills:[...accumulator.ignoredSkills].sort()}}spawnCommand(command,args,options){let env=getEnv();return spawnProcess(command,args,{cwd:options?.cwd,stdio:isStdoutTakenOver()?["ignore",2,2]:"inherit",env,windowsHide:!0})}spawnCaptureCommand(command,args,options){let baseEnv=getEnv(),env=options?.env?{...baseEnv,...options.env}:baseEnv;return spawnProcess(command,args,{cwd:options?.cwd,stdio:["ignore","pipe","pipe"],env,windowsHide:!0})}runCommandCapture(command,args,options){return new Promise((resolvePromise,reject)=>{let child=this.spawnCaptureCommand(command,args,options),stdout="",stderr="",timedOut=!1,timeout=typeof options?.timeoutMs=="number"?setTimeout(()=>{timedOut=!0,signalSpawnedChild(child)},options.timeoutMs):void 0;child.stdout?.on("data",data=>{stdout+=data.toString()}),child.stderr?.on("data",data=>{stderr+=data.toString()}),child.once("error",error=>{timeout&&clearTimeout(timeout),reject(error)}),child.once("close",(code,signal)=>{if(timeout&&clearTimeout(timeout),timedOut){reject(new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`));return}if(code===0){resolvePromise(stdout.trim());return}let exitStatus=code===null?`signal ${signal??"unknown"}`:`code ${code}`;reject(new Error(`${command} ${args.join(" ")} failed with ${exitStatus}: ${stderr||stdout}`))})})}runCommand(command,args,options){return new Promise((resolvePromise,reject)=>{let child=this.spawnCommand(command,args,options);child.on("error",reject),child.on("exit",code=>{code===0?resolvePromise():reject(new Error(`${command} ${args.join(" ")} failed with code ${code}`))})})}runCommandSync(command,args){let env=getEnv(),result=spawnProcessSync(command,args,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env,windowsHide:!0});if(result.error||result.status!==0)throw new Error(`Failed to run ${command} ${args.join(" ")}: ${result.error?.message||result.stderr||result.stdout}`);return(result.stdout||result.stderr||"").trim()}};var MANUAL_CONTINUE_CUSTOM_TYPE="manual-continue";function isManualContinueSubmission(input){return input.text.trim()==="."&&input.hasMessages&&!input.hasImages}var MANUAL_CONTINUE_DIRECTIVE=`<system-notice>
Continue.
Resume the most recent intent and complete the unfinished work.
If you were interrupted mid-step, resume exactly where you stopped.
Never pause to summarize progress, re-confirm the plan, or ask whether to proceed; continue.
</system-notice>`;var KIMI_RETRYABLE_STATUS_CODES=new Set([408,409,429,500,502,503,504,529]);function classifyKimiHttpStatus(statusCode){return statusCode===void 0||!KIMI_RETRYABLE_STATUS_CODES.has(statusCode)?{verdict:"terminal"}:statusCode===429?{verdict:"rate-limited"}:{verdict:"transient"}}function assertNever(kind){throw new Error(`Unhandled retry failure kind: ${kind}`)}var classifyKimiFailure=failure=>{switch(failure.kind){case"abort":case"refusal":case"sensitive":case"quota-exhausted":case"image-format":case"unknown":return{verdict:"terminal"};case"connection":case"timeout":case"provider":return{verdict:"transient"};case"empty-response":return failure.finishReason==="filtered"?{verdict:"terminal"}:{verdict:"transient"};case"http-status":return classifyKimiHttpStatus(failure.statusCode);default:return assertNever(failure.kind)}},SENPI_STRUCTURED_RETRYABLE_STATUS_CODES=new Set([408,409,429,500,502,503,504,522,524,529]),SENPI_STRUCTURED_TERMINAL_PROVIDER_CODES=new Set(["insufficient_quota","credits_required",...USAGE_LIMIT_EXHAUSTION.codes]),classifySenpiAssistantFailure=failure=>{switch(failure.kind){case"abort":case"refusal":case"sensitive":case"quota-exhausted":case"image-format":return{verdict:"terminal"}}let regexVerdict=classifyErrorMessage(failure.message);return regexVerdict==="non-retryable"?{verdict:"terminal"}:failure.shouldRetry===!1?{verdict:"terminal"}:failure.providerCodes?.some(code=>SENPI_STRUCTURED_TERMINAL_PROVIDER_CODES.has(code))?{verdict:"terminal"}:regexVerdict==="retryable"?{verdict:"transient"}:failure.statusCode!==void 0&&SENPI_STRUCTURED_RETRYABLE_STATUS_CODES.has(failure.statusCode)?failure.statusCode===429?{verdict:"rate-limited"}:{verdict:"transient"}:{verdict:"terminal"}};var extractNormalizedHint=failure=>failure.retryAfterMs,senpiDefaultTurnStrategy=()=>{throw new Error("senpi-default turn tier strategy must be injected by coding-agent")},SENPI_DEFAULT_RETRY_PROFILE={id:"senpi-default",providerRequest:{enabled:!0,maxRetries:0,backoff:{baseDelayMs:500,growthFactor:2,perAttemptCapMs:8e3,jitter:{mode:"subtractive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"override",acceptZero:!0,ceiling:{maxDelayMs:6e4,onExceeded:"error-with-marker"}},classify:classifySenpiAssistantFailure},turn:{enabled:!0,maxRetries:5,backoff:{baseDelayMs:2e3,growthFactor:2,perAttemptCapMs:8e3,jitter:{mode:"additive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"tiered",strategy:senpiDefaultTurnStrategy},classify:classifySenpiAssistantFailure},fallback:{terminal:"immediate-if-eligible",transient:"after-turn-budget",rateLimited:"tiered",resetBudgetOnModelChange:!0}},KIMI_CODE_RETRY_PROFILE={id:"kimi-code",providerRequest:{enabled:!1,maxRetries:0,backoff:{baseDelayMs:500,growthFactor:2,perAttemptCapMs:32e3,jitter:{mode:"additive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"override",acceptZero:!1,ceiling:{maxDelayMs:null,onExceeded:"error-with-marker"}},classify:classifyKimiFailure},turn:{enabled:!0,maxRetries:9,backoff:{baseDelayMs:500,growthFactor:2,perAttemptCapMs:32e3,jitter:{mode:"additive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"override",acceptZero:!1,ceiling:{maxDelayMs:null,onExceeded:"error-with-marker"}},classify:classifyKimiFailure},fallback:{terminal:"immediate-if-eligible",transient:"after-turn-budget",rateLimited:"after-turn-budget",resetBudgetOnModelChange:!0}};var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHash as createHash3,randomUUID}from"crypto";import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync5,renameSync,rmSync as rmSync2,writeFileSync as writeFileSync2}from"fs";import{mkdir,readFile as readFile2,rename,rm,writeFile}from"fs/promises";import{homedir as homedir3}from"os";import{dirname as dirname3,join as join4}from"path";import{isDeepStrictEqual}from"util";var DEFAULT_COMPACTION_TOKEN_SETTINGS={reserveTokens:16384,keepRecentTokens:2e4};function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNonNegativeSafeInteger(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function compactionEnabled(settings){return settings?.enabled??!0}function compactionTokenSetting(settings,field,forModel){let ordinary=settings?.[field];if(ordinary!==void 0&&!isNonNegativeSafeInteger(ordinary))throw new Error(`Invalid compaction.${field} setting: ${String(ordinary)}. Expected a non-negative safe integer.`);let modelKey=forModel?`${forModel.provider}/${forModel.id}`:void 0,entry=modelKey!==void 0?settings?.modelOverrides?.[modelKey]:void 0;if(entry!==void 0&&!isPlainObject(entry))throw new Error(`Invalid compaction.modelOverrides["${modelKey}"] setting: ${String(entry)}. Expected an object.`);let override=entry?.[field];if(override!==void 0&&!isNonNegativeSafeInteger(override))throw new Error(`Invalid compaction.modelOverrides["${modelKey}"].${field} setting: ${String(override)}. Expected a non-negative safe integer.`);return override??ordinary??DEFAULT_COMPACTION_TOKEN_SETTINGS[field]}function compactionReserveTokens(settings,forModel){return compactionTokenSetting(settings,"reserveTokens",forModel)}function compactionKeepRecentTokens(settings,forModel){return compactionTokenSetting(settings,"keepRecentTokens",forModel)}var DEFAULTS={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4,speculativeEnabled:!0,speculativeFraction:.75,speculativeCooldownMs:3e4,restorationEnabled:!0,restorationMaxItems:10,restorationMaxTokensPerItem:5e3,restorationMaxTotalTokens:5e4,restorationContextRatio:.15,idleCompactionEnabled:!0,graceBandEnabled:!0,toolAdmissionEnabled:!0,reserveScalingEnabled:!0};function finiteNumber(value,fallback,minimum=0){return typeof value=="number"&&Number.isFinite(value)?Math.max(minimum,value):fallback}function resolveCompactionSettings(settings,forModel){let raw=settings;return{enabled:typeof raw?.enabled=="boolean"?raw.enabled:DEFAULTS.enabled,reserveTokens:compactionReserveTokens(settings,forModel),keepRecentTokens:compactionKeepRecentTokens(settings,forModel),speculativeEnabled:typeof raw?.speculativeEnabled=="boolean"?raw.speculativeEnabled:DEFAULTS.speculativeEnabled,speculativeFraction:finiteNumber(raw?.speculativeFraction,DEFAULTS.speculativeFraction),speculativeCooldownMs:finiteNumber(raw?.speculativeCooldownMs,DEFAULTS.speculativeCooldownMs),restorationEnabled:typeof raw?.restorationEnabled=="boolean"?raw.restorationEnabled:DEFAULTS.restorationEnabled,restorationMaxItems:finiteNumber(raw?.restorationMaxItems,DEFAULTS.restorationMaxItems),restorationMaxTokensPerItem:finiteNumber(raw?.restorationMaxTokensPerItem,DEFAULTS.restorationMaxTokensPerItem),restorationMaxTotalTokens:finiteNumber(raw?.restorationMaxTotalTokens,DEFAULTS.restorationMaxTotalTokens),restorationContextRatio:finiteNumber(raw?.restorationContextRatio,DEFAULTS.restorationContextRatio),idleCompactionEnabled:typeof raw?.idleCompactionEnabled=="boolean"?raw.idleCompactionEnabled:DEFAULTS.idleCompactionEnabled,graceBandEnabled:typeof raw?.graceBandEnabled=="boolean"?raw.graceBandEnabled:DEFAULTS.graceBandEnabled,toolAdmissionEnabled:typeof raw?.toolAdmissionEnabled=="boolean"?raw.toolAdmissionEnabled:DEFAULTS.toolAdmissionEnabled,reserveScalingEnabled:typeof raw?.reserveScalingEnabled=="boolean"?raw.reserveScalingEnabled:DEFAULTS.reserveScalingEnabled,speculativeLeadTokens:typeof raw?.speculativeLeadTokens=="number"&&Number.isFinite(raw.speculativeLeadTokens)?Math.max(0,raw.speculativeLeadTokens):void 0,summarizationMaxDurationMs:typeof raw?.summarizationMaxDurationMs=="number"&&Number.isFinite(raw.summarizationMaxDurationMs)&&raw.summarizationMaxDurationMs>0?raw.summarizationMaxDurationMs:void 0}}var CONTINUE_FROM_LEAF_CUSTOM_TYPE="continue-from-leaf",CONTINUE_FROM_LEAF_DIRECTIVE=`<system-notice>
Continue from where the conversation ends.
Your last reply may have been edited by the user; treat its current text as your own words.
Carry on from it without repeating it, apologizing for it, or commenting on the edit.
</system-notice>`,CONTINUE_FROM_LEAF_MESSAGES={streaming:"Wait for the current response to finish before continuing.",nothing_to_continue:"There is nothing to continue: the session has no messages yet.",leaf_not_assistant:"There is no answer to continue: the conversation ends on a user message. Send it, or retry it, instead."},ContinueFromLeafError=class extends Error{constructor(code){super(CONTINUE_FROM_LEAF_MESSAGES[code]),this.name="ContinueFromLeafError",this.code=code}};function trackTurnAdmission(input){let resolveStarted,promise=new Promise(resolve6=>{resolveStarted=resolve6}),agentStartSeen=!1,startDispositionSeen=!1,maybeStarted=()=>{agentStartSeen&&startDispositionSeen&&resolveStarted?.()};input.disposition.then(disposition=>{if(disposition==="delegated"){resolveStarted?.();return}disposition==="started"&&(startDispositionSeen=!0,maybeStarted())});let unsubscribe=input.subscribe(event=>{event.type==="agent_start"&&(agentStartSeen=!0,maybeStarted())});return{promise,dispose:unsubscribe}}var STOP_RESUME_CUSTOM_TYPE="session-resumed",DIRECTIVE="<system-reminder>The user stopped the previous turn and has now resumed. Tool calls that the Stop interrupted show an aborted result; they were not re-run and their side effects may be partial. Check their effects before repeating any of them, then continue the work.</system-reminder>";function stopResumeDirective(cause="stop"){return cause==="interrupted"?{customType:STOP_RESUME_CUSTOM_TYPE,content:"<system-reminder>The previous run was interrupted and has now resumed. Interrupted tool calls may have partial side effects and were not re-run. Check their effects before repeating any of them, then continue the work.</system-reminder>",display:!1,details:{resumeCause:cause}}:{customType:STOP_RESUME_CUSTOM_TYPE,content:DIRECTIVE,display:!1}}var MAX_ENGINE_TURNS_PER_USER_INPUT=0,MAX_ENGINE_TURNS_PER_RESUME_WINDOW=8,MAX_TOOL_FREE_ENGINE_TURNS_PER_WINDOW=12,ENGINE_TURN_WINDOW_MS=6e4,ENGINE_TURN_START_ENTRY_TYPE="engine-turn-start",ENGINE_TURN_LIMIT_ENTRY_TYPE="engine-turn-limit",ENGINE_TURN_LIMIT_EVENT="engine:turn-limit";function engineTurnLimitNotice(stop){return stop.reason==="resume-window"?`Paused: the agent started ${stop.sinceUserInput} turns on its own in this resume window. Send any message to continue.`:stop.reason==="per-user-input"?`Paused: the agent started ${stop.sinceUserInput} turns on its own since your last message. Send any message to continue.`:`Paused: the agent started ${stop.toolFreeInWindow} turns on its own in the last minute without doing any work. Send any message to continue.`}function isUserDirectedTurn(customType){return customType===MANUAL_CONTINUE_CUSTOM_TYPE||customType===CONTINUE_FROM_LEAF_CUSTOM_TYPE||customType===STOP_RESUME_CUSTOM_TYPE}function resetsEngineTurnHistory(customType,details){return isUserDirectedTurn(customType)&&!(customType===STOP_RESUME_CUSTOM_TYPE&&details?.resumeCause==="interrupted")}function isUserMessage(entry){return entry.type==="custom_message"?resetsEngineTurnHistory(entry.customType,entry.details):entry.type==="message"&&entry.message.role==="user"}function isEngineTurnStart(entry){return entry.type==="custom"&&entry.customType===ENGINE_TURN_START_ENTRY_TYPE}function callsATool(entry){return entry.type==="message"&&entry.message.role==="assistant"&&entry.message.content.some(block=>block.type==="toolCall")}var engineTurnHistory={initial:()=>({starts:[]}),add:(history,entry)=>{if(isUserMessage(entry))return{starts:[]};if(isEngineTurnStart(entry))history.starts.push({at:Date.parse(entry.timestamp),toolUsed:!1});else if(callsATool(entry)){let latest=history.starts.at(-1);latest!==void 0&&(latest.toolUsed=!0)}return history}};function engineTurnStop(history,now,limits,inProcess=[]){let sinceUserInput=history.starts.length,toolFreeInWindow=0;for(let start of history.starts)now-start.at>=ENGINE_TURN_WINDOW_MS||start.toolUsed||(toolFreeInWindow+=1);sinceUserInput=Math.max(sinceUserInput,inProcess.length),toolFreeInWindow=Math.max(toolFreeInWindow,inProcess.filter(record=>!record.toolUsed&&now-record.at<ENGINE_TURN_WINDOW_MS).length);let resumeLimit=limits.maxPerResumeWindow??0;return resumeLimit>0&&sinceUserInput>=resumeLimit?{reason:"resume-window",sinceUserInput,toolFreeInWindow}:limits.maxPerUserInput>0&&sinceUserInput>=limits.maxPerUserInput?{reason:"per-user-input",sinceUserInput,toolFreeInWindow}:limits.maxToolFreePerMinute>0&&toolFreeInWindow>=limits.maxToolFreePerMinute?{reason:"tool-free-rate",sinceUserInput,toolFreeInWindow}:null}import{resolve as resolve4}from"node:path";function isHealthExhaustionFailure(errorMessage){return isBillingErrorMessage(errorMessage)||isQuotaExhaustionMessage(errorMessage)}var CircuitProbes=class{constructor(circuits){this.circuits=circuits}isOpen(selector){return this.circuits?.isOpen(selector)??!1}governs(selector){return this.circuits?.governs(selector)??!1}isExhausted(selector){return this.circuits?.isExhausted(selector)??!1}admit(selector){let admission=this.circuits?.admit(selector)??{kind:"closed"};return admission.kind==="probe"&&this.token?.selector!==selector&&(this.release(),this.token=admission.token),admission.kind}holds(selector){return this.token?.selector===selector}get probing(){return this.token?.selector}noteFailure(selector,failure){this.circuits?.noteFailure(selector,failure),this.token?.selector===selector&&(this.token=void 0)}accept(selector){this.circuits?.close(selector),this.token?.selector===selector&&(this.token=void 0)}release(){this.token&&this.circuits?.release(this.token),this.token=void 0}releaseAll(){this.token=void 0,this.circuits?.releaseAll()}};var DEFAULT_CIRCUIT_COOLDOWN_MS=6e4,DEFAULT_CIRCUIT_MAX_COOLDOWN_MS=30*6e4;function nonNegativeMs(value,fallback){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:fallback}function resolveFallbackCircuitSettings(settings){let cooldownMs=nonNegativeMs(settings?.circuitCooldownMs,DEFAULT_CIRCUIT_COOLDOWN_MS),maxCooldownMs=nonNegativeMs(settings?.circuitMaxCooldownMs,DEFAULT_CIRCUIT_MAX_COOLDOWN_MS);return{cooldownMs,maxCooldownMs:Math.max(cooldownMs,maxCooldownMs)}}var FallbackCircuitBreaker=class{constructor(){this.circuits=new Map,this.generations=0}get size(){return this.circuits.size}open(selector,request){let previous=this.circuits.get(selector),sameEpisode=previous!==void 0&&request.now<previous.openUntil,consecutiveOpens=(previous?.consecutiveOpens??0)+(sameEpisode?0:1),cooldownMs=sameEpisode?previous.cooldownMs:Math.min(request.cooldownMs*2**(consecutiveOpens-1),request.maxCooldownMs),retryAfterMs=request.retryAfterMs,hinted=retryAfterMs!==void 0&&Number.isFinite(retryAfterMs)&&retryAfterMs>0?request.now+retryAfterMs:0,retryFloorUntil=Math.max(hinted,previous&&previous.retryFloorUntil>request.now?previous.retryFloorUntil:0),resetWindowMs=request.resetWindowMs,hintedUntil=Math.min(retryFloorUntil,request.now+request.maxCooldownMs),openUntil=resetWindowMs!==void 0&&Number.isFinite(resetWindowMs)&&resetWindowMs>0?Math.max(request.now+Math.min(resetWindowMs,request.maxCooldownMs),hintedUntil):Math.max(sameEpisode?previous.openUntil:request.now+cooldownMs,hintedUntil);return this.circuits.set(selector,{openUntil,retryFloorUntil,consecutiveOpens,cooldownMs,maxCooldownMs:request.maxCooldownMs,probe:void 0,exhausted:request.exhausted===!0||sameEpisode&&previous.exhausted}),openUntil}isOpen(selector,now,owner){let circuit=this.circuits.get(selector);return circuit?now<circuit.openUntil?!0:circuit.probe!==void 0&&circuit.probe.owner!==owner:!1}admit(selector,now,owner){let circuit=this.circuits.get(selector);return circuit?now<circuit.openUntil?{kind:"open"}:circuit.probe&&circuit.probe.owner!==owner?{kind:"open"}:(circuit.probe??={owner,generation:++this.generations},{kind:"probe",token:{selector,owner,generation:circuit.probe.generation}}):{kind:"closed"}}release(token){let probe=this.circuits.get(token.selector)?.probe;if(probe&&probe.owner===token.owner&&probe.generation===token.generation){let circuit=this.circuits.get(token.selector);circuit&&(circuit.probe=void 0)}}releaseOwnersWithPrefix(prefix2){for(let circuit of this.circuits.values())circuit.probe?.owner.startsWith(prefix2)&&(circuit.probe=void 0)}close(selector){this.circuits.delete(selector)}has(selector){return this.circuits.has(selector)}isExhausted(selector){return this.circuits.get(selector)?.exhausted===!0}sweep(now){for(let[selector,circuit]of this.circuits)!circuit.probe&&now>=circuit.openUntil+circuit.maxCooldownMs&&this.circuits.delete(selector)}};function createFallbackCircuitAccess(deps){let enabled=()=>deps.settings().cooldownMs>0;return{noteFailure(selector,failure){if(!enabled())return;let{cooldownMs,maxCooldownMs}=deps.settings(),now=deps.now(),message=failure.errorMessage,retryAfterMs=failure.retryAfterMs??(message===void 0?void 0:parseRetryAfterMsMarker(message)),reset=message!==void 0&&usageLimitScope(message)!==void 0?usageLimitReset(message,(deps.wallNow??deps.now)()):void 0,resetWindowMs=reset!==void 0&&(reset.kind==="absolute"||reset.ms>=cooldownMs)?reset.ms:void 0;deps.breaker.sweep(now);let exhausted=message!==void 0&&(isHealthExhaustionFailure(message)||usageLimitScope(message)==="account"),openUntil=deps.breaker.open(selector,{now,cooldownMs,maxCooldownMs,retryAfterMs,resetWindowMs,exhausted});deps.logger.info("circuit_opened",{selector,durationMs:openUntil-now,retryAfterMs,resetWindowMs})},governs:selector=>enabled()&&deps.breaker.has(selector),isExhausted:selector=>enabled()&&deps.breaker.isExhausted(selector),isOpen:(selector,lane="turn")=>enabled()&&deps.breaker.isOpen(selector,deps.now(),laneOwner(deps.owner(),lane)),admit:(selector,lane="turn")=>enabled()?deps.breaker.admit(selector,deps.now(),laneOwner(deps.owner(),lane)):{kind:"closed"},release:token=>deps.breaker.release(token),releaseAll:()=>deps.breaker.releaseOwnersWithPrefix(`${deps.owner()}:`),close:selector=>deps.breaker.close(selector)}}function laneOwner(session,lane){return`${session}:${lane}`}var breakersByAgentDir=new Map;function evictUnheldEmptyBreakers(){for(let[key,entry]of breakersByAgentDir)entry.owners===0&&entry.breaker.size===0&&breakersByAgentDir.delete(key)}function entryFor(agentDir){let key=resolve4(agentDir),entry=breakersByAgentDir.get(key);return entry||(evictUnheldEmptyBreakers(),entry={breaker:new FallbackCircuitBreaker,owners:0},breakersByAgentDir.set(key,entry)),entry}function acquireFallbackCircuits(agentDir){let entry=entryFor(agentDir);entry.owners++;let released=!1;return{breaker:entry.breaker,release(){released||(released=!0,entry.owners--,evictUnheldEmptyBreakers())}}}function monotonicNow(){return performance.timeOrigin+performance.now()}function isPlainObject2(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function describeValue(value){return value===null?"null":Array.isArray(value)?"an array":`a ${typeof value}`}function isNonNegativeSafeInteger2(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function isFiniteAtLeast(value,min){return typeof value=="number"&&Number.isFinite(value)&&value>=min}function isFiniteRatio(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=1}function validateStageKnobs(stage,providerId,stageName,warnings){if(stage===void 0)return;if(!isPlainObject2(stage)){warnings.push(`retry.providers.${providerId}.${stageName} must be a plain object, but got ${describeValue(stage)}.`);return}let out={},invalid=[];if(stage.enabled!==void 0&&(typeof stage.enabled=="boolean"?out.enabled=stage.enabled:invalid.push("enabled")),stage.maxRetries!==void 0&&(isNonNegativeSafeInteger2(stage.maxRetries)?out.maxRetries=stage.maxRetries:invalid.push("maxRetries")),stage.baseDelayMs!==void 0&&(isNonNegativeSafeInteger2(stage.baseDelayMs)?out.baseDelayMs=stage.baseDelayMs:invalid.push("baseDelayMs")),stage.growthFactor!==void 0&&(isFiniteAtLeast(stage.growthFactor,1)?out.growthFactor=stage.growthFactor:invalid.push("growthFactor")),stage.perAttemptCapMs!==void 0&&(stage.perAttemptCapMs===null?out.perAttemptCapMs=null:isNonNegativeSafeInteger2(stage.perAttemptCapMs)?out.perAttemptCapMs=stage.perAttemptCapMs:invalid.push("perAttemptCapMs")),stage.jitter!==void 0)if(isPlainObject2(stage.jitter)){let mode=stage.jitter.mode;mode==="none"?out.jitter={mode:"none"}:(mode==="additive"||mode==="subtractive")&&isFiniteRatio(stage.jitter.ratio)?out.jitter={mode,ratio:stage.jitter.ratio}:invalid.push("jitter")}else invalid.push("jitter");if(stage.serverHintMaxDelayMs!==void 0&&(stage.serverHintMaxDelayMs===null?out.serverHintMaxDelayMs=null:isNonNegativeSafeInteger2(stage.serverHintMaxDelayMs)?out.serverHintMaxDelayMs=stage.serverHintMaxDelayMs:invalid.push("serverHintMaxDelayMs")),invalid.length>0){warnings.push(`retry.providers.${providerId}.${stageName} has invalid knob(s): ${invalid.join(", ")}.`);return}return out}function validateRetryProviderOverrides(value,knownProviderIds,tieredProviderIds){if(value===void 0)return{overrides:{},warnings:[]};if(!isPlainObject2(value))return{overrides:{},warnings:[`retry.providers must be a plain object keyed by provider id, but got ${describeValue(value)}.`]};let overrides={},warnings=[];for(let[providerId,entry]of Object.entries(value)){if(!knownProviderIds.has(providerId)){warnings.push(`retry.providers.${providerId}: unknown provider id "${providerId}".`);continue}if(!isPlainObject2(entry)){warnings.push(`retry.providers.${providerId} must be a plain object, but got ${describeValue(entry)}.`);continue}let stageWarnings=[],providerRequest=validateStageKnobs(entry.providerRequest,providerId,"providerRequest",stageWarnings),turn=validateStageKnobs(entry.turn,providerId,"turn",stageWarnings);if(stageWarnings.length>0){warnings.push(...stageWarnings);continue}if(tieredProviderIds?.has(providerId)&&(providerRequest?.serverHintMaxDelayMs!==void 0||turn?.serverHintMaxDelayMs!==void 0)){warnings.push(`retry.providers.${providerId}: serverHintMaxDelayMs is invalid for a tiered stage (tier thresholds own that strategy).`);continue}let result={};if(providerRequest!==void 0&&(result.providerRequest=providerRequest),turn!==void 0&&(result.turn=turn),providerRequest===void 0&&turn===void 0){warnings.push(`retry.providers.${providerId} has no recognized knobs.`);continue}overrides[providerId]=result}return{overrides,warnings}}var DEFAULT_FALLBACK_CHAINS={"claude-fable-5-2":["claude-opus-5-5","claude-opus-5"],"claude-fable-5-1":["claude-opus-5-5","claude-opus-5"],"claude-fable-5":["claude-opus-5-5","claude-opus-5"],"claude-opus-5-5":["claude-fable-5-2:medium","kimi-k3.1-pro:max"]};function cloneDefaultFallbackChains(){let chains={};for(let[key,entries]of Object.entries(DEFAULT_FALLBACK_CHAINS))chains[key]=[...entries];return chains}function isPlainObject3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isStringArray(value){return Array.isArray(value)&&value.every(entry=>typeof entry=="string")}function resolveFallbackChains(value,sessionPolicy){let base=()=>sessionPolicy?{}:cloneDefaultFallbackChains();if(value===void 0||!isPlainObject3(value))return base();let chains=base();for(let[key,entries]of Object.entries(value)){if(!isStringArray(entries))return base();chains[key]=[...entries]}return chains}function resolveRetryFallbackSettings(settings,options={}){return{modelFallback:typeof settings?.modelFallback=="boolean"?settings.modelFallback:!0,chains:resolveFallbackChains(settings?.fallbackChains,options.sessionPolicy===!0),revertPolicy:settings?.fallbackRevertPolicy==="never"?"never":"cooldown-expiry"}}function resolveAbortServerSideFallback(settings){return typeof settings?.abortServerSideFallback=="boolean"?settings.abortServerSideFallback:!0}var DEFAULT_HINTED_WAIT_CAP_MS=3e5,DEFAULT_PROBE_BACK_MAX_MS=36e5;function resolveHintPolicySettings(settings){let hintedWaitCapMs=typeof settings?.hintedWaitCapMs=="number"&&settings.hintedWaitCapMs>=0?settings.hintedWaitCapMs:DEFAULT_HINTED_WAIT_CAP_MS,probeBackMaxMs=typeof settings?.probeBackMaxMs=="number"&&settings.probeBackMaxMs>=0?settings.probeBackMaxMs:DEFAULT_PROBE_BACK_MAX_MS;return probeBackMaxMs<=hintedWaitCapMs?{hintedWaitCapMs:DEFAULT_HINTED_WAIT_CAP_MS,probeBackMaxMs:DEFAULT_PROBE_BACK_MAX_MS}:{hintedWaitCapMs,probeBackMaxMs}}function parseSettingsJson(content){content=stripBom(content);let withoutComments=[],inString=!1,escaped=!1;for(let index=0;index<content.length;index+=1){let char=content[index],next=content[index+1];if(inString){withoutComments.push(char),escaped?escaped=!1:char==="\\"?escaped=!0:char==='"'&&(inString=!1);continue}if(char==='"'){inString=!0,withoutComments.push(char);continue}if(char==="/"&&next==="/"){for(withoutComments.push(" "," "),index+=2;index<content.length&&content[index]!==`
`&&content[index]!=="\r";)withoutComments.push(" "),index+=1;index<content.length&&withoutComments.push(content[index]);continue}if(char==="/"&&next==="*"){withoutComments.push(" "," "),index+=2;let closed=!1;for(;index<content.length;index+=1){if(content[index]==="*"&&content[index+1]==="/"){withoutComments.push(" "," "),index+=1,closed=!0;break}withoutComments.push(content[index]===`
`||content[index]==="\r"?content[index]:" ")}if(!closed)throw new SyntaxError("Unterminated block comment in settings");continue}withoutComments.push(char)}let normalized=withoutComments;inString=!1,escaped=!1;for(let index=0;index<normalized.length;index+=1){let char=normalized[index];if(inString){escaped?escaped=!1:char==="\\"?escaped=!0:char==='"'&&(inString=!1);continue}if(char==='"'){inString=!0;continue}if(char!==",")continue;let nextIndex=index+1;for(;nextIndex<normalized.length&&/\s/.test(normalized[nextIndex]);)nextIndex+=1;(normalized[nextIndex]==="}"||normalized[nextIndex]==="]")&&(normalized[index]=" ")}let parsed=JSON.parse(normalized.join(""));if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new TypeError("Settings must contain a JSON object");return parsed}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function withoutOverride(overrides,field,nestedKey){if(!(field in overrides))return overrides;let next={...overrides},current=next[field];if(nestedKey===void 0||!isRecord(current))return delete next[field],next;if(!(nestedKey in current))return overrides;let nested={...current};return delete nested[nestedKey],Object.keys(nested).length===0?delete next[field]:next[field]=nested,next}var RETIRED_NESTED_KEYS=[["experimental","sharedHost"]];function removeRetiredSettingsKeys(raw){let removed=!1;for(let[parent,key]of RETIRED_NESTED_KEYS){let container=raw[parent];if(typeof container!="object"||container===null||Array.isArray(container)||!(key in container))continue;let remaining={...container};delete remaining[key],Object.keys(remaining).length===0?delete raw[parent]:raw[parent]=remaining,removed=!0}return removed}var failedRewrites=new Set;function writeRawScopedSettings(storage,scope){let target=storage.selectSource?.(scope)?.path??storage;if(!failedRewrites.has(target))try{storage.withLock(scope,current=>{if(!current)return;let raw=parseSettingsJson(current);return removeRetiredSettingsKeys(raw)?JSON.stringify(raw,null,2):void 0})}catch(error){failedRewrites.add(target);let detail=error instanceof Error?`${error.name}: ${error.message}`:String(error);try{appendDebugLogEntry(`settings: could not remove retired ${scope} settings keys`,detail)}catch{}}}var STATE_KEYS=new Set(["tipsHistory","changelogSeen","lastChangelogVersion","modelThinkingLevels","modelLastOnThinkingLevels","modelServiceTiers"]),failedMigrations=new Set,reportedStateErrors=new Set;function logStateError(storage,error){let target=storage.selectSource?.("global")?.path??storage;if(reportedStateErrors.has(target))return;reportedStateErrors.add(target);let detail=error instanceof Error?`${error.name}: ${error.message}`:String(error);try{appendDebugLogEntry("settings: could not read or save state.json; using empty bookkeeping",detail)}catch{}}function parseStateSettings(storage,content){let raw;try{raw=content?parseSettingsJson(content):{}}catch(error){return logStateError(storage,error),{}}for(let field of["modelThinkingLevels","modelLastOnThinkingLevels","modelServiceTiers"]){let map=raw[field];if(typeof map!="object"||map===null||Array.isArray(map))continue;let normalized={};for(let[key,value]of Object.entries(map)){let canonical=normalizeModelRef(key);(key===canonical||!Object.hasOwn(map,canonical))&&(normalized[canonical]=value)}raw[field]=normalized}return raw}function migrateSettingsState(storage){let withStateLock=storage.withStateLock?.bind(storage);if(!withStateLock)return;let target=storage.selectSource?.("global")?.path??storage;if(!failedMigrations.has(target))try{storage.withLock("global",current=>{if(!current)return;let raw=parseSettingsJson(current);if([...STATE_KEYS].some(key=>Object.hasOwn(raw,key))){withStateLock(stateContent=>{let state=stateContent?parseSettingsJson(stateContent):{},changed=!1;for(let key of STATE_KEYS)Object.hasOwn(raw,key)&&!Object.hasOwn(state,key)&&(state[key]=raw[key],changed=!0);return changed?JSON.stringify(state,null,2):void 0});for(let key of STATE_KEYS)delete raw[key];return JSON.stringify(raw,null,2)}})}catch(error){failedMigrations.add(target);let detail=error instanceof Error?`${error.name}: ${error.message}`:String(error);try{appendDebugLogEntry("settings: could not migrate global state keys",detail)}catch{}}}function readSettingsState(storage){let state={};try{storage.withStateLock?.(current=>{let raw=parseStateSettings(storage,current);for(let key of STATE_KEYS)Object.hasOwn(raw,key)&&(state[key]=raw[key])})}catch(error){return logStateError(storage,error),{}}return state}var TERMINAL_MOUSE_MODES=["off","whilePending","always"];function isTerminalMouseMode(value){return value==="off"||value==="whilePending"||value==="always"}var DEFAULT_STREAM_START_TIMEOUT_MS=3e5,DEFAULT_PROVIDER_STREAM_RETRY_TIMEOUT_MS=3e4,DEFAULT_STREAM_KEEP_ALIVE_TIMEOUT_MS=9e5,DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS=2e3,DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS=1e4,DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS=2e3,DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS=6e4,DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS=12e5,THINKING_LEVEL_VALUES=new Set(["off","minimal","low","medium","high","xhigh","max"]),MODEL_SERVICE_TIER_VALUES=new Set(["auto","flex","priority"]);function modelMemoryKey(provider,modelId){return`${provider}/${modelId}`}function readModelMemoryEntry(map,key,allowed){if(typeof map!="object"||map===null||Array.isArray(map))return;let value=map[key];return typeof value=="string"&&allowed.has(value)?value:void 0}function isMergeableObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function deepMergeObjects(base,overrides){let result={...base};for(let key of Object.keys(overrides)){let overrideValue=overrides[key];if(overrideValue===void 0)continue;let baseValue=base[key];result[key]=isMergeableObject(baseValue)&&isMergeableObject(overrideValue)?deepMergeObjects(baseValue,overrideValue):overrideValue}return result}var DEFAULT_TOOL_NAMES=["read","bash","edit","write","grep"];function isToolModifier(entry){return typeof entry=="string"&&(entry.startsWith("+")||entry.startsWith("-"))}function mergeDefaultTools(base,overrides){return overrides===void 0?base:!Array.isArray(base)||!Array.isArray(overrides)||!overrides.every(isToolModifier)?overrides:[...base,...overrides]}function resolveDefaultTools(entries){let plain=entries.filter(entry=>!isToolModifier(entry)),tools=plain.length>0||entries.length===0?plain:[...DEFAULT_TOOL_NAMES];for(let entry of entries){if(!isToolModifier(entry))continue;let name=entry.slice(1),index=tools.indexOf(name);entry.startsWith("+")&&index===-1&&name?tools.push(name):entry.startsWith("-")&&index!==-1&&tools.splice(index,1)}return tools}function deepMergeSettings(base,overrides){let merged=deepMergeObjects(base,overrides);overrides.retry?.fallbackChains!==void 0&&(merged.retry={...merged.retry,fallbackChains:structuredClone(overrides.retry.fallbackChains)});let defaultTools=mergeDefaultTools(base.defaultTools,overrides.defaultTools);return defaultTools===void 0?merged:{...merged,defaultTools}}function resolveAskUserTimeoutMinutes(value){return typeof value!="number"||!Number.isFinite(value)?30:Math.min(120,Math.max(1,Math.floor(value)))}function parseTimeoutSetting(value,settingName){let timeoutMs=parseHttpIdleTimeoutMs(value);if(timeoutMs!==void 0)return timeoutMs;if(value!==void 0)throw new Error(`Invalid ${settingName} setting: ${String(value)}`)}var SELF_WRITE_TTL_MS=15e3,MAX_SELF_WRITES_PER_PATH=8,selfWritesByPath=new Map,selfWriteClock=Date.now;function recordSelfWrite(absPath,content){let now=selfWriteClock(),writes=selfWritesByPath.get(absPath)??new Map;for(let[hash2,recordedAt]of writes)now-recordedAt>SELF_WRITE_TTL_MS&&writes.delete(hash2);let hash=createHash3("sha256").update(content).digest("hex");for(writes.delete(hash),writes.set(hash,now);writes.size>MAX_SELF_WRITES_PER_PATH;){let oldestHash=writes.keys().next().value;if(oldestHash===void 0)break;writes.delete(oldestHash)}selfWritesByPath.set(absPath,writes)}function wasSelfWrite(absPath,hash){let writes=selfWritesByPath.get(absPath);if(!writes)return!1;let now=selfWriteClock();for(let[trackedHash,recordedAt]of writes)now-recordedAt>SELF_WRITE_TTL_MS&&writes.delete(trackedHash);return writes.delete(hash)?(writes.size===0&&selfWritesByPath.delete(absPath),!0):(writes.size===0&&selfWritesByPath.delete(absPath),!1)}function getSettingsDirectory(cwd,agentDir,scope,homeDir){if(scope==="global")return resolvePath(agentDir);let resolvedCwd=resolvePath(cwd);return findNearestParentConfigDir(resolvedCwd,homeDir,CONFIG_DIR_NAME)??join4(resolvedCwd,CONFIG_DIR_NAME)}function resolveSettingsSource(cwd,agentDir,scope,homeDir=homedir3()){let directory=getSettingsDirectory(cwd,agentDir,scope,homeDir),jsoncPath=join4(directory,"settings.jsonc");if(existsSync4(jsoncPath))return{path:jsoncPath,format:"jsonc",reason:"explicit-jsonc",scope};let jsonPath=join4(directory,"settings.json");if(existsSync4(jsonPath))return{path:jsonPath,format:"json",reason:"json-only",scope}}function getSettingsPath2(cwd,agentDir,scope,homeDir=homedir3()){return resolveSettingsSource(cwd,agentDir,scope,homeDir)?.path??join4(getSettingsDirectory(cwd,agentDir,scope,homeDir),"settings.json")}function getInMemorySettingsPath(scope){return scope==="global"?"/__senpi_in_memory__/settings.json":"/__senpi_in_memory__/.senpi/settings.json"}function toSettingsError(scope,error,path2){return{scope,...path2?{path:path2}:{},error:error instanceof Error?error:new Error(String(error))}}var SettingsLockBusy=class extends Error{},FileSettingsStorage=class{constructor(cwd,agentDir,homeDir=homedir3()){this.cwd=cwd,this.agentDir=agentDir,this.homeDir=homeDir,this.globalSettingsPath=getSettingsPath2(cwd,agentDir,"global",homeDir),this.projectSettingsPath=getSettingsPath2(cwd,agentDir,"project",homeDir)}selectSource(scope){let source=resolveSettingsSource(this.cwd,this.agentDir,scope,this.homeDir),path2=source?.path??join4(getSettingsDirectory(this.cwd,this.agentDir,scope,this.homeDir),"settings.json");return scope==="global"?this.globalSettingsPath=path2:this.projectSettingsPath=path2,source}tryAcquireLockSync(path2){try{return import_proper_lockfile.default.lockSync(path2,{...FILE_STORAGE_LOCK_OPTIONS,retries:0})}catch(error){throw isLockError(error)?new SettingsLockBusy:error}}acquireLockSyncWithRetry(path2){let startedAt=Date.now(),attempt=0;for(;;)try{return import_proper_lockfile.default.lockSync(path2,{...FILE_STORAGE_LOCK_OPTIONS,retries:0})}catch(error){if(!isLockError(error))throw error;let waitedMs=Date.now()-startedAt;if(waitedMs>=FILE_STORAGE_SYNC_LOCK_BUDGET_MS)throw new CredentialStoreBusyError(path2,waitedMs,error);let delayMs=Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS*2**attempt,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_SYNC_LOCK_BUDGET_MS-waitedMs);attempt++;let sleeper=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(sleeper,0,0,delayMs)}}async acquireLockWithRetry(path2){let startedAt=Date.now(),attempt=0;for(;;)try{return await lockWithLossHandling(path2,{...FILE_STORAGE_LOCK_OPTIONS,retries:0})}catch(error){if(!isLockError(error))throw error;let waitedMs=Date.now()-startedAt;if(waitedMs>=FILE_STORAGE_LOCK_RETRY_BUDGET_MS)throw new CredentialStoreBusyError(path2,waitedMs,error);let delayMs=Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS*2**attempt,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_BUDGET_MS-waitedMs);attempt++,await new Promise(resolve6=>setTimeout(resolve6,delayMs))}}async withLockAsync(scope,fn,underLock){let path2=scope==="global"?this.globalSettingsPath:this.projectSettingsPath;return this.withPathLockAsync(path2,fn,underLock)}withStateLockAsync(fn){return this.withPathLockAsync(join4(resolvePath(this.agentDir),"state.json"),fn)}async withPathLockAsync(path2,fn,underLock){let readCurrent=async()=>{try{return await readFile2(path2,"utf-8")}catch(error){if(error.code==="ENOENT")return;throw error}},current=await readCurrent(),next=fn(current);if(next===void 0)return;await mkdir(dirname3(path2),{recursive:!0});let lock=await this.acquireLockWithRetry(path2);try{underLock?.();let lockedContent=await readCurrent();if(lockedContent!==current&&(next=fn(lockedContent)),next!==void 0){let tempPath=`${path2}.${process.pid}.${randomUUID()}.tmp`;try{await writeFile(tempPath,next,"utf-8"),lock.assertHeld(),await rename(tempPath,path2),recordSelfWrite(path2,next)}catch(error){throw await rm(tempPath,{force:!0}),error}}}finally{await lock.release()}}tryWithLock(scope,fn){try{return this.withLock(scope,fn,!1),!0}catch(error){if(error instanceof SettingsLockBusy)return!1;throw error}}withLock(scope,fn,waitForLock=!0){let path2=scope==="global"?this.globalSettingsPath:this.projectSettingsPath;this.withPathLock(path2,fn,waitForLock)}withStateLock(fn){this.withPathLock(join4(resolvePath(this.agentDir),"state.json"),fn)}tryWithStateLock(fn){try{return this.withPathLock(join4(resolvePath(this.agentDir),"state.json"),fn,!1),!0}catch(error){if(error instanceof SettingsLockBusy)return!1;throw error}}withPathLock(path2,fn,waitForLock=!0){let dir=dirname3(path2),current=existsSync4(path2)?readFileSync5(path2,"utf-8"):void 0,next=fn(current);if(next===void 0)return;existsSync4(dir)||mkdirSync2(dir,{recursive:!0});let release=waitForLock?this.acquireLockSyncWithRetry(path2):this.tryAcquireLockSync(path2);try{let underLock=existsSync4(path2)?readFileSync5(path2,"utf-8"):void 0;if(underLock!==current&&(next=fn(underLock)),next!==void 0){let tempPath=`${path2}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync2(tempPath,next,"utf-8"),recordSelfWrite(path2,next),renameSync(tempPath,path2)}catch(error){throw rmSync2(tempPath,{force:!0}),error}}}finally{release()}}},InMemorySettingsStorage=class{withStateLock(fn){let next=fn(this.state);next!==void 0&&(this.state=next)}withLock(scope,fn){let current=scope==="global"?this.global:this.project,next=fn(current);next!==void 0&&(scope==="global"?this.global=next:this.project=next,recordSelfWrite(getInMemorySettingsPath(scope),next))}},SettingsManager=class _SettingsManager{constructor(storage,initialGlobal,initialProject,globalLoadError=null,projectLoadError=null,initialErrors=[],projectTrusted=!0,initialSources=[],settingsPaths={}){this.runtimeOverrides={},this.modifiedFields=new Set,this.modifiedNestedFields=new Map,this.modifiedProjectFields=new Set,this.modifiedProjectNestedFields=new Map,this.globalSettingsLoadError=null,this.projectSettingsLoadError=null,this.writeQueue=Promise.resolve(),this.selectedSources=new Map,this.sourceListeners=[],this.providerSettingsListeners=new Set,this.projectTrustLocked=!1,this.trustFromFullAccess=!1,this.trustEpoch=0,this.storage=storage,this.globalSettings=initialGlobal,this.projectSettings=initialProject,this.projectTrusted=projectTrusted,this.globalSettingsLoadError=globalLoadError,this.projectSettingsLoadError=projectLoadError,this.errors=[...initialErrors],this.settingsPaths=settingsPaths;for(let source of initialSources)this.selectedSources.set(source.scope,source);this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}static create(cwd,agentDir=getAgentDir(),options={}){let storage=new FileSettingsStorage(cwd,agentDir);return _SettingsManager.fromStorage(storage,options)}static fromStorage(storage,options={}){let projectTrusted=options.projectTrusted??!0,initialSources=[],settingsPaths={},globalSource=storage.selectSource?.("global");globalSource&&(initialSources.push(globalSource),settingsPaths.global=globalSource.path);let globalLoad=_SettingsManager.tryLoadFromStorage(storage,"global"),projectSource=projectTrusted?storage.selectSource?.("project"):void 0;projectSource&&(initialSources.push(projectSource),settingsPaths.project=projectSource.path);let projectLoad=_SettingsManager.tryLoadFromStorage(storage,"project",projectTrusted),initialErrors=[];globalLoad.error&&initialErrors.push(toSettingsError("global",globalLoad.error,settingsPaths.global)),projectLoad.error&&initialErrors.push(toSettingsError("project",projectLoad.error,settingsPaths.project));let manager=new _SettingsManager(storage,globalLoad.settings,projectLoad.settings,globalLoad.error,projectLoad.error,initialErrors,projectTrusted,initialSources,settingsPaths);return manager.trustFromFullAccess=options.trustFromFullAccess===!0,manager.projectTrustLocked=options.projectTrustLocked===!0,manager}static inMemory(settings={},options={}){let storage=new InMemorySettingsStorage,initialSettings=_SettingsManager.migrateSettings(structuredClone(settings));return storage.withLock("global",()=>JSON.stringify(initialSettings,null,2)),_SettingsManager.fromStorage(storage,options)}static loadFromStorage(storage,scope,projectTrusted=!0){if(scope==="project"&&!projectTrusted)return{};let content;storage.withLock(scope,current=>{content=current});let raw=content?parseSettingsJson(content):{};return removeRetiredSettingsKeys(raw)&&scope==="global"&&writeRawScopedSettings(storage,scope),scope==="global"&&storage.withStateLock&&([...STATE_KEYS].some(key=>Object.hasOwn(raw,key))&&migrateSettingsState(storage),Object.assign(raw,readSettingsState(storage))),_SettingsManager.migrateSettings(raw)}static tryLoadFromStorage(storage,scope,projectTrusted=!0){try{return{settings:_SettingsManager.loadFromStorage(storage,scope,projectTrusted),error:null}}catch(error){return{settings:{},error}}}static migrateSettings(settings){if("queueMode"in settings&&!("steeringMode"in settings)&&(settings.steeringMode=settings.queueMode,delete settings.queueMode),!("transport"in settings)&&typeof settings.websockets=="boolean"&&(settings.transport=settings.websockets?"websocket":"sse",delete settings.websockets),"skills"in settings&&typeof settings.skills=="object"&&settings.skills!==null&&!Array.isArray(settings.skills)){let skillsSettings=settings.skills;skillsSettings.enableSkillCommands!==void 0&&settings.enableSkillCommands===void 0&&(settings.enableSkillCommands=skillsSettings.enableSkillCommands),Array.isArray(skillsSettings.customDirectories)&&skillsSettings.customDirectories.length>0?settings.skills=skillsSettings.customDirectories:delete settings.skills}if("retry"in settings&&typeof settings.retry=="object"&&settings.retry!==null&&!Array.isArray(settings.retry)){let retrySettings=settings.retry,providerSettings=typeof retrySettings.provider=="object"&&retrySettings.provider!==null?retrySettings.provider:void 0;typeof retrySettings.maxDelayMs=="number"&&(providerSettings?.maxRetryDelayMs===void 0||providerSettings?.maxRetryDelayMs===null)&&(retrySettings.provider={...providerSettings??{},maxRetryDelayMs:retrySettings.maxDelayMs}),delete retrySettings.maxDelayMs}return _SettingsManager.migrateRenamedProviderIds(settings),settings}static providerSettingsKey(providerId){return`${providerId.split("-").map((part,i)=>i===0?part:part.charAt(0).toUpperCase()+part.slice(1)).join("")}Provider`}static migrateRenamedProviderIds(settings){for(let[legacyId,canonicalId]of Object.entries(LEGACY_PROVIDER_IDS)){let legacyKey=_SettingsManager.providerSettingsKey(legacyId),canonicalKey=_SettingsManager.providerSettingsKey(canonicalId);legacyKey in settings&&!(canonicalKey in settings)&&(settings[canonicalKey]=settings[legacyKey],delete settings[legacyKey])}typeof settings.defaultProvider=="string"&&(settings.defaultProvider=normalizeProviderId(settings.defaultProvider)),typeof settings.defaultModel=="string"&&(settings.defaultModel=normalizeModelRef(settings.defaultModel)),Array.isArray(settings.favoriteModels)&&(settings.favoriteModels=settings.favoriteModels.map(entry=>typeof entry=="string"?normalizeModelRef(entry):entry));for(let field of["modelThinkingLevels","modelServiceTiers","modelLastOnThinkingLevels"]){let map=settings[field];typeof map=="object"&&map!==null&&!Array.isArray(map)&&(settings[field]=_SettingsManager.rekeyByModelRef(map))}if(typeof settings.retry=="object"&&settings.retry!==null&&!Array.isArray(settings.retry)){let retry=settings.retry,chains=retry.fallbackChains;if(typeof chains=="object"&&chains!==null&&!Array.isArray(chains)){let rekeyed={};for(let[key,rungs]of Object.entries(chains)){let nextRungs=Array.isArray(rungs)?rungs.map(rung=>typeof rung=="string"?normalizeModelRef(rung):rung):rungs;rekeyed[normalizeModelRef(key)]=nextRungs}retry.fallbackChains=rekeyed}}}static rekeyByModelRef(map){let out={};for(let[key,value]of Object.entries(map))out[normalizeModelRef(key)]=value;return out}getSettings(){return structuredClone(this.settings)}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}getGlobalContextFilePath(){return this.runtimeOverrides.contextFiles?.globalPath??this.globalSettings.contextFiles?.globalPath}readProjectSettingsFile(path2){let content;try{return this.storage.withLock("project",current=>{content=current}),content===void 0?{path:path2,exists:!1,settings:null,error:null}:{path:path2,exists:!0,settings:_SettingsManager.migrateSettings(parseSettingsJson(content)),error:null}}catch(error){return{path:path2,exists:content!==void 0,settings:null,error:String(error)}}}async setProjectSetting(key,value){if(this.assertProjectTrustedForWrite(),this.projectSettingsLoadError)throw new Error(`Project settings file could not be read; refusing to write: ${this.projectSettingsLoadError.message}`);let field=key,recordedBefore=new Set(this.errors);this.updateProjectSettings(field,settings=>{value===null?delete settings[field]:settings[key]=value}),await this.flush();let failure=this.errors.find(entry=>entry.scope==="project"&&!recordedBefore.has(entry));if(failure)throw failure.error}getProviderSettings(){return structuredClone(this.settings.providers??{})}getProviderConcurrencyLimit(providerId){let value=readByProviderId(this.settings.providers,providerId)?.maxConcurrency;return typeof value=="number"&&Number.isInteger(value)&&value>0?value:1/0}subscribeToProviderSettings(listener){return this.providerSettingsListeners.add(listener),()=>this.providerSettingsListeners.delete(listener)}updateSettings(settings){this.settings=settings;for(let listener of this.providerSettingsListeners)listener()}getPromptCacheGoalBackstopMaxSeconds(){return this.projectSettings.promptCache?.goalBackstopMaxSeconds??this.globalSettings.promptCache?.goalBackstopMaxSeconds??270}getPromptCacheSessionAffinity(){return this.settings.promptCache?.sessionAffinity??!0}getPromptCacheKeepAliveSettings(){let configured=this.settings.promptCache?.keepAlive;return{enabled:configured?.enabled??!1,maxRequestsPerSession:configured?.maxRequestsPerSession??3,maxCostUsdPerSession:configured?.maxCostUsdPerSession??.05,marginSeconds:configured?.marginSeconds??60}}getAskUserSettings(){let configured=this.settings.askUser;return{enabled:typeof configured?.enabled=="boolean"?configured.enabled:!0,timeoutMinutes:resolveAskUserTimeoutMinutes(configured?.timeoutMinutes),bell:typeof configured?.bell=="boolean"?configured.bell:!0}}getJobWidgetsSettings(){let configured=this.settings.jobWidgets,model=typeof configured?.model=="string"?configured.model.trim():"",after=configured?.authorAfterMs;return{enabled:typeof configured?.enabled=="boolean"?configured.enabled:!0,model:model.length>0?model:void 0,authorAfterMs:typeof after=="number"&&Number.isFinite(after)&&after>=0?Math.trunc(after):15e3}}getEngineTurnSettings(){let configured=this.settings.engineTurns,limit=(value,fallback)=>typeof value=="number"&&Number.isInteger(value)&&value>=0?value:fallback;return{maxPerUserInput:limit(configured?.maxPerUserInput,MAX_ENGINE_TURNS_PER_USER_INPUT),maxPerResumeWindow:limit(configured?.maxPerResumeWindow,MAX_ENGINE_TURNS_PER_RESUME_WINDOW),maxToolFreePerMinute:limit(configured?.maxToolFreePerMinute,MAX_TOOL_FREE_ENGINE_TURNS_PER_WINDOW)}}getTurnInactivityMs(){return this.settings.turn_inactivity_ms}getTurnMaxRuntimeMs(){return this.settings.turn_max_runtime_ms}getThreadChainCountLimit(){let configured=this.settings.threads?.chainCountLimit;return typeof configured=="number"&&Number.isSafeInteger(configured)&&configured>=0?configured:void 0}getTodoFirstTurnPlan(fallback="force"){let configured=this.settings.todo?.firstTurnPlan;return configured==="force"||configured==="remind"||configured==="off"?configured:fallback}getTodoTurnEndBackstop(){let configured=this.settings.todo?.turnEndBackstop;return typeof configured=="boolean"?configured:!0}isProjectTrusted(){return this.projectTrusted}isProjectTrustLocked(){return this.projectTrustLocked}isTrustFromFullAccess(){return this.trustFromFullAccess&&this.projectTrusted}canRestoreFullAccessTrust(){return this.trustFromFullAccess&&!this.projectTrusted}getTrustEpoch(){return this.trustEpoch}setProjectTrusted(trusted){if(this.projectTrusted===trusted)return;if(this.projectTrusted=trusted,this.trustEpoch+=1,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!trusted){this.projectSettings={},this.projectSettingsLoadError=null,this.updateSettings(this.mergedSettings());return}this.selectAndPublishSource("project");let projectLoad=_SettingsManager.tryLoadFromStorage(this.storage,"project",trusted);this.projectSettings=projectLoad.settings,this.projectSettingsLoadError=projectLoad.error,projectLoad.error&&this.recordError("project",projectLoad.error),this.updateSettings(this.mergedSettings())}async reload(){await this.writeQueue,this.selectAndPublishSource("global");let globalLoad=_SettingsManager.tryLoadFromStorage(this.storage,"global");globalLoad.error?(this.globalSettingsLoadError=globalLoad.error,this.recordError("global",globalLoad.error)):(this.globalSettings=globalLoad.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),this.projectTrusted&&this.selectAndPublishSource("project");let projectLoad=_SettingsManager.tryLoadFromStorage(this.storage,"project",this.projectTrusted);projectLoad.error?(this.projectSettingsLoadError=projectLoad.error,this.recordError("project",projectLoad.error)):(this.projectSettings=projectLoad.settings,this.projectSettingsLoadError=null),this.updateSettings(this.mergedSettings())}getSelectedSettingsSources(){return[...this.selectedSources.values()].map(source=>({...source}))}subscribeToSourceSelection(listener){return this.sourceListeners.push(listener),()=>{let index=this.sourceListeners.indexOf(listener);index!==-1&&this.sourceListeners.splice(index,1)}}selectAndPublishSource(scope){let source=this.storage.selectSource?.(scope);if(!source){this.selectedSources.delete(scope);return}this.selectedSources.set(scope,source);for(let listener of this.sourceListeners)listener({...source})}applyOverrides(overrides){this.runtimeOverrides=deepMergeSettings(this.runtimeOverrides,overrides),this.updateSettings(this.mergedSettings())}mergedSettings(){return deepMergeSettings(deepMergeSettings(this.globalSettings,this.projectSettings),this.runtimeOverrides)}markModified(field,nestedKey){this.runtimeOverrides=withoutOverride(this.runtimeOverrides,field,nestedKey),this.modifiedFields.add(field),nestedKey&&(this.modifiedNestedFields.has(field)||this.modifiedNestedFields.set(field,new Set),this.modifiedNestedFields.get(field).add(nestedKey))}markProjectModified(field,nestedKey){this.runtimeOverrides=withoutOverride(this.runtimeOverrides,field,nestedKey),this.modifiedProjectFields.add(field),nestedKey&&(this.modifiedProjectNestedFields.has(field)||this.modifiedProjectNestedFields.set(field,new Set),this.modifiedProjectNestedFields.get(field).add(nestedKey))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(scope,error){let normalizedError=error instanceof Error?error:new Error(String(error));this.errors.push(toSettingsError(scope,normalizedError,this.settingsPaths[scope]))}clearModifiedScope(scope){if(scope==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(scope,task){this.writeQueue=this.writeQueue.then(async()=>{scope==="project"&&this.assertProjectTrustedForWrite(),await task(),this.clearModifiedScope(scope)}).catch(error=>{this.recordError(scope,error)})}cloneModifiedNestedFields(source){let snapshot=new Map;for(let[key,value]of source.entries())snapshot.set(key,new Set(value));return snapshot}persistScopedSettings(scope,snapshotSettings,modifiedFields,modifiedNestedFields,state=!1){let merge=current=>{let raw=state?parseStateSettings(this.storage,current):current?parseSettingsJson(current):{},currentFileSettings=_SettingsManager.migrateSettings(structuredClone(raw)),mergedSettings={...currentFileSettings};for(let field of modifiedFields){let value=snapshotSettings[field];if(modifiedNestedFields.has(field)&&typeof value=="object"&&value!==null){let nestedModified=modifiedNestedFields.get(field),baseNested=currentFileSettings[field]??{},inMemoryNested=value,mergedNested={...baseNested};for(let nestedKey of nestedModified)inMemoryNested[nestedKey]===void 0?delete mergedNested[nestedKey]:mergedNested[nestedKey]=inMemoryNested[nestedKey];mergedSettings[field]=mergedNested}else value===void 0?delete mergedSettings[field]:mergedSettings[field]=value}return isDeepStrictEqual(currentFileSettings,mergedSettings)?void 0:JSON.stringify(mergedSettings,null,2)},storage=this.storage;if(state&&storage.withStateLock){if(!storage.withStateLockAsync||!storage.tryWithStateLock){storage.withStateLock(merge);return}return storage.tryWithStateLock(merge)?void 0:storage.withStateLockAsync(merge)}if(!storage.withLockAsync||!storage.tryWithLock){storage.withLock(scope,merge);return}if(!storage.tryWithLock(scope,merge))return storage.withLockAsync(scope,merge,scope==="project"?()=>this.assertProjectTrustedForWrite():void 0)}save(){if(this.updateSettings(this.mergedSettings()),this.globalSettingsLoadError)return;let snapshotGlobalSettings=structuredClone(this.globalSettings),modifiedFields=new Set(this.modifiedFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",async()=>{if(this.storage.withStateLock){let stateFields=new Set([...modifiedFields].filter(key=>STATE_KEYS.has(key)));if(stateFields.size>0)try{await this.persistScopedSettings("global",snapshotGlobalSettings,stateFields,modifiedNestedFields,!0)}catch(error){logStateError(this.storage,error)}for(let key of STATE_KEYS)modifiedFields.delete(key)}modifiedFields.size>0&&await this.persistScopedSettings("global",snapshotGlobalSettings,modifiedFields,modifiedNestedFields)})}saveProjectSettings(settings){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(settings),this.updateSettings(this.mergedSettings()),this.projectSettingsLoadError)return;let snapshotProjectSettings=structuredClone(this.projectSettings),modifiedFields=new Set(this.modifiedProjectFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>this.persistScopedSettings("project",snapshotProjectSettings,modifiedFields,modifiedNestedFields))}updateProjectSettings(field,update){this.assertProjectTrustedForWrite();let projectSettings=structuredClone(this.projectSettings);update(projectSettings),this.markProjectModified(field),this.saveProjectSettings(projectSettings)}async flush(){await this.writeQueue}drainErrors(){let drained=[...this.errors];return this.errors=[],drained}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(version){this.globalSettings.lastChangelogVersion=version,this.markModified("lastChangelogVersion"),this.save()}getChangelogSeen(source="engine"){return this.settings.changelogSeen?.[source]??(source==="engine"?this.settings.lastChangelogVersion:void 0)}setChangelogSeen(source,version){!source||this.globalSettings.changelogSeen?.[source]===version||(this.globalSettings.changelogSeen={...this.globalSettings.changelogSeen??{},[source]:version},this.markModified("changelogSeen",source),this.save())}getSessionDir(){let sessionDir=this.settings.sessionDir;return sessionDir&&normalizePath(sessionDir)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(provider){this.globalSettings.defaultProvider=provider,this.markModified("defaultProvider"),this.save()}setDefaultModel(modelId){this.globalSettings.defaultModel=modelId,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(provider,modelId){this.globalSettings.defaultProvider=provider,this.globalSettings.defaultModel=modelId,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"all"}setSteeringMode(mode){this.globalSettings.steeringMode=mode,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(mode){this.globalSettings.followUpMode=mode,this.markModified("followUpMode"),this.save()}getThemeSetting(){let value=this.settings.theme;if(typeof value=="string")return value}getTheme(){let theme2=this.getThemeSetting();return theme2?.includes("/")?void 0:theme2}setTheme(theme2){this.globalSettings.theme=theme2,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(level){this.globalSettings.defaultThinkingLevel=level,this.markModified("defaultThinkingLevel"),this.save()}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}getModelThinkingLevel(provider,modelId){return readModelMemoryEntry(this.settings.modelThinkingLevels,modelMemoryKey(provider,modelId),THINKING_LEVEL_VALUES)}setModelThinkingLevel(provider,modelId,level,options={}){let key=modelMemoryKey(provider,modelId),existing=this.globalSettings.modelThinkingLevels,map=typeof existing=="object"&&existing!==null&&!Array.isArray(existing)?{...existing}:{};level===void 0?delete map[key]:map[key]=level,this.globalSettings.modelThinkingLevels=map,this.markModified("modelThinkingLevels",key),level!=="off"&&!options.preserveLastOn&&this.updateModelLastOnThinkingLevel(key,level),this.save()}getModelLastOnThinkingLevel(provider,modelId){let level=readModelMemoryEntry(this.settings.modelLastOnThinkingLevels,modelMemoryKey(provider,modelId),THINKING_LEVEL_VALUES);return level==="off"?void 0:level}setModelLastOnThinkingLevel(provider,modelId,level){this.updateModelLastOnThinkingLevel(modelMemoryKey(provider,modelId),level==="off"?void 0:level),this.save()}updateModelLastOnThinkingLevel(key,level){let existing=this.globalSettings.modelLastOnThinkingLevels,map=typeof existing=="object"&&existing!==null&&!Array.isArray(existing)?{...existing}:{};level===void 0?delete map[key]:map[key]=level,this.globalSettings.modelLastOnThinkingLevels=map,this.markModified("modelLastOnThinkingLevels",key)}getModelServiceTier(provider,modelId){return readModelMemoryEntry(this.settings.modelServiceTiers,modelMemoryKey(provider,modelId),MODEL_SERVICE_TIER_VALUES)}setModelServiceTier(provider,modelId,tier){let key=modelMemoryKey(provider,modelId),existing=this.globalSettings.modelServiceTiers,map=typeof existing=="object"&&existing!==null&&!Array.isArray(existing)?{...existing}:{};tier===void 0?delete map[key]:map[key]=tier,this.globalSettings.modelServiceTiers=map,this.markModified("modelServiceTiers",key),this.save()}getTransport(){return this.settings.transport??"auto"}getOpenAIServiceTier(){return this.settings.openai?.serviceTier}setTransport(transport){this.globalSettings.transport=transport,this.markModified("transport"),this.save()}getCompactionEnabled(){return compactionEnabled(this.settings.compaction)}setCompactionEnabled(enabled){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=enabled,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(forModel){return compactionReserveTokens(this.settings.compaction,forModel)}getCompactionKeepRecentTokens(forModel){return compactionKeepRecentTokens(this.settings.compaction,forModel)}getCompactionSettings(forModel){return{...resolveCompactionSettings(this.settings.compaction,forModel),model:this.settings.compaction?.model}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(enabled){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=enabled,this.markModified("retry","enabled"),this.save()}isRetryMaxAgentDelayMsConfigured(){return this.settings.retry?.maxAgentDelayMs!==void 0}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??SENPI_DEFAULT_RETRY_PROFILE.turn.maxRetries,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS}}getAbortServerSideFallback(){return resolveAbortServerSideFallback(this.settings.retry)}getRawFallbackChains(){return this.settings.retry?.fallbackChains}getFallbackChainsScope(){if(this.projectSettings.retry?.fallbackChains!==void 0)return"project";if(this.globalSettings.retry?.fallbackChains!==void 0)return"global"}getRetryFallbackSettings(){return resolveRetryFallbackSettings(this.settings.retry,{sessionPolicy:this.runtimeOverrides.retry?.fallbackChains!==void 0})}getFallbackCircuitSettings(){return resolveFallbackCircuitSettings(this.settings.fallback)}getHintPolicySettings(){return resolveHintPolicySettings(this.settings.retry)}setFallbackChain(key,entries){this.globalSettings.retry||(this.globalSettings.retry={});let chains=this.getGlobalFallbackChains();this.globalSettings.retry.fallbackChains={...chains,[key]:[...entries]},this.markModified("retry","fallbackChains"),this.save()}removeFallbackChain(key){let chains=this.getGlobalFallbackChains();key in chains&&(this.globalSettings.retry||(this.globalSettings.retry={}),delete chains[key],this.globalSettings.retry.fallbackChains=chains,this.markModified("retry","fallbackChains"),this.save())}setModelFallbackEnabled(enabled){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.modelFallback=enabled,this.markModified("retry","modelFallback"),this.save()}setFallbackRevertPolicy(policy){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.fallbackRevertPolicy=policy,this.markModified("retry","fallbackRevertPolicy"),this.save()}getGlobalFallbackChains(){let fallbackChains=this.globalSettings.retry?.fallbackChains;if(typeof fallbackChains!="object"||fallbackChains===null||Array.isArray(fallbackChains))return{};let chains={};for(let[key,entries]of Object.entries(fallbackChains))Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(chains[key]=[...entries]);return chains}getHttpIdleTimeoutMs(){return parseTimeoutSetting(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??DEFAULT_HTTP_IDLE_TIMEOUT_MS}setHttpIdleTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs)||timeoutMs<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(timeoutMs),this.markModified("httpIdleTimeoutMs"),this.save()}getSessionShutdownHandlerWarnMs(){return parseTimeoutSetting(this.settings.sessionShutdownHandlerWarnMs,"sessionShutdownHandlerWarnMs")??DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS}setSessionShutdownHandlerWarnMs(warnMs){if(!Number.isFinite(warnMs)||warnMs<0)throw new Error(`Invalid sessionShutdownHandlerWarnMs setting: ${String(warnMs)}`);this.globalSettings.sessionShutdownHandlerWarnMs=Math.floor(warnMs),this.markModified("sessionShutdownHandlerWarnMs"),this.save()}getSessionShutdownHandlerTimeoutMs(){return parseTimeoutSetting(this.settings.sessionShutdownHandlerTimeoutMs,"sessionShutdownHandlerTimeoutMs")??DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS}setSessionShutdownHandlerTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs)||timeoutMs<0)throw new Error(`Invalid sessionShutdownHandlerTimeoutMs setting: ${String(timeoutMs)}`);this.globalSettings.sessionShutdownHandlerTimeoutMs=Math.floor(timeoutMs),this.markModified("sessionShutdownHandlerTimeoutMs"),this.save()}getSessionShutdownQuitBudgetMs(){return parseTimeoutSetting(this.settings.sessionShutdownQuitBudgetMs,"sessionShutdownQuitBudgetMs")??DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS}setSessionShutdownQuitBudgetMs(budgetMs){if(!Number.isFinite(budgetMs)||budgetMs<0)throw new Error(`Invalid sessionShutdownQuitBudgetMs setting: ${String(budgetMs)}`);this.globalSettings.sessionShutdownQuitBudgetMs=Math.floor(budgetMs),this.markModified("sessionShutdownQuitBudgetMs"),this.save()}getExtensionEventHandlerWarnMs(){return parseTimeoutSetting(this.settings.extensionEventHandlerWarnMs,"extensionEventHandlerWarnMs")??DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS}getExtensionEventHandlerTimeoutMs(){return parseTimeoutSetting(this.settings.extensionEventHandlerTimeoutMs,"extensionEventHandlerTimeoutMs")??DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}resolveRetryProfile(provider){let base=provider?.retryPolicy??SENPI_DEFAULT_RETRY_PROFILE,declared=provider?.retryPolicy!==void 0,turnBackoff={...base.turn.backoff};declared||this.settings.retry?.maxRetries!==void 0&&(turnBackoff.baseDelayMs=this.settings.retry.baseDelayMs??turnBackoff.baseDelayMs);let turnMaxRetries=base.turn.maxRetries,turnBaseDelayMs=turnBackoff.baseDelayMs;declared||(this.settings.retry?.maxRetries!==void 0&&(turnMaxRetries=this.settings.retry.maxRetries),this.settings.retry?.baseDelayMs!==void 0&&(turnBaseDelayMs=this.settings.retry.baseDelayMs));let providerOverride=this._resolveRetryProviderOverride(provider?.id);providerOverride?.turn?.maxRetries!==void 0&&(turnMaxRetries=providerOverride.turn.maxRetries),providerOverride?.turn?.baseDelayMs!==void 0&&(turnBaseDelayMs=providerOverride.turn.baseDelayMs);let turnEnabled=this.getRetryEnabled()?providerOverride?.turn?.enabled??base.turn.enabled:!1,tierStrategy=base.turn.serverHint.mode==="tiered"?base.turn.serverHint.strategy:()=>{throw new Error("not tiered")},turn={enabled:turnEnabled,maxRetries:turnMaxRetries,backoff:{...base.turn.backoff,baseDelayMs:turnBaseDelayMs},extractServerHint:base.turn.extractServerHint,serverHint:base.turn.serverHint.mode==="tiered"?{mode:"tiered",strategy:tierStrategy}:base.turn.serverHint,classify:base.turn.classify};return{id:base.id,providerRequest:base.providerRequest,turn,fallback:base.fallback}}_resolveRetryProviderOverride(providerId){if(providerId===void 0)return;let raw=this.settings.retry?.providers;if(raw===void 0)return;let{overrides}=validateRetryProviderOverrides(raw,new Set([providerId]));return overrides[providerId]}getProviderStreamRetryTimeoutMs(){let explicit=this.settings.retry?.provider?.streamRetryTimeoutMs;return explicit!==void 0?explicit>0?explicit:void 0:DEFAULT_PROVIDER_STREAM_RETRY_TIMEOUT_MS}getAgentStreamIdleTimeoutMs(){let providerTimeoutMs=this.settings.retry?.provider?.timeoutMs;if(providerTimeoutMs!==void 0)return providerTimeoutMs;let httpIdleTimeoutMs=this.getHttpIdleTimeoutMs();return httpIdleTimeoutMs===0?void 0:httpIdleTimeoutMs}getAgentStreamStartTimeoutMs(){let explicit=this.settings.retry?.provider?.streamStartTimeoutMs;if(explicit!==void 0)return explicit>0?explicit:void 0;let idleTimeoutMs=this.getAgentStreamIdleTimeoutMs();if(idleTimeoutMs!==void 0)return Math.min(DEFAULT_STREAM_START_TIMEOUT_MS,idleTimeoutMs)}getAgentStreamKeepAliveTimeoutMs(){let explicit=this.settings.retry?.provider?.keepAliveTimeoutMs;return explicit!==void 0?explicit>0?explicit:void 0:DEFAULT_STREAM_KEEP_ALIVE_TIMEOUT_MS}getWebSocketConnectTimeoutMs(){return parseTimeoutSetting(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!1}getSmoothStreaming(){return this.settings.smoothStreaming??!0}getSmoothStreamingFps(){let fps=this.settings.smoothStreamingFps;return typeof fps!="number"||!Number.isFinite(fps)?60:Math.min(120,Math.max(30,fps))}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){let configuredEditor=this.settings.externalEditor;if(typeof configuredEditor=="string"&&configuredEditor.trim()!=="")return configuredEditor;let environmentEditor=process.env.VISUAL||process.env.EDITOR;return environmentEditor||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(hide){this.globalSettings.hideThinkingBlock=hide,this.markModified("hideThinkingBlock"),this.save()}setSmoothStreaming(enabled){this.globalSettings.smoothStreaming=enabled,this.markModified("smoothStreaming"),this.save()}setSmoothStreamingFps(fps){this.globalSettings.smoothStreamingFps=fps,this.markModified("smoothStreamingFps"),this.save()}setShowCacheMissNotices(show2){this.globalSettings.showCacheMissNotices=show2,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){let shellPath=this.settings.shellPath;return shellPath&&normalizePath(shellPath)}setShellPath(path2){this.globalSettings.shellPath=path2,this.markModified("shellPath"),this.save()}getQuietStartup(){let value=this.settings.quietStartup;return value===!0||value==="header"?value:!1}setQuietStartup(quiet){this.globalSettings.quietStartup=quiet,this.markModified("quietStartup"),this.save()}getTipsEnabled(){return this.settings.tips??!0}getReducedMotion(){return this.settings.reducedMotion??!1}getTipsHistory(){let history=this.settings.tipsHistory;return typeof history!="object"||history===null||Array.isArray(history)?{}:{...history}}setTipsHistory(history){this.globalSettings.tipsHistory=history,this.markModified("tipsHistory"),this.save()}setTipShown(tipId,timestamp){let history=this.getTipsHistory();history[tipId]=timestamp,this.globalSettings.tipsHistory=history,this.markModified("tipsHistory",tipId),this.save()}getDefaultProjectTrust(){let value=this.globalSettings.defaultProjectTrust;return value==="always"||value==="never"?value:"ask"}setDefaultProjectTrust(defaultProjectTrust){this.globalSettings.defaultProjectTrust=defaultProjectTrust,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getBashRedactSecretsInOutput(){return this.settings.tools?.bash?.redactSecretsInOutput===!0}setShellCommandPrefix(prefix2){this.globalSettings.shellCommandPrefix=prefix2,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(command){this.globalSettings.npmCommand=command?[...command]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!1}setCollapseChangelog(collapse){this.globalSettings.collapseChangelog=collapse,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(enabled){this.globalSettings.enableInstallTelemetry=enabled,this.markModified("enableInstallTelemetry"),this.save()}getEnableSessionShare(){return this.settings.enableSessionShare??!0}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(enabled){this.globalSettings.enableAnalytics=enabled,this.markModified("enableAnalytics"),enabled&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=randomUUID(),this.markModified("trackingId")),this.save()}getOrCreateDeviceId(){return this.globalSettings.deviceId||(this.globalSettings.deviceId=randomUUID(),this.markModified("deviceId"),this.save()),this.globalSettings.deviceId}getPackages(){return[...this.settings.packages??[]]}getDisabledBuiltinExtensions(){return[...this.settings.disabledBuiltinExtensions??[]]}getEnabledBuiltinExtensions(){return this.settings.enabledBuiltinExtensions?[...this.settings.enabledBuiltinExtensions]:void 0}setPackages(packages){this.globalSettings.packages=packages,this.markModified("packages"),this.save()}setProjectPackages(packages){this.updateProjectSettings("packages",settings=>{settings.packages=packages})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(paths){this.globalSettings.extensions=paths,this.markModified("extensions"),this.save()}setProjectExtensionPaths(paths){this.updateProjectSettings("extensions",settings=>{settings.extensions=paths})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(paths){this.globalSettings.skills=paths,this.markModified("skills"),this.save()}setProjectSkillPaths(paths){this.updateProjectSettings("skills",settings=>{settings.skills=paths})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(paths){this.globalSettings.prompts=paths,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(paths){this.updateProjectSettings("prompts",settings=>{settings.prompts=paths})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(paths){this.globalSettings.themes=paths,this.markModified("themes"),this.save()}setProjectThemePaths(paths){this.updateProjectSettings("themes",settings=>{settings.themes=paths})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(enabled){this.globalSettings.enableSkillCommands=enabled,this.markModified("enableSkillCommands"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){let terminal=this.settings.terminal,imageSetting=terminal?.images,imageOverride=imageSetting!==void 0?imageSetting:envValue("IMAGE_PROTOCOL")?.toLowerCase(),trueColorSetting=terminal?.trueColor,trueColorOverride=trueColorSetting!==void 0?trueColorSetting:envValue("TRUE_COLOR"),hyperlinksSetting=terminal?.hyperlinks,hyperlinksOverride=hyperlinksSetting!==void 0?hyperlinksSetting:envValue("HYPERLINKS");return{...imageOverride==="kitty"||imageOverride==="iterm2"?{images:imageOverride}:imageOverride===!1||imageOverride==="none"||imageOverride==="0"?{images:null}:{},...typeof trueColorOverride=="boolean"?{trueColor:trueColorOverride}:trueColorOverride==="1"||trueColorOverride==="0"?{trueColor:trueColorOverride==="1"}:{},...typeof hyperlinksOverride=="boolean"?{hyperlinks:hyperlinksOverride}:hyperlinksOverride==="1"||hyperlinksOverride==="0"?{hyperlinks:hyperlinksOverride==="1"}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(show2){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=show2,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){let width=this.settings.terminal?.imageWidthCells;return typeof width!="number"||!Number.isFinite(width)?60:Math.max(1,Math.floor(width))}setImageWidthCells(width){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(width)),this.markModified("terminal","imageWidthCells"),this.save()}getTerminalMouse(){let value=this.settings.terminal?.mouse;return isTerminalMouseMode(value)?value:"whilePending"}setTerminalMouse(mouse){if(!isTerminalMouseMode(mouse))throw new TypeError("Invalid terminal.mouse");this.globalSettings.terminal??={},this.globalSettings.terminal.mouse=mouse,this.markModified("terminal","mouse"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:envValue("CLEAR_ON_SHRINK")==="1"}setClearOnShrink(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=enabled,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=enabled,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":"regular"}setTuiMode(mode){this.globalSettings.tuiMode=mode,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(output){this.globalSettings.fullscreenExitOutput=output,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){let mode=this.settings.fullscreenScrollbar;return mode==="always"||mode==="hidden"?mode:"auto"}setFullscreenScrollbar(mode){this.globalSettings.fullscreenScrollbar=mode,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(enabled){this.globalSettings.fullscreenCopyOnSelect=enabled,this.markModified("fullscreenCopyOnSelect"),this.save()}getFullscreenWheelScrollLines(){let lines=this.settings.fullscreenWheelScrollLines;return typeof lines=="number"&&Number.isFinite(lines)?Math.max(1,Math.min(100,Math.floor(lines))):"auto"}setFullscreenWheelScrollLines(lines){this.globalSettings.fullscreenWheelScrollLines=lines==="auto"?lines:Math.max(1,Math.min(100,Math.floor(lines))),this.markModified("fullscreenWheelScrollLines"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(enabled){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=enabled,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}getMaxHistoricalImages(){let value=this.settings.images?.maxHistoricalImages;return Number.isInteger(value)&&value!==void 0&&value>=0?value:void 0}setBlockImages(blocked){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=blocked,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getRecommendedModels(){return this.settings.recommendedModels?[...this.settings.recommendedModels]:void 0}getFavoriteModels(){return this.settings.favoriteModels}setFavoriteModels(patterns){this.globalSettings.favoriteModels=patterns,this.markModified("favoriteModels"),this.save()}getDefaultTools(){let tools=this.settings.defaultTools;if(tools!==void 0)return resolveDefaultTools(Array.isArray(tools)?tools.filter(tool=>typeof tool=="string"):[])}setEnabledModels(patterns){this.globalSettings.enabledModels=patterns,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(action){this.globalSettings.doubleEscapeAction=action,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){let mode=this.settings.treeFilterMode;return mode&&["default","no-tools","user-only","labeled-only","all"].includes(mode)?mode:"default"}setTreeFilterMode(mode){this.globalSettings.treeFilterMode=mode,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??envValue("HARDWARE_CURSOR")==="1"}setShowHardwareCursor(enabled){this.globalSettings.showHardwareCursor=enabled,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??0}setEditorPaddingX(padding){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(padding))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===0?0:1}setOutputPad(padding){this.globalSettings.outputPad=padding,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(maxVisible){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(maxVisible))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){let mode=this.settings.markdown?.mermaid;return mode==="off"||mode==="final"?mode:"streaming"}setMermaidRenderingMode(mode){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=mode,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(warnings){this.globalSettings.warnings={...warnings},this.markModified("warnings"),this.save()}};import{mkdirSync as mkdirSync3,readFileSync as readFileSync6,renameSync as renameSync2,writeFileSync as writeFileSync3}from"node:fs";import{dirname as dirname4,join as join5}from"node:path";function hintPath(agentDir=getAgentDir()){return join5(agentDir,"cache","terminal-theme.json")}function readTerminalThemeHint(agentDir){try{let parsed=JSON.parse(readFileSync6(hintPath(agentDir),"utf8"));if(typeof parsed!="object"||parsed===null)return;let value=parsed.terminalTheme;return value==="light"||value==="dark"?value:void 0}catch{return}}function writeTerminalThemeHint(terminalTheme,agentDir){try{let path2=hintPath(agentDir);mkdirSync3(dirname4(path2),{recursive:!0});let temporary=`${path2}.${process.pid}.tmp`;writeFileSync3(temporary,`${JSON.stringify({terminalTheme})}
`),renameSync2(temporary,path2)}catch{}}var TERMINAL_QUERY_TIMEOUT_MS=100;function requestTerminalColors(ui,apply){let query;try{query=ui.queryTerminalColors({timeoutMs:TERMINAL_QUERY_TIMEOUT_MS,onLateReply:apply})}catch{query=Promise.resolve({})}return query.then(apply,()=>apply({}))}function sameRgb(a,b){return a===b||a!==void 0&&b!==void 0&&a.r===b.r&&a.g===b.g&&a.b===b.b}function sameTerminalColors(a,b){return!sameRgb(a.foreground,b.foreground)||!sameRgb(a.background,b.background)?!1:a.palette===b.palette?!0:!a.palette||!b.palette||a.palette.length!==b.palette.length?!1:a.palette.every((color,index)=>sameRgb(color,b.palette?.[index]))}var InteractiveThemeController=class{constructor(ui,options){this.autoSyncEnabled=!1,this.terminalColorQuery=Promise.resolve(),this.ui=ui,this.getSettingsManager=options.getSettingsManager,this.showError=options.showError,this.onChanged=options.onChanged,this.currentThemeSetting=options.initialThemeSetting;let rememberedTheme=readTerminalThemeHint();rememberedTheme&&setTerminalColorScheme(rememberedTheme),this.activeThemeName=this.resolveThemeName(),markTerminalColorsPending(),initTheme(this.activeThemeName,!0),this.bindTerminalColorSchemeListener()}rebindTui(){this.terminalColorSchemeUnsubscribe?.(),this.bindTerminalColorSchemeListener(),this.ui.setTerminalColorSchemeNotifications(this.autoSyncEnabled)}applyFromSettings(){let themeSetting=this.getThemeSetting(),themeName=this.resolveThemeName();this.setAutoSync(parseAutoThemeSetting(themeSetting)!==void 0||themeName===SYSTEM_THEME_NAME),this.applyThemeName(themeName,themeSetting!==void 0),this.queryTerminalColors()}waitForTerminalColors(){return this.terminalColorQuery}getThemeSelection(){return this.currentThemeSetting??this.getSettingsManager().getThemeSetting()??this.activeThemeName}setThemeName(themeName,showError=!1){this.setAutoSync(themeName===SYSTEM_THEME_NAME);let result=this.applyThemeName(themeName,showError);return result.success&&(this.currentThemeSetting=themeName),result}setThemeSetting(themeSetting){this.currentThemeSetting=themeSetting,this.applyFromSettings()}setThemeInstance(themeInstance){return this.setAutoSync(!1),setThemeInstance(themeInstance),this.activeThemeName="<in-memory>",this.notifyChanged(),{success:!0}}preview(themeSettingOrName){let themeName=resolveThemeSetting(themeSettingOrName,getTerminalTheme())??this.activeThemeName;themeName&&setTheme(themeName,!0).success&&(this.ui.invalidate(),this.ui.requestRender())}disableAutoSync(){this.setAutoSync(!1)}dispose(){this.setAutoSync(!1),this.terminalColorSchemeUnsubscribe?.(),this.terminalColorSchemeUnsubscribe=void 0}getTerminalTheme(){return getTerminalTheme()}getThemeSetting(){return this.currentThemeSetting??this.getSettingsManager().getThemeSetting()}resolveThemeName(){return resolveThemeSetting(this.getThemeSetting(),getTerminalTheme())??SYSTEM_THEME_NAME}applyThemeName(themeName,showError=!1){let result=setTheme(themeName,!0);return this.activeThemeName=result.success?themeName:SYSTEM_THEME_NAME,this.notifyChanged(),!result.success&&showError&&this.showError(`Failed to load theme "${themeName}": ${result.error}
Fell back to the system theme.`),result}queryTerminalColors(){this.terminalColorQuery=requestTerminalColors(this.ui,colors=>this.applyTerminalColors(colors))}applyTerminalColors(reported){let previous=this.terminalColors,next={foreground:reported.foreground??previous?.foreground,background:reported.background??previous?.background,palette:reported.palette??previous?.palette};previous&&sameTerminalColors(previous,next)||(this.terminalColors=next,setTerminalColors(next),next.background&&writeTerminalThemeHint(getTerminalTheme()),this.reapplyForTerminal(),this.ui.invalidate(),this.ui.requestRender())}reapplyForTerminal(){if(this.activeThemeName==="<in-memory>")return;let themeName=this.resolveThemeName();(themeName===SYSTEM_THEME_NAME||themeName!==this.activeThemeName)&&this.applyThemeName(themeName)}setAutoSync(enabled){this.autoSyncEnabled!==enabled&&(this.autoSyncEnabled=enabled,this.ui.setTerminalColorSchemeNotifications(enabled))}bindTerminalColorSchemeListener(){this.terminalColorSchemeUnsubscribe=this.ui.onTerminalColorSchemeChange(terminalTheme=>this.applyTerminalColorSchemeChange(terminalTheme))}applyTerminalColorSchemeChange(terminalTheme){if(!this.autoSyncEnabled)return;let previous=getTerminalTheme();setTerminalColorScheme(terminalTheme),writeTerminalThemeHint(getTerminalTheme()),getTerminalTheme()!==previous&&this.reapplyForTerminal(),this.queryTerminalColors()}notifyChanged(){this.ui.invalidate(),this.onChanged()}};import{existsSync as existsSync5}from"fs";function areExperimentalFeaturesEnabled(){return envValue("EXPERIMENTAL")==="1"}var THEME_OPTIONS=[{value:SYSTEM_THEME_NAME,label:"System (matches your terminal colors)"},{value:"dark",label:"Dark"},{value:"light",label:"Light"}],ANALYTICS_OPTIONS=[{value:!0,label:"Share anonymous usage data"},{value:!1,label:"Don't share"}],SETUP_LOGO_LINES=["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588"],FirstTimeSetupComponent=class extends Container{constructor(options){super(),this.step="theme",this.analyticsIndex=0,this.options=options,this.themeIndex=0,this.update()}invalidate(){this.update(),super.invalidate()}update(){this.clear(),this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("accent",SETUP_LOGO_LINES.join(`
`)),1,0)),this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("accent",theme.bold(`Welcome to ${APP_NAME}, the minimal coding agent.`)),1,0)),this.addChild(new Spacer(1)),this.step==="theme"?(this.addChild(new Text(theme.fg("text","Pick a theme."),1,0)),this.addChild(new Spacer(1)),this.addOptionList(THEME_OPTIONS.map(option=>option.label),this.themeIndex)):(this.addChild(new Text(theme.fg("text","Opt-in to anonymous usage data sharing?"),1,0)),this.addChild(new Text(theme.fg("muted",`Opting in stores a tracking identifier in settings.json and enables anonymous
usage analytics. This helps us to better debug, reproduce, and resolve issues
and bugs within Pi. You can observe what is shared using /privacy and make
changes anytime in settings.json.`),1,0)),this.addChild(new Spacer(1)),this.addOptionList(ANALYTICS_OPTIONS.map(option=>option.label),this.analyticsIndex)),this.addChild(new Spacer(1)),this.addChild(new Text(rawKeyHint("\u2191\u2193","navigate")+" "+keyHint("tui.select.confirm",this.step==="theme"?"continue":"finish")+" "+keyHint("tui.select.cancel","skip setup"),1,0)),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder)}addOptionList(labels,selectedIndex){for(let i=0;i<labels.length;i++){let isSelected=i===selectedIndex,prefix2=isSelected?theme.fg("accent","\u2192 "):" ",label=isSelected?theme.fg("accent",labels[i]):theme.fg("text",labels[i]);this.addChild(new Text(`${prefix2}${label}`,1,0))}}moveSelection(delta){if(this.step==="theme"){let next=Math.max(0,Math.min(THEME_OPTIONS.length-1,this.themeIndex+delta));next!==this.themeIndex&&(this.themeIndex=next,this.options.onThemePreview(THEME_OPTIONS[this.themeIndex].value))}else this.analyticsIndex=Math.max(0,Math.min(ANALYTICS_OPTIONS.length-1,this.analyticsIndex+delta));this.update()}handleInput(keyData){let kb=getKeybindings();kb.matches(keyData,"tui.select.up")||keyData==="k"?this.moveSelection(-1):kb.matches(keyData,"tui.select.down")||keyData==="j"?this.moveSelection(1):kb.matches(keyData,"tui.select.confirm")||keyData===`
`?this.step==="theme"?(this.step="analytics",this.update()):this.options.onSubmit({theme:THEME_OPTIONS[this.themeIndex].value,shareAnalytics:ANALYTICS_OPTIONS[this.analyticsIndex].value}):kb.matches(keyData,"tui.select.cancel")&&this.options.onCancel()}};var OFFICIAL_PACKAGE_NAME="@earendil-works/pi-coding-agent",OFFICIAL_APP_NAME="pi",OFFICIAL_CONFIG_DIR_NAME=".pi";function isOfficialDistribution({packageName,appName,configDirName}){return packageName===OFFICIAL_PACKAGE_NAME&&appName===OFFICIAL_APP_NAME&&configDirName===OFFICIAL_CONFIG_DIR_NAME}function loadThemes(resources){let themes=[],seen=new Set;for(let resource of resources)if(resource.enabled)try{let loadedTheme=loadThemeFromPath(resource.path);if(loadedTheme.name){if(seen.has(loadedTheme.name))continue;seen.add(loadedTheme.name)}themes.push(loadedTheme)}catch{}return themes}async function loadStartupThemes(settingsManager){let globalSettingsManager=SettingsManager.inMemory(settingsManager.getGlobalSettings(),{projectTrusted:!1}),resolvedPaths=await new DefaultPackageManager({cwd:process.cwd(),agentDir:getAgentDir(),settingsManager:globalSettingsManager}).resolve(async()=>"skip");return loadThemes(resolvedPaths.themes)}async function createStartupTui(settingsManager){setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),setRegisteredThemes(await loadStartupThemes(settingsManager)),markTerminalColorsPending(),initTheme(resolveThemeSetting(settingsManager.getThemeSetting(),getTerminalTheme())??SYSTEM_THEME_NAME),setKeybindings(KeybindingsManager.create());let ui=new TUI(new ProcessTerminal({onExternalStdoutWrite:appendHiddenTuiStdout}),settingsManager.getShowHardwareCursor());return ui.setClearOnShrink(settingsManager.getClearOnShrink()),ui}function startStartupTui(ui,settingsManager){ui.start();let themeSetting=settingsManager.getThemeSetting();queryStartupTerminalColors(ui,()=>{setTheme(resolveThemeSetting(themeSetting,getTerminalTheme())??SYSTEM_THEME_NAME)})}function queryStartupTerminalColors(ui,onColors){requestTerminalColors(ui,colors=>{setTerminalColors(colors),onColors(),ui.invalidate(),ui.requestRender()})}async function clearStartupTui(ui){ui.clear(),ui.requestRender(),await new Promise(resolve6=>setTimeout(resolve6,25))}function shouldRunFirstTimeSetup(settingsPath=getSettingsPath()){return!isOfficialDistribution({packageName:PACKAGE_NAME,appName:APP_NAME,configDirName:CONFIG_DIR_NAME})||!areExperimentalFeaturesEnabled()||process.env[ENV_AGENT_DIR]?!1:!existsSync5(settingsPath)}async function showStartupSelector(settingsManager,title,options){let ui=await createStartupTui(settingsManager);return new Promise(resolve6=>{let settled=!1,finish=async result=>{settled||(settled=!0,await clearStartupTui(ui),ui.stop(),resolve6(result))},selector=new ExtensionSelectorComponent(title,options.map(option=>option.label),option=>{finish(options.find(entry=>entry.label===option)?.value)},()=>{finish(void 0)},{tui:ui});ui.addChild(selector),ui.setFocus(selector),startStartupTui(ui,settingsManager)})}async function showFirstTimeSetup(settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve6=>{let settled=!1,finish=async result=>{settled||(settled=!0,result&&(settingsManager.setTheme(result.theme),settingsManager.setEnableAnalytics(result.shareAnalytics),await settingsManager.flush()),await clearStartupTui(ui),ui.stop(),resolve6())};ui.start();let previewTheme=SYSTEM_THEME_NAME;setTheme(previewTheme);let component=new FirstTimeSetupComponent({onThemePreview:themeName=>{previewTheme=themeName,setTheme(themeName),ui.requestRender()},onSubmit:result=>{finish(result)},onCancel:()=>{finish(void 0)}});ui.addChild(component),ui.setFocus(component),ui.requestRender(),queryStartupTerminalColors(ui,()=>setTheme(previewTheme))})}async function showStartupInput(settingsManager,title,placeholder){let ui=await createStartupTui(settingsManager);return new Promise(resolve6=>{let settled=!1,finish=async result=>{settled||(settled=!0,input.dispose(),await clearStartupTui(ui),ui.stop(),resolve6(result))},input=new ExtensionInputComponent(title,placeholder,value=>{finish(value)},()=>{finish(void 0)},{tui:ui});ui.addChild(input),ui.setFocus(input),startStartupTui(ui,settingsManager)})}import{spawnSync}from"node:child_process";import{existsSync as existsSync7}from"node:fs";import{unlink}from"node:fs/promises";import*as os from"node:os";import{createHash as createHash4,randomBytes}from"node:crypto";import{chmodSync as chmodSync2,existsSync as existsSync6,lstatSync as lstatSync2,mkdirSync as mkdirSync4,readdirSync as readdirSync3,renameSync as renameSync3,rmSync as rmSync3,statSync as statSync4,writeFileSync as writeFileSync4}from"node:fs";import{open as open2}from"node:fs/promises";import{dirname as dirname5,join as join6,resolve as resolve5}from"node:path";var MAX_TOOL_IMAGE_BYTES=20*1024*1024,MAX_SESSION_MEDIA_BYTES=256*1024*1024,DEFAULT_LIMITS={perImage:MAX_TOOL_IMAGE_BYTES,perSession:MAX_SESSION_MEDIA_BYTES},MEDIA_DIRECTORY="media",EXTENSIONS={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"},reserved=new Map,SIGNATURES={"image/png":bytes=>bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),"image/jpeg":bytes=>bytes.subarray(0,3).equals(Buffer.from([255,216,255])),"image/gif":bytes=>bytes.subarray(0,4).toString("latin1")==="GIF8","image/webp":bytes=>bytes.subarray(0,4).toString("latin1")==="RIFF"&&bytes.subarray(8,12).toString("latin1")==="WEBP"};function assertRealDirectoryChain(root,callDirectory){for(let path2 of[dirname5(root),root,callDirectory]){let stat;try{stat=lstatSync2(path2)}catch{continue}if(!stat.isDirectory())throw new Error(`not a real directory: ${path2}`)}}var outcomes=new WeakMap;function liveToolMediaScope(entry){let manager=entry.runtime?.session.sessionManager,sessionFile=manager?.getSessionFile()??entry.worker?.snapshot?.state.sessionFile,durableSessionId=manager?.getSessionId()??entry.worker?.snapshot?.state.sessionId;return sessionFile===void 0||durableSessionId===void 0?void 0:{sessionDir:dirname5(sessionFile),durableSessionId}}function toolMediaRoot(scope){return assertValidSessionId(scope.durableSessionId),join6(scope.sessionDir,MEDIA_DIRECTORY,scope.durableSessionId)}function directoryBytes(directory){let total=0;for(let entry of readdirSync3(directory,{withFileTypes:!0})){let path2=join6(directory,entry.name);total+=entry.isDirectory()?directoryBytes(path2):statSync4(path2).size}return total}function storedBytes(root){let known=reserved.get(root);if(known!==void 0)return known;let scanned=existsSync6(root)?directoryBytes(root):0;return reserved.set(root,scanned),scanned}var unavailable=reason=>({unavailableReason:reason});function writeImage(root,path2,bytes){let callDirectory=dirname5(path2);mkdirSync4(callDirectory,{recursive:!0,mode:448}),assertRealDirectoryChain(root,callDirectory);let staging=`${path2}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync4(staging,bytes,{mode:384,flag:"wx"}),renameSync3(staging,path2),chmodSync2(path2,256)}catch(cause){throw rmSync3(staging,{force:!0}),cause}}function persistToolImage(scope,ref,block,limits=DEFAULT_LIMITS){let known=outcomes.get(block);if(known!==void 0)return known;let outcome=store(scope,ref,block,limits);return(!("unavailableReason"in outcome)||outcome.unavailableReason!=="storage_error")&&outcomes.set(block,outcome),outcome}function store(scope,ref,block,limits){let extension=EXTENSIONS[(block.mimeType??"").toLowerCase()];if(extension===void 0)return unavailable("storage_error");if(base64ByteLength(block.data)>limits.perImage)return unavailable("image_too_large");let bytes=Buffer.from(block.data,"base64");if(bytes.length>limits.perImage)return unavailable("image_too_large");if(SIGNATURES[(block.mimeType??"").toLowerCase()]?.(bytes)!==!0)return unavailable("storage_error");try{let root=toolMediaRoot(scope),callDirectory=createHash4("sha256").update(ref.toolCallId).digest("hex"),digest=createHash4("sha256").update(bytes).digest("hex"),path2=resolve5(root,callDirectory,`${ref.contentIndex}-${digest}.${extension}`);if(assertRealDirectoryChain(root,dirname5(path2)),existsSync6(path2))return{path:path2};let used=storedBytes(root);if(used+bytes.length>limits.perSession)return unavailable("session_limit");reserved.set(root,used+bytes.length);try{writeImage(root,path2,bytes)}catch(cause){throw reserved.set(root,storedBytes(root)-bytes.length),cause}return{path:path2}}catch{return unavailable("storage_error")}}function toolMediaPersister(scope){return(ref,block)=>{let current=scope();return current===void 0?void 0:persistToolImage(current,ref,block)}}function removeToolMedia(scope){let root=toolMediaRoot(scope);reserved.delete(root),makeTreeWritable(root),rmSync3(root,{recursive:!0,force:!0})}function makeTreeWritable(path2){let entries;try{if(!lstatSync2(path2).isDirectory())return;chmodSync2(path2,448),entries=readdirSync3(path2,{withFileTypes:!0})}catch{return}for(let entry of entries){let child=join6(path2,entry.name);if(entry.isDirectory())makeTreeWritable(child);else if(entry.isFile())try{chmodSync2(child,384)}catch{}}}async function toolMediaScopeOfSessionFile(sessionFile){try{let handle=await open2(sessionFile,"r");try{let{buffer,bytesRead}=await handle.read(Buffer.alloc(4096),0,4096,0),firstLine=buffer.subarray(0,bytesRead).toString("utf8").split(`
`,1)[0]??"",id=JSON.parse(firstLine).id;return typeof id=="string"?{sessionDir:dirname5(sessionFile),durableSessionId:id}:void 0}finally{await handle.close()}}catch{return}}function normalizeWhitespaceLower(text){return text.toLowerCase().replace(/\s+/g," ").trim()}var searchTextCache=new WeakMap;function getSessionSearchText(session){let cached=searchTextCache.get(session);if(cached)return cached;let fileNameId=sessionFileNameId(session.path),text=`${fileNameId===void 0||fileNameId===session.id?session.id:`${session.id} ${fileNameId}`} ${session.name??""} ${session.allMessagesText} ${session.cwd}`,entry={text,lower:text.toLowerCase()};return searchTextCache.set(session,entry),entry}function prepareTokens(parsed){return parsed.tokens.map(token=>token.kind==="phrase"?{kind:"phrase",normalized:normalizeWhitespaceLower(token.value)}:{kind:"fuzzy",lower:token.value.toLowerCase()})}function hasSessionName(session){return!!session.name?.trim()}function matchesNameFilter(session,filter2){return filter2==="all"?!0:hasSessionName(session)}function parseSearchQuery(query){let trimmed=query.trim();if(!trimmed)return{mode:"tokens",tokens:[],regex:null};if(trimmed.startsWith("re:")){let pattern=trimmed.slice(3).trim();if(!pattern)return{mode:"regex",tokens:[],regex:null,error:"Empty regex"};try{return{mode:"regex",tokens:[],regex:new RegExp(pattern,"i")}}catch(err){let msg=err instanceof Error?err.message:String(err);return{mode:"regex",tokens:[],regex:null,error:msg}}}let tokens=[],buf="",inQuote=!1,hadUnclosedQuote=!1,flush=kind=>{let v=buf.trim();buf="",v&&tokens.push({kind,value:v})};for(let i=0;i<trimmed.length;i++){let ch=trimmed[i];if(ch==='"'){inQuote?(flush("phrase"),inQuote=!1):(flush("fuzzy"),inQuote=!0);continue}if(!inQuote&&/\s/.test(ch)){flush("fuzzy");continue}buf+=ch}return inQuote&&(hadUnclosedQuote=!0),hadUnclosedQuote?{mode:"tokens",tokens:trimmed.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0).map(t=>({kind:"fuzzy",value:t})),regex:null}:(flush(inQuote?"phrase":"fuzzy"),{mode:"tokens",tokens,regex:null})}function matchPrepared(session,parsed,tokens){let searchText=getSessionSearchText(session);if(parsed.mode==="regex"){if(!parsed.regex)return{matches:!1,score:0};let idx=searchText.text.search(parsed.regex);return idx<0?{matches:!1,score:0}:{matches:!0,score:idx*.1}}if(tokens.length===0)return{matches:!0,score:0};let totalScore=0;for(let token of tokens){if(token.kind==="phrase"){if(searchText.normalized??=normalizeWhitespaceLower(searchText.text),!token.normalized)continue;let idx=searchText.normalized.indexOf(token.normalized);if(idx<0)return{matches:!1,score:0};totalScore+=idx*.1;continue}let m=fuzzyMatchLower(token.lower,searchText.lower);if(!m.matches)return{matches:!1,score:0};totalScore+=m.score}return{matches:!0,score:totalScore}}function filterAndSortSessions(sessions,query,sortMode,nameFilter="all"){let nameFiltered=nameFilter==="all"?sessions:sessions.filter(session=>matchesNameFilter(session,nameFilter));if(!query.trim())return nameFiltered;let parsed=parseSearchQuery(query);if(parsed.error)return[];let tokens=prepareTokens(parsed);if(sortMode==="recent"){let filtered=[];for(let s of nameFiltered)matchPrepared(s,parsed,tokens).matches&&filtered.push(s);return filtered}let scored=[];for(let s of nameFiltered){let res=matchPrepared(s,parsed,tokens);res.matches&&scored.push({session:s,score:res.score})}return scored.sort((a,b)=>a.score!==b.score?a.score-b.score:b.session.modified.getTime()-a.session.modified.getTime()),scored.map(r=>r.session)}function createCanonicalPathResolver(){let cache2=new Map;return path2=>{if(!path2)return path2;let canonical=cache2.get(path2);return canonical===void 0&&(canonical=canonicalizePath(path2),cache2.set(path2,canonical)),canonical}}function buildSessionTree(sessions,canonicalize){let byPath=new Map;for(let session of sessions){let sessionPath=canonicalize(session.path)??session.path;byPath.set(sessionPath,{session,children:[],latestActivity:session.modified.getTime()})}let roots=[];for(let session of sessions){let sessionPath=canonicalize(session.path)??session.path,node=byPath.get(sessionPath),parentPath=canonicalize(session.parentSessionPath);parentPath&&byPath.has(parentPath)?byPath.get(parentPath).children.push(node):roots.push(node)}let updateLatestActivity=node=>{let latestActivity=node.session.modified.getTime();for(let child of node.children)latestActivity=Math.max(latestActivity,updateLatestActivity(child));return node.latestActivity=latestActivity,latestActivity};for(let root of roots)updateLatestActivity(root);let sortNodes=nodes=>{nodes.sort((a,b)=>b.latestActivity-a.latestActivity);for(let node of nodes)sortNodes(node.children)};return sortNodes(roots),roots}function flattenSessionTree(roots){let result=[],walk=(node,depth,ancestorContinues,isLast)=>{result.push({session:node.session,depth,isLast,ancestorContinues});for(let i=0;i<node.children.length;i++){let childIsLast=i===node.children.length-1,continues=depth>0?!isLast:!1;walk(node.children[i],depth+1,[...ancestorContinues,continues],childIsLast)}};for(let i=0;i<roots.length;i++)walk(roots[i],0,[],i===roots.length-1);return result}function shortenPath(path2){let home=os.homedir();return path2&&(path2.startsWith(home)?`~${path2.slice(home.length)}`:path2)}function formatSessionDate(date){let diffMs=new Date().getTime()-date.getTime(),diffMins=Math.floor(diffMs/6e4),diffHours=Math.floor(diffMs/36e5),diffDays=Math.floor(diffMs/864e5);return diffMins<1?"now":diffMins<60?`${diffMins}m`:diffHours<24?`${diffHours}h`:diffDays<7?`${diffDays}d`:diffDays<30?`${Math.floor(diffDays/7)}w`:diffDays<365?`${Math.floor(diffDays/30)}mo`:`${Math.floor(diffDays/365)}y`}var SessionSelectorHeader=class{constructor(scope,sortMode,nameFilter,requestRender){this.loading=!1,this.loadProgress=null,this.showPath=!1,this.confirmingDeletePath=null,this.statusMessage=null,this.statusTimeout=null,this.showRenameHint=!1,this.scope=scope,this.sortMode=sortMode,this.nameFilter=nameFilter,this.requestRender=requestRender}setScope(scope){this.scope=scope}setSortMode(sortMode){this.sortMode=sortMode}setNameFilter(nameFilter){this.nameFilter=nameFilter}setLoading(loading){this.loading=loading,this.loadProgress=null}setProgress(loaded,total){this.loadProgress={loaded,total}}setShowPath(showPath){this.showPath=showPath}setShowRenameHint(show2){this.showRenameHint=show2}setConfirmingDeletePath(path2){this.confirmingDeletePath=path2}clearStatusTimeout(){this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null)}setStatusMessage(msg,autoHideMs){this.clearStatusTimeout(),this.statusMessage=msg,!(!msg||!autoHideMs)&&(this.statusTimeout=setTimeout(()=>{this.statusMessage=null,this.statusTimeout=null,this.requestRender()},autoHideMs))}invalidate(){}render(width){let title=this.scope==="current"?"Resume Session (Current Folder)":"Resume Session (All)",leftText=theme.bold(title),sortLabel=this.sortMode==="threaded"?"Threaded":this.sortMode==="recent"?"Recent":"Fuzzy",sortText=theme.fg("muted","Sort: ")+theme.fg("accent",sortLabel),nameLabel=this.nameFilter==="all"?"All":"Named",nameText=theme.fg("muted","Name: ")+theme.fg("accent",nameLabel),scopeText;if(this.loading){let progressText=this.loadProgress?`${this.loadProgress.loaded}/${this.loadProgress.total}`:"...";scopeText=`${theme.fg("muted","\u25CB Current Folder | ")}${theme.fg("accent",`Loading ${progressText}`)}`}else this.scope==="current"?scopeText=`${theme.fg("accent","\u25C9 Current Folder")}${theme.fg("muted"," | \u25CB All")}`:scopeText=`${theme.fg("muted","\u25CB Current Folder | ")}${theme.fg("accent","\u25C9 All")}`;let rightText=truncateToWidth(`${scopeText} ${nameText} ${sortText}`,width,""),availableLeft=Math.max(0,width-visibleWidth(rightText)-1),left=truncateToWidth(leftText,availableLeft,""),spacing=Math.max(0,width-visibleWidth(left)-visibleWidth(rightText)),hintLine1,hintLine2;if(this.confirmingDeletePath!==null){let confirmHint=`Delete session? ${keyHint("tui.select.confirm","confirm")} \xB7 ${keyHint("tui.select.cancel","cancel")}`;hintLine1=theme.fg("error",truncateToWidth(confirmHint,width,"\u2026")),hintLine2=""}else if(this.statusMessage){let color=this.statusMessage.type==="error"?"error":"accent";hintLine1=theme.fg(color,truncateToWidth(this.statusMessage.message,width,"\u2026")),hintLine2=""}else{let pathState=this.showPath?"(on)":"(off)",sep5=theme.fg("muted"," \xB7 "),hint1=keyHint("tui.input.tab","scope")+sep5+theme.fg("muted",'re:<pattern> regex \xB7 "phrase" exact'),hint2Parts=[keyHint("app.session.toggleSort","sort"),keyHint("app.session.toggleNamedFilter","named"),keyHint("app.session.delete","delete"),keyHint("app.session.togglePath",`path ${pathState}`)];this.showRenameHint&&hint2Parts.push(keyHint("app.session.rename","rename"));let hint2=hint2Parts.join(sep5);hintLine1=truncateToWidth(hint1,width,"\u2026"),hintLine2=truncateToWidth(hint2,width,"\u2026")}return[`${left}${" ".repeat(spacing)}${rightText}`,hintLine1,hintLine2]}},SessionList=class{getSelectedSessionPath(){return this.filteredSessions[this.selectedIndex]?.session.path}get focused(){return this._focused}set focused(value){this._focused=value,this.searchInput.focused=value}constructor(sessions,showCwd,sortMode,nameFilter,keybindings,currentSessionFilePath){this.allSessions=[],this.filteredSessions=[],this.selectedIndex=0,this.selectionTouched=!1,this.showCwd=!1,this.sortMode="threaded",this.nameFilter="all",this.showPath=!1,this.confirmingDeletePath=null,this.canonicalPath=createCanonicalPathResolver(),this.onExit=()=>{},this.maxVisible=10,this._focused=!1,this.allSessions=sessions,this.filteredSessions=[],this.searchInput=new Input,this.showCwd=showCwd,this.sortMode=sortMode,this.nameFilter=nameFilter,this.keybindings=keybindings,this.currentSessionCanonicalPath=this.canonicalPath(currentSessionFilePath),this.filterSessions(""),this.searchInput.onSubmit=()=>{if(this.filteredSessions[this.selectedIndex]){let selected=this.filteredSessions[this.selectedIndex];this.onSelect&&this.onSelect(selected.session.path)}}}setSortMode(sortMode){this.sortMode=sortMode,this.filterSessions(this.searchInput.getValue())}setNameFilter(nameFilter){this.nameFilter=nameFilter,this.filterSessions(this.searchInput.getValue())}setSessions(sessions,showCwd){let selectedPath=this.selectionTouched?this.getSelectedSessionPath():void 0;if(this.allSessions=sessions,this.canonicalPath=createCanonicalPathResolver(),this.showCwd=showCwd,this.filterSessions(this.searchInput.getValue()),!this.selectionTouched)this.selectedIndex=0;else if(selectedPath){let selectedIndex=this.filteredSessions.findIndex(node=>node.session.path===selectedPath);selectedIndex>=0&&(this.selectedIndex=selectedIndex)}}filterSessions(query){let trimmed=query.trim(),resumable=this.allSessions.filter(session=>!this.isLiveSessionWithoutConversation(session)),nameFiltered=this.nameFilter==="all"?resumable:resumable.filter(session=>hasSessionName(session));if(this.sortMode==="threaded"&&!trimmed){let roots=buildSessionTree(nameFiltered,this.canonicalPath);this.filteredSessions=flattenSessionTree(roots)}else{let filtered=filterAndSortSessions(nameFiltered,query,this.sortMode,"all");this.filteredSessions=filtered.map(session=>({session,depth:0,isLast:!0,ancestorContinues:[]}))}this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredSessions.length-1))}setConfirmingDeletePath(path2){this.confirmingDeletePath=path2,this.onDeleteConfirmationChange?.(path2)}startDeleteConfirmationForSelectedSession(){let selected=this.filteredSessions[this.selectedIndex];if(selected){if(this.isCurrentSessionPath(selected.session.path)){this.onError?.("Cannot delete the currently active session");return}this.setConfirmingDeletePath(selected.session.path)}}isLiveSessionWithoutConversation(session){return session.messageCount===0&&!hasSessionName(session)&&this.isCurrentSessionPath(session.path)}isCurrentSessionPath(path2){return this.currentSessionCanonicalPath?(this.canonicalPath(path2)??path2)===this.currentSessionCanonicalPath:!1}invalidate(){}render(width){let lines=[];if(lines.push(...this.searchInput.render(width)),lines.push(""),this.filteredSessions.length===0){let emptyMessage;if(this.nameFilter==="named"){let toggleKey=keyText("app.session.toggleNamedFilter");this.showCwd?emptyMessage=` No named sessions found. Press ${toggleKey} to show all.`:emptyMessage=` No named sessions in current folder. Press ${toggleKey} to show all, or Tab to view all.`}else this.showCwd?emptyMessage=" No sessions found":emptyMessage=" No sessions in current folder. Press Tab to view all.";return lines.push(theme.fg("muted",truncateToWidth(emptyMessage,width,"\u2026"))),lines}let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredSessions.length-this.maxVisible)),endIndex2=Math.min(startIndex+this.maxVisible,this.filteredSessions.length);for(let i=startIndex;i<endIndex2;i++){let node=this.filteredSessions[i],session=node.session,isSelected=i===this.selectedIndex,isConfirmingDelete=session.path===this.confirmingDeletePath,isCurrent=this.isCurrentSessionPath(session.path),prefix2=this.buildTreePrefix(node),hasName=!!session.name,normalizedMessage=(session.name??session.firstMessage).replace(/[\x00-\x1f\x7f]/g," ").trim(),age=formatSessionDate(session.modified),rightPart=`${String(session.messageCount)} ${age}`;(this.showCwd||session.moved)&&session.cwd&&(rightPart=`${shortenPath(session.cwd)} ${rightPart}`);let movedBadge=session.moved?"moved from ":"";this.showPath&&(rightPart=`${shortenPath(session.path)} ${rightPart}`);let cursor=isSelected?theme.fg("accent","\u203A "):" ",prefixWidth=visibleWidth(prefix2),rightWidth=visibleWidth(rightPart)+2,availableForMsg=width-2-prefixWidth-rightWidth,truncatedMsg=truncateToWidth(normalizedMessage,Math.max(10,availableForMsg),"\u2026"),messageColor=null;isConfirmingDelete?messageColor="error":isCurrent?messageColor="accent":hasName&&(messageColor="warning");let styledMsg=messageColor?theme.fg(messageColor,truncatedMsg):truncatedMsg;isSelected&&(styledMsg=theme.bold(styledMsg));let leftPart=cursor+theme.fg("dim",prefix2)+styledMsg,leftWidth=visibleWidth(leftPart),spacing=Math.max(1,width-leftWidth-visibleWidth(movedBadge+rightPart)),styledRight=(movedBadge?theme.fg("warning",movedBadge):"")+theme.fg(isConfirmingDelete?"error":"dim",rightPart),line=leftPart+" ".repeat(spacing)+styledRight;isSelected&&(line=theme.bg("selectedBg",line)),lines.push(truncateToWidth(line,width))}if(startIndex>0||endIndex2<this.filteredSessions.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredSessions.length})`,scrollInfo=theme.fg("muted",truncateToWidth(scrollText,width,""));lines.push(scrollInfo)}return lines}buildTreePrefix(node){if(node.depth===0)return"";let parts=node.ancestorContinues.map(continues=>continues?"\u2502 ":" "),branch=node.isLast?"\u2514\u2500 ":"\u251C\u2500 ";return parts.join("")+branch}handleInput(keyData){let kb=getKeybindings();if(this.confirmingDeletePath!==null){if(kb.matches(keyData,"tui.select.confirm")){let pathToDelete=this.confirmingDeletePath;this.setConfirmingDeletePath(null),this.onDeleteSession?.(pathToDelete);return}if(kb.matches(keyData,"tui.select.cancel")){this.setConfirmingDeletePath(null);return}return}if(kb.matches(keyData,"tui.input.tab")){this.onToggleScope&&this.onToggleScope();return}if(kb.matches(keyData,"app.session.toggleSort")){this.onToggleSort?.();return}if(this.keybindings.matches(keyData,"app.session.toggleNamedFilter")){this.onToggleNameFilter?.();return}if(kb.matches(keyData,"app.session.togglePath")){this.showPath=!this.showPath,this.onTogglePath?.(this.showPath);return}if(kb.matches(keyData,"app.session.delete")){this.startDeleteConfirmationForSelectedSession();return}if(kb.matches(keyData,"app.session.rename")){let selected=this.filteredSessions[this.selectedIndex];selected&&this.onRenameSession?.(selected.session.path);return}if(kb.matches(keyData,"app.session.deleteNoninvasive")){if(this.searchInput.getValue().length>0){this.searchInput.handleInput(keyData),this.filterSessions(this.searchInput.getValue());return}this.startDeleteConfirmationForSelectedSession();return}if(this.selectionTouched=!0,kb.matches(keyData,"tui.select.up"))this.selectedIndex=Math.max(0,this.selectedIndex-1);else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+1);else if(kb.matches(keyData,"tui.select.pageUp"))this.selectedIndex=Math.max(0,this.selectedIndex-this.maxVisible);else if(kb.matches(keyData,"tui.select.pageDown"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+this.maxVisible);else if(kb.matches(keyData,"tui.select.confirm")){let selected=this.filteredSessions[this.selectedIndex];selected&&this.onSelect&&this.onSelect(selected.session.path)}else kb.matches(keyData,"tui.select.cancel")?this.onCancel&&this.onCancel():(this.searchInput.handleInput(keyData),this.filterSessions(this.searchInput.getValue()))}};function withMediaOutcome(result,mediaError){return mediaError===void 0?result:{...result,mediaError}}async function deleteSessionFile(sessionPath){let mediaScope=await toolMediaScopeOfSessionFile(sessionPath),removeMedia=()=>{if(mediaScope!==void 0)try{removeToolMedia(mediaScope);return}catch(cause){let reason=cause instanceof Error?cause.message:String(cause);return`${toolMediaRoot(mediaScope)}: ${reason}`}},trashArgs=sessionPath.startsWith("-")?["--",sessionPath]:[sessionPath],trashResult=spawnSync("trash",trashArgs,{encoding:"utf-8"}),getTrashErrorHint=()=>{let parts=[];trashResult.error&&parts.push(trashResult.error.message);let stderr=trashResult.stderr?.trim();return stderr&&parts.push(stderr.split(`
`)[0]??stderr),parts.length===0?null:`trash: ${parts.join(" \xB7 ").slice(0,200)}`};if(trashResult.status===0||!existsSync7(sessionPath))return withMediaOutcome({ok:!0,method:"trash"},removeMedia());try{return await unlink(sessionPath),withMediaOutcome({ok:!0,method:"unlink"},removeMedia())}catch(err){let unlinkError=err instanceof Error?err.message:String(err),trashErrorHint=getTrashErrorHint();return{ok:!1,method:"unlink",error:trashErrorHint?`${unlinkError} (${trashErrorHint})`:unlinkError}}}var SessionSelectorComponent=class extends Container{handleInput(data){if(this.mode==="rename"){if(getKeybindings().matches(data,"tui.select.cancel")){this.exitRenameMode();return}this.renameInput.handleInput(data);return}this.sessionList.handleInput(data)}get focused(){return this._focused}set focused(value){this._focused=value,this.sessionList.focused=value,this.renameInput.focused=value,value&&this.mode==="rename"&&(this.renameInput.focused=!0)}buildBaseLayout(content,options){this.clear(),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder(s=>theme.fg("accent",s))),this.addChild(new Spacer(1)),(options?.showHeader??!0)&&(this.addChild(this.header),this.addChild(new Spacer(1))),this.addChild(content),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder(s=>theme.fg("accent",s)))}constructor(currentSessionsLoader,allSessionsLoader,onSelect,onCancel,onExit,requestRender,options,currentSessionFilePath){super(),this.canRename=!0,this.scope="current",this.sortMode="threaded",this.nameFilter="all",this.currentSessions=null,this.allSessions=null,this.currentLoad=null,this.allLoad=null,this.mode="list",this.renameInput=new Input,this.renameTargetPath=null,this._focused=!1,this.keybindings=options?.keybindings??KeybindingsManager.create(),this.currentSessionsLoader=currentSessionsLoader,this.allSessionsLoader=allSessionsLoader,this.requestRender=requestRender,this.header=new SessionSelectorHeader(this.scope,this.sortMode,this.nameFilter,this.requestRender);let renameSession=options?.renameSession;this.renameSession=renameSession,this.canRename=!!renameSession,this.header.setShowRenameHint(options?.showRenameHint??this.canRename),this.sessionList=new SessionList([],!1,this.sortMode,this.nameFilter,this.keybindings,currentSessionFilePath),this.buildBaseLayout(this.sessionList),this.renameInput.onSubmit=value=>{this.confirmRename(value)};let clearStatusMessage=()=>this.header.setStatusMessage(null);this.sessionList.onSelect=sessionPath=>{clearStatusMessage(),this.cancelLoads(),onSelect(sessionPath)},this.sessionList.onCancel=()=>{clearStatusMessage(),this.cancelLoads(),onCancel()},this.sessionList.onExit=()=>{clearStatusMessage(),this.cancelLoads(),onExit()},this.sessionList.onToggleScope=()=>this.toggleScope(),this.sessionList.onToggleSort=()=>this.toggleSortMode(),this.sessionList.onToggleNameFilter=()=>this.toggleNameFilter(),this.sessionList.onRenameSession=sessionPath=>{if(!renameSession||(this.scope==="current"?this.currentLoad:this.allLoad))return;let session=(this.scope==="all"?this.allSessions??[]:this.currentSessions??[]).find(s=>s.path===sessionPath);this.enterRenameMode(sessionPath,session?.name)},this.sessionList.onTogglePath=showPath=>{this.header.setShowPath(showPath),this.requestRender()},this.sessionList.onDeleteConfirmationChange=path2=>{this.header.setConfirmingDeletePath(path2),this.requestRender()},this.sessionList.onError=msg=>{this.header.setStatusMessage({type:"error",message:msg},3e3),this.requestRender()},this.sessionList.onDeleteSession=async sessionPath=>{let result=await deleteSessionFile(sessionPath);if(result.ok){this.currentSessions&&(this.currentSessions=this.currentSessions.filter(s=>s.path!==sessionPath)),this.allSessions&&(this.allSessions=this.allSessions.filter(s=>s.path!==sessionPath));let sessions=this.scope==="all"?this.allSessions??[]:this.currentSessions??[],showCwd=this.scope==="all";this.sessionList.setSessions(sessions,showCwd);let msg=result.method==="trash"?"Session moved to trash":"Session deleted";result.mediaError?this.header.setStatusMessage({type:"error",message:`${msg}, but its images were not removed: ${result.mediaError}`},8e3):this.header.setStatusMessage({type:"info",message:msg},2e3),await this.refreshSessionsAfterMutation()}else{let errorMessage=result.error??"Unknown error";this.header.setStatusMessage({type:"error",message:`Failed to delete: ${errorMessage}`},3e3)}this.requestRender()},this.loadScope("current")}cancelLoads(){this.currentLoad&&(this.currentLoad.abort(),this.currentLoad=null,this.currentSessions=null),this.allLoad&&(this.allLoad.abort(),this.allLoad=null,this.allSessions=null)}enterRenameMode(sessionPath,currentName){this.mode="rename",this.renameTargetPath=sessionPath,this.renameInput.setValue(currentName??""),this.renameInput.focused=!0;let panel=new Container;panel.addChild(new Text(theme.bold("Rename Session"),1,0)),panel.addChild(new Spacer(1)),panel.addChild(this.renameInput),panel.addChild(new Spacer(1)),panel.addChild(new Text(theme.fg("muted",`${keyText("tui.select.confirm")} to save \xB7 ${keyText("tui.select.cancel")} to cancel`),1,0)),this.buildBaseLayout(panel,{showHeader:!1}),this.requestRender()}exitRenameMode(){this.mode="list",this.renameTargetPath=null,this.buildBaseLayout(this.sessionList),this.requestRender()}async confirmRename(value){let next=value.trim();if(!next)return;let target=this.renameTargetPath;if(!target){this.exitRenameMode();return}let renameSession=this.renameSession;if(!renameSession){this.exitRenameMode();return}try{await renameSession(target,next),await this.refreshSessionsAfterMutation()}finally{this.exitRenameMode()}}async loadScope(scope){if(scope==="current"?this.currentLoad:this.allLoad)return;let showCwd=scope==="all",controller=new AbortController;scope==="current"?this.currentLoad=controller:this.allLoad=controller,this.header.setScope(scope),this.header.setLoading(!0),this.requestRender();let isActive=()=>(scope==="current"?this.currentLoad:this.allLoad)===controller,onProgress=(loaded,total,partialSessions)=>{if(isActive()){if(partialSessions){let sessions=[...partialSessions];scope==="current"?this.currentSessions=sessions:this.allSessions=sessions,scope===this.scope&&this.sessionList.setSessions(sessions,showCwd)}scope===this.scope&&(this.header.setProgress(loaded,total),this.requestRender())}};try{let sessions=await(scope==="current"?this.currentSessionsLoader(onProgress,controller.signal):this.allSessionsLoader(onProgress,controller.signal));if(!isActive()||(scope==="current"?(this.currentSessions=sessions,this.currentLoad=null):(this.allSessions=sessions,this.allLoad=null),scope!==this.scope))return;this.header.setLoading(!1),this.sessionList.setSessions(sessions,showCwd),this.requestRender()}catch(err){if(!isActive()||(scope==="current"?(this.currentLoad=null,this.currentSessions=null):(this.allLoad=null,this.allSessions=null),scope!==this.scope))return;let message=err instanceof Error?err.message:String(err);this.header.setLoading(!1),this.header.setStatusMessage({type:"error",message:`Failed to load sessions: ${message}`},4e3),this.sessionList.setSessions([],showCwd),this.requestRender()}}toggleSortMode(){this.sortMode=this.sortMode==="threaded"?"recent":this.sortMode==="recent"?"relevance":"threaded",this.header.setSortMode(this.sortMode),this.sessionList.setSortMode(this.sortMode),this.requestRender()}toggleNameFilter(){this.nameFilter=this.nameFilter==="all"?"named":"all",this.header.setNameFilter(this.nameFilter),this.sessionList.setNameFilter(this.nameFilter),this.requestRender()}async refreshSessionsAfterMutation(){this.cancelLoads(),this.currentSessions=null,this.allSessions=null,await this.loadScope(this.scope)}toggleScope(){this.scope=this.scope==="current"?"all":"current";let sessions=this.scope==="current"?this.currentSessions:this.allSessions,loading=(this.scope==="current"?this.currentLoad:this.allLoad)!==null;this.header.setScope(this.scope),this.header.setLoading(loading),this.sessionList.setSessions(sessions??[],this.scope==="all"),this.requestRender(),sessions===null&&!loading&&this.loadScope(this.scope)}getSessionList(){return this.sessionList}};export{areExperimentalFeaturesEnabled,minimatch,parseGitUrl,readPiManifest,SKILL_FRONTMATTER_PREFIX_BYTES,shouldSkipSkillWalkDirectoryName,addIgnoreRules,readSkillMarkdownSource,skillProjectRoot,insideSkillRoot,buildSkillAllowedSet,BlockedSkillLinkError,authorizeSkillPath,readSkillFileCheckedSync,readSkillFileChecked,DefaultPackageManager,KIMI_CODE_RETRY_PROFILE,CONTINUE_FROM_LEAF_CUSTOM_TYPE,CONTINUE_FROM_LEAF_DIRECTIVE,ContinueFromLeafError,trackTurnAdmission,MANUAL_CONTINUE_CUSTOM_TYPE,isManualContinueSubmission,MANUAL_CONTINUE_DIRECTIVE,STOP_RESUME_CUSTOM_TYPE,stopResumeDirective,ENGINE_TURN_START_ENTRY_TYPE,ENGINE_TURN_LIMIT_ENTRY_TYPE,ENGINE_TURN_LIMIT_EVENT,engineTurnLimitNotice,isUserDirectedTurn,resetsEngineTurnHistory,engineTurnHistory,engineTurnStop,isHealthExhaustionFailure,CircuitProbes,createFallbackCircuitAccess,acquireFallbackCircuits,monotonicNow,parseSettingsJson,TERMINAL_MOUSE_MODES,isTerminalMouseMode,DEFAULT_STREAM_START_TIMEOUT_MS,DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS,DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS,DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS,DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS,DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS,DEFAULT_TOOL_NAMES,wasSelfWrite,resolveSettingsSource,getSettingsPath2 as getSettingsPath,FileSettingsStorage,SettingsManager,InteractiveThemeController,createStartupTui,startStartupTui,shouldRunFirstTimeSetup,showStartupSelector,showFirstTimeSetup,showStartupInput,liveToolMediaScope,toolMediaPersister,SessionSelectorComponent};