@code-yeongyu/senpi 2026.10.10-10 → 2026.10.10-11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/dist/bundle/chunks/{anthropic-messages-2B35OVB7.js → anthropic-messages-I4Z6VKS3.js} +1 -1
- package/dist/bundle/chunks/{app-server-command-CV6N7JDD.js → app-server-command-HYNHHQJH.js} +1 -1
- package/dist/bundle/chunks/chunk-2KZKVRVC.js +8 -0
- package/dist/bundle/chunks/chunk-4XSQBLXM.js +2 -0
- package/dist/bundle/chunks/{chunk-ZPJHS64R.js → chunk-5BRVRFJI.js} +1 -1
- package/dist/bundle/chunks/{chunk-4WZF7G6N.js → chunk-B2RD7QJJ.js} +6 -6
- package/dist/bundle/chunks/chunk-DRVT7RIO.js +2 -0
- package/dist/bundle/chunks/chunk-FOGXAY3T.js +2 -0
- package/dist/bundle/chunks/{chunk-5AKP2VFB.js → chunk-GNZDD5BK.js} +2 -3
- package/dist/bundle/chunks/{chunk-ZCYTYHDN.js → chunk-IAYFQEXI.js} +1 -1
- package/dist/bundle/chunks/{chunk-HKRW6HT5.js → chunk-KTRCQYDF.js} +2 -2
- package/dist/bundle/chunks/chunk-M4C6Z7UT.js +288 -0
- package/dist/bundle/chunks/chunk-ML3WDDTX.js +2505 -0
- package/dist/bundle/chunks/chunk-NV3IPLK6.js +9 -0
- package/dist/bundle/chunks/chunk-OZ2N2E6U.js +2 -0
- package/dist/bundle/chunks/{chunk-JRGNL6WM.js → chunk-QXREUA5F.js} +1 -1
- package/dist/bundle/chunks/{chunk-QQZREV6B.js → chunk-SSH4CLHJ.js} +1 -1
- package/dist/bundle/chunks/chunk-TOZBUPZP.js +3 -0
- package/dist/bundle/chunks/chunk-WASCMT6Y.js +2 -0
- package/dist/bundle/chunks/chunk-YU4AYH4C.js +2 -0
- package/dist/bundle/chunks/chunk-ZHE7JDBG.js +6 -0
- package/dist/bundle/chunks/{chunk-NTH33AXY.js → chunk-ZJOYLQXK.js} +1 -1
- package/dist/bundle/chunks/cli-main-WTXDD6H5.js +3 -0
- package/dist/bundle/chunks/{help-fast-path-5P73752B.js → help-fast-path-IQAJFO2G.js} +1 -1
- package/dist/bundle/chunks/host-command-7YS2Y6AT.js +2 -0
- package/dist/bundle/chunks/{host-lifecycle-B24G65GD.js → host-lifecycle-UG7RS5EU.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +1 -1
- package/dist/bundle/chunks/interactive-mode-WLMPVMRU.js +2 -0
- package/dist/bundle/chunks/multi-session-host-4SUEFZMU.js +26 -0
- package/dist/bundle/chunks/{package-manager-cli-PXP63ZPT.js → package-manager-cli-XEUK2RUM.js} +1 -1
- package/dist/bundle/chunks/rotation-stream-JXT3JYW5.js +2 -0
- package/dist/bundle/chunks/rpc-mode-G3DAUZCR.js +2 -0
- package/dist/bundle/chunks/runtime-session-6DAEMII3.js +2 -0
- package/dist/bundle/chunks/{schedule-command-MGZLHARF.js → schedule-command-DGLRLVWY.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-MCV37VI5.js +3 -0
- package/dist/bundle/chunks/session-picker-WEFWH5O4.js +2 -0
- package/dist/bundle/chunks/session-worker.js +387 -383
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/cli/session-opening.d.ts +5 -0
- package/dist/cli/session-opening.js +11 -0
- package/dist/core/agent-session.d.ts +5 -0
- package/dist/core/agent-session.js +46 -1
- package/dist/core/engine-paused.d.ts +6 -0
- package/dist/core/engine-paused.js +50 -0
- package/dist/core/extensions/builtin/goal/continuation.js +2 -0
- package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js +3 -1
- package/dist/core/extensions/builtin/goal/elapsed-ticker.js +2 -0
- package/dist/core/extensions/builtin/goal/index.js +4 -8
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +54 -13
- package/dist/core/extensions/builtin/goal/monitor-continuation.js +2 -1
- package/dist/core/extensions/builtin/goal/persistence.js +2 -0
- package/dist/core/extensions/builtin/goal/store.d.ts +5 -0
- package/dist/core/extensions/builtin/goal/store.js +44 -0
- package/dist/core/extensions/builtin/goal/types.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/service-connection.js +1 -0
- package/dist/core/extensions/builtin/mcp/service-types.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/service.js +257 -74
- package/dist/core/extensions/builtin/terminal/process-identity.d.ts +1 -3
- package/dist/core/extensions/builtin/terminal/process-identity.js +1 -7
- package/dist/core/extensions/builtin/terminal/process-start-probe.js +11 -7
- package/dist/core/extensions/builtin/ttsr/index.js +19 -0
- package/dist/core/foreign-session-holders.d.ts +7 -0
- package/dist/core/foreign-session-holders.js +63 -0
- package/dist/core/moved-session-cwd.d.ts +7 -0
- package/dist/core/moved-session-cwd.js +23 -0
- package/dist/core/moved-sessions.d.ts +6 -0
- package/dist/core/moved-sessions.js +83 -24
- package/dist/core/resume-target.js +3 -1
- package/dist/core/session-holders.d.ts +2 -1
- package/dist/core/session-holders.js +4 -4
- package/dist/core/session-manager.js +12 -10
- package/dist/core/webview/webview-readiness.d.ts +2 -0
- package/dist/core/webview/webview-readiness.js +9 -0
- package/dist/core/webview/webview-service.d.ts +4 -0
- package/dist/core/webview/webview-service.js +30 -5
- package/dist/main.js +14 -3
- package/dist/modes/app-server/daemon/process.d.ts +4 -0
- package/dist/modes/app-server/daemon/process.js +52 -4
- package/dist/modes/interactive/interactive-mode.js +7 -0
- package/dist/modes/rpc/connection-handler.js +3 -2
- package/dist/modes/rpc/custom-capability.d.ts +2 -0
- package/dist/modes/rpc/custom-capability.js +2 -0
- package/dist/modes/rpc/host-capabilities.js +3 -1
- package/dist/modes/rpc/host-daemon-registration.js +15 -6
- package/dist/modes/rpc/host-legacy.js +8 -1
- package/dist/modes/rpc/host-reservations.d.ts +2 -0
- package/dist/modes/rpc/host-reservations.js +56 -3
- package/dist/modes/rpc/host-supervisor-log.d.ts +1 -0
- package/dist/modes/rpc/host-supervisor-log.js +9 -0
- package/dist/modes/rpc/multi-session-host.js +8 -6
- package/dist/modes/rpc/rpc-mode.d.ts +3 -1
- package/dist/modes/rpc/rpc-mode.js +3 -1
- package/dist/modes/rpc/rpc-types.d.ts +3 -1
- package/dist/modes/rpc/rpc-types.js +2 -0
- package/dist/modes/rpc/session-command-router.d.ts +1 -1
- package/dist/modes/rpc/session-command-router.js +18 -14
- package/dist/modes/rpc/session-held.d.ts +8 -0
- package/dist/modes/rpc/session-held.js +127 -0
- package/dist/modes/rpc/session-registry-types.d.ts +1 -1
- package/dist/modes/rpc/session-registry.d.ts +2 -0
- package/dist/modes/rpc/session-registry.js +4 -0
- package/dist/modes/rpc/session-worker-client.d.ts +3 -3
- package/dist/modes/rpc/session-worker-client.js +24 -12
- package/dist/modes/rpc/worker-session-claims.d.ts +15 -0
- package/dist/modes/rpc/worker-session-claims.js +61 -0
- package/dist/modes/rpc/worker-session-registry.d.ts +4 -0
- package/dist/modes/rpc/worker-session-registry.js +51 -8
- package/dist/utils/shell.d.ts +6 -2
- package/dist/utils/shell.js +20 -6
- package/docs/rpc.md +21 -1
- package/docs/session-format.md +9 -0
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-6Y7VGPJB.js +0 -9
- package/dist/bundle/chunks/chunk-JEZWV7JW.js +0 -17
- package/dist/bundle/chunks/chunk-LR5EN45D.js +0 -7
- package/dist/bundle/chunks/chunk-MYVBK47X.js +0 -2
- package/dist/bundle/chunks/chunk-O6YOQUVX.js +0 -2773
- package/dist/bundle/chunks/chunk-TJPMB4VH.js +0 -2
- package/dist/bundle/chunks/chunk-U5KVIAHJ.js +0 -2
- package/dist/bundle/chunks/chunk-XMHO4QQN.js +0 -7
- package/dist/bundle/chunks/cli-main-TM4UFZVC.js +0 -3
- package/dist/bundle/chunks/host-command-MWQNTWFA.js +0 -2
- package/dist/bundle/chunks/interactive-mode-CBQW7WRK.js +0 -2
- package/dist/bundle/chunks/multi-session-host-4KXWGRNS.js +0 -25
- package/dist/bundle/chunks/rotation-stream-FQH63DMY.js +0 -2
- package/dist/bundle/chunks/rpc-mode-7WHJHMUP.js +0 -2
- package/dist/bundle/chunks/runtime-session-CWJNFRHY.js +0 -2
- package/dist/bundle/chunks/session-control-endpoint-OH7XV2FN.js +0 -3
- package/dist/bundle/chunks/session-picker-UUSW6YSU.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
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 = () => {}; } }
|
|
2
|
-
import{SYSTEM_THEME_NAME,SettingsManager,appendHiddenTuiStdout,getTerminalTheme,initTheme,isStdoutTakenOver,loadThemeFromPath,markTerminalColorsPending,parseAutoThemeSetting,resolveThemeSetting,setRegisteredThemes,setTerminalColorScheme,setTerminalColors,setTheme,setThemeInstance,theme}from"./chunk-NTH33AXY.js";import{KeybindingsManager}from"./chunk-4GPJOGXZ.js";import{Container,Input,ProcessTerminal,Spacer,TUI,Text,fuzzyMatchLower,getKeybindings,nextRenderRevision,setCapabilityOverrides,setKeybindings,truncateToWidth,visibleWidth}from"./chunk-KCVSSFOV.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{dropFailedAssistantTurns}from"./chunk-ZPJHS64R.js";import{CONTEXT_PROVENANCE_FIELD,contextProvenanceFingerprint,copyContextProvenance,getContextProvenance}from"./chunk-2JKDZXIY.js";import{require_semver}from"./chunk-ZOFZRJSL.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,PACKAGE_NAME,canonicalizePath,envValue,getAgentDir,getSessionsDir,getSettingsPath,isLocalPath,markPathIgnoredByCloudSync,normalizePath,resolvePath,spawnProcess,spawnProcessSync,stripBom}from"./chunk-463OK2Y4.js";import{getCurrentSystemMessage,isModelType,lazyStream,normalizeProviderId}from"./chunk-L4HVJWIF.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 require_ignore=__commonJS({"node_modules/ignore/index.js"(exports,module){function makeArray(subject){return Array.isArray(subject)?subject:[subject]}var UNDEFINED=void 0,EMPTY="",SPACE=" ",ESCAPE="\\",REGEX_LITERAL_SPECIAL=/[.*+?()[\]{}^$|\\/]/,REGEX_TEST_BLANK_LINE=/^\uFEFF? *$/,REGEX_INVALID_TRAILING_BACKSLASH=/(?:[^\\]|^)\\$/,REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION=/^\\!/,REGEX_REPLACE_LEADING_EXCAPED_HASH=/^\\#/,REGEX_SPLITALL_CRLF=/\r?\n/g,DOUBLE_SLASH="//",SLASH_CODE=47,DOT_CODE=46,SLASH="/",TMP_KEY_IGNORE="node-ignore";typeof Symbol<"u"&&(TMP_KEY_IGNORE=Symbol.for("node-ignore"));var KEY_IGNORE=TMP_KEY_IGNORE,define=(object,key,value)=>(Object.defineProperty(object,key,{value}),value),RETURN_FALSE=()=>!1,cleanRangeBackSlash=slashes=>{let{length}=slashes;return slashes.slice(0,length-length%2)},POSIX_CLASSES={alnum:"0-9A-Za-z",alpha:"A-Za-z",blank:" \\t",cntrl:"\\x00-\\x1f\\x7f",digit:"0-9",graph:"!-.0-~",lower:"a-z",print:" -.0-~",punct:"!-.:-@\\[-`{-~",space:" \\t\\n\\r",upper:"A-Z",xdigit:"0-9A-Fa-f"},CLASS_MEMBERS_TO_ESCAPE="\\]^-[",escapeMember=char=>CLASS_MEMBERS_TO_ESCAPE.indexOf(char)<0?char:ESCAPE+char,NON_SLASH="(?!\\/)",classSource=(negated,body)=>{if(negated)return`[^\\/${body}]`;let source=`[${body}]`;return new RegExp(source).test("/")?NON_SLASH+source:source},scanBracket=(pattern,start)=>{let{length}=pattern,index=start+1,negated=EMPTY,lead=pattern[index];(lead==="!"||lead==="^")&&(negated="^",index++);let body=EMPTY,prev=EMPTY;for(;;){let char=pattern[index];if(char===UNDEFINED)return null;if(char===ESCAPE){let escaped=pattern[index+1];if(escaped===UNDEFINED)return null;body+=escapeMember(escaped),prev=escaped,index++}else if(char==="-"&&prev&&index+1<length&&pattern[index+1]!=="]"){index++;let to=pattern[index];to===ESCAPE&&(to=pattern[index+=1]),prev<=to&&(body+=`-${escapeMember(to)}`),prev=EMPTY}else if(char==="["&&pattern[index+1]===":"){let nameStart=index+2,end=nameStart;for(;end<length&&pattern[end]!=="]";)end++;if(end===length)return null;if(end>nameStart&&pattern[end-1]===":"){let expanded=POSIX_CLASSES[pattern.slice(nameStart,end-1)];if(expanded===UNDEFINED)return null;body+=expanded,prev=EMPTY,index=end}else body+=escapeMember("["),prev="[",index=nameStart-2}else body+=escapeMember(char),prev=char;if(index++,pattern[index]==="]")return{end:index,source:classSource(negated,body)}}},NEVER_MATCH="[]",PLACEHOLDER="\0",REGEX_RESTORE_PLACEHOLDER=new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,"g"),TRAILING_WILDCARD="\uE000",extractBrackets=pattern=>{let sources=[],hold=source=>`${PLACEHOLDER}${sources.push(source)-1}${PLACEHOLDER}`,{length}=pattern,out=EMPTY,index=0;for(;index<length;){let char=pattern[index];if(char===ESCAPE){let escaped=pattern[index+1];escaped==="*"||escaped==="["||escaped===SPACE||escaped===ESCAPE?out+=pattern.slice(index,index+2):out+=hold(REGEX_LITERAL_SPECIAL.test(escaped)?ESCAPE+escaped:escaped),index+=2}else if(char===PLACEHOLDER)out+=hold(`[${PLACEHOLDER}]`),index++;else if(char==="["){let scanned=scanBracket(pattern,index);scanned===null?(out+=hold(NEVER_MATCH),index=length):(out+=hold(scanned.source),index=scanned.end+1)}else out+=char,index++}return{source:out,sources}},DIRECT=null,REGEX_INNER_SLASH=/\/(?!$)/,REPLACERS=[[/^\uFEFF/,()=>EMPTY,"\uFEFF"],[/[\r\n]+$/,()=>EMPTY],[/((?:\\\\)*?)(\\? +)$/,(_,m1,m2)=>m1+(m2.indexOf("\\")===0?SPACE:EMPTY)],[/(\\+?) /g,(_,m1)=>{let{length}=m1;return m1.slice(0,length-length%2)+SPACE}],[/[\\$.|*+(){^]/g,match2=>`\\${match2}`],[/(?!\\)\?/g,()=>"[^/]","?"],[/^\//,()=>"^",SLASH],[/\//g,()=>"\\/",SLASH],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?","*"],[DIRECT,(source,pattern)=>!source||source[0]==="^"?source:(REGEX_INNER_SLASH.test(pattern)?"^":"(?:^|\\/)")+source],[/\\\/\\\*\\\*(?=\\\/|$)/g,(_,index,str)=>index+6<str.length?str.slice(index+6)==="\\/"?"(?:\\/[^\\/]+)+":"(?:\\/[^\\/]+)*":"\\/.+","*"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(_,p1,p2)=>{let unescaped=p2.replace(/\\\*/g,"[^\\/]*");return p1+unescaped},"*"],[/(^|[^\\])((?:\\\\)*)\\\*$/,(match2,p1,p2)=>p2.length/2%2===0?p1+p2+TRAILING_WILDCARD:match2,"*"],[/\\\\\\(?=[$.|*+(){^])/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\\/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\[([^\]/]*?)(\\*)($|\])/g,(match2,range2,endEscape,close)=>`\\[${range2}${cleanRangeBackSlash(endEscape)}${close}`,"["],[DIRECT,source=>{let last=source[source.length-1];return!last||last===TRAILING_WILDCARD?source:last===SLASH?`${source}$`:`${source}(?=$|\\/$)`}]],REGEX_REPLACE_TRAILING_WILDCARD=/(^|\\\/)?\uE000$/,MODE_IGNORE="regex",MODE_CHECK_IGNORE="checkRegex",UNDERSCORE="_",TRAILING_WILD_CARD_REPLACERS={[MODE_IGNORE](_,p1){return`${p1?`${p1}[^/]+`:"[^/]*"}(?=$|\\/$)`},[MODE_CHECK_IGNORE](_,p1){return`${p1?`${p1}[^/]*`:"[^/]*"}(?=$|\\/$)`}},WILDCARD="[^\\/]*",pinWildcards=source=>{if(source.indexOf(WILDCARD)<0)return source;let tokens=[],{length}=source,index=0;for(;index<length;){let char=source[index];if(source.startsWith(WILDCARD,index))tokens.push({wildcard:!0}),index+=WILDCARD.length;else if(char==="["){let end=index+1;for(source[end]==="^"&&end++,source[end]==="]"&&end++;end<length&&source[end]!=="]";)end+=source[end]===ESCAPE?2:1;end++,tokens.push({single:source.slice(index,end)}),index=end}else if(char===ESCAPE)tokens.push({single:source.slice(index,index+2)}),index+=2;else if(char==="("){let depth=0,end=index;do source[end]===ESCAPE?end++:source[end]==="("?depth++:source[end]===")"&&depth--,end++;while(end<length&&depth>0);"*+?".indexOf(source[end])>=0&&end++,tokens.push({boundary:source.slice(index,end)}),index=end}else char==="^"||char==="$"?(tokens.push({boundary:char}),index++):(tokens.push({single:char}),index++)}let out=EMPTY,run=[],flush=()=>{let lastWildcard;run.forEach((token,at)=>{token.wildcard&&(lastWildcard=at)}),run.forEach((token,at)=>{if(!token.wildcard){out+=token.single;return}out+=at===lastWildcard?WILDCARD:`(?:(?!${run[at+1].single})[^\\/])*`}),run=[]};return tokens.forEach(token=>{if(token.boundary===void 0){run.push(token);return}flush(),out+=token.boundary}),flush(),out},makeRegexPrefix=pattern=>{let{source,sources}=extractBrackets(pattern),replaced=REPLACERS.reduce((prev,[matcher,replacer,required])=>matcher===DIRECT?replacer(prev,pattern):required!==UNDEFINED&&prev.indexOf(required)<0?prev:matcher.test(prev)?prev.replace(matcher,replacer.bind(pattern)):prev,source);return sources.length?replaced.replace(REGEX_RESTORE_PLACEHOLDER,(match2,index)=>sources[index]):replaced},matchesBasename=body=>{let index=body.indexOf(SLASH);return index<0||index===body.length-1},basenameOf=path2=>{let end=path2.length-1,index=path2.lastIndexOf(SLASH,path2[end]===SLASH?end-1:end);return index<0?path2:path2.slice(index+1)},parentOf=path2=>{if(path2.charCodeAt(0)===SLASH_CODE||path2.indexOf(DOUBLE_SLASH)>=0){let slices=path2.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY}let end=path2.length-1,cut=path2.lastIndexOf(SLASH,path2.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY:path2.slice(0,cut+1)},isString=subject=>typeof subject=="string",checkPattern=pattern=>pattern&&isString(pattern)&&!REGEX_TEST_BLANK_LINE.test(pattern)&&!REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)&&pattern.indexOf("#")!==0,splitPattern=pattern=>pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean),IgnoreRule=class{constructor(pattern,mark,body,ignoreCase,negative,prefix){this.pattern=pattern,this.mark=mark,this.negative=negative,define(this,"body",body),define(this,"ignoreCase",ignoreCase),define(this,"regexPrefix",prefix)}get _basenameOnly(){return define(this,"_basenameOnly",matchesBasename(this.body))}get regex(){let key=UNDERSCORE+MODE_IGNORE;return this[key]?this[key]:this._make(MODE_IGNORE,key)}get checkRegex(){let key=UNDERSCORE+MODE_CHECK_IGNORE;return this[key]?this[key]:this._make(MODE_CHECK_IGNORE,key)}_make(mode,key){let str=pinWildcards(this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,TRAILING_WILD_CARD_REPLACERS[mode])),regex=this.ignoreCase?new RegExp(str,"i"):new RegExp(str);return define(this,key,regex)}},createRule=({pattern,mark},ignoreCase)=>{let negative=!1,body=pattern;body.indexOf("!")===0&&(negative=!0,body=body.substr(1)),body=body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION,"!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH,"#");let regexPrefix=makeRegexPrefix(body);return new IgnoreRule(pattern,mark,body,ignoreCase,negative,regexPrefix)},RuleManager=class{constructor(ignoreCase){this._ignoreCase=ignoreCase,this._rules=[],this._basenameCount=0}_add(pattern){if(pattern&&pattern[KEY_IGNORE]){this._rules=this._rules.concat(pattern._rules._rules),this._basenameCount+=pattern._rules._basenameCount,this._added=!0;return}if(isString(pattern)&&(pattern={pattern}),checkPattern(pattern.pattern)){let rule=createRule(pattern,this._ignoreCase);this._added=!0,this._rules.push(rule),matchesBasename(rule.body)&&this._basenameCount++}}add(pattern){return this._added=!1,makeArray(isString(pattern)?splitPattern(pattern):pattern).forEach(this._add,this),this._added}test(path2,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename4=shortcut?basenameOf(path2):path2;for(let index=0;index<length;index++){let rule=rules[index],{negative}=rule;!(unignored===negative&&ignored!==unignored||negative&&!ignored&&!unignored&&!checkUnignored)&&rule[mode].test(shortcut&&rule._basenameOnly?basename4:path2)&&(ignored=!negative,unignored=negative,matchedRule=negative?UNDEFINED:rule)}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}},throwError=(message,Ctor)=>{throw new Ctor(message)},checkPath=(path2,originalPath,doThrow)=>isString(path2)?path2?checkPath.isNotRelative(path2)?doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`,RangeError):!0:doThrow("path must not be empty",TypeError):doThrow(`path must be a string, but got \`${originalPath}\``,TypeError),isNotRelative=path2=>{let first=path2.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path2.length===1)return!0;let second=path2.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path2.length===2||path2.charCodeAt(2)===SLASH_CODE};checkPath.isNotRelative=isNotRelative;checkPath.convert=p=>p;var Ignore=class{constructor({ignorecase=!0,ignoreCase=ignorecase,allowRelativePaths=!1}={}){define(this,KEY_IGNORE,!0),this._rules=new RuleManager(ignoreCase),this._strictPathCheck=!allowRelativePaths,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(pattern){return this._rules.add(pattern)&&this._initCache(),this}addPattern(pattern){return this.add(pattern)}_test(originalPath,cache2,checkUnignored){let path2=originalPath&&checkPath.convert(originalPath);return checkPath(path2,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path2,cache2,checkUnignored)}checkIgnore(path2){if(path2.charCodeAt(path2.length-1)!==SLASH_CODE)return this.test(path2);let parentPath=parentOf(path2);if(parentPath){let parent=this._t(parentPath,this._testCache,!0);if(parent.ignored)return parent}return this._rules.test(path2,!1,MODE_CHECK_IGNORE)}_t(path2,cache2,checkUnignored){if(path2 in cache2)return cache2[path2];let parentPath=parentOf(path2),parent=parentPath?this._t(parentPath,cache2,checkUnignored):UNDEFINED;return cache2[path2]=parent&&parent.ignored?parent:this._rules.test(path2,checkUnignored,MODE_IGNORE)}ignores(path2){return this._test(path2,this._ignoreCache,!1).ignored}createFilter(){return path2=>!this.ignores(path2)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path2){return this._test(path2,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path2=>checkPath(path2&&checkPath.convert(path2),path2,RETURN_FALSE),setupWindows=()=>{let makePosix=str=>/^\\\\\?\\/.test(str)||/["<>|\u0000-\u001F]+/u.test(str)?str:str.replace(/\\/g,"/");checkPath.convert=makePosix;let REGEX_TEST_WINDOWS_PATH_ABSOLUTE=/^[a-z]:\//i;checkPath.isNotRelative=path2=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path2)||isNotRelative(path2)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});var VIRTUAL_MODEL_API="pi-virtual",VIRTUAL_MODEL_STATE_ENTRY="pi.virtual-model-state",THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isVirtualModel(model){return model.api===VIRTUAL_MODEL_API}function findLatestResponse(messages){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.role==="assistant"&&message.stopReason!=="error"&&message.stopReason!=="aborted")return message}}function getBranchSelection(branch,getModel){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId};if(entry.type==="message"&&entry.message.role==="assistant"&&!isVirtualModel(entry.message)){let response={provider:entry.message.provider,modelId:entry.message.model},change=findLastModelChange(branch,i),model=change&&getModel(change.provider,change.modelId);return change&&model&&isVirtualModel(model)?change:response}}}function findLastModelChange(branch,before){for(let i=before-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId}}}function getVirtualModelState(branch,provider,modelId){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type!=="custom"||entry.customType!==VIRTUAL_MODEL_STATE_ENTRY)continue;let data=entry.data;if(data?.provider===provider&&data.modelId===modelId)return data.state}}function createVirtualModel(definition){let levels=definition.thinkingLevels??["off"],thinkingLevelMap={};for(let level of THINKING_LEVELS)thinkingLevelMap[level]=levels.includes(level)?level:null;return{id:definition.id,name:definition.name,api:VIRTUAL_MODEL_API,provider:definition.provider,baseUrl:"",reasoning:levels.some(level=>level!=="off"),thinkingLevelMap,input:definition.input??["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:definition.contextWindow??0,maxTokens:definition.maxTokens??0}}function unroutedStream(model){return lazyStream(model,async()=>{throw new Error(`Virtual model ${model.provider}/${model.id} must be routed before streaming`)})}function withVirtualModels(providerId,provider,virtualModels){if(!provider)return{id:providerId,name:providerId,auth:{apiKey:{name:"Virtual model",resolve:async()=>({auth:{},source:"virtual"})}},getModels:()=>virtualModels,stream:unroutedStream,streamSimple:unroutedStream};let ids=new Set(virtualModels.map(model=>model.id)),physical=models=>models.filter(model=>!isVirtualModel(model)&&!(isModelType(model,"chat")&&ids.has(model.id))),virtual=models=>models.filter(model=>isVirtualModel(model)),{filterModels,filterAllModels}=provider;return{...provider,getModels:()=>[...physical(provider.getModels()),...virtualModels],getAllModels:()=>[...physical(provider.getAllModels?.()??provider.getModels()),...virtualModels],filterModels:(models,credential)=>{let real=physical(models);return[...filterModels?.(real,credential)??real,...virtual(models)]},filterAllModels:filterAllModels&&((models,credential)=>[...filterAllModels(physical(models),credential),...virtual(models)]),stream:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.stream(model,context,options),streamSimple:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.streamSimple(model,context,options)}}var ENVIRONMENT_CONTEXT_MESSAGE_TYPE="environment-context";function resolveEnvironmentContext(cwd,now=new Date){return{cwd:cwd.replace(/\\/g,"/"),currentDate:now.toISOString().slice(0,10)}}function formatEnvironmentContext(context){return["<environment_context>",` <cwd>${context.cwd}</cwd>`,` <current_date>${context.currentDate}</current_date>`,"</environment_context>"].join(`
|
|
2
|
+
import{SYSTEM_THEME_NAME,SettingsManager,appendHiddenTuiStdout,getTerminalTheme,initTheme,isStdoutTakenOver,loadThemeFromPath,markTerminalColorsPending,parseAutoThemeSetting,resolveThemeSetting,setRegisteredThemes,setTerminalColorScheme,setTerminalColors,setTheme,setThemeInstance,theme}from"./chunk-ZJOYLQXK.js";import{resolveMovedPath}from"./chunk-TOZBUPZP.js";import{KeybindingsManager}from"./chunk-4GPJOGXZ.js";import{Container,Input,ProcessTerminal,Spacer,TUI,Text,fuzzyMatchLower,getKeybindings,nextRenderRevision,setCapabilityOverrides,setKeybindings,truncateToWidth,visibleWidth}from"./chunk-KCVSSFOV.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{require_ignore}from"./chunk-YU4AYH4C.js";import{dropFailedAssistantTurns}from"./chunk-5BRVRFJI.js";import{CONTEXT_PROVENANCE_FIELD,contextProvenanceFingerprint,copyContextProvenance,getContextProvenance}from"./chunk-2JKDZXIY.js";import{require_semver}from"./chunk-ZOFZRJSL.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,PACKAGE_NAME,canonicalizePath,envValue,getAgentDir,getSessionsDir,getSettingsPath,isLocalPath,markPathIgnoredByCloudSync,normalizePath,resolvePath,spawnProcess,spawnProcessSync,stripBom}from"./chunk-463OK2Y4.js";import{getCurrentSystemMessage,isModelType,lazyStream,normalizeProviderId}from"./chunk-L4HVJWIF.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 VIRTUAL_MODEL_API="pi-virtual",VIRTUAL_MODEL_STATE_ENTRY="pi.virtual-model-state",THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isVirtualModel(model){return model.api===VIRTUAL_MODEL_API}function findLatestResponse(messages){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.role==="assistant"&&message.stopReason!=="error"&&message.stopReason!=="aborted")return message}}function getBranchSelection(branch,getModel){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId};if(entry.type==="message"&&entry.message.role==="assistant"&&!isVirtualModel(entry.message)){let response={provider:entry.message.provider,modelId:entry.message.model},change=findLastModelChange(branch,i),model=change&&getModel(change.provider,change.modelId);return change&&model&&isVirtualModel(model)?change:response}}}function findLastModelChange(branch,before){for(let i=before-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId}}}function getVirtualModelState(branch,provider,modelId){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type!=="custom"||entry.customType!==VIRTUAL_MODEL_STATE_ENTRY)continue;let data=entry.data;if(data?.provider===provider&&data.modelId===modelId)return data.state}}function createVirtualModel(definition){let levels=definition.thinkingLevels??["off"],thinkingLevelMap={};for(let level of THINKING_LEVELS)thinkingLevelMap[level]=levels.includes(level)?level:null;return{id:definition.id,name:definition.name,api:VIRTUAL_MODEL_API,provider:definition.provider,baseUrl:"",reasoning:levels.some(level=>level!=="off"),thinkingLevelMap,input:definition.input??["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:definition.contextWindow??0,maxTokens:definition.maxTokens??0}}function unroutedStream(model){return lazyStream(model,async()=>{throw new Error(`Virtual model ${model.provider}/${model.id} must be routed before streaming`)})}function withVirtualModels(providerId,provider,virtualModels){if(!provider)return{id:providerId,name:providerId,auth:{apiKey:{name:"Virtual model",resolve:async()=>({auth:{},source:"virtual"})}},getModels:()=>virtualModels,stream:unroutedStream,streamSimple:unroutedStream};let ids=new Set(virtualModels.map(model=>model.id)),physical=models=>models.filter(model=>!isVirtualModel(model)&&!(isModelType(model,"chat")&&ids.has(model.id))),virtual=models=>models.filter(model=>isVirtualModel(model)),{filterModels,filterAllModels}=provider;return{...provider,getModels:()=>[...physical(provider.getModels()),...virtualModels],getAllModels:()=>[...physical(provider.getAllModels?.()??provider.getModels()),...virtualModels],filterModels:(models,credential)=>{let real=physical(models);return[...filterModels?.(real,credential)??real,...virtual(models)]},filterAllModels:filterAllModels&&((models,credential)=>[...filterAllModels(physical(models),credential),...virtual(models)]),stream:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.stream(model,context,options),streamSimple:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.streamSimple(model,context,options)}}var ENVIRONMENT_CONTEXT_MESSAGE_TYPE="environment-context";function resolveEnvironmentContext(cwd,now=new Date){return{cwd:cwd.replace(/\\/g,"/"),currentDate:now.toISOString().slice(0,10)}}function formatEnvironmentContext(context){return["<environment_context>",` <cwd>${context.cwd}</cwd>`,` <current_date>${context.currentDate}</current_date>`,"</environment_context>"].join(`
|
|
3
3
|
`)}function isEnvironmentContext(value){if(typeof value!="object"||value===null)return!1;let candidate=value;return typeof candidate.cwd=="string"&&typeof candidate.currentDate=="string"}function latestEnvironmentContext(messages){for(let index=messages.length-1;index>=0;index--){let message=messages[index];if(message.role==="custom"&&message.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&isEnvironmentContext(message.details))return message.details}}function createEnvironmentContextMessage(context,timestamp=Date.now()){return{role:"custom",customType:ENVIRONMENT_CONTEXT_MESSAGE_TYPE,content:formatEnvironmentContext(context),display:!1,details:{cwd:context.cwd,currentDate:context.currentDate},timestamp}}function environmentContextMessageIfChanged(messages,current){let latest=latestEnvironmentContext(messages);if(!(latest?.cwd===current.cwd&&latest.currentDate===current.currentDate))return createEnvironmentContextMessage(current)}function contentBlocks(content){return typeof content=="string"?[{type:"text",text:content}]:content}function foldEnvironmentContextIntoNextUserMessage(messages,environmentMessages){let folded=[];for(let index=0;index<messages.length;index++){let message=messages[index],next=messages[index+1];if(environmentMessages.has(message)&&message.role==="user"&&next?.role==="user"&&!environmentMessages.has(next)){folded.push({...next,content:[...contentBlocks(message.content),...contentBlocks(next.content)]}),index++;continue}folded.push(message)}return folded}var PROVIDER_IMAGE_REJECTION_PATTERN=/does not represent a valid image|image_parse_error|invalid_image|unsupported image|could not process image|unable to process input image|image_url'?\.?[^\n]*invalid base64|expected a base64-encoded data url|image was specified using the image\/[a-z]+ media type|unsupported media type for base64 image|invalid data url for image/i;function isProviderImageRejection(errorMessage){return errorMessage!==void 0&&PROVIDER_IMAGE_REJECTION_PATTERN.test(errorMessage)}function rejectedImagePlaceholder(source){return`[Image omitted: the provider rejected this image (${source}) as invalid, so it is no longer sent with the conversation.]`}function field(message,key){return key in message?message[key]:void 0}function contentBlocks2(message){let content=field(message,"content");return Array.isArray(content)?content:[]}function toolCallSource(block){let args=block.arguments;if(typeof args!="object"||args===null)return;let record=args;for(let key of["path","file_path","filePath"]){let value=record[key];if(typeof value=="string"&&value.trim().length>0)return value}}function imageSource(message,toolCallSources){if(message.role!=="toolResult")return"an attached image";let toolCallId=field(message,"toolCallId"),known=typeof toolCallId=="string"?toolCallSources.get(toolCallId):void 0;if(known)return known;let toolName=field(message,"toolName");return typeof toolName=="string"?`${toolName} tool result`:"a tool result"}function scanRejectedImages(messages){let toolCallSources=new Map,rejections=new Map,unconfirmed=[];return messages.forEach((message,messageIndex)=>{if(message.role==="assistant"){for(let block of contentBlocks2(message)){let source=block.type==="toolCall"?toolCallSource(block):void 0;source&&typeof block.id=="string"&&toolCallSources.set(block.id,source)}let stopReason=field(message,"stopReason"),errorMessage=field(message,"errorMessage");stopReason==="error"&&isProviderImageRejection(typeof errorMessage=="string"?errorMessage:void 0)?(unconfirmed.length>0&&rejections.set(messageIndex,unconfirmed),unconfirmed=[]):stopReason!=="error"&&stopReason!=="aborted"&&(unconfirmed=[]);return}message.role!=="user"&&message.role!=="toolResult"||contentBlocks2(message).forEach((block,blockIndex)=>{block.type==="image"&&unconfirmed.push({messageIndex,blockIndex,source:imageSource(message,toolCallSources)})})}),rejections}function rejectedImageSources(messages,failedTurn){let failedIndex=messages.lastIndexOf(failedTurn);return(scanRejectedImages(messages).get(failedIndex)??[]).map(image=>image.source)}function omitProviderRejectedImages(messages){let rejected=new Map;for(let images of scanRejectedImages(messages).values())for(let image of images){let blocks=rejected.get(image.messageIndex)??new Map;blocks.set(image.blockIndex,image.source),rejected.set(image.messageIndex,blocks)}return rejected.size===0?messages:messages.map((message,messageIndex)=>{let blocks=rejected.get(messageIndex);if(!blocks)return message;let content=contentBlocks2(message).map((block,blockIndex)=>{let source=blocks.get(blockIndex);return source===void 0?block:{type:"text",text:rejectedImagePlaceholder(source)}});return{...message,content}})}function isUserWord(value){return typeof value=="object"&&value!==null&&"label"in value&&typeof value.label=="string"&&"text"in value&&typeof value.text=="string"}function toolResultUserWords(message){let details=message.details;return typeof details!="object"||details===null||!("userWords"in details)?[]:Array.isArray(details.userWords)?details.userWords.filter(isUserWord):[]}function userWordBlocks(words){return words.flatMap(word=>[{type:"text",text:`[${word.label}]`},{type:"text",text:word.text}])}function appendToolResultUserWords(messages){if(!messages.some(message=>message.role==="toolResult"&&toolResultUserWords(message).length>0))return messages;let result=[],pending=[],source,flush=next=>{source&&!startsWithBlocks(next,pending)&&result.push(wordMessage(pending,source)),pending=[],source=void 0};for(let message of messages){if(message.role!=="toolResult"&&flush(message),result.push(message),message.role!=="toolResult")continue;let blocks=userWordBlocks(toolResultUserWords(message));blocks.length!==0&&(pending.push(...blocks),source=message)}return flush(void 0),result}function wordMessage(content,source){let message={role:"user",content,timestamp:source.timestamp},provenance=getContextProvenance(source);if(!provenance)return message;let{integrity,...owned}=provenance;if(!(integrity===void 0||integrity===contextProvenanceFingerprint(source)))return message;let sealed=integrity===void 0?owned:{...owned,integrity:contextProvenanceFingerprint(message)};return Object.assign(message,{[CONTEXT_PROVENANCE_FIELD]:sealed})}function startsWithBlocks(message,blocks){if(message?.role!=="user"||typeof message.content=="string")return!1;let content=message.content;return blocks.every((block,index)=>{let candidate=content[index];return candidate?.type==="text"&&candidate.text===block.text})}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
|
|
4
4
|
|
|
5
5
|
<summary>
|
|
@@ -16,7 +16,7 @@ ${msg.output}
|
|
|
16
16
|
|
|
17
17
|
Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(text+=`
|
|
18
18
|
|
|
19
|
-
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"system":case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(appendToolResultUserWords(dropFailedAssistantTurns(omitProviderRejectedImages(converted))),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,IMAGE_ELISION_PLACEHOLDER="[Image elided: an older image was removed to keep the request within the provider's size limit. Re-read the source file if you need to view it again.]",BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,limitHistory=maxHistoricalImages!==void 0,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),imagesToElide=new Set,keptImages=0,keptHistoricalImages=0,imageBytes=0,cutoffReached=!1;for(let messageIndex=messages.length-1;messageIndex>=0;messageIndex--){let message=messages[messageIndex];if(!(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)))for(let blockIndex=message.content.length-1;blockIndex>=0;blockIndex--){let block=message.content[blockIndex];if(block.type!=="image")continue;let isCurrentTurn=limitHistory&&messageIndex>lastAssistantIndex,isProtectedHistory=limitHistory&&!isCurrentTurn&&keptHistoricalImages<maxHistoricalImages;if(limitHistory&&!isCurrentTurn&&!isProtectedHistory||cutoffReached&&!isCurrentTurn&&!isProtectedHistory){imagesToElide.add(`${messageIndex}:${blockIndex}`);continue}if(isCurrentTurn||isProtectedHistory||keptImages<alwaysKeepNewest||imageBytes+block.data.length<=budgetBytes){keptImages++,isCurrentTurn||keptHistoricalImages++,imageBytes+=block.data.length;continue}cutoffReached=!0,imagesToElide.add(`${messageIndex}:${blockIndex}`)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)))return message;let replaced=message.content.map((block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)?{type:"text",text:IMAGE_ELISION_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,IMAGE_ELISION_PLACEHOLDER)}})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID as randomUUID2}from"crypto";import{appendFileSync,closeSync as closeSync3,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync as openSync3,readdirSync,readFileSync as readFileSync2,readSync as readSync2,rmSync as rmSync4,statSync as statSync2,writeFileSync as writeFileSync3}from"fs";import{appendFile as appendFile2,open as open2,readdir as readdir2,rm as rm3}from"fs/promises";import{join as join5,resolve as resolve2}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";import{existsSync}from"fs";import{readdir}from"fs/promises";import{join as join2}from"path";import{stat as stat2}from"fs/promises";import{resolve}from"path";import{open}from"fs/promises";import{StringDecoder}from"string_decoder";import{execFile}from"node:child_process";var REPOSITORY_IDENTITY_ENTRY_TYPE="repository-identity",GIT_TIMEOUT_MS=5e3,COMMIT_HASH=/^[0-9a-f]{40,64}$/,GIT_LOCATION_ENV=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"]),runGit=(dir,args)=>new Promise(resolve5=>{let env=Object.fromEntries(Object.entries(process.env).filter(([name])=>!GIT_LOCATION_ENV.has(name)));execFile("git",["-C",dir,...args],{env,timeout:GIT_TIMEOUT_MS,windowsHide:!0},(error,stdout)=>{resolve5(error?void 0:stdout)})});async function readRepositoryIdentity(dir,run=runGit){let[roots,origin]=await Promise.all([run(dir,["rev-list","--max-parents=0","HEAD"]),run(dir,["config","--get","remote.origin.url"])]),rootCommits=(roots??"").split(/\s+/).filter(line=>COMMIT_HASH.test(line)).sort(),originUrl=origin?.trim()?normalizeRemoteUrl(origin):void 0;if(!(rootCommits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits}:{rootCommits,originUrl}}function normalizeRemoteUrl(url){let trimmed=url.trim(),scpLike=/^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/.exec(trimmed);return(scpLike?`${scpLike[1]}/${scpLike[2]}`:trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").replace(/^[^@/]+@/,"").replace(/^([^/:]+):\d+\//,"$1/")).replace(/\/+$/,"").replace(/\.git$/i,"").toLowerCase()}function compareRepositoryIdentities(a,b){return a===void 0||b===void 0?"unknown":a.rootCommits.length>0&&b.rootCommits.length>0?a.rootCommits.some(commit=>b.rootCommits.includes(commit))?"same":"different":a.originUrl!==void 0&&b.originUrl!==void 0?a.originUrl===b.originUrl?"same":"different":"unknown"}function parseRepositoryIdentity(value){if(typeof value!="object"||value===null)return;let{rootCommits,originUrl}=value;if(!Array.isArray(rootCommits)||!rootCommits.every(commit=>typeof commit=="string")||originUrl!==void 0&&typeof originUrl!="string")return;let commits=rootCommits.filter(commit=>COMMIT_HASH.test(commit)).sort();if(!(commits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits:commits}:{rootCommits:commits,originUrl}}function sameRepositoryIdentity(a,b){return a===void 0||b===void 0?a===b:a.originUrl===b.originUrl&&a.rootCommits.join(",")===b.rootCommits.join(",")}function parseEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function isMessageWithContent(message){return typeof message=="object"&&message!==null&&typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function visibleMessage(entry){if(entry.type!=="message")return null;let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return null;let messageTime=message.timestamp,entryTime=Date.parse(entry.timestamp),time=typeof messageTime=="number"?messageTime:Number.isNaN(entryTime)?void 0:entryTime;return{text:extractTextContent(message),role:message.role,time}}function sessionInfoName(entry){return entry.type!=="session_info"?null:entry.name?.trim()||void 0}function newAccumulator(){return{header:null,name:void 0,firstUserMessage:"",messageCount:0,lastActivityTime:void 0,repositoryIdentity:void 0,texts:[]}}function accumulateLine(accumulator,line){let entry=parseEntryLine(line);if(!entry)return!0;if(!accumulator.header)return entry.type!=="session"||typeof entry.id!="string"?!1:(accumulator.header=entry,!0);if(entry.type==="custom"&&entry.customType===REPOSITORY_IDENTITY_ENTRY_TYPE)return accumulator.repositoryIdentity=parseRepositoryIdentity(entry.data)??accumulator.repositoryIdentity,!0;let infoName=sessionInfoName(entry);if(infoName!==null)return accumulator.name=infoName,!0;if(entry.type!=="message")return!0;accumulator.messageCount++;let visible=visibleMessage(entry);return!visible||(typeof visible.time=="number"&&(accumulator.lastActivityTime=Math.max(accumulator.lastActivityTime??0,visible.time)),!visible.text)||(accumulator.texts.push(visible.text),!accumulator.firstUserMessage&&visible.role==="user"&&(accumulator.firstUserMessage=visible.text)),!0}var LINE_READ_BUFFER_SIZE=1024*1024;async function readFileLines(filePath,onLine){let handle=await open(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(LINE_READ_BUFFER_SIZE),pending="",bytes=0,lastByte=-1,emit=line=>onLine(line.endsWith("\r")?line.slice(0,-1):line);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;bytes+=bytesRead,lastByte=buffer[bytesRead-1]??-1;let searchFrom=pending.length;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
19
|
+
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"system":case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(appendToolResultUserWords(dropFailedAssistantTurns(omitProviderRejectedImages(converted))),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,IMAGE_ELISION_PLACEHOLDER="[Image elided: an older image was removed to keep the request within the provider's size limit. Re-read the source file if you need to view it again.]",BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,limitHistory=maxHistoricalImages!==void 0,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),imagesToElide=new Set,keptImages=0,keptHistoricalImages=0,imageBytes=0,cutoffReached=!1;for(let messageIndex=messages.length-1;messageIndex>=0;messageIndex--){let message=messages[messageIndex];if(!(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)))for(let blockIndex=message.content.length-1;blockIndex>=0;blockIndex--){let block=message.content[blockIndex];if(block.type!=="image")continue;let isCurrentTurn=limitHistory&&messageIndex>lastAssistantIndex,isProtectedHistory=limitHistory&&!isCurrentTurn&&keptHistoricalImages<maxHistoricalImages;if(limitHistory&&!isCurrentTurn&&!isProtectedHistory||cutoffReached&&!isCurrentTurn&&!isProtectedHistory){imagesToElide.add(`${messageIndex}:${blockIndex}`);continue}if(isCurrentTurn||isProtectedHistory||keptImages<alwaysKeepNewest||imageBytes+block.data.length<=budgetBytes){keptImages++,isCurrentTurn||keptHistoricalImages++,imageBytes+=block.data.length;continue}cutoffReached=!0,imagesToElide.add(`${messageIndex}:${blockIndex}`)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)))return message;let replaced=message.content.map((block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)?{type:"text",text:IMAGE_ELISION_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,IMAGE_ELISION_PLACEHOLDER)}})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID as randomUUID2}from"crypto";import{appendFileSync,closeSync as closeSync3,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync as openSync3,readdirSync,readFileSync as readFileSync2,readSync as readSync2,rmSync as rmSync4,statSync as statSync2,writeFileSync as writeFileSync3}from"fs";import{appendFile as appendFile2,open as open2,readdir as readdir2,rm as rm3}from"fs/promises";import{join as join5,resolve as resolve2}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";function sessionCwdMatcher(resolvedCwd){let mapped=new Map;return cwd=>{if(cwd===void 0||cwd==="")return!1;if(resolvePath(cwd)===resolvedCwd)return!0;let target=mapped.get(cwd);return target===void 0&&(target=resolvePath(resolveMovedPath(cwd)),mapped.set(cwd,target)),target===resolvedCwd}}import{existsSync}from"fs";import{readdir}from"fs/promises";import{join as join2}from"path";import{stat as stat2}from"fs/promises";import{resolve}from"path";import{open}from"fs/promises";import{StringDecoder}from"string_decoder";import{execFile}from"node:child_process";var REPOSITORY_IDENTITY_ENTRY_TYPE="repository-identity",GIT_TIMEOUT_MS=5e3,COMMIT_HASH=/^[0-9a-f]{40,64}$/,GIT_LOCATION_ENV=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"]),runGit=(dir,args)=>new Promise(resolve5=>{let env=Object.fromEntries(Object.entries(process.env).filter(([name])=>!GIT_LOCATION_ENV.has(name)));execFile("git",["-C",dir,...args],{env,timeout:GIT_TIMEOUT_MS,windowsHide:!0},(error,stdout)=>{resolve5(error?void 0:stdout)})});async function readRepositoryIdentity(dir,run=runGit){let[roots,origin]=await Promise.all([run(dir,["rev-list","--max-parents=0","HEAD"]),run(dir,["config","--get","remote.origin.url"])]),rootCommits=(roots??"").split(/\s+/).filter(line=>COMMIT_HASH.test(line)).sort(),originUrl=origin?.trim()?normalizeRemoteUrl(origin):void 0;if(!(rootCommits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits}:{rootCommits,originUrl}}function normalizeRemoteUrl(url){let trimmed=url.trim(),scpLike=/^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/.exec(trimmed);return(scpLike?`${scpLike[1]}/${scpLike[2]}`:trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").replace(/^[^@/]+@/,"").replace(/^([^/:]+):\d+\//,"$1/")).replace(/\/+$/,"").replace(/\.git$/i,"").toLowerCase()}function compareRepositoryIdentities(a,b){return a===void 0||b===void 0?"unknown":a.rootCommits.length>0&&b.rootCommits.length>0?a.rootCommits.some(commit=>b.rootCommits.includes(commit))?"same":"different":a.originUrl!==void 0&&b.originUrl!==void 0?a.originUrl===b.originUrl?"same":"different":"unknown"}function parseRepositoryIdentity(value){if(typeof value!="object"||value===null)return;let{rootCommits,originUrl}=value;if(!Array.isArray(rootCommits)||!rootCommits.every(commit=>typeof commit=="string")||originUrl!==void 0&&typeof originUrl!="string")return;let commits=rootCommits.filter(commit=>COMMIT_HASH.test(commit)).sort();if(!(commits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits:commits}:{rootCommits:commits,originUrl}}function sameRepositoryIdentity(a,b){return a===void 0||b===void 0?a===b:a.originUrl===b.originUrl&&a.rootCommits.join(",")===b.rootCommits.join(",")}function parseEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function isMessageWithContent(message){return typeof message=="object"&&message!==null&&typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function visibleMessage(entry){if(entry.type!=="message")return null;let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return null;let messageTime=message.timestamp,entryTime=Date.parse(entry.timestamp),time=typeof messageTime=="number"?messageTime:Number.isNaN(entryTime)?void 0:entryTime;return{text:extractTextContent(message),role:message.role,time}}function sessionInfoName(entry){return entry.type!=="session_info"?null:entry.name?.trim()||void 0}function newAccumulator(){return{header:null,name:void 0,firstUserMessage:"",messageCount:0,lastActivityTime:void 0,repositoryIdentity:void 0,texts:[]}}function accumulateLine(accumulator,line){let entry=parseEntryLine(line);if(!entry)return!0;if(!accumulator.header)return entry.type!=="session"||typeof entry.id!="string"?!1:(accumulator.header=entry,!0);if(entry.type==="custom"&&entry.customType===REPOSITORY_IDENTITY_ENTRY_TYPE)return accumulator.repositoryIdentity=parseRepositoryIdentity(entry.data)??accumulator.repositoryIdentity,!0;let infoName=sessionInfoName(entry);if(infoName!==null)return accumulator.name=infoName,!0;if(entry.type!=="message")return!0;accumulator.messageCount++;let visible=visibleMessage(entry);return!visible||(typeof visible.time=="number"&&(accumulator.lastActivityTime=Math.max(accumulator.lastActivityTime??0,visible.time)),!visible.text)||(accumulator.texts.push(visible.text),!accumulator.firstUserMessage&&visible.role==="user"&&(accumulator.firstUserMessage=visible.text)),!0}var LINE_READ_BUFFER_SIZE=1024*1024;async function readFileLines(filePath,onLine){let handle=await open(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(LINE_READ_BUFFER_SIZE),pending="",bytes=0,lastByte=-1,emit=line=>onLine(line.endsWith("\r")?line.slice(0,-1):line);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;bytes+=bytesRead,lastByte=buffer[bytesRead-1]??-1;let searchFrom=pending.length;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
20
20
|
`,searchFrom);for(;newlineIndex!==-1;){if(!emit(pending.slice(lineStart,newlineIndex)))return{completed:!1,bytes,endsWithNewline:!1};lineStart=newlineIndex+1,newlineIndex=pending.indexOf(`
|
|
21
21
|
`,lineStart)}pending=pending.slice(lineStart)}return pending+=decoder.end(),pending&&!emit(pending)?{completed:!1,bytes,endsWithNewline:!1}:{completed:!0,bytes,endsWithNewline:lastByte===10}}finally{await handle.close()}}async function readSessionSummary(filePath){let accumulator=newAccumulator();try{if(!(await readFileLines(filePath,line=>accumulateLine(accumulator,line))).completed)return null}catch(error){if(error instanceof Error)return null;throw error}let header=accumulator.header;return header?{header,name:accumulator.name,firstUserMessage:accumulator.firstUserMessage,messageCount:accumulator.messageCount,lastActivityTime:accumulator.lastActivityTime,allMessagesText:accumulator.texts.join(" "),...accumulator.repositoryIdentity?{repositoryIdentity:accumulator.repositoryIdentity}:{}}:null}import{stat}from"fs/promises";import{basename,join}from"path";import{appendFile,rename,rm,writeFile}from"fs/promises";var SESSION_SUMMARY_INDEX_FILE=".session-summaries.index",INDEX_VERSION=2,HEADER_LINE=`${JSON.stringify({version:INDEX_VERSION})}
|
|
22
22
|
`,UNUSABLE={usable:!1,entries:new Map,entryBytes:0,endsWithNewline:!0};function isObject(value){return typeof value=="object"&&value!==null}function isOptional(value,type){return value===void 0||typeof value===type}function isSessionSummary(value){return!isObject(value)||!isObject(value.header)?!1:value.header.type==="session"&&typeof value.header.id=="string"&&typeof value.firstUserMessage=="string"&&typeof value.messageCount=="number"&&typeof value.allMessagesText=="string"&&isOptional(value.name,"string")&&isOptional(value.lastActivityTime,"number")&&(value.repositoryIdentity===void 0||parseRepositoryIdentity(value.repositoryIdentity)!==void 0)}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}function toIndexEntry(file,stamp,summary){if(!(summary.lastActivityTime!==void 0&&!Number.isFinite(summary.lastActivityTime)))return withLine(file,stamp,summary,`${JSON.stringify({file,size:stamp.size,mtimeMs:stamp.mtimeMs,summary})}
|
|
@@ -27,14 +27,14 @@ Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(t
|
|
|
27
27
|
`,lineStart);for(;newlineIndex!==-1;){let entry=parseSessionEntryLine(pending.slice(lineStart,newlineIndex));entry&&entries.push(entry),lineStart=newlineIndex+1,newlineIndex=pending.indexOf(`
|
|
28
28
|
`,lineStart)}pending=pending.slice(lineStart)}pending+=decoder.end();let finalEntry=parseSessionEntryLine(pending);finalEntry&&entries.push(finalEntry)}finally{closeSync3(fd)}if(entries.length===0)return entries;let header=entries[0];return header.type!=="session"||typeof header.id!="string"?[]:entries}function parseSessionHeaderCandidate(line){if(!line.trim())return;let entry=parseSessionEntryLine(line);if(entry)return entry.type!=="session"||typeof entry.id!="string"?null:entry}function readSessionHeader(filePath){let fd=openSync3(filePath,"r");try{let decoder=new StringDecoder2("utf8"),buffer=Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE),lineChunks=[],scannedBytes=0;for(;scannedBytes<MAX_SESSION_HEADER_SCAN_BYTES;){let readLength=Math.min(buffer.length,MAX_SESSION_HEADER_SCAN_BYTES-scannedBytes),bytesRead=readSync2(fd,buffer,0,readLength,null);if(bytesRead===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;scannedBytes+=bytesRead;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
|
|
29
29
|
`,lineStart);for(;newlineIndex!==-1;){lineChunks.push(chunk.slice(lineStart,newlineIndex));let header=parseSessionHeaderCandidate(lineChunks.join(""));if(header!==void 0)return header;lineChunks.length=0,lineStart=newlineIndex+1,newlineIndex=chunk.indexOf(`
|
|
30
|
-
`,lineStart)}lineChunks.push(chunk.slice(lineStart))}let probe=Buffer.allocUnsafe(1);if(readSync2(fd,probe,0,probe.length,null)===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;throw new SessionHeaderScanLimitError(filePath)}finally{closeSync3(fd)}}function readSessionHeaderForDiscovery(filePath){try{return readSessionHeader(filePath)}catch{return null}}function getSessionHeaderCwd(header){let cwd=header.cwd;return typeof cwd=="string"?cwd:void 0}function
|
|
30
|
+
`,lineStart)}lineChunks.push(chunk.slice(lineStart))}let probe=Buffer.allocUnsafe(1);if(readSync2(fd,probe,0,probe.length,null)===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;throw new SessionHeaderScanLimitError(filePath)}finally{closeSync3(fd)}}function readSessionHeaderForDiscovery(filePath){try{return readSessionHeader(filePath)}catch{return null}}function getSessionHeaderCwd(header){let cwd=header.cwd;return typeof cwd=="string"?cwd:void 0}function findMostRecentSession(sessionDir,cwd){let resolvedSessionDir=normalizePath(sessionDir),matchesCwd=cwd?sessionCwdMatcher(resolvePath(cwd)):void 0;try{let files=readdirSync(resolvedSessionDir).filter(file=>file.endsWith(".jsonl")).map(file=>join5(resolvedSessionDir,file)).map(path2=>({path:path2,mtime:statSync2(path2).mtimeMs})).sort((a,b)=>b.mtime-a.mtime);for(let{path:path2}of files){let header=readSessionHeaderForDiscovery(path2);if(header&&(!matchesCwd||matchesCwd(getSessionHeaderCwd(header))))return path2}return null}catch{return null}}var sessionEntryLoader=loadEntriesFromFile;var SETUP_ONLY_ENTRY_TYPES=new Set(["session","model_change","model_change_rejected","thinking_level_change"]);function isConversationEntry(entry){return entry.type==="message"&&(entry.message.role==="user"||entry.message.role==="assistant")}var SessionManager=class _SessionManager{constructor(cwd,sessionDir,sessionFile,persist,newSessionOptions,preloadedFileEntries){this.sessionId="",this.flushed=!1,this.tailMayBeTorn=!1,this.fileEntries=[],this.byId=new Map,this.entryOrdersById=new Map,this.messageEntryPositions=new WeakMap,this.labelsById=new Map,this.labelTimestampsById=new Map,this.leafId=null,this.residentStore=new ResidentStringStore,this.mirrorTrimmed=!1,this.trimmedIds=new Set,this.idsInUse={has:id=>this.byId.has(id)||this.trimmedIds.has(id)},this.fullEntryCount=0,this.compactEntriesCache=null,this.compactView=null,this.projectionMemo=null,this.historyView=null,this.compactLookup=null,this.mutationCount=0,this.entriesCache=null,this.branchCache=null,this.sessionNameCache=void 0,this.usageTotals={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,latestCacheHitRate:void 0},this.cwd=resolvePath(cwd),this.sessionDir=normalizePath(sessionDir),this.persist=persist,persist&®isterSessionWriter(this),persist&&this.sessionDir&&!existsSync3(this.sessionDir)&&mkdirSync2(this.sessionDir,{recursive:!0}),this.residentStore.configure({blobsDir:()=>this.persist&&this.sessionId?join5(this.sessionDir,"resident-blobs",this.sessionId):void 0}),sessionFile?this._setSessionFile(sessionFile,preloadedFileEntries,newSessionOptions):preloadedFileEntries?.length?this._loadEntries(preloadedFileEntries,newSessionOptions):this.newSession(newSessionOptions)}reloadFromDisk(){if(!this.sessionFile||!existsSync3(this.sessionFile))return;let fileEntries=loadEntriesFromFile(this.sessionFile);if(fileEntries.length===0){if(statSync2(this.sessionFile).size===0)return;throw new Error(`Session file is not a valid ${APP_NAME} session: ${this.sessionFile}`)}this._setSessionFile(this.sessionFile,fileEntries)}setSessionFile(sessionFile){this._setSessionFile(sessionFile)}_setSessionFile(sessionFile,preloadedFileEntries,newSessionOptions){if(this.persist&&reserveSessionWrite(resolvePath(sessionFile)),this.sessionFile=resolvePath(sessionFile),this.mirrorTrimmed=!1,this.trimmedIds.clear(),this.residentStore.clear(),existsSync3(this.sessionFile)){let entries=preloadedFileEntries??loadEntriesFromFile(this.sessionFile);if(entries.length===0){let explicitPath=this.sessionFile;if(statSync2(explicitPath).size>0)throw new Error(`Session file is not a valid ${APP_NAME} session: ${explicitPath}`);this._resetToNewSession(newSessionOptions),this._rewriteFile(),this.flushed=!0;return}this.fileEntries=entries;let header=this.fileEntries.find(e=>e.type==="session");this.sessionId=header?.id??createSessionId(),this._releaseBlobsDirUnlessShared(),migrateToCurrentVersion(this.fileEntries)&&this._rewriteFile(),this.fileEntries=this.fileEntries.map(entry=>this.residentStore.externalize(entry)),this._buildIndex(),this.mutationCount++,this.flushed=!0}else this._resetToNewSession(newSessionOptions),newSessionOptions?.id!==void 0&&(this._rewriteFile(),this.flushed=!0)}newSession(options){let timestamp=this._resetToNewSession(options);if(this.persist){let fileTimestamp=timestamp.replace(/[:.]/g,"-"),path2=join5(this.getSessionDir(),`${fileTimestamp}_${this.sessionId}.jsonl`);reserveSessionWrite(path2),this.sessionFile=path2}return this.sessionFile}_resetToNewSession(options){options?.id!==void 0&&assertValidSessionId(options.id);let previousBlobsDir=this.residentStore.resolvedBlobsDir();this.sessionId=options?.id??createSessionId();let timestamp=new Date().toISOString(),header={type:"session",version:CURRENT_SESSION_VERSION,id:this.sessionId,timestamp,cwd:this.cwd,parentSession:options?.parentSession};return this.fileEntries=[header],this.mirrorTrimmed=!1,this.trimmedIds.clear(),this.fullEntryCount=0,this.residentStore.clear(),previousBlobsDir&&this._removeBlobsDir(previousBlobsDir),this.byId.clear(),this.entryOrdersById.clear(),this.messageEntryPositions=new WeakMap,this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.sessionNameCache=void 0,this.usageTotals={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,latestCacheHitRate:void 0},this.mutationCount++,this.flushed=!1,timestamp}_loadEntries(entries,options){let header=entries.find(e=>e.type==="session");header?(this.fileEntries=entries,this.sessionId=header.id,migrateToCurrentVersion(this.fileEntries)&&this._rewriteFile()):(this.newSession(options),this.fileEntries=this.fileEntries.concat(entries)),this.fileEntries=this.fileEntries.map(entry=>this.residentStore.externalize(entry)),this._buildIndex(),this.mutationCount++}_buildIndex(){this.byId.clear(),this.entryOrdersById.clear(),this.messageEntryPositions=new WeakMap,this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.sessionNameCache=void 0,this.usageTotals={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,latestCacheHitRate:void 0};let fullEntryCount=0;for(let[order,entry]of this.fileEntries.entries())entry.type!=="session"&&(fullEntryCount++,this.byId.set(entry.id,entry),this.entryOrdersById.set(entry.id,order),this.leafId=entry.id,this._accumulateUsage(entry),entry.type==="session_info"&&(this.sessionNameCache=entry.name?.trim()||void 0),entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId))));this.mirrorTrimmed||(this.fullEntryCount=fullEntryCount)}_rewriteFile(){!this.persist||!this.sessionFile||(reserveSessionWrite(this.sessionFile),replaceFileAtomically(this.sessionFile,this._serializedFileEntries()))}*_serializedFileEntries(){for(let entry of this.fileEntries)yield`${JSON.stringify(this.residentStore.materialize(entry))}
|
|
31
31
|
`}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return this.sessionDir===getDefaultSessionDirPath(this.cwd)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}getResidentStore(){return this.residentStore}getResidentStoreStats(){return this.residentStore.stats()}persistHeaderNow(){if(!this.persist||!this.sessionFile||this.flushed)return this.headerWrite??Promise.resolve();let sessionFile=this.sessionFile;return this.headerWrite??=this._writeHeaderAsync(sessionFile).finally(()=>{this.headerWrite=void 0}),this.headerWrite}isTranscriptFlushed(){return this.flushed}async discardHeaderOnlyFile(){return await this.headerWrite,!this.persist||!this.sessionFile||!this.flushed||!this.fileEntries.every(entry=>SETUP_ONLY_ENTRY_TYPES.has(entry.type))?!1:(await rm3(this.sessionFile,{force:!0}),this.flushed=!1,!0)}async _writeHeaderAsync(sessionFile){reserveSessionWrite(sessionFile);let entries=this.fileEntries,serialize=batch=>batch.map(e=>`${JSON.stringify(this.residentStore.materialize(e))}
|
|
32
32
|
`).join(""),written=0,handle=await open2(sessionFile,"wx");try{for(;written<entries.length;){let batch=entries.slice(written);written+=batch.length,await handle.writeFile(serialize(batch))}let closing=handle;for(handle=void 0,await closing.close();written<entries.length&&this.sessionFile===sessionFile&&this.fileEntries===entries;){let batch=entries.slice(written);written+=batch.length,await appendFile2(sessionFile,serialize(batch))}}catch(error){return discardFailedFirstFlushAsync(sessionFile,handle,error)}this.sessionFile===sessionFile&&this.fileEntries===entries&&written===entries.length&&(this.flushed=!0)}_hasConversation(){return this.fileEntries.some(isConversationEntry)}_persist(entry){if(!this.persist||!this.sessionFile)return;reserveSessionWrite(this.sessionFile);let persistedEntry=this.residentStore.materialize(entry);if(this.flushed){this.tailMayBeTorn&&(truncateToLastCompleteLine(this.sessionFile),this.tailMayBeTorn=!1);try{appendFileSync(this.sessionFile,`${JSON.stringify(persistedEntry)}
|
|
33
33
|
`)}catch(error){throw this.tailMayBeTorn=!0,error}return}if(!isConversationEntry(entry)&&!this._hasConversation()||this.headerWrite)return;let fd=openSync3(this.sessionFile,"wx");try{for(let e of[...this.fileEntries,entry])writeFileSync3(fd,`${JSON.stringify(this.residentStore.materialize(e))}
|
|
34
34
|
`)}catch(error){discardFailedFirstFlush(this.sessionFile,fd,error)}closeSync3(fd),this.flushed=!0}_appendEntry(entry,shareable){let residentEntry=this.residentStore.externalize(entry);this._persist(residentEntry),this._commitEntry(this._shareMessage(residentEntry,shareable))}_shareMessage(residentEntry,shareable){if(shareable===void 0||residentEntry.type!=="message"||!this.residentStore.isTokenFree(residentEntry)||!isPlainJson(shareable))return residentEntry;let shared={...residentEntry,message:{...shareable}};return this.residentStore.adoptTokenFree(shared),shared}_commitEntry(residentEntry){this.fileEntries.push(residentEntry),this.byId.set(residentEntry.id,residentEntry),this.entryOrdersById.set(residentEntry.id,this.fileEntries.length-1),this.leafId=residentEntry.id,this.fullEntryCount++,this._accumulateUsage(residentEntry),this.mutationCount++}appendEntry(entry){this._appendEntry(entry);let order=this.entryOrdersById.get(entry.id);entry.type==="message"&&order!==void 0&&this.messageEntryPositions.set(entry.message,{entryId:entry.id,order}),entry.type==="session_info"&&(this.sessionNameCache=entry.name?.trim()||void 0),entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId)))}_materializeEntry(entry){let missingResidentString=!1,materialized=this.residentStore.materialize(entry,()=>{missingResidentString=!0});if(missingResidentString&&this.sessionFile){let persisted=loadEntriesFromFile(this.sessionFile).find(candidate=>candidate.id===entry.id);if(persisted)return persisted}if(materialized.type==="message"){let order=this.entryOrdersById.get(materialized.id);order!==void 0&&this.messageEntryPositions.set(materialized.message,{entryId:materialized.id,order})}return materialized}_accumulateUsage(entry){if(entry.type!=="message"||entry.message.role!=="assistant")return;let usage=entry.message.usage;if(!usage)return;this.usageTotals.input+=usage.input,this.usageTotals.output+=usage.output,this.usageTotals.cacheRead+=usage.cacheRead,this.usageTotals.cacheWrite+=usage.cacheWrite,this.usageTotals.cost+=usage.cost?.total??0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite;this.usageTotals.latestCacheHitRate=latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}getUsageTotals(){return this.usageTotals}appendMessage(message){return this._appendMessage(message,!1)}appendOwnedMessage(message){return this._appendMessage(message,!0)}_appendMessage(message,owned){let entry={type:"message",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),message};this._appendEntry(entry,owned?message:void 0);let order=this.entryOrdersById.get(entry.id);return order!==void 0&&this.messageEntryPositions.set(message,{entryId:entry.id,order}),entry.id}getMessageEntryPosition(message){return this.messageEntryPositions.get(message)}getEntryOrder(entryId){return this.entryOrdersById.get(entryId)}appendThinkingLevelChange(thinkingLevel,thinkingSelection,trigger){let entry={type:"thinking_level_change",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel,thinkingSelection,...trigger===void 0?{}:{triggerSource:trigger.source},...trigger?.actor===void 0?{}:{triggerActor:trigger.actor}};return this._appendEntry(entry),entry.id}appendConfigurationUpdate(effort){let entry={type:"configuration_update",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),reasoning:{effort}};return this._appendEntry(entry),entry.id}appendModelChangeRejected(details){let entry={type:"model_change_rejected",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),...details};return this._appendEntry(entry),entry.id}appendModelChange(provider,modelId,reason,originalProvider,originalModelId,attribution){let entry={type:"model_change",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),provider,modelId,reason,originalProvider,originalModelId,...attribution===void 0?{}:{source:attribution.origin.source},...attribution?.origin.actor===void 0?{}:{actor:attribution.origin.actor},...attribution?.duringTurn?{duringTurn:!0}:{}};return this._appendEntry(entry),entry.id}appendUsage(kind,provider,model,usage,note){let entry={type:"usage",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),kind,provider,model,usage,...note?{note}:{}};return this._appendEntry(entry),entry}appendCompaction(summary,firstKeptEntryId,tokensBefore,details,fromHook,usage){let timestamp=new Date().toISOString(),systemMessage=getCurrentSystemMessage(this.buildSessionProjection().messages),id=generateId(this.idsInUse),entry={type:"compaction",id,parentId:this.leafId,timestamp,summary,firstKeptEntryId:firstKeptEntryId??id,tokensBefore,details,usage,fromHook,...systemMessage?{systemMessage:{...systemMessage,timestamp:new Date(timestamp).getTime()}}:{}};return this._appendEntry(entry),this._trimMirrorAfterCompaction(entry),entry.id}dispose(){unregisterSessionWriter(this),this._releaseBlobsDirUnlessShared()}_releaseBlobsDirUnlessShared(){let blobsDir=this.residentStore.resolvedBlobsDir();blobsDir&&(this.sessionFile&&hasOtherLiveSessionWriter(this.sessionFile,this)||this._removeBlobsDir(blobsDir))}_removeBlobsDir(dir){try{rmSync4(dir,{force:!0,recursive:!0})}catch{}}_trimMirrorAfterCompaction(compaction){if(!this.persist)return;let firstKeptIndex=this.fileEntries.findIndex(entry=>entry.id===compaction.firstKeptEntryId),compactionIndex=this.fileEntries.findIndex(entry=>entry.id===compaction.id);if(firstKeptIndex<0||compactionIndex<firstKeptIndex)return;let header=this.fileEntries.find(entry=>entry.type==="session"),retained=[...this.fileEntries.slice(0,firstKeptIndex).filter(entry=>entry.type!=="message"),...this.fileEntries.slice(firstKeptIndex,compactionIndex+1)],parentId=null;for(let entry of retained)entry.type!=="session"&&(entry.parentId=parentId),parentId=entry.type==="session"?null:entry.id;let retainedIds=new Set(retained.map(entry=>entry.id));for(let entry of this.fileEntries)entry.type!=="session"&&!retainedIds.has(entry.id)&&this.trimmedIds.add(entry.id);this.residentStore.spillResident(),this.mirrorTrimmed=!0,this.fileEntries=[header,...retained].filter(entry=>entry!==void 0).map(entry=>this.residentStore.externalize(entry)),this._buildIndex(),this.mutationCount++}appendCustomEntry(customType,data){let entry={type:"custom",customType,data,id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendSessionInfo(name){let sanitizedName=name.replace(/[\r\n]+/g," ").trim(),entry={type:"session_info",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),name:sanitizedName};return this._appendEntry(entry),this.sessionNameCache=sanitizedName||void 0,entry.id}getSessionName(){return this.sessionNameCache}appendCustomMessageEntry(customType,content,display,details){let entry={type:"custom_message",customType,content,display,details,id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendContextEdit(targetId,replacement){if(replacement!==null&&(typeof replacement!="object"||!("content"in replacement)||typeof replacement.content!="string"&&!Array.isArray(replacement.content)))throw new Error("Context edit replacement must be null or contain string/array content");let target=this.byId.get(targetId);if(!target)throw new Error(`Entry ${targetId} not found`);if(!this.getBranch().some(entry2=>entry2.id===targetId))throw new Error(`Entry ${targetId} is not on the active branch`);if(!(target.type==="custom_message"||target.type==="message"&&(target.message.role==="user"||target.message.role==="assistant"||target.message.role==="toolResult")))throw new Error(`Entry ${targetId} does not contribute editable model content`);let targetRole=target.type==="message"?target.message.role:"custom",normalizedReplacement=replacement!==null&&(targetRole==="assistant"||targetRole==="toolResult")&&typeof replacement.content=="string"?{content:[{type:"text",text:replacement.content}]}:replacement,entry={type:"context_edit",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,replacement:normalizedReplacement};return this._appendEntry(entry),entry.id}getLeafId(){return this.leafId}getLeafEntry(){let entry=this.leafId?this.byId.get(this.leafId):void 0;return entry?this._materializeEntry(entry):void 0}getEntry(id){let entry=this.byId.get(id);if(entry)return this._materializeEntry(entry);if(this.mirrorTrimmed&&this.sessionFile){let persisted=this._loadFullHistoryEntries().find(candidate=>candidate.id===id);return persisted?this.residentStore.materialize(persisted):void 0}}getChildren(parentId){let children=[];for(let entry of this.byId.values())entry.parentId===parentId&&children.push(this._materializeEntry(entry));return children}getLabel(id){return this.labelsById.get(id)}appendLabelChange(targetId,label){if(!this.byId.has(targetId))throw new Error(`Entry ${targetId} not found`);let entry={type:"label",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,label};return this._appendEntry(entry),label?(this.labelsById.set(targetId,label),this.labelTimestampsById.set(targetId,entry.timestamp)):(this.labelsById.delete(targetId),this.labelTimestampsById.delete(targetId)),entry.id}getBranch(fromId){if(fromId===void 0&&this.branchCache!==null&&this.branchCache.leafId===this.leafId&&this.branchCache.mutation===this.mutationCount)return this.branchCache.entries;if(fromId===void 0){let extended=this._extendBranchCache();if(extended!==void 0)return extended}let path2=[],startId=fromId??this.leafId,entriesById=this.byId;fromId!==void 0&&!entriesById.has(fromId)&&this.mirrorTrimmed&&this.sessionFile&&(entriesById=new Map(this._loadFullHistoryEntries().filter(entry=>entry.type!=="session").map(entry=>[entry.id,this.residentStore.materialize(entry)])));let current=startId?entriesById.get(startId):void 0,visited=new Set;for(;current&&!visited.has(current);)visited.add(current),path2.push(current),current=current.parentId?entriesById.get(current.parentId):void 0;path2.reverse();let materializedPath=(entriesById===this.byId?this._fromCompactView(path2):void 0)??this._materializeEntries(path2);return fromId===void 0&&(this.branchCache={leafId:this.leafId,mutation:this.mutationCount,entries:materializedPath,source:this.fileEntries}),materializedPath}_extendBranchCache(){let cache2=this.branchCache;if(cache2===null||cache2.source!==this.fileEntries||cache2.leafId===null)return;let added=[],current=this.leafId?this.byId.get(this.leafId):void 0;for(;current&¤t.id!==cache2.leafId;){if(added.length>=256)return;added.push(current),current=current.parentId?this.byId.get(current.parentId):void 0}if(current===void 0)return;added.reverse();let entries=[...cache2.entries,...this._fromCompactView(added)??this._materializeEntries(added)];return this.branchCache={leafId:this.leafId,mutation:this.mutationCount,entries,source:this.fileEntries},entries}buildContextEntries(){return buildContextEntries(this._getCompactEntries(),this.leafId)}buildSessionProjection(){let{projection}=this._projectCurrent();return{...projection,messages:[...projection.messages],entries:[...projection.entries]}}_projectCurrent(){let entries=this._getCompactEntries(),memo=this.projectionMemo;if(memo?.source===entries&&memo.leafId===this.leafId)return memo.result;let path2=this._extendPath(memo,entries)??buildSessionPath(entries,this.leafId),result=projectSession(entries,this.leafId,void 0,path2);return this.projectionMemo={source:entries,leafId:this.leafId,path:path2,result},result}_extendPath(memo,entries){if(!memo||memo.leafId===null||this.leafId===null)return;let previous=memo.source;if(entries.length<=previous.length||entries[previous.length-1]!==previous[previous.length-1])return;let parentId=memo.leafId,appended=[];for(let index=previous.length;index<entries.length;index++){let entry=entries[index];if(entry.parentId!==parentId)return;appended.push(entry),parentId=entry.id}if(parentId===this.leafId)return[...memo.path,...appended]}buildSessionContext(){let{projection,settings}=this._projectCurrent(),{thinkingLevel,thinkingSelection,model,configurationUpdate}=settings;return{messages:[...projection.messages],thinkingLevel,thinkingSelection,model,configurationUpdate}}hasContextMessages(){return this.hasBranchEntry(entry=>entry.type==="message"||entry.type==="custom_message"||entry.type==="compaction"||entry.type==="branch_summary"&&!!entry.summary)}hasThinkingLevelChanges(){return this.hasBranchEntry(entry=>entry.type==="thinking_level_change")}countCompactions(){let count=0;for(let entry of this.fileEntries)entry.type==="compaction"&&count++;return count}hasBranchEntry(predicate){let current=this.leafId?this.byId.get(this.leafId):void 0,visited=new Set;for(;current&&!visited.has(current);){if(predicate(current))return!0;visited.add(current),current=current.parentId?this.byId.get(current.parentId):void 0}return!1}getHeader(){let h=this.fileEntries.find(e=>e.type==="session");return h?this.residentStore.materialize(h):null}getEntries(){if(this.mirrorTrimmed&&this.sessionFile){let extended=this._extendView(this.historyView);if(extended!==void 0)return this.historyView={source:this.fileEntries,length:this.fileEntries.length,entries:extended},extended;let history=this._loadFullHistoryEntries().filter(e=>e.type!=="session").map(entry=>this.residentStore.materialize(entry));return this.historyView={source:this.fileEntries,length:this.fileEntries.length,entries:history},history}if(this.entriesCache!==null&&this.entriesCache.mutation===this.mutationCount)return this.entriesCache.entries;let materializedEntries=this._getCompactEntries();return this.entriesCache={mutation:this.mutationCount,entries:materializedEntries},materializedEntries}getEntryCount(){return this.fullEntryCount}dropMaterializedCaches(){this.entriesCache=null,this.branchCache=null,this.compactEntriesCache=null,this.compactView=null,this.historyView=null,this.compactLookup=null,this.projectionMemo=null}holdsMaterializedHistory(){return this.historyView!==null}_extendView(view){if(view===null||view.source!==this.fileEntries||view.length>this.fileEntries.length)return;if(view.length===this.fileEntries.length)return view.entries;let missing=!1,tail=[];for(let entry of this.fileEntries.slice(view.length)){if(entry.type==="session")continue;let materialized=this.residentStore.materialize(entry,()=>{missing=!0});tail.push(materialized)}if(!missing)return this._bindMessagePositions(tail),[...view.entries,...tail]}_fromCompactView(path2){let entries=this._getCompactEntries(),lookup=this.compactLookup;(lookup===null||lookup.length>entries.length||lookup.length>0&&lookup.entries[lookup.length-1]!==entries[lookup.length-1])&&(lookup={entries,length:0,map:new Map});for(let index=lookup.length;index<entries.length;index++){let entry=entries[index];lookup.map.set(entry.id,entry)}this.compactLookup={entries,length:entries.length,map:lookup.map};let shared=[];for(let entry of path2){let materialized=lookup.map.get(entry.id);if(materialized===void 0||materialized.parentId!==entry.parentId)return;shared.push(materialized)}return shared}_bindMessagePositions(entries){for(let entry of entries){if(entry.type!=="message")continue;let order=this.entryOrdersById.get(entry.id);order!==void 0&&this.messageEntryPositions.set(entry.message,{entryId:entry.id,order})}}_materializeEntries(entries){return materializeSessionEntries(entries,{residentStore:this.residentStore,loadHistoryEntries:()=>this._loadFullHistoryEntries(),onMaterialized:entry=>{if(entry.type!=="message")return;let order=this.entryOrdersById.get(entry.id);order!==void 0&&this.messageEntryPositions.set(entry.message,{entryId:entry.id,order})}})}_getCompactEntries(){let extended=this._extendView(this.compactView);if(extended!==void 0)return this.compactView={source:this.fileEntries,length:this.fileEntries.length,entries:extended},extended;this.compactEntriesCache?.mutation!==this.mutationCount&&(this.compactEntriesCache={mutation:this.mutationCount,entries:this.fileEntries.filter(e=>e.type!=="session")});let entries=this.compactEntriesCache.entries,missingEntryIds=new Set;for(let entry of entries)this.residentStore.materialize(entry,()=>{missingEntryIds.add(entry.id)});if(missingEntryIds.size>0&&this.sessionFile){let persistedById=new Map(this._loadFullHistoryEntries().map(entry=>[entry.id,entry]));for(let index=0;index<entries.length;index++){let entry=entries[index];if(!missingEntryIds.has(entry.id))continue;let persisted=persistedById.get(entry.id);persisted&&(entries[index]=this.residentStore.externalize(persisted))}}let materialized=entries.map(entry=>this.residentStore.materialize(entry));return this._bindMessagePositions(materialized),this.compactView={source:this.fileEntries,length:this.fileEntries.length,entries:materialized},materialized}_loadFullHistoryEntries(){return this.sessionFile?sessionEntryLoader(this.sessionFile):this.fileEntries}getTree(){let entries=this.getEntries(),nodeMap=new Map,roots=[];for(let entry of entries){if(nodeMap.has(entry.id))continue;let label=this.labelsById.get(entry.id),labelTimestamp=this.labelTimestampsById.get(entry.id);nodeMap.set(entry.id,{entry,children:[],label,labelTimestamp})}for(let entry of entries){let node=nodeMap.get(entry.id);if(node.entry===entry)if(entry.parentId===null||entry.parentId===entry.id)roots.push(node);else{let parent=nodeMap.get(entry.parentId);parent?parent.children.push(node):roots.push(node)}}let stack=[...roots];for(;stack.length>0;){let node=stack.pop();node.children.sort((a,b)=>new Date(a.entry.timestamp).getTime()-new Date(b.entry.timestamp).getTime()),stack.push(...node.children)}return roots}branch(branchFromId){if(!this.byId.has(branchFromId)&&this.sessionFile&&this.reloadFromDisk(),!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);this.leafId=branchFromId,this.mutationCount++}resetLeaf(){this.leafId=null,this.mutationCount++}branchWithSummary(branchFromId,summary,details,fromHook,usage){if(branchFromId!==null&&!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);let fromId=this.leafId??"root",entry={type:"branch_summary",id:generateId(this.idsInUse),parentId:branchFromId,timestamp:new Date().toISOString(),fromId,summary,details,usage,fromHook};return this._appendEntry(entry),entry.id}createBranchedSession(leafId){let previousSessionFile=this.sessionFile,path2=this.getBranch(leafId);if(path2.length===0)throw new Error(`Entry ${leafId} not found`);let pathWithoutLabels=[],replacementByLabelId=new Map,pendingLabelIds=[],pathParentId=null;for(let entry of path2){if(entry.type==="label"){pendingLabelIds.push(entry.id);continue}for(let labelId of pendingLabelIds)replacementByLabelId.set(labelId,entry.id);pendingLabelIds.length=0,pathWithoutLabels.push(entry.type==="compaction"?{...entry,parentId:pathParentId,firstKeptEntryId:entry.firstKeptEntryId===entry.id?entry.id:replacementByLabelId.get(entry.firstKeptEntryId)??entry.firstKeptEntryId}:{...entry,parentId:pathParentId}),pathParentId=entry.id}let newSessionId=createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join5(this.getSessionDir(),`${fileTimestamp}_${newSessionId}.jsonl`),header={type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:this.cwd,parentSession:this.persist?previousSessionFile:void 0},pathEntryIds=new Set(pathWithoutLabels.map(e=>e.id)),labelsToWrite=[];for(let[targetId,label]of this.labelsById)pathEntryIds.has(targetId)&&labelsToWrite.push({targetId,label,timestamp:this.labelTimestampsById.get(targetId)});if(this.persist){let parentId2=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null,labelEntries2=[];for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set(pathEntryIds)),parentId:parentId2,timestamp:labelTimestamp,targetId,label};pathEntryIds.add(labelEntry.id),labelEntries2.push(labelEntry),parentId2=labelEntry.id}reserveSessionWrite(newSessionFile);let branchedEntries2=this._materializeEntries([...pathWithoutLabels,...labelEntries2]),previousBlobsDir=this.residentStore.resolvedBlobsDir();return this.residentStore.clear(),previousBlobsDir&&this._removeBlobsDir(previousBlobsDir),this.mirrorTrimmed=!1,this.trimmedIds.clear(),this.sessionId=newSessionId,this.sessionFile=newSessionFile,this.fileEntries=[header,...branchedEntries2.map(entry=>this.residentStore.externalize(entry))],this._buildIndex(),this.mutationCount++,this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,newSessionFile}let labelEntries=[],parentId=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null;for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set([...pathEntryIds,...labelEntries.map(e=>e.id)])),parentId,timestamp:labelTimestamp,targetId,label};labelEntries.push(labelEntry),parentId=labelEntry.id}let branchedEntries=this._materializeEntries([...pathWithoutLabels,...labelEntries]);this.residentStore.clear(),this.fileEntries=[header,...branchedEntries.map(entry=>this.residentStore.externalize(entry))],this.sessionId=newSessionId,this._buildIndex(),this.mutationCount++}static create(cwd,sessionDir,options){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd);return new _SessionManager(cwd,dir,void 0,!0,options)}static open(path2,sessionDir,cwdOverride,options){let resolvedPath=resolvePath(path2);reserveSessionWrite(resolvedPath);let header=null,preloadedFileEntries;if(cwdOverride===void 0&&existsSync3(resolvedPath))try{header=readSessionHeader(resolvedPath)}catch(error){if(!(error instanceof SessionHeaderScanLimitError))throw error;preloadedFileEntries=loadEntriesFromFile(resolvedPath);let firstEntry=preloadedFileEntries[0];header=firstEntry?.type==="session"?firstEntry:null}if(existsSync3(resolvedPath)){let content=readFileSync2(resolvedPath);content.length>0&&content[content.length-1]!==10&&appendFileSync(resolvedPath,`
|
|
35
|
-
`)}let
|
|
35
|
+
`)}let headerCwd=header?getSessionHeaderCwd(header):void 0,cwd=cwdOverride??(headerCwd&&resolveMovedPath(headerCwd))??process.cwd(),dir=sessionDir?normalizePath(sessionDir):resolve2(resolvedPath,"..");return new _SessionManager(cwd,dir,resolvedPath,!0,options,preloadedFileEntries)}static continueRecent(cwd,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),filterCwd=sessionDir!==void 0&&dir!==getDefaultSessionDirPath(cwd),mostRecent=findMostRecentSession(dir,filterCwd?cwd:void 0);return mostRecent?new _SessionManager(cwd,dir,mostRecent,!0):new _SessionManager(cwd,dir,void 0,!0)}static inMemory(cwd=process.cwd(),options,entries){return new _SessionManager(cwd,"",void 0,!1,options,entries)}static forkFrom(sourcePath,targetCwd,sessionDir,options){let resolvedSourcePath=resolvePath(sourcePath),resolvedTargetCwd=resolvePath(targetCwd),sourceEntries=loadEntriesFromFile(resolvedSourcePath);if(sourceEntries.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);if(!sourceEntries.find(e=>e.type==="session"))throw new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(resolvedTargetCwd);existsSync3(dir)||mkdirSync2(dir,{recursive:!0}),options?.id!==void 0&&assertValidSessionId(options.id);let newSessionId=options?.id??createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join5(dir,`${fileTimestamp}_${newSessionId}.jsonl`),newHeader={type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:resolvedTargetCwd,parentSession:resolvedSourcePath};reserveSessionWrite(newSessionFile),writeFileSync3(newSessionFile,`${JSON.stringify(newHeader)}
|
|
36
36
|
`,{flag:"wx"});for(let entry of sourceEntries)entry.type!=="session"&&appendFileSync(newSessionFile,`${JSON.stringify(entry)}
|
|
37
|
-
`);return new _SessionManager(resolvedTargetCwd,dir,newSessionFile,!0)}static findById(cwd,id,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),filterCwd=sessionDir!==void 0&&dir!==getDefaultSessionDirPath(cwd),resolvedCwd=resolvePath(cwd);try{for(let file of readdirSync(dir)){if(!file.endsWith(".jsonl"))continue;let path2=join5(dir,file),header=readSessionHeaderForDiscovery(path2);if(header?.id===id&&!(filterCwd&&!sessionCwdMatches(getSessionHeaderCwd(header),resolvedCwd)))return path2}}catch{}}static async list(cwd,sessionDir,onProgress,signal){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),filterCwd=sessionDir!==void 0&&dir!==getDefaultSessionDirPath(cwd),resolvedCwd=resolvePath(cwd),includeSession=session=>!filterCwd||sessionCwdMatches(session.cwd,resolvedCwd),sessions=(await listSessionsFromDir(dir,onProgress?(loaded,total,partialSessions)=>onProgress(loaded,total,partialSessions?.filter(includeSession)):void 0,signal)).filter(includeSession);return sortSessionInfos(sessions)}static async listAll(sessionDirOrOnProgress,onProgressOrSignal,signal){let customSessionDir=typeof sessionDirOrOnProgress=="string"?normalizePath(sessionDirOrOnProgress):void 0,progress=typeof sessionDirOrOnProgress=="function"?sessionDirOrOnProgress:typeof onProgressOrSignal=="function"?onProgressOrSignal:void 0,abortSignal=typeof sessionDirOrOnProgress=="string"||typeof onProgressOrSignal=="function"?signal:onProgressOrSignal??signal;if(abortSignal?.throwIfAborted(),customSessionDir)return sortSessionInfos(await listSessionsFromDir(customSessionDir,progress,abortSignal));let sessionsDir=getSessionsDir();try{if(!existsSync3(sessionsDir))return[];let dirs=(await readdir2(sessionsDir,{withFileTypes:!0})).filter(entry=>entry.isDirectory()||entry.isSymbolicLink()).map(entry=>join5(sessionsDir,entry.name)),totalFiles=0,dirFiles=[];for(let dir of dirs)try{let files=(await readdir2(dir)).filter(f=>f.endsWith(".jsonl"));dirFiles.push(files.map(f=>join5(dir,f))),totalFiles+=files.length}catch{dirFiles.push([])}let loaded=0,partialSessions=[],onLoaded=info=>{loaded++,info&&partialSessions.push(info);let publish=loaded===1||loaded%ALL_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===totalFiles;progress?.(loaded,totalFiles,publish?sortSessionInfos([...partialSessions]):void 0)},sessions=[];for(let[index,dir]of dirs.entries())sessions.push(...await listSessionFilesInDir(dir,dirFiles[index]??[],onLoaded,abortSignal));return sortSessionInfos(sessions)}catch{return abortSignal?.throwIfAborted(),[]}}};var DynamicBorder=class{constructor(color=str=>theme.fg("border",str)){this.revision=nextRenderRevision(),this.color=color}invalidate(){this.revision=nextRenderRevision()}getRenderRevision(){return this.revision}render(width){return[this.color("\u2500".repeat(Math.max(1,width)))]}};var KEY_DISPLAY_ALIASES=new Map([["escape","esc"]]);function formatKeyPart(part,options){let lowerPart=part.toLowerCase(),displayPart=KEY_DISPLAY_ALIASES.get(lowerPart)??(process.platform==="darwin"&&lowerPart==="alt"?"option":part);return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}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 existsSync5,globSync,mkdirSync as mkdirSync3,readdirSync as readdirSync3,readFileSync as readFileSync5,rmSync as rmSync5,statSync as statSync4,writeFileSync as writeFileSync4}from"node:fs";import{homedir}from"node:os";var import_ignore2=__toESM(require_ignore(),1);import{basename as basename3,dirname as dirname2,join as join7,relative as relative2,resolve as resolve3,sep as sep3}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 assertValidPattern=pattern=>{if(typeof pattern!="string")throw new TypeError("invalid pattern");if(pattern.length>65536)throw new TypeError("pattern is too long")};var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},braceEscape=s=>s.replace(/[[\]\\-]/g,"\\$&"),regexpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),rangesToString=ranges=>ranges.join(""),parseClass=(glob,position)=>{let pos=position;if(glob.charAt(pos)!=="[")throw new Error("not in a brace expression");let ranges=[],negs=[],i=pos+1,sawStart=!1,uflag=!1,escaping=!1,negate=!1,endPos=pos,rangeStart="";WHILE:for(;i<glob.length;){let c=glob.charAt(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,u,neg]]of Object.entries(posixClasses))if(glob.startsWith(cls,i)){if(rangeStart)return["$.",!1,glob.length-pos,!0];i+=cls.length,neg?negs.push(unip):ranges.push(unip),uflag=uflag||u;continue WHILE}}if(escaping=!1,rangeStart){c>rangeStart?ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c)):c===rangeStart&&ranges.push(braceEscape(c)),rangeStart="",i++;continue}if(glob.startsWith("-]",i+1)){ranges.push(braceEscape(c+"-")),i+=2;continue}if(glob.startsWith("-",i+1)){rangeStart=c,i+=2;continue}ranges.push(braceEscape(c)),i++}if(endPos<i)return["",!1,0,!1];if(!ranges.length&&!negs.length)return["$.",!1,glob.length-pos,!0];if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){let r=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r),!1,endPos-pos,!1]}let sranges="["+(negate?"^":"")+rangesToString(ranges)+"]",snegs="["+(negate?"":"^")+rangesToString(negs)+"]";return[ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs,uflag,endPos-pos,!0]};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 _a,types=new Set(["!","?","+","*","@"]),isExtglobType=c=>types.has(c),isExtglobAST=c=>isExtglobType(c.type),adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))",startNoDot="(?!\\.)",addPatternStart=new Set(["[","."]),justDots=new Set(["..","."]),reSpecials=new Set("().*{}+?[]^$\\!"),regExpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),qmark="[^/]",star=qmark+"*?",starNoEmpty=qmark+"+?",ID=0,AST=class{type;#root;#hasMagic;#uflag=!1;#parts=[];#parent;#parentIndex;#negs;#filledNegs=!1;#options;#toString;#emptyExt=!1;id=++ID;get depth(){return(this.#parent?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#root.id,parent:this.#parent?.id,depth:this.depth,partsLength:this.#parts.length,parts:this.#parts}}constructor(type,parent,options={}){this.type=type,type&&(this.#hasMagic=!0),this.#parent=parent,this.#root=this.#parent?this.#parent.#root:this,this.#options=this.#root===this?options:this.#root.#options,this.#negs=this.#root===this?[]:this.#root.#negs,type==="!"&&!this.#root.#filledNegs&&this.#negs.push(this),this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(let p of this.#parts)if(typeof p!="string"&&(p.type||p.hasMagic))return this.#hasMagic=!0;return this.#hasMagic}toString(){return this.#toString!==void 0?this.#toString:this.type?this.#toString=this.type+"("+this.#parts.map(p=>String(p)).join("|")+")":this.#toString=this.#parts.map(p=>String(p)).join("")}#fillNegs(){if(this!==this.#root)throw new Error("should only call on root");if(this.#filledNegs)return this;this.toString(),this.#filledNegs=!0;let n;for(;n=this.#negs.pop();){if(n.type!=="!")continue;let p=n,pp=p.#parent;for(;pp;){for(let i=p.#parentIndex+1;!pp.type&&i<pp.#parts.length;i++)for(let part of n.#parts){if(typeof part=="string")throw new Error("string part in extglob AST??");part.copyIn(pp.#parts[i])}p=pp,pp=p.#parent}}return this}push(...parts){for(let p of parts)if(p!==""){if(typeof p!="string"&&!(p instanceof _a&&p.#parent===this))throw new Error("invalid part: "+p);this.#parts.push(p)}}toJSON(){let ret=this.type===null?this.#parts.slice().map(p=>typeof p=="string"?p:p.toJSON()):[this.type,...this.#parts.map(p=>p.toJSON())];return this.isStart()&&!this.type&&ret.unshift([]),this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type==="!")&&ret.push({}),ret}isStart(){if(this.#root===this)return!0;if(!this.#parent?.isStart())return!1;if(this.#parentIndex===0)return!0;let p=this.#parent;for(let i=0;i<this.#parentIndex;i++){let pp=p.#parts[i];if(!(pp instanceof _a&&pp.type==="!"))return!1}return!0}isEnd(){if(this.#root===this||this.#parent?.type==="!")return!0;if(!this.#parent?.isEnd())return!1;if(!this.type)return this.#parent?.isEnd();let pl=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===pl-1}copyIn(part){typeof part=="string"?this.push(part):this.push(part.clone(this))}clone(parent){let c=new _a(this.type,parent);for(let p of this.#parts)c.copyIn(p);return c}static#parseAST(str,ast,pos,opt,extDepth){let maxDepth=opt.maxExtglobRecursion??2,escaping=!1,inBrace=!1,braceStart=-1,braceNeg=!1;if(ast.type===null){let i2=pos,acc2="";for(;i2<str.length;){let c=str.charAt(i2++);if(escaping||c==="\\"){escaping=!escaping,acc2+=c;continue}if(inBrace){i2===braceStart+1?(c==="^"||c==="!")&&(braceNeg=!0):c==="]"&&!(i2===braceStart+2&&braceNeg)&&(inBrace=!1),acc2+=c;continue}else if(c==="["){inBrace=!0,braceStart=i2,braceNeg=!1,acc2+=c;continue}if(!opt.noext&&isExtglobType(c)&&str.charAt(i2)==="("&&extDepth<=maxDepth){ast.push(acc2),acc2="";let ext2=new _a(c,ast);i2=_a.#parseAST(str,ext2,i2,opt,extDepth+1),ast.push(ext2);continue}acc2+=c}return ast.push(acc2),i2}let i=pos+1,part=new _a(null,ast),parts=[],acc="";for(;i<str.length;){let c=str.charAt(i++);if(escaping||c==="\\"){escaping=!escaping,acc+=c;continue}if(inBrace){i===braceStart+1?(c==="^"||c==="!")&&(braceNeg=!0):c==="]"&&!(i===braceStart+2&&braceNeg)&&(inBrace=!1),acc+=c;continue}else if(c==="["){inBrace=!0,braceStart=i,braceNeg=!1,acc+=c;continue}if(!opt.noext&&isExtglobType(c)&&str.charAt(i)==="("&&(extDepth<=maxDepth||ast&&ast.#canAdoptType(c))){let depthAdd=ast&&ast.#canAdoptType(c)?0:1;part.push(acc),acc="";let ext2=new _a(c,part);part.push(ext2),i=_a.#parseAST(str,ext2,i,opt,extDepth+depthAdd);continue}if(c==="|"){part.push(acc),acc="",parts.push(part),part=new _a(null,ast);continue}if(c===")")return acc===""&&ast.#parts.length===0&&(ast.#emptyExt=!0),part.push(acc),acc="",ast.push(...parts,part),i;acc+=c}return ast.type=null,ast.#hasMagic=void 0,ast.#parts=[str.substring(pos-1)],i}#canAdoptWithSpace(child){return this.#canAdopt(child,adoptionWithSpaceMap)}#canAdopt(child,map=adoptionMap){if(!child||typeof child!="object"||child.type!==null||child.#parts.length!==1||this.type===null)return!1;let gc=child.#parts[0];return!gc||typeof gc!="object"||gc.type===null?!1:this.#canAdoptType(gc.type,map)}#canAdoptType(c,map=adoptionAnyMap){return!!map.get(this.type)?.includes(c)}#adoptWithSpace(child,index){let gc=child.#parts[0],blank=new _a(null,gc,this.options);blank.#parts.push(""),gc.push(blank),this.#adopt(child,index)}#adopt(child,index){let gc=child.#parts[0];this.#parts.splice(index,1,...gc.#parts);for(let p of gc.#parts)typeof p=="object"&&(p.#parent=this);this.#toString=void 0}#canUsurpType(c){return!!usurpMap.get(this.type)?.has(c)}#canUsurp(child){if(!child||typeof child!="object"||child.type!==null||child.#parts.length!==1||this.type===null||this.#parts.length!==1)return!1;let gc=child.#parts[0];return!gc||typeof gc!="object"||gc.type===null?!1:this.#canUsurpType(gc.type)}#usurp(child){let m=usurpMap.get(this.type),gc=child.#parts[0],nt=m?.get(gc.type);if(!nt)return!1;this.#parts=gc.#parts;for(let p of this.#parts)typeof p=="object"&&(p.#parent=this);this.type=nt,this.#toString=void 0,this.#emptyExt=!1}static fromGlob(pattern,options={}){let ast=new _a(null,void 0,options);return _a.#parseAST(pattern,ast,0,options,0),ast}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();let glob=this.toString(),[re,body,hasMagic,uflag]=this.toRegExpSource();if(!(hasMagic||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase()))return body;let flags=(this.#options.nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags),{_src:re,_glob:glob})}get options(){return this.#options}toRegExpSource(allowDot){let dot=allowDot??!!this.#options.dot;if(this.#root===this&&(this.#flatten(),this.#fillNegs()),!isExtglobAST(this)){let noEmpty=this.isStart()&&this.isEnd()&&!this.#parts.some(s=>typeof s!="string"),src=this.#parts.map(p=>{let[re,_,hasMagic,uflag]=typeof p=="string"?_a.#parseGlob(p,this.#hasMagic,noEmpty):p.toRegExpSource(allowDot);return this.#hasMagic=this.#hasMagic||hasMagic,this.#uflag=this.#uflag||uflag,re}).join(""),start2="";if(this.isStart()&&typeof this.#parts[0]=="string"&&!(this.#parts.length===1&&justDots.has(this.#parts[0]))){let aps=addPatternStart,needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4)),needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}let end="";return this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type==="!"&&(end="(?:$|\\/)"),[start2+src+end,unescape(src),this.#hasMagic=!!this.#hasMagic,this.#uflag]}let repeated=this.type==="*"||this.type==="+",start=this.type==="!"?"(?:(?!(?:":"(?:",body=this.#partsToRegExp(dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){let s=this.toString(),me=this;return me.#parts=[s],me.type=null,me.#hasMagic=void 0,[s,unescape(this.toString()),!1,!1]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":this.#partsToRegExp(!0);bodyDotAllowed===body&&(bodyDotAllowed=""),bodyDotAllowed&&(body=`(?:${body})(?:${bodyDotAllowed})*?`);let final="";if(this.type==="!"&&this.#emptyExt)final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty;else{let close=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?")?":`)${this.type}`;final=start+body+close}return[final,unescape(body),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#flatten(){if(isExtglobAST(this)){let iterations=0,done=!1;do{done=!0;for(let i=0;i<this.#parts.length;i++){let c=this.#parts[i];typeof c=="object"&&(c.#flatten(),this.#canAdopt(c)?(done=!1,this.#adopt(c,i)):this.#canAdoptWithSpace(c)?(done=!1,this.#adoptWithSpace(c,i)):this.#canUsurp(c)&&(done=!1,this.#usurp(c)))}}while(!done&&++iterations<10)}else for(let p of this.#parts)typeof p=="object"&&p.#flatten();this.#toString=void 0}#partsToRegExp(dot){return this.#parts.map(p=>{if(typeof p=="string")throw new Error("string type in extglob ast??");let[re,_,_hasMagic,uflag]=p.toRegExpSource(dot);return this.#uflag=this.#uflag||uflag,re}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")}static#parseGlob(glob,hasMagic,noEmpty=!1){let escaping=!1,re="",uflag=!1,inStar=!1;for(let i=0;i<glob.length;i++){let c=glob.charAt(i);if(escaping){escaping=!1,re+=(reSpecials.has(c)?"\\":"")+c;continue}if(c==="*"){if(inStar)continue;inStar=!0,re+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star,hasMagic=!0;continue}else inStar=!1;if(c==="\\"){i===glob.length-1?re+="\\\\":escaping=!0;continue}if(c==="["){let[src,needUflag,consumed,magic]=parseClass(glob,i);if(consumed){re+=src,uflag=uflag||needUflag,i+=consumed-1,hasMagic=hasMagic||magic;continue}}if(c==="?"){re+=qmark,hasMagic=!0;continue}re+=regExpEscape(c)}return[re,unescape(glob),!!hasMagic,uflag]}};_a=AST;var escape=(s,{windowsPathsNoEscape=!1,magicalBraces=!1}={})=>magicalBraces?windowsPathsNoEscape?s.replace(/[?*()[\]{}]/g,"[$&]"):s.replace(/[?*()[\]\\{}]/g,"\\$&"):windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");var minimatch=(p,pattern,options={})=>(assertValidPattern(pattern),!options.nocomment&&pattern.charAt(0)==="#"?!1:new Minimatch(pattern,options).match(p)),starDotExtRE=/^\*+([^+@!?*[(]*)$/,starDotExtTest=ext2=>f=>!f.startsWith(".")&&f.endsWith(ext2),starDotExtTestDot=ext2=>f=>f.endsWith(ext2),starDotExtTestNocase=ext2=>(ext2=ext2.toLowerCase(),f=>!f.startsWith(".")&&f.toLowerCase().endsWith(ext2)),starDotExtTestNocaseDot=ext2=>(ext2=ext2.toLowerCase(),f=>f.toLowerCase().endsWith(ext2)),starDotStarRE=/^\*+\.\*+$/,starDotStarTest=f=>!f.startsWith(".")&&f.includes("."),starDotStarTestDot=f=>f!=="."&&f!==".."&&f.includes("."),dotStarRE=/^\.\*+$/,dotStarTest=f=>f!=="."&&f!==".."&&f.startsWith("."),starRE=/^\*+$/,starTest=f=>f.length!==0&&!f.startsWith("."),starTestDot=f=>f.length!==0&&f!=="."&&f!=="..",qmarksRE=/^\?+([^+@!?*[(]*)?$/,qmarksTestNocase=([$0,ext2=""])=>{let noext=qmarksTestNoExt([$0]);return ext2?(ext2=ext2.toLowerCase(),f=>noext(f)&&f.toLowerCase().endsWith(ext2)):noext},qmarksTestNocaseDot=([$0,ext2=""])=>{let noext=qmarksTestNoExtDot([$0]);return ext2?(ext2=ext2.toLowerCase(),f=>noext(f)&&f.toLowerCase().endsWith(ext2)):noext},qmarksTestDot=([$0,ext2=""])=>{let noext=qmarksTestNoExtDot([$0]);return ext2?f=>noext(f)&&f.endsWith(ext2):noext},qmarksTest=([$0,ext2=""])=>{let noext=qmarksTestNoExt([$0]);return ext2?f=>noext(f)&&f.endsWith(ext2):noext},qmarksTestNoExt=([$0])=>{let len=$0.length;return f=>f.length===len&&!f.startsWith(".")},qmarksTestNoExtDot=([$0])=>{let len=$0.length;return f=>f.length===len&&f!=="."&&f!==".."},defaultPlatform=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&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 qmark2="[^/]",star2=qmark2+"*?",twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?",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}},AST:class extends orig.AST{constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},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)),makeRe:(pattern,options={})=>orig.makeRe(pattern,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 makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;var 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=/[?*]|[+@!]\(.*?\)|\[|\]/,regExpEscape2=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;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.regexp=null,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.make()}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}debug(..._){}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.braceExpand())],options.debug&&(this.debug=(...args)=>console.error(...args)),this.debug(this.pattern,this.globSet);let rawGlobParts=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(rawGlobParts),this.debug(this.pattern,this.globParts);let set=this.globParts.map((s,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){let isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&!globMagic.test(s[3]),isDrive=/^[a-z]:/i.test(s[0]);if(isUNC)return[...s.slice(0,4),...s.slice(4).map(ss=>this.parse(ss))];if(isDrive)return[s[0],...s.slice(1).map(ss=>this.parse(ss))]}return s.map(ss=>this.parse(ss))});if(this.debug(this.pattern,set),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]==="?"&&typeof p[3]=="string"&&/^[a-z]:$/i.test(p[3])&&(p[2]="?")}this.debug(this.pattern,this.set)}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=>(parts=parts.reduce((set,part)=>{let prev=set[set.length-1];return part==="**"&&prev==="**"?set:part===".."&&prev&&prev!==".."&&prev!=="."&&prev!=="**"?(set.pop(),set):(set.push(part),set)},[]),parts.length===0?[""]:parts))}levelTwoFileOptimize(parts){Array.isArray(parts)||(parts=this.slashSplit(parts));let 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 dd=0;for(;(dd=parts.indexOf("..",dd+1))!==-1;){let p=parts[dd-1];p&&p!=="."&&p!==".."&&p!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(p))&&(didSomething=!0,parts.splice(dd-1,2),dd-=2)}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let 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;didSomething=!0,parts.splice(gs,1);let other=parts.slice(0);other[gs]="**",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 dd=0;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-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i=0;i<globParts.length-1;i++)for(let j=i+1;j<globParts.length;j++){let matched=this.partsMatch(globParts[i],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i]=[],globParts[j]=matched;break}}return globParts.filter(gs=>gs.length)}partsMatch(a,b,emptyGSMatch=!1){let ai=0,bi=0,result=[],which="";for(;ai<a.length&&bi<b.length;)if(a[ai]===b[bi])result.push(which==="b"?b[bi]:a[ai]),ai++,bi++;else if(emptyGSMatch&&a[ai]==="**"&&b[bi]===a[ai+1])result.push(a[ai]),ai++;else if(emptyGSMatch&&b[bi]==="**"&&a[ai]===b[bi+1])result.push(b[bi]),bi++;else if(a[ai]==="*"&&b[bi]&&(this.options.dot||!b[bi].startsWith("."))&&b[bi]!=="**"){if(which==="b")return!1;which="a",result.push(a[ai]),ai++,bi++}else if(b[bi]==="*"&&a[ai]&&(this.options.dot||!a[ai].startsWith("."))&&a[ai]!=="**"){if(which==="a")return!1;which="b",result.push(b[bi]),ai++,bi++}else return!1;return a.length===b.length&&result}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}matchOne(file,pattern,partial=!1){let fileStartIndex=0,patternStartIndex=0;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()&&(pattern[pdi]=fd,patternStartIndex=pdi,fileStartIndex=fdi)}}let{optimizationLevel=1}=this.options;return optimizationLevel>=2&&(file=this.levelTwoFileOptimize(file)),pattern.includes(GLOBSTAR)?this.#matchGlobstar(file,pattern,partial,fileStartIndex,patternStartIndex):this.#matchOne(file,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file,pattern,partial,fileIndex,patternIndex){let firstgs=pattern.indexOf(GLOBSTAR,patternIndex),lastgs=pattern.lastIndexOf(GLOBSTAR),[head,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head.length){let fileHead=file.slice(fileIndex,fileIndex+head.length);if(!this.#matchOne(fileHead,head,partial,0,0))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 i2=fileIndex;i2<file.length-fileTailMatch;i2++){let f=String(file[i2]);if(sawSome=!0,f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return partial||sawSome}let bodySegments=[[[],0]],currentBody=bodySegments[0],nonGsParts=0,nonGsPartsSums=[0];for(let b of body)b===GLOBSTAR?(nonGsPartsSums.push(nonGsParts),currentBody=[[],0],bodySegments.push(currentBody)):(currentBody[0].push(b),nonGsParts++);let i=bodySegments.length-1,fileLength=file.length-fileTailMatch;for(let b of bodySegments)b[1]=fileLength-(nonGsPartsSums[i--]+b[0].length);return!!this.#matchGlobStarBodySections(file,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)}#matchGlobStarBodySections(file,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){let bs=bodySegments[bodyIndex];if(!bs){for(let i=fileIndex;i<file.length;i++){sawTail=!0;let f=file[i];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return sawTail}let[body,after]=bs;for(;fileIndex<=after;){if(this.#matchOne(file.slice(0,fileIndex+body.length),body,partial,fileIndex,0)&&globStarDepth<this.maxGlobstarRecursion){let sub=this.#matchGlobStarBodySections(file,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(sub!==!1)return sub}let f=file[fileIndex];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;fileIndex++}return partial||null}#matchOne(file,pattern,partial,fileIndex,patternIndex){let fi,pi,pl,fl;for(fi=fileIndex,pi=patternIndex,fl=file.length,pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){this.debug("matchOne loop");let p=pattern[pi],f=file[fi];if(this.debug(pattern,p,f),p===!1||p===GLOBSTAR)return!1;let hit;if(typeof p=="string"?(hit=f===p,this.debug("string match",p,f,hit)):(hit=p.test(f),this.debug("pattern match",p,f,hit)),!hit)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)}parse(pattern){assertValidPattern(pattern);let options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m,fastTest=null;(m=pattern.match(starRE))?fastTest=options.dot?starTestDot:starTest:(m=pattern.match(starDotExtRE))?fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1]):(m=pattern.match(qmarksRE))?fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m):(m=pattern.match(starDotStarRE))?fastTest=options.dot?starDotStarTestDot:starDotStarTest:(m=pattern.match(dotStarRE))&&(fastTest=dotStarTest);let re=AST.fromGlob(pattern,this.options).toMMPattern();return fastTest&&typeof re=="object"&&Reflect.defineProperty(re,"test",{value:fastTest}),re}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let set=this.set;if(!set.length)return this.regexp=!1,this.regexp;let options=this.options,twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot,flags=new Set(options.nocase?["i"]:[]),re=set.map(pattern=>{let pp=pattern.map(p=>{if(p instanceof RegExp)for(let f of p.flags.split(""))flags.add(f);return typeof p=="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp.forEach((p,i)=>{let next=pp[i+1],prev=pp[i-1];p!==GLOBSTAR||prev===GLOBSTAR||(prev===void 0?next!==void 0&&next!==GLOBSTAR?pp[i+1]="(?:\\/|"+twoStar+"\\/)?"+next:pp[i]=twoStar:next===void 0?pp[i-1]=prev+"(?:\\/|\\/"+twoStar+")?":next!==GLOBSTAR&&(pp[i-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next,pp[i+1]=GLOBSTAR))});let filtered=pp.filter(p=>p!==GLOBSTAR);if(this.partial&&filtered.length>=1){let prefixes=[];for(let i=1;i<=filtered.length;i++)prefixes.push(filtered.slice(0,i).join("/"));return"(?:"+prefixes.join("|")+")"}return filtered.join("/")}).join("|"),[open4,close]=set.length>1?["(?:",")"]:["",""];re="^"+open4+re+close+"$",this.partial&&(re="^(?:\\/|"+open4+re.slice(1,-1)+close+")$"),this.negate&&(re="^(?!"+re+").+$");try{this.regexp=new RegExp(re,[...flags].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(p){return this.preserveMultipleSlashes?p.split("/"):this.isWindows&&/^\/\/[^/]+/.test(p)?["",...p.split(/\/+/)]:p.split(/\/+/)}match(f,partial=this.partial){if(this.debug("match",f,this.pattern),this.comment)return!1;if(this.empty)return f==="";if(f==="/"&&partial)return!0;let options=this.options;this.isWindows&&(f=f.split("\\").join("/"));let ff=this.slashSplit(f);this.debug(this.pattern,"split",ff);let set=this.set;this.debug(this.pattern,"set",set);let filename=ff[ff.length-1];if(!filename)for(let i=ff.length-2;!filename&&i>=0;i--)filename=ff[i];for(let pattern of set){let file=ff;if(options.matchBase&&pattern.length===1&&(file=[filename]),this.matchOne(file,pattern,partial))return options.flipNegate?!0:!this.negate}return options.flipNegate?!1:this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;var import_semver=__toESM(require_semver(),1);import{readFileSync as readFileSync3}from"node:fs";var RESOURCE_FIELDS=["extensions","skills","prompts","themes","hooks"];function isObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg=JSON.parse(stripBom(readFileSync3(packageJsonPath,"utf-8")));if(!isObject2(pkg)||!isObject2(pkg.pi))return null;let manifest={};typeof pkg.pi.system=="boolean"&&(manifest.system=pkg.pi.system);for(let field2 of RESOURCE_FIELDS){let entries=pkg.pi[field2];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field2]=entries)}return manifest}catch{return null}}var import_ignore=__toESM(require_ignore(),1);import{closeSync as closeSync4,existsSync as existsSync4,fstatSync as fstatSync2,openSync as openSync4,readdirSync as readdirSync2,readFileSync as readFileSync4,readSync as readSync3,statSync as statSync3}from"node:fs";import{join as join6,relative,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(`
|
|
37
|
+
`);return new _SessionManager(resolvedTargetCwd,dir,newSessionFile,!0)}static findById(cwd,id,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),filterCwd=sessionDir!==void 0&&dir!==getDefaultSessionDirPath(cwd),matchesCwd=sessionCwdMatcher(resolvePath(cwd));try{for(let file of readdirSync(dir)){if(!file.endsWith(".jsonl"))continue;let path2=join5(dir,file),header=readSessionHeaderForDiscovery(path2);if(header?.id===id&&!(filterCwd&&!matchesCwd(getSessionHeaderCwd(header))))return path2}}catch{}}static async list(cwd,sessionDir,onProgress,signal){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),filterCwd=sessionDir!==void 0&&dir!==getDefaultSessionDirPath(cwd),matchesCwd=sessionCwdMatcher(resolvePath(cwd)),includeSession=session=>!filterCwd||matchesCwd(session.cwd),sessions=(await listSessionsFromDir(dir,onProgress?(loaded,total,partialSessions)=>onProgress(loaded,total,partialSessions?.filter(includeSession)):void 0,signal)).filter(includeSession);return sortSessionInfos(sessions)}static async listAll(sessionDirOrOnProgress,onProgressOrSignal,signal){let customSessionDir=typeof sessionDirOrOnProgress=="string"?normalizePath(sessionDirOrOnProgress):void 0,progress=typeof sessionDirOrOnProgress=="function"?sessionDirOrOnProgress:typeof onProgressOrSignal=="function"?onProgressOrSignal:void 0,abortSignal=typeof sessionDirOrOnProgress=="string"||typeof onProgressOrSignal=="function"?signal:onProgressOrSignal??signal;if(abortSignal?.throwIfAborted(),customSessionDir)return sortSessionInfos(await listSessionsFromDir(customSessionDir,progress,abortSignal));let sessionsDir=getSessionsDir();try{if(!existsSync3(sessionsDir))return[];let dirs=(await readdir2(sessionsDir,{withFileTypes:!0})).filter(entry=>entry.isDirectory()||entry.isSymbolicLink()).map(entry=>join5(sessionsDir,entry.name)),totalFiles=0,dirFiles=[];for(let dir of dirs)try{let files=(await readdir2(dir)).filter(f=>f.endsWith(".jsonl"));dirFiles.push(files.map(f=>join5(dir,f))),totalFiles+=files.length}catch{dirFiles.push([])}let loaded=0,partialSessions=[],onLoaded=info=>{loaded++,info&&partialSessions.push(info);let publish=loaded===1||loaded%ALL_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===totalFiles;progress?.(loaded,totalFiles,publish?sortSessionInfos([...partialSessions]):void 0)},sessions=[];for(let[index,dir]of dirs.entries())sessions.push(...await listSessionFilesInDir(dir,dirFiles[index]??[],onLoaded,abortSignal));return sortSessionInfos(sessions)}catch{return abortSignal?.throwIfAborted(),[]}}};var DynamicBorder=class{constructor(color=str=>theme.fg("border",str)){this.revision=nextRenderRevision(),this.color=color}invalidate(){this.revision=nextRenderRevision()}getRenderRevision(){return this.revision}render(width){return[this.color("\u2500".repeat(Math.max(1,width)))]}};var KEY_DISPLAY_ALIASES=new Map([["escape","esc"]]);function formatKeyPart(part,options){let lowerPart=part.toLowerCase(),displayPart=KEY_DISPLAY_ALIASES.get(lowerPart)??(process.platform==="darwin"&&lowerPart==="alt"?"option":part);return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}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 existsSync5,globSync,mkdirSync as mkdirSync3,readdirSync as readdirSync3,readFileSync as readFileSync5,rmSync as rmSync5,statSync as statSync4,writeFileSync as writeFileSync4}from"node:fs";import{homedir}from"node:os";var import_ignore2=__toESM(require_ignore(),1);import{basename as basename3,dirname as dirname2,join as join7,relative as relative2,resolve as resolve3,sep as sep3}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 assertValidPattern=pattern=>{if(typeof pattern!="string")throw new TypeError("invalid pattern");if(pattern.length>65536)throw new TypeError("pattern is too long")};var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},braceEscape=s=>s.replace(/[[\]\\-]/g,"\\$&"),regexpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),rangesToString=ranges=>ranges.join(""),parseClass=(glob,position)=>{let pos=position;if(glob.charAt(pos)!=="[")throw new Error("not in a brace expression");let ranges=[],negs=[],i=pos+1,sawStart=!1,uflag=!1,escaping=!1,negate=!1,endPos=pos,rangeStart="";WHILE:for(;i<glob.length;){let c=glob.charAt(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,u,neg]]of Object.entries(posixClasses))if(glob.startsWith(cls,i)){if(rangeStart)return["$.",!1,glob.length-pos,!0];i+=cls.length,neg?negs.push(unip):ranges.push(unip),uflag=uflag||u;continue WHILE}}if(escaping=!1,rangeStart){c>rangeStart?ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c)):c===rangeStart&&ranges.push(braceEscape(c)),rangeStart="",i++;continue}if(glob.startsWith("-]",i+1)){ranges.push(braceEscape(c+"-")),i+=2;continue}if(glob.startsWith("-",i+1)){rangeStart=c,i+=2;continue}ranges.push(braceEscape(c)),i++}if(endPos<i)return["",!1,0,!1];if(!ranges.length&&!negs.length)return["$.",!1,glob.length-pos,!0];if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){let r=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r),!1,endPos-pos,!1]}let sranges="["+(negate?"^":"")+rangesToString(ranges)+"]",snegs="["+(negate?"":"^")+rangesToString(negs)+"]";return[ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs,uflag,endPos-pos,!0]};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 _a,types=new Set(["!","?","+","*","@"]),isExtglobType=c=>types.has(c),isExtglobAST=c=>isExtglobType(c.type),adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))",startNoDot="(?!\\.)",addPatternStart=new Set(["[","."]),justDots=new Set(["..","."]),reSpecials=new Set("().*{}+?[]^$\\!"),regExpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),qmark="[^/]",star=qmark+"*?",starNoEmpty=qmark+"+?",ID=0,AST=class{type;#root;#hasMagic;#uflag=!1;#parts=[];#parent;#parentIndex;#negs;#filledNegs=!1;#options;#toString;#emptyExt=!1;id=++ID;get depth(){return(this.#parent?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#root.id,parent:this.#parent?.id,depth:this.depth,partsLength:this.#parts.length,parts:this.#parts}}constructor(type,parent,options={}){this.type=type,type&&(this.#hasMagic=!0),this.#parent=parent,this.#root=this.#parent?this.#parent.#root:this,this.#options=this.#root===this?options:this.#root.#options,this.#negs=this.#root===this?[]:this.#root.#negs,type==="!"&&!this.#root.#filledNegs&&this.#negs.push(this),this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(let p of this.#parts)if(typeof p!="string"&&(p.type||p.hasMagic))return this.#hasMagic=!0;return this.#hasMagic}toString(){return this.#toString!==void 0?this.#toString:this.type?this.#toString=this.type+"("+this.#parts.map(p=>String(p)).join("|")+")":this.#toString=this.#parts.map(p=>String(p)).join("")}#fillNegs(){if(this!==this.#root)throw new Error("should only call on root");if(this.#filledNegs)return this;this.toString(),this.#filledNegs=!0;let n;for(;n=this.#negs.pop();){if(n.type!=="!")continue;let p=n,pp=p.#parent;for(;pp;){for(let i=p.#parentIndex+1;!pp.type&&i<pp.#parts.length;i++)for(let part of n.#parts){if(typeof part=="string")throw new Error("string part in extglob AST??");part.copyIn(pp.#parts[i])}p=pp,pp=p.#parent}}return this}push(...parts){for(let p of parts)if(p!==""){if(typeof p!="string"&&!(p instanceof _a&&p.#parent===this))throw new Error("invalid part: "+p);this.#parts.push(p)}}toJSON(){let ret=this.type===null?this.#parts.slice().map(p=>typeof p=="string"?p:p.toJSON()):[this.type,...this.#parts.map(p=>p.toJSON())];return this.isStart()&&!this.type&&ret.unshift([]),this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type==="!")&&ret.push({}),ret}isStart(){if(this.#root===this)return!0;if(!this.#parent?.isStart())return!1;if(this.#parentIndex===0)return!0;let p=this.#parent;for(let i=0;i<this.#parentIndex;i++){let pp=p.#parts[i];if(!(pp instanceof _a&&pp.type==="!"))return!1}return!0}isEnd(){if(this.#root===this||this.#parent?.type==="!")return!0;if(!this.#parent?.isEnd())return!1;if(!this.type)return this.#parent?.isEnd();let pl=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===pl-1}copyIn(part){typeof part=="string"?this.push(part):this.push(part.clone(this))}clone(parent){let c=new _a(this.type,parent);for(let p of this.#parts)c.copyIn(p);return c}static#parseAST(str,ast,pos,opt,extDepth){let maxDepth=opt.maxExtglobRecursion??2,escaping=!1,inBrace=!1,braceStart=-1,braceNeg=!1;if(ast.type===null){let i2=pos,acc2="";for(;i2<str.length;){let c=str.charAt(i2++);if(escaping||c==="\\"){escaping=!escaping,acc2+=c;continue}if(inBrace){i2===braceStart+1?(c==="^"||c==="!")&&(braceNeg=!0):c==="]"&&!(i2===braceStart+2&&braceNeg)&&(inBrace=!1),acc2+=c;continue}else if(c==="["){inBrace=!0,braceStart=i2,braceNeg=!1,acc2+=c;continue}if(!opt.noext&&isExtglobType(c)&&str.charAt(i2)==="("&&extDepth<=maxDepth){ast.push(acc2),acc2="";let ext2=new _a(c,ast);i2=_a.#parseAST(str,ext2,i2,opt,extDepth+1),ast.push(ext2);continue}acc2+=c}return ast.push(acc2),i2}let i=pos+1,part=new _a(null,ast),parts=[],acc="";for(;i<str.length;){let c=str.charAt(i++);if(escaping||c==="\\"){escaping=!escaping,acc+=c;continue}if(inBrace){i===braceStart+1?(c==="^"||c==="!")&&(braceNeg=!0):c==="]"&&!(i===braceStart+2&&braceNeg)&&(inBrace=!1),acc+=c;continue}else if(c==="["){inBrace=!0,braceStart=i,braceNeg=!1,acc+=c;continue}if(!opt.noext&&isExtglobType(c)&&str.charAt(i)==="("&&(extDepth<=maxDepth||ast&&ast.#canAdoptType(c))){let depthAdd=ast&&ast.#canAdoptType(c)?0:1;part.push(acc),acc="";let ext2=new _a(c,part);part.push(ext2),i=_a.#parseAST(str,ext2,i,opt,extDepth+depthAdd);continue}if(c==="|"){part.push(acc),acc="",parts.push(part),part=new _a(null,ast);continue}if(c===")")return acc===""&&ast.#parts.length===0&&(ast.#emptyExt=!0),part.push(acc),acc="",ast.push(...parts,part),i;acc+=c}return ast.type=null,ast.#hasMagic=void 0,ast.#parts=[str.substring(pos-1)],i}#canAdoptWithSpace(child){return this.#canAdopt(child,adoptionWithSpaceMap)}#canAdopt(child,map=adoptionMap){if(!child||typeof child!="object"||child.type!==null||child.#parts.length!==1||this.type===null)return!1;let gc=child.#parts[0];return!gc||typeof gc!="object"||gc.type===null?!1:this.#canAdoptType(gc.type,map)}#canAdoptType(c,map=adoptionAnyMap){return!!map.get(this.type)?.includes(c)}#adoptWithSpace(child,index){let gc=child.#parts[0],blank=new _a(null,gc,this.options);blank.#parts.push(""),gc.push(blank),this.#adopt(child,index)}#adopt(child,index){let gc=child.#parts[0];this.#parts.splice(index,1,...gc.#parts);for(let p of gc.#parts)typeof p=="object"&&(p.#parent=this);this.#toString=void 0}#canUsurpType(c){return!!usurpMap.get(this.type)?.has(c)}#canUsurp(child){if(!child||typeof child!="object"||child.type!==null||child.#parts.length!==1||this.type===null||this.#parts.length!==1)return!1;let gc=child.#parts[0];return!gc||typeof gc!="object"||gc.type===null?!1:this.#canUsurpType(gc.type)}#usurp(child){let m=usurpMap.get(this.type),gc=child.#parts[0],nt=m?.get(gc.type);if(!nt)return!1;this.#parts=gc.#parts;for(let p of this.#parts)typeof p=="object"&&(p.#parent=this);this.type=nt,this.#toString=void 0,this.#emptyExt=!1}static fromGlob(pattern,options={}){let ast=new _a(null,void 0,options);return _a.#parseAST(pattern,ast,0,options,0),ast}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();let glob=this.toString(),[re,body,hasMagic,uflag]=this.toRegExpSource();if(!(hasMagic||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase()))return body;let flags=(this.#options.nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags),{_src:re,_glob:glob})}get options(){return this.#options}toRegExpSource(allowDot){let dot=allowDot??!!this.#options.dot;if(this.#root===this&&(this.#flatten(),this.#fillNegs()),!isExtglobAST(this)){let noEmpty=this.isStart()&&this.isEnd()&&!this.#parts.some(s=>typeof s!="string"),src=this.#parts.map(p=>{let[re,_,hasMagic,uflag]=typeof p=="string"?_a.#parseGlob(p,this.#hasMagic,noEmpty):p.toRegExpSource(allowDot);return this.#hasMagic=this.#hasMagic||hasMagic,this.#uflag=this.#uflag||uflag,re}).join(""),start2="";if(this.isStart()&&typeof this.#parts[0]=="string"&&!(this.#parts.length===1&&justDots.has(this.#parts[0]))){let aps=addPatternStart,needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4)),needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}let end="";return this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type==="!"&&(end="(?:$|\\/)"),[start2+src+end,unescape(src),this.#hasMagic=!!this.#hasMagic,this.#uflag]}let repeated=this.type==="*"||this.type==="+",start=this.type==="!"?"(?:(?!(?:":"(?:",body=this.#partsToRegExp(dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){let s=this.toString(),me=this;return me.#parts=[s],me.type=null,me.#hasMagic=void 0,[s,unescape(this.toString()),!1,!1]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":this.#partsToRegExp(!0);bodyDotAllowed===body&&(bodyDotAllowed=""),bodyDotAllowed&&(body=`(?:${body})(?:${bodyDotAllowed})*?`);let final="";if(this.type==="!"&&this.#emptyExt)final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty;else{let close=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?")?":`)${this.type}`;final=start+body+close}return[final,unescape(body),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#flatten(){if(isExtglobAST(this)){let iterations=0,done=!1;do{done=!0;for(let i=0;i<this.#parts.length;i++){let c=this.#parts[i];typeof c=="object"&&(c.#flatten(),this.#canAdopt(c)?(done=!1,this.#adopt(c,i)):this.#canAdoptWithSpace(c)?(done=!1,this.#adoptWithSpace(c,i)):this.#canUsurp(c)&&(done=!1,this.#usurp(c)))}}while(!done&&++iterations<10)}else for(let p of this.#parts)typeof p=="object"&&p.#flatten();this.#toString=void 0}#partsToRegExp(dot){return this.#parts.map(p=>{if(typeof p=="string")throw new Error("string type in extglob ast??");let[re,_,_hasMagic,uflag]=p.toRegExpSource(dot);return this.#uflag=this.#uflag||uflag,re}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")}static#parseGlob(glob,hasMagic,noEmpty=!1){let escaping=!1,re="",uflag=!1,inStar=!1;for(let i=0;i<glob.length;i++){let c=glob.charAt(i);if(escaping){escaping=!1,re+=(reSpecials.has(c)?"\\":"")+c;continue}if(c==="*"){if(inStar)continue;inStar=!0,re+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star,hasMagic=!0;continue}else inStar=!1;if(c==="\\"){i===glob.length-1?re+="\\\\":escaping=!0;continue}if(c==="["){let[src,needUflag,consumed,magic]=parseClass(glob,i);if(consumed){re+=src,uflag=uflag||needUflag,i+=consumed-1,hasMagic=hasMagic||magic;continue}}if(c==="?"){re+=qmark,hasMagic=!0;continue}re+=regExpEscape(c)}return[re,unescape(glob),!!hasMagic,uflag]}};_a=AST;var escape=(s,{windowsPathsNoEscape=!1,magicalBraces=!1}={})=>magicalBraces?windowsPathsNoEscape?s.replace(/[?*()[\]{}]/g,"[$&]"):s.replace(/[?*()[\]\\{}]/g,"\\$&"):windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");var minimatch=(p,pattern,options={})=>(assertValidPattern(pattern),!options.nocomment&&pattern.charAt(0)==="#"?!1:new Minimatch(pattern,options).match(p)),starDotExtRE=/^\*+([^+@!?*[(]*)$/,starDotExtTest=ext2=>f=>!f.startsWith(".")&&f.endsWith(ext2),starDotExtTestDot=ext2=>f=>f.endsWith(ext2),starDotExtTestNocase=ext2=>(ext2=ext2.toLowerCase(),f=>!f.startsWith(".")&&f.toLowerCase().endsWith(ext2)),starDotExtTestNocaseDot=ext2=>(ext2=ext2.toLowerCase(),f=>f.toLowerCase().endsWith(ext2)),starDotStarRE=/^\*+\.\*+$/,starDotStarTest=f=>!f.startsWith(".")&&f.includes("."),starDotStarTestDot=f=>f!=="."&&f!==".."&&f.includes("."),dotStarRE=/^\.\*+$/,dotStarTest=f=>f!=="."&&f!==".."&&f.startsWith("."),starRE=/^\*+$/,starTest=f=>f.length!==0&&!f.startsWith("."),starTestDot=f=>f.length!==0&&f!=="."&&f!=="..",qmarksRE=/^\?+([^+@!?*[(]*)?$/,qmarksTestNocase=([$0,ext2=""])=>{let noext=qmarksTestNoExt([$0]);return ext2?(ext2=ext2.toLowerCase(),f=>noext(f)&&f.toLowerCase().endsWith(ext2)):noext},qmarksTestNocaseDot=([$0,ext2=""])=>{let noext=qmarksTestNoExtDot([$0]);return ext2?(ext2=ext2.toLowerCase(),f=>noext(f)&&f.toLowerCase().endsWith(ext2)):noext},qmarksTestDot=([$0,ext2=""])=>{let noext=qmarksTestNoExtDot([$0]);return ext2?f=>noext(f)&&f.endsWith(ext2):noext},qmarksTest=([$0,ext2=""])=>{let noext=qmarksTestNoExt([$0]);return ext2?f=>noext(f)&&f.endsWith(ext2):noext},qmarksTestNoExt=([$0])=>{let len=$0.length;return f=>f.length===len&&!f.startsWith(".")},qmarksTestNoExtDot=([$0])=>{let len=$0.length;return f=>f.length===len&&f!=="."&&f!==".."},defaultPlatform=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&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 qmark2="[^/]",star2=qmark2+"*?",twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?",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}},AST:class extends orig.AST{constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},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)),makeRe:(pattern,options={})=>orig.makeRe(pattern,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 makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;var 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=/[?*]|[+@!]\(.*?\)|\[|\]/,regExpEscape2=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;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.regexp=null,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.make()}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}debug(..._){}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.braceExpand())],options.debug&&(this.debug=(...args)=>console.error(...args)),this.debug(this.pattern,this.globSet);let rawGlobParts=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(rawGlobParts),this.debug(this.pattern,this.globParts);let set=this.globParts.map((s,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){let isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&!globMagic.test(s[3]),isDrive=/^[a-z]:/i.test(s[0]);if(isUNC)return[...s.slice(0,4),...s.slice(4).map(ss=>this.parse(ss))];if(isDrive)return[s[0],...s.slice(1).map(ss=>this.parse(ss))]}return s.map(ss=>this.parse(ss))});if(this.debug(this.pattern,set),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]==="?"&&typeof p[3]=="string"&&/^[a-z]:$/i.test(p[3])&&(p[2]="?")}this.debug(this.pattern,this.set)}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=>(parts=parts.reduce((set,part)=>{let prev=set[set.length-1];return part==="**"&&prev==="**"?set:part===".."&&prev&&prev!==".."&&prev!=="."&&prev!=="**"?(set.pop(),set):(set.push(part),set)},[]),parts.length===0?[""]:parts))}levelTwoFileOptimize(parts){Array.isArray(parts)||(parts=this.slashSplit(parts));let 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 dd=0;for(;(dd=parts.indexOf("..",dd+1))!==-1;){let p=parts[dd-1];p&&p!=="."&&p!==".."&&p!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(p))&&(didSomething=!0,parts.splice(dd-1,2),dd-=2)}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let 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;didSomething=!0,parts.splice(gs,1);let other=parts.slice(0);other[gs]="**",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 dd=0;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-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i=0;i<globParts.length-1;i++)for(let j=i+1;j<globParts.length;j++){let matched=this.partsMatch(globParts[i],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i]=[],globParts[j]=matched;break}}return globParts.filter(gs=>gs.length)}partsMatch(a,b,emptyGSMatch=!1){let ai=0,bi=0,result=[],which="";for(;ai<a.length&&bi<b.length;)if(a[ai]===b[bi])result.push(which==="b"?b[bi]:a[ai]),ai++,bi++;else if(emptyGSMatch&&a[ai]==="**"&&b[bi]===a[ai+1])result.push(a[ai]),ai++;else if(emptyGSMatch&&b[bi]==="**"&&a[ai]===b[bi+1])result.push(b[bi]),bi++;else if(a[ai]==="*"&&b[bi]&&(this.options.dot||!b[bi].startsWith("."))&&b[bi]!=="**"){if(which==="b")return!1;which="a",result.push(a[ai]),ai++,bi++}else if(b[bi]==="*"&&a[ai]&&(this.options.dot||!a[ai].startsWith("."))&&a[ai]!=="**"){if(which==="a")return!1;which="b",result.push(b[bi]),ai++,bi++}else return!1;return a.length===b.length&&result}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}matchOne(file,pattern,partial=!1){let fileStartIndex=0,patternStartIndex=0;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()&&(pattern[pdi]=fd,patternStartIndex=pdi,fileStartIndex=fdi)}}let{optimizationLevel=1}=this.options;return optimizationLevel>=2&&(file=this.levelTwoFileOptimize(file)),pattern.includes(GLOBSTAR)?this.#matchGlobstar(file,pattern,partial,fileStartIndex,patternStartIndex):this.#matchOne(file,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file,pattern,partial,fileIndex,patternIndex){let firstgs=pattern.indexOf(GLOBSTAR,patternIndex),lastgs=pattern.lastIndexOf(GLOBSTAR),[head,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head.length){let fileHead=file.slice(fileIndex,fileIndex+head.length);if(!this.#matchOne(fileHead,head,partial,0,0))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 i2=fileIndex;i2<file.length-fileTailMatch;i2++){let f=String(file[i2]);if(sawSome=!0,f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return partial||sawSome}let bodySegments=[[[],0]],currentBody=bodySegments[0],nonGsParts=0,nonGsPartsSums=[0];for(let b of body)b===GLOBSTAR?(nonGsPartsSums.push(nonGsParts),currentBody=[[],0],bodySegments.push(currentBody)):(currentBody[0].push(b),nonGsParts++);let i=bodySegments.length-1,fileLength=file.length-fileTailMatch;for(let b of bodySegments)b[1]=fileLength-(nonGsPartsSums[i--]+b[0].length);return!!this.#matchGlobStarBodySections(file,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)}#matchGlobStarBodySections(file,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){let bs=bodySegments[bodyIndex];if(!bs){for(let i=fileIndex;i<file.length;i++){sawTail=!0;let f=file[i];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return sawTail}let[body,after]=bs;for(;fileIndex<=after;){if(this.#matchOne(file.slice(0,fileIndex+body.length),body,partial,fileIndex,0)&&globStarDepth<this.maxGlobstarRecursion){let sub=this.#matchGlobStarBodySections(file,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(sub!==!1)return sub}let f=file[fileIndex];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;fileIndex++}return partial||null}#matchOne(file,pattern,partial,fileIndex,patternIndex){let fi,pi,pl,fl;for(fi=fileIndex,pi=patternIndex,fl=file.length,pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){this.debug("matchOne loop");let p=pattern[pi],f=file[fi];if(this.debug(pattern,p,f),p===!1||p===GLOBSTAR)return!1;let hit;if(typeof p=="string"?(hit=f===p,this.debug("string match",p,f,hit)):(hit=p.test(f),this.debug("pattern match",p,f,hit)),!hit)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)}parse(pattern){assertValidPattern(pattern);let options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m,fastTest=null;(m=pattern.match(starRE))?fastTest=options.dot?starTestDot:starTest:(m=pattern.match(starDotExtRE))?fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1]):(m=pattern.match(qmarksRE))?fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m):(m=pattern.match(starDotStarRE))?fastTest=options.dot?starDotStarTestDot:starDotStarTest:(m=pattern.match(dotStarRE))&&(fastTest=dotStarTest);let re=AST.fromGlob(pattern,this.options).toMMPattern();return fastTest&&typeof re=="object"&&Reflect.defineProperty(re,"test",{value:fastTest}),re}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let set=this.set;if(!set.length)return this.regexp=!1,this.regexp;let options=this.options,twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot,flags=new Set(options.nocase?["i"]:[]),re=set.map(pattern=>{let pp=pattern.map(p=>{if(p instanceof RegExp)for(let f of p.flags.split(""))flags.add(f);return typeof p=="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp.forEach((p,i)=>{let next=pp[i+1],prev=pp[i-1];p!==GLOBSTAR||prev===GLOBSTAR||(prev===void 0?next!==void 0&&next!==GLOBSTAR?pp[i+1]="(?:\\/|"+twoStar+"\\/)?"+next:pp[i]=twoStar:next===void 0?pp[i-1]=prev+"(?:\\/|\\/"+twoStar+")?":next!==GLOBSTAR&&(pp[i-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next,pp[i+1]=GLOBSTAR))});let filtered=pp.filter(p=>p!==GLOBSTAR);if(this.partial&&filtered.length>=1){let prefixes=[];for(let i=1;i<=filtered.length;i++)prefixes.push(filtered.slice(0,i).join("/"));return"(?:"+prefixes.join("|")+")"}return filtered.join("/")}).join("|"),[open4,close]=set.length>1?["(?:",")"]:["",""];re="^"+open4+re+close+"$",this.partial&&(re="^(?:\\/|"+open4+re.slice(1,-1)+close+")$"),this.negate&&(re="^(?!"+re+").+$");try{this.regexp=new RegExp(re,[...flags].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(p){return this.preserveMultipleSlashes?p.split("/"):this.isWindows&&/^\/\/[^/]+/.test(p)?["",...p.split(/\/+/)]:p.split(/\/+/)}match(f,partial=this.partial){if(this.debug("match",f,this.pattern),this.comment)return!1;if(this.empty)return f==="";if(f==="/"&&partial)return!0;let options=this.options;this.isWindows&&(f=f.split("\\").join("/"));let ff=this.slashSplit(f);this.debug(this.pattern,"split",ff);let set=this.set;this.debug(this.pattern,"set",set);let filename=ff[ff.length-1];if(!filename)for(let i=ff.length-2;!filename&&i>=0;i--)filename=ff[i];for(let pattern of set){let file=ff;if(options.matchBase&&pattern.length===1&&(file=[filename]),this.matchOne(file,pattern,partial))return options.flipNegate?!0:!this.negate}return options.flipNegate?!1:this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;var import_semver=__toESM(require_semver(),1);import{readFileSync as readFileSync3}from"node:fs";var RESOURCE_FIELDS=["extensions","skills","prompts","themes","hooks"];function isObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg=JSON.parse(stripBom(readFileSync3(packageJsonPath,"utf-8")));if(!isObject2(pkg)||!isObject2(pkg.pi))return null;let manifest={};typeof pkg.pi.system=="boolean"&&(manifest.system=pkg.pi.system);for(let field2 of RESOURCE_FIELDS){let entries=pkg.pi[field2];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field2]=entries)}return manifest}catch{return null}}var import_ignore=__toESM(require_ignore(),1);import{closeSync as closeSync4,existsSync as existsSync4,fstatSync as fstatSync2,openSync as openSync4,readdirSync as readdirSync2,readFileSync as readFileSync4,readSync as readSync3,statSync as statSync3}from"node:fs";import{join as join6,relative,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(`
|
|
38
38
|
---`),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,prefix){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=prefix?`${prefix}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules(ig,dir,rootDir){let relativeDir=relative(rootDir,dir),prefix=relativeDir?`${toPosixPath(relativeDir)}/`:"";for(let filename of IGNORE_FILE_NAMES){let ignorePath=join6(dir,filename);if(existsSync4(ignorePath))try{let patterns=readFileSync4(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern(line,prefix)).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=openSync4(filePath,"r")}catch{return decodeFrontmatterSource(readFileSync4(filePath))}try{let prefix=Buffer.allocUnsafe(SKILL_FRONTMATTER_PREFIX_BYTES),bytesRead=readSync3(fd,prefix,0,SKILL_FRONTMATTER_PREFIX_BYTES,0),prefixBuf=prefix.subarray(0,bytesRead);if(bytesRead<SKILL_FRONTMATTER_PREFIX_BYTES||frontmatterPrefixEnd(prefixBuf)!==void 0)return decodeFrontmatterSource(prefixBuf);let restSize=fstatSync2(fd).size-bytesRead;if(restSize<=0)return decodeFrontmatterSource(prefixBuf);let rest=Buffer.allocUnsafe(restSize);return readSync3(fd,rest,0,restSize,bytesRead),decodeFrontmatterSource(Buffer.concat([prefixBuf,rest]))}finally{closeSync4(fd)}}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir){let entries=[];if(!existsSync4(dir))return entries;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore.default)();addIgnoreRules(ig,dir,root);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join6(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync3(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=join6(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=toPosixPath(relative(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&!ig.ignores(relPath)&&(mode==="pi"&&dir===root||mode==="agents"&&dir!==root)){entries.push(fullPath);continue}isDir&&(ig.ignores(`${relPath}/`)||entries.push(...collectSkillEntries(fullPath,mode,ig,root)))}}catch{}return entries}function collectAutoSkillEntries(dir,mode){return collectSkillEntries(dir,mode)}function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync5("/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(sep3).join("/")}function getHomeDir(){return process.env.HOME||homedir()}function getExtensionTempFolder(agentDir){let tempFolder=join7(agentDir,"tmp","extensions");return mkdirSync3(tempFolder,{recursive:!0,mode:448}),chmodSync(tempFolder,448),tempFolder}function prefixIgnorePattern2(line,prefix){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=prefix?`${prefix}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules2(ig,dir,rootDir){let relativeDir=relative2(rootDir,dir),prefix=relativeDir?`${toPosixPath2(relativeDir)}/`:"";for(let filename of IGNORE_FILE_NAMES2){let ignorePath=join7(dir,filename);if(existsSync5(ignorePath))try{let patterns=readFileSync5(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix)).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(sep3).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(!existsSync5(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore2.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync3(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join7(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync4(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 findGitRepoRoot(startDir){let dir=resolve3(startDir);for(;;){if(existsSync5(join7(dir,".git")))return dir;let parent=dirname2(dir);if(parent===dir)return null;dir=parent}}function collectAncestorAgentsSkillDirs(startDir){let skillDirs=[],resolvedStartDir=resolve3(startDir),gitRepoRoot=findGitRepoRoot(resolvedStartDir),dir=resolvedStartDir;for(;skillDirs.push(join7(dir,".agents","skills")),!(gitRepoRoot&&dir===gitRepoRoot);){let parent=dirname2(dir);if(parent===dir)break;dir=parent}return skillDirs}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync5(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync3(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join7(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync4(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(!existsSync5(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync3(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join7(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync4(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=join7(dir,"package.json");if(existsSync5(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=resolve3(dir,extPath);existsSync5(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=join7(dir,"index.ts"),indexJs=join7(dir,"index.js");return existsSync5(indexTs)?[indexTs]:existsSync5(indexJs)?[indexJs]:null}function collectAutoExtensionEntries(dir){let entries=[];if(!existsSync5(dir))return entries;let rootEntries=resolveExtensionEntries(dir);if(rootEntries)return rootEntries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync3(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join7(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync4(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){return resourceType==="skills"?collectSkillEntries(dir,"pi"):resourceType==="extensions"?collectAutoExtensionEntries(dir):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename3(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentName=isSkillFile?basename3(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=basename3(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 existsSync5(path2)?path2:void 0}if(parsed.type==="git"){let path2=this.getGitInstallPath(parsed,scope);return existsSync5(path2)?path2:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path2=this.resolvePathFromBase(parsed.path,baseDir);return existsSync5(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=join7(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(!existsSync5(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=existsSync5(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!existsSync5(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(!(!existsSync5(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(!existsSync5(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(existsSync5(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(existsSync5(resolved))try{let stats=statSync4(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=join7(installedPath,"package.json");if(existsSync5(packageJsonPath))try{let content=readFileSync5(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=>basename3(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(!existsSync5(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(existsSync5(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),mkdirSync3(dirname2(targetDir),{recursive:!0}),rmSync5(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=join7(targetDir,"package.json");existsSync5(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}catch(error){throw rmSync5(targetDir,{recursive:!0,force:!0}),this.pruneEmptyGitParents(targetDir,gitRoot),error}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync5(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=join7(targetDir,"package.json");if(!existsSync5(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync5(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}${sep3}`)?!existsSync5(dependencyPath):!1})}catch{return!1}}async repairMissingGitDependencies(targetDir){this.hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}getGitUpdateMarkerPath(targetDir){return join7(dirname2(targetDir),`.${basename3(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=join7(targetDir,"package.json");existsSync5(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir}),rmSync5(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()){existsSync5(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync4(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);rmSync5(targetDir,{recursive:!0,force:!0}),rmSync5(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(!existsSync5(current)){current=dirname2(current);continue}if(readdirSync3(current).length>0)break;try{rmSync5(current,{recursive:!0,force:!0})}catch{break}current=dirname2(current)}}ensureNpmProject(installRoot){existsSync5(installRoot)||mkdirSync3(installRoot,{recursive:!0}),markPathIgnoredByCloudSync(installRoot),this.ensureGitIgnore(installRoot);let packageJsonPath=join7(installRoot,"package.json");existsSync5(packageJsonPath)||writeFileSync4(packageJsonPath,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(dir){existsSync5(dir)||mkdirSync3(dir,{recursive:!0});let ignorePath=join7(dir,".gitignore");existsSync5(ignorePath)||writeFileSync4(ignorePath,`*
|
|
39
39
|
!.gitignore
|
|
40
40
|
`,"utf-8")}getNpmInstallRoot(scope,temporary){return temporary?this.getTemporaryDir("npm"):scope==="project"?(this.assertProjectTrustedForScope(scope),join7(this.cwd,CONFIG_DIR_NAME,"npm")):join7(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=join7(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"?join7(this.getTemporaryDir("npm"),"node_modules",source.name):scope==="project"?(this.assertProjectTrustedForScope(scope),join7(this.cwd,CONFIG_DIR_NAME,"npm","node_modules",source.name)):join7(this.agentDir,"npm","node_modules",source.name)}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join7(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=this.getManagedNpmInstallPath(source,scope);if(scope!=="user"||existsSync5(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync5(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),join7(this.cwd,CONFIG_DIR_NAME,"git")):join7(this.agentDir,"git")}getTemporaryDir(prefix,suffix,ref){let root=this.resolveManagedPath(getExtensionTempFolder(this.agentDir),prefix),hash=createHash2("sha256").update(`${prefix}-${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}${sep3}`))throw new Error(`Refusing to use path outside package install root: ${resolvedPath}`);return resolvedPath}getBaseDirForScope(scope){return scope==="project"?(this.assertProjectTrustedForScope(scope),join7(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){let manifest=readPiManifest(join7(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=join7(packageRoot,resourceType);if(existsSync5(dir)){let files=collectResourceFiles(dir,resourceType);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(join7(packageRoot,"package.json"))?.[resourceType];if(entries){this.addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join7(packageRoot,resourceType);if(existsSync5(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)this.addResource(target,f,metadata,!0)}}applyPackageFilter(packageRoot,userPatterns,resourceType,target,metadata){let{allFiles}=this.collectManifestFiles(packageRoot,resourceType);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),enabledByUser=applyAutoloadDisabledPatterns(allFiles,userPatterns,packageRoot);for(let[filePath,enabled]of enabledByUser)this.addResource(target,filePath,metadata,enabled)}collectManifestFiles(packageRoot,resourceType){let entries=readPiManifest(join7(packageRoot,"package.json"))?.[resourceType];if(entries&&entries.length>0){let allFiles2=this.collectFilesFromManifestEntries(entries,packageRoot,resourceType),manifestPatterns=entries.filter(isOverridePattern),enabledByManifest=manifestPatterns.length>0?applyPatterns(allFiles2,manifestPatterns,packageRoot):new Set(allFiles2);return{allFiles:Array.from(enabledByManifest),enabledByManifest}}let conventionDir=join7(packageRoot,resourceType);if(!existsSync5(conventionDir))return{allFiles:[],enabledByManifest:new Set};let allFiles=collectResourceFiles(conventionDir,resourceType);return{allFiles,enabledByManifest:new Set(allFiles)}}addManifestEntries(entries,root,resourceType,target,metadata){if(!entries)return;let allFiles=this.collectFilesFromManifestEntries(entries,root,resourceType),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){let resolved=entries.filter(entry=>!isOverridePattern(entry)).flatMap(entry=>hasGlobPattern(entry)?expandPackageGlob(entry,root):[resolve3(root,entry)]);return this.collectFilesFromPaths(resolved,resourceType)}resolveLocalEntries(entries,resourceType,target,metadata,baseDir){if(entries.length===0)return;let{plain,patterns}=splitPatterns(entries),resolvedPlain=plain.map(p=>this.resolvePathFromBase(p,baseDir)),allFiles=this.collectFilesFromPaths(resolvedPlain,resourceType),enabledPaths=applyPatterns(allFiles,patterns,baseDir);for(let f of allFiles)this.addResource(target,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:join7(globalBaseDir,"extensions"),skills:join7(globalBaseDir,"skills"),prompts:join7(globalBaseDir,"prompts"),themes:join7(globalBaseDir,"themes"),hooks:join7(globalBaseDir,"hooks")},projectDirs={extensions:join7(projectBaseDir,"extensions"),skills:join7(projectBaseDir,"skills"),prompts:join7(projectBaseDir,"prompts"),themes:join7(projectBaseDir,"themes"),hooks:join7(projectBaseDir,"hooks")},legacyProjectBaseDir=join7(this.cwd,".pi"),legacyProjectDirs={extensions:join7(legacyProjectBaseDir,"extensions"),skills:join7(legacyProjectBaseDir,"skills"),prompts:join7(legacyProjectBaseDir,"prompts"),themes:join7(legacyProjectBaseDir,"themes"),hooks:join7(legacyProjectBaseDir,"hooks")},userAgentsSkillsDir=join7(getHomeDir(),".agents","skills"),projectTrusted=this.settingsManager.isProjectTrusted(),projectAgentsSkillDirs=projectTrusted?collectAncestorAgentsSkillDirs(this.cwd).filter(dir=>resolve3(dir)!==resolve3(userAgentsSkillsDir)):[],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)}};projectTrusted&&(addResources("extensions",collectAutoExtensionEntries(projectDirs.extensions),projectMetadata,projectOverrides.extensions,projectBaseDir),addResources("skills",collectAutoSkillEntries(projectDirs.skills,"pi"),projectMetadata,projectOverrides.skills,projectBaseDir));for(let agentsSkillsDir of projectAgentsSkillDirs){let agentsBaseDir=dirname2(agentsSkillsDir),agentsMetadata={...projectMetadata,baseDir:agentsBaseDir};addResources("skills",collectAutoSkillEntries(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),addResources("skills",collectAutoSkillEntries(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),addResources("skills",collectAutoSkillEntries(userDirs.skills,"pi"),userMetadata,userOverrides.skills,globalBaseDir);let userAgentsBaseDir=dirname2(userAgentsSkillsDir),userAgentsMetadata={...userMetadata,baseDir:userAgentsBaseDir};addResources("skills",collectAutoSkillEntries(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)}collectFilesFromPaths(paths,resourceType){let files=[];for(let p of paths)if(existsSync5(p))try{let stats=statSync4(p);stats.isFile()?files.push(p):stats.isDirectory()&&files.push(...collectResourceFiles(p,resourceType))}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}}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{extensions:mapToResolved(accumulator.extensions),skills:mapToResolved(accumulator.skills),prompts:mapToResolved(accumulator.prompts),themes:mapToResolved(accumulator.themes),hooks:mapToResolved(accumulator.hooks)}}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,child.kill()},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 CountdownTimer=class{constructor(timeoutMs,tui,onTick,onExpire){this.tui=tui,this.onTick=onTick,this.onExpire=onExpire,this.remainingSeconds=Math.ceil(timeoutMs/1e3),this.onTick(this.remainingSeconds),this.intervalId=setInterval(()=>{this.remainingSeconds--,this.onTick(this.remainingSeconds),this.tui?.requestRender(),this.remainingSeconds<=0&&(this.dispose(),this.onExpire())},1e3)}dispose(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}};var ExtensionInputComponent=class extends Container{get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}constructor(title,_placeholder,onSubmit,onCancel,opts){super(),this._focused=!1,this.onSubmitCallback=onSubmit,this.onCancelCallback=onCancel,this.baseTitle=title,this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.titleText=new Text(theme.fg("accent",title),1,0),this.addChild(this.titleText),opts?.description&&(this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("text",opts.description),1,0))),this.addChild(new Spacer(1)),opts?.timeout&&opts.timeout>0&&opts.tui&&(this.countdown=new CountdownTimer(opts.timeout,opts.tui,s=>this.titleText.setText(theme.fg("accent",`${this.baseTitle} (${s}s)`)),()=>this.onCancelCallback())),this.input=new Input,opts?.initialValue&&this.input.handleInput(opts.initialValue),this.addChild(this.input),this.addChild(new Spacer(1)),this.addChild(new Text(`${keyHint("tui.select.confirm","submit")} ${keyHint("tui.select.cancel","cancel")}`,1,0)),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder)}handleInput(keyData){let kb=getKeybindings();kb.matches(keyData,"tui.select.confirm")||keyData===`
|
|
@@ -48,4 +48,4 @@ and bugs within Pi. You can observe what is shared using /privacy and make
|
|
|
48
48
|
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,prefix=isSelected?theme.fg("accent","\u2192 "):" ",label=isSelected?theme.fg("accent",labels[i]):theme.fg("text",labels[i]);this.addChild(new Text(`${prefix}${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===`
|
|
49
49
|
`?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(resolve5=>setTimeout(resolve5,25))}function shouldRunFirstTimeSetup(settingsPath=getSettingsPath()){return!isOfficialDistribution({packageName:PACKAGE_NAME,appName:APP_NAME,configDirName:CONFIG_DIR_NAME})||!areExperimentalFeaturesEnabled()||process.env[ENV_AGENT_DIR]?!1:!existsSync6(settingsPath)}async function showStartupSelector(settingsManager,title,options){let ui=await createStartupTui(settingsManager);return new Promise(resolve5=>{let settled=!1,finish=async result=>{settled||(settled=!0,await clearStartupTui(ui),ui.stop(),resolve5(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(resolve5=>{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(),resolve5())};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(resolve5=>{let settled=!1,finish=async result=>{settled||(settled=!0,input.dispose(),await clearStartupTui(ui),ui.stop(),resolve5(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 existsSync8}from"node:fs";import{unlink}from"node:fs/promises";import*as os from"node:os";import{createHash as createHash3,randomBytes as randomBytes2}from"node:crypto";import{chmodSync as chmodSync2,existsSync as existsSync7,lstatSync,mkdirSync as mkdirSync5,readdirSync as readdirSync4,renameSync as renameSync4,rmSync as rmSync6,statSync as statSync5,writeFileSync as writeFileSync6}from"node:fs";import{open as open3}from"node:fs/promises";import{dirname as dirname4,join as join9,resolve as resolve4}from"node:path";var MEDIA_BEARING_RECORD_TYPES=new Set(["tool_execution_end","message_start","message_end","turn_end","agent_end","entry_appended"]),MEDIA_BEARING_RESPONSE_COMMANDS=new Set(["get_messages","get_entries","get_tree","get_state","open_session"]);function base64ByteLength(data){let padding=data.endsWith("==")?2:data.endsWith("=")?1:0;return Math.max(0,Math.floor(data.length*3/4)-padding)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isInlineImage(value){return isPlainObject(value)&&value.type==="image"&&typeof value.data=="string"}function omitContentImages(content,toolCallId,persist){let replaced;for(let index=0;index<content.length;index++){let block=content[index];if(!isInlineImage(block))continue;replaced??=[...content];let ref={toolCallId,contentIndex:index};replaced[index]={type:"image_ref",mimeType:typeof block.mimeType=="string"?block.mimeType:"application/octet-stream",byteLength:base64ByteLength(block.data),ref,...persist?.(ref,block)}}return replaced??content}function omitToolResultImages(message,persist){let content=message.content,toolCallId=typeof message.toolCallId=="string"?message.toolCallId:"";if(!Array.isArray(content))return message;let omitted=omitContentImages(content,toolCallId,persist);return omitted===content?message:{...message,content:omitted}}function walk(value,persist){if(Array.isArray(value)){let replaced2;for(let index=0;index<value.length;index++){let next=walk(value[index],persist);next!==value[index]&&(replaced2??=[...value],replaced2[index]=next)}return replaced2??value}if(!isPlainObject(value))return value;let scrubbed=value.role==="toolResult"?omitToolResultImages(value,persist):value,replaced=scrubbed===value?void 0:{...scrubbed};for(let[key,child]of Object.entries(scrubbed)){if(key==="content"&&scrubbed!==value||!isPlainObject(child)&&!Array.isArray(child))continue;let next=walk(child,persist);next!==child&&(replaced??={...scrubbed},replaced[key]=next)}return replaced??value}function omitToolExecutionEndImages(record,persist){let result=record.result;if(!isPlainObject(result)||!Array.isArray(result.content))return record;let toolCallId=typeof record.toolCallId=="string"?record.toolCallId:"",omitted=omitContentImages(result.content,toolCallId,persist);return omitted===result.content?record:{...record,result:{...result,content:omitted}}}function carriesMedia(record){return typeof record.type!="string"?!1:MEDIA_BEARING_RECORD_TYPES.has(record.type)?!0:record.type==="response"&&typeof record.command=="string"?MEDIA_BEARING_RESPONSE_COMMANDS.has(record.command):!1}function omitInlineMedia(record,persist){let typed=record;if(!carriesMedia(typed))return record;let scrubbed=typed.type==="tool_execution_end"?omitToolExecutionEndImages(typed,persist):typed,walked=walk(scrubbed,persist);return walked===typed?record:walked}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[dirname4(root),root,callDirectory]){let stat3;try{stat3=lstatSync(path2)}catch{continue}if(!stat3.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:dirname4(sessionFile),durableSessionId}}function toolMediaRoot(scope){return assertValidSessionId(scope.durableSessionId),join9(scope.sessionDir,MEDIA_DIRECTORY,scope.durableSessionId)}function directoryBytes(directory){let total=0;for(let entry of readdirSync4(directory,{withFileTypes:!0})){let path2=join9(directory,entry.name);total+=entry.isDirectory()?directoryBytes(path2):statSync5(path2).size}return total}function storedBytes(root){let known=reserved.get(root);if(known!==void 0)return known;let scanned=existsSync7(root)?directoryBytes(root):0;return reserved.set(root,scanned),scanned}var unavailable=reason=>({unavailableReason:reason});function writeImage(root,path2,bytes){let callDirectory=dirname4(path2);mkdirSync5(callDirectory,{recursive:!0,mode:448}),assertRealDirectoryChain(root,callDirectory);let staging=`${path2}.${randomBytes2(6).toString("hex")}.tmp`;try{writeFileSync6(staging,bytes,{mode:384,flag:"wx"}),renameSync4(staging,path2),chmodSync2(path2,256)}catch(cause){throw rmSync6(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=createHash3("sha256").update(ref.toolCallId).digest("hex"),digest=createHash3("sha256").update(bytes).digest("hex"),path2=resolve4(root,callDirectory,`${ref.contentIndex}-${digest}.${extension}`);if(assertRealDirectoryChain(root,dirname4(path2)),existsSync7(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),rmSync6(root,{recursive:!0,force:!0})}function makeTreeWritable(path2){let entries;try{if(!lstatSync(path2).isDirectory())return;chmodSync2(path2,448),entries=readdirSync4(path2,{withFileTypes:!0})}catch{return}for(let entry of entries){let child=join9(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 open3(sessionFile,"r");try{let{buffer,bytesRead}=await handle.read(Buffer.alloc(4096),0,4096,0),firstLine=buffer.subarray(0,bytesRead).toString("utf8").split(`
|
|
50
50
|
`,1)[0]??"",id=JSON.parse(firstLine).id;return typeof id=="string"?{sessionDir:dirname4(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 text=`${session.id} ${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=[],walk2=(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;walk2(node.children[i],depth+1,[...ancestorContinues,continues],childIsLast)}};for(let i=0;i<roots.length;i++)walk2(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(show){this.showRenameHint=show}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)",sep4=theme.fg("muted"," \xB7 "),hint1=keyHint("tui.input.tab","scope")+sep4+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(sep4);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(),nameFiltered=this.nameFilter==="all"?this.allSessions:this.allSessions.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)}}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)),endIndex=Math.min(startIndex+this.maxVisible,this.filteredSessions.length);for(let i=startIndex;i<endIndex;i++){let node=this.filteredSessions[i],session=node.session,isSelected=i===this.selectedIndex,isConfirmingDelete=session.path===this.confirmingDeletePath,isCurrent=this.isCurrentSessionPath(session.path),prefix=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(prefix),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",prefix)+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||endIndex<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(`
|
|
51
|
-
`)[0]??stderr),parts.length===0?null:`trash: ${parts.join(" \xB7 ").slice(0,200)}`};if(trashResult.status===0||!existsSync8(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{minimatch,VIRTUAL_MODEL_STATE_ENTRY,isVirtualModel,findLatestResponse,getBranchSelection,getVirtualModelState,createVirtualModel,withVirtualModels,REPOSITORY_IDENTITY_ENTRY_TYPE,readRepositoryIdentity,compareRepositoryIdentities,parseRepositoryIdentity,sameRepositoryIdentity,readFileLines,listSessionsFromDir,reserveSessionWrite,unregisterSessionWriter,resolveEnvironmentContext,environmentContextMessageIfChanged,rejectedImageSources,toolResultUserWords,userWordBlocks,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,inheritSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionProjection,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,SessionManager,DynamicBorder,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint,areExperimentalFeaturesEnabled,
|
|
51
|
+
`)[0]??stderr),parts.length===0?null:`trash: ${parts.join(" \xB7 ").slice(0,200)}`};if(trashResult.status===0||!existsSync8(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{minimatch,VIRTUAL_MODEL_STATE_ENTRY,isVirtualModel,findLatestResponse,getBranchSelection,getVirtualModelState,createVirtualModel,withVirtualModels,sessionCwdMatcher,REPOSITORY_IDENTITY_ENTRY_TYPE,readRepositoryIdentity,compareRepositoryIdentities,parseRepositoryIdentity,sameRepositoryIdentity,parseEntryLine,readFileLines,listSessionsFromDir,reserveSessionWrite,unregisterSessionWriter,resolveEnvironmentContext,environmentContextMessageIfChanged,rejectedImageSources,toolResultUserWords,userWordBlocks,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,inheritSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionProjection,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,findMostRecentSession,SessionManager,DynamicBorder,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint,areExperimentalFeaturesEnabled,parseGitUrl,readPiManifest,shouldSkipSkillWalkDirectoryName,readSkillMarkdownSource,DefaultPackageManager,CountdownTimer,ExtensionInputComponent,ExtensionSelectorComponent,InteractiveThemeController,createStartupTui,startStartupTui,shouldRunFirstTimeSetup,showStartupSelector,showFirstTimeSetup,showStartupInput,omitInlineMedia,liveToolMediaScope,toolMediaPersister,SessionSelectorComponent};
|