@code-yeongyu/senpi 2026.9.19-2 → 2026.9.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/bundle/chunks/{app-server-command-QBJ4GPN7.js → app-server-command-B35FQUTE.js} +1 -1
  3. package/dist/bundle/chunks/{bun-extension-importer-JQZRPNJH.js → bun-extension-importer-HHH4TV4B.js} +3 -3
  4. package/dist/bundle/chunks/{chunk-YRN3PCTM.js → chunk-DQZB4GVV.js} +4 -4
  5. package/dist/bundle/chunks/{chunk-EHSDTQ6I.js → chunk-E5R67F7G.js} +37 -37
  6. package/dist/bundle/chunks/{chunk-5E5TLB76.js → chunk-TWGC3TBR.js} +2 -2
  7. package/dist/bundle/chunks/{chunk-RLRLQRI2.js → chunk-V2ZB62DG.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-3FRTRCR6.js → chunk-YXQG2SUX.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-PLZK7ABD.js → chunk-Z4LHCTJ6.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-3Q4WGKFA.js → chunk-ZMFHNH6U.js} +1 -1
  11. package/dist/bundle/chunks/{cli-main-MLJ2H637.js → cli-main-USVT7JMN.js} +1 -1
  12. package/dist/bundle/chunks/{interactive-host-runtime-AITXUDCT.js → interactive-host-runtime-ELBAZ4LN.js} +1 -1
  13. package/dist/bundle/chunks/{interactive-mode-7C75IXNF.js → interactive-mode-R6225BKI.js} +1 -1
  14. package/dist/bundle/chunks/{list-tips-KTDNGQUK.js → list-tips-Z7T2ACVU.js} +1 -1
  15. package/dist/bundle/chunks/{multi-session-host-2YCJKQOL.js → multi-session-host-QNEBJW2P.js} +3 -3
  16. package/dist/bundle/chunks/{package-manager-cli-4ANSELYT.js → package-manager-cli-4MVJ3JSE.js} +1 -1
  17. package/dist/bundle/chunks/{rpc-mode-OPFQIWFP.js → rpc-mode-CXVDRIBU.js} +1 -1
  18. package/dist/bundle/chunks/{session-picker-DXCITGLS.js → session-picker-6N666KQZ.js} +1 -1
  19. package/dist/bundle/chunks/session-worker.js +66 -66
  20. package/dist/bundle/cli.js +1 -1
  21. package/dist/bundle/index.js +1 -1
  22. package/dist/bundle/rpc-entry.js +1 -1
  23. package/dist/core/agent-session-services.d.ts.map +1 -1
  24. package/dist/core/agent-session-services.js +14 -1
  25. package/dist/core/agent-session-services.js.map +1 -1
  26. package/dist/core/agent-session.d.ts +45 -0
  27. package/dist/core/agent-session.d.ts.map +1 -1
  28. package/dist/core/agent-session.js +233 -11
  29. package/dist/core/agent-session.js.map +1 -1
  30. package/dist/core/extensions/builtin/ask-user/extension.d.ts.map +1 -1
  31. package/dist/core/extensions/builtin/ask-user/extension.js +16 -5
  32. package/dist/core/extensions/builtin/ask-user/extension.js.map +1 -1
  33. package/dist/core/extensions/builtin/ask-user/format.d.ts +5 -0
  34. package/dist/core/extensions/builtin/ask-user/format.d.ts.map +1 -1
  35. package/dist/core/extensions/builtin/ask-user/format.js +4 -0
  36. package/dist/core/extensions/builtin/ask-user/format.js.map +1 -1
  37. package/dist/core/extensions/builtin/ask-user/notify.d.ts +2 -0
  38. package/dist/core/extensions/builtin/ask-user/notify.d.ts.map +1 -1
  39. package/dist/core/extensions/builtin/ask-user/notify.js +2 -0
  40. package/dist/core/extensions/builtin/ask-user/notify.js.map +1 -1
  41. package/dist/core/extensions/builtin/ask-user/registry.d.ts +15 -2
  42. package/dist/core/extensions/builtin/ask-user/registry.d.ts.map +1 -1
  43. package/dist/core/extensions/builtin/ask-user/registry.js +13 -0
  44. package/dist/core/extensions/builtin/ask-user/registry.js.map +1 -1
  45. package/dist/core/extensions/builtin/ask-user/render.d.ts +6 -0
  46. package/dist/core/extensions/builtin/ask-user/render.d.ts.map +1 -1
  47. package/dist/core/extensions/builtin/ask-user/render.js +9 -0
  48. package/dist/core/extensions/builtin/ask-user/render.js.map +1 -1
  49. package/dist/core/extensions/builtin/ask-user/resume.d.ts.map +1 -1
  50. package/dist/core/extensions/builtin/ask-user/resume.js +59 -24
  51. package/dist/core/extensions/builtin/ask-user/resume.js.map +1 -1
  52. package/dist/core/extensions/builtin/ask-user/tool.d.ts +1 -1
  53. package/dist/core/extensions/builtin/ask-user/tool.d.ts.map +1 -1
  54. package/dist/core/extensions/builtin/ask-user/tool.js +98 -17
  55. package/dist/core/extensions/builtin/ask-user/tool.js.map +1 -1
  56. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts +18 -0
  57. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts.map +1 -1
  58. package/dist/core/extensions/builtin/compaction/model-usability-budget.js +16 -8
  59. package/dist/core/extensions/builtin/compaction/model-usability-budget.js.map +1 -1
  60. package/dist/core/extensions/builtin/compaction/switch-admission.d.ts +23 -0
  61. package/dist/core/extensions/builtin/compaction/switch-admission.d.ts.map +1 -0
  62. package/dist/core/extensions/builtin/compaction/switch-admission.js +19 -0
  63. package/dist/core/extensions/builtin/compaction/switch-admission.js.map +1 -0
  64. package/dist/core/extensions/builtin/goal/index.d.ts.map +1 -1
  65. package/dist/core/extensions/builtin/goal/index.js +10 -0
  66. package/dist/core/extensions/builtin/goal/index.js.map +1 -1
  67. package/dist/core/extensions/bun-extension-commonjs.d.ts +1 -1
  68. package/dist/core/extensions/bun-extension-commonjs.d.ts.map +1 -1
  69. package/dist/core/extensions/bun-extension-commonjs.js +3 -3
  70. package/dist/core/extensions/bun-extension-commonjs.js.map +1 -1
  71. package/dist/core/extensions/bun-extension-importer.d.ts.map +1 -1
  72. package/dist/core/extensions/bun-extension-importer.js +4 -1
  73. package/dist/core/extensions/bun-extension-importer.js.map +1 -1
  74. package/dist/core/extensions/bun-extension-registry.d.ts.map +1 -1
  75. package/dist/core/extensions/bun-extension-registry.js +5 -9
  76. package/dist/core/extensions/bun-extension-registry.js.map +1 -1
  77. package/dist/core/resolved-paths-memo.d.ts +31 -0
  78. package/dist/core/resolved-paths-memo.d.ts.map +1 -0
  79. package/dist/core/resolved-paths-memo.js +57 -0
  80. package/dist/core/resolved-paths-memo.js.map +1 -0
  81. package/dist/core/resource-loader.d.ts +4 -1
  82. package/dist/core/resource-loader.d.ts.map +1 -1
  83. package/dist/core/resource-loader.js +25 -12
  84. package/dist/core/resource-loader.js.map +1 -1
  85. package/dist/core/retry-fallback/settings.d.ts +10 -2
  86. package/dist/core/retry-fallback/settings.d.ts.map +1 -1
  87. package/dist/core/retry-fallback/settings.js +28 -6
  88. package/dist/core/retry-fallback/settings.js.map +1 -1
  89. package/dist/core/skill-discovery.d.ts.map +1 -1
  90. package/dist/core/skill-discovery.js +11 -1
  91. package/dist/core/skill-discovery.js.map +1 -1
  92. package/dist/main.d.ts +10 -0
  93. package/dist/main.d.ts.map +1 -1
  94. package/dist/main.js +19 -2
  95. package/dist/main.js.map +1 -1
  96. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts +2 -5
  97. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts.map +1 -1
  98. package/dist/modes/interactive/components/ask-user-answer-chip.js +1 -4
  99. package/dist/modes/interactive/components/ask-user-answer-chip.js.map +1 -1
  100. package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
  101. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  102. package/dist/modes/interactive/components/assistant-message.js +8 -0
  103. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  104. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts +1 -0
  105. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts.map +1 -1
  106. package/dist/modes/interactive/components/assistant-render-descriptors.js +4 -0
  107. package/dist/modes/interactive/components/assistant-render-descriptors.js.map +1 -1
  108. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  109. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  110. package/dist/modes/interactive/components/status-indicator.js +15 -2
  111. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  112. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  113. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  114. package/dist/modes/interactive/interactive-mode.js +81 -6
  115. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  116. package/dist/modes/interactive/provider-error-presentation.d.ts +18 -0
  117. package/dist/modes/interactive/provider-error-presentation.d.ts.map +1 -0
  118. package/dist/modes/interactive/provider-error-presentation.js +100 -0
  119. package/dist/modes/interactive/provider-error-presentation.js.map +1 -0
  120. package/dist/modes/rpc/rpc-types.d.ts +18 -0
  121. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  122. package/dist/modes/rpc/rpc-types.js.map +1 -1
  123. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  124. package/dist/modes/rpc/session-command-router.js +14 -0
  125. package/dist/modes/rpc/session-command-router.js.map +1 -1
  126. package/dist/modes/rpc/session-event-writer.d.ts +9 -1
  127. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  128. package/dist/modes/rpc/session-event-writer.js +21 -0
  129. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  130. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  131. package/dist/modes/rpc/session-registry.js +9 -2
  132. package/dist/modes/rpc/session-registry.js.map +1 -1
  133. package/dist/modes/rpc/session-worker-requests.d.ts +10 -1
  134. package/dist/modes/rpc/session-worker-requests.d.ts.map +1 -1
  135. package/dist/modes/rpc/session-worker-requests.js +8 -2
  136. package/dist/modes/rpc/session-worker-requests.js.map +1 -1
  137. package/dist/modes/rpc/session-worker-requests.test.d.ts +2 -0
  138. package/dist/modes/rpc/session-worker-requests.test.d.ts.map +1 -0
  139. package/dist/modes/rpc/session-worker-requests.test.js +44 -0
  140. package/dist/modes/rpc/session-worker-requests.test.js.map +1 -0
  141. package/docs/rpc.md +7 -0
  142. package/docs/settings.md +1 -1
  143. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
  144. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  145. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  146. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  147. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  148. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  149. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  150. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  151. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  152. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  153. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  154. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  155. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  156. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  157. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.d.ts.map +1 -1
  158. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.js +26 -3
  159. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.js.map +1 -1
  160. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
  161. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +13 -6
  162. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
  163. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
  164. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +11 -3
  165. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
  166. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +15 -2
  167. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
  168. package/node_modules/@earendil-works/pi-tui/dist/tui.js +45 -2
  169. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  170. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  171. package/package.json +8 -8
@@ -1,10 +1,10 @@
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{KeybindingsManager}from"./chunk-3Q4WGKFA.js";import{detectTerminalBackgroundFromEnv,detectTerminalThemeForAuto,initTheme,isStdoutTakenOver,loadThemeFromPath,parseAutoThemeSetting,resolveThemeSetting,setRegisteredThemes,setTheme,theme}from"./chunk-RLRLQRI2.js";import{Container,Input,ProcessTerminal,Spacer,TUI,Text,fuzzyMatch,getKeybindings,setCapabilityOverrides,setKeybindings,truncateToWidth,visibleWidth}from"./chunk-YRN3PCTM.js";import{SettingsManager}from"./chunk-PLZK7ABD.js";import{require_semver}from"./chunk-I7YUNMWH.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,PACKAGE_NAME,canonicalizePath,envValue,getAgentDir,getDebugLogPath,getSettingsPath,isLocalPath,markPathIgnoredByCloudSync,resolvePath,spawnProcess,spawnProcessSync,stripBom}from"./chunk-H5RK2RYZ.js";import{__commonJS,__require,__toESM}from"./chunk-VR4X5O2Z.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:path3})=>`https://${domain}/${user}/${project}${maybeJoin("/",editpath,"/",maybeEncode(committish||"HEAD"),"/",path3)}`,browsetemplate:({domain,user,project,committish,treepath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}`,browsetreetemplate:({domain,user,project,committish,treepath,path:path3,fragment,hashformat})=>`https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish||"HEAD")}/${path3}${maybeJoin("#",hashformat(fragment||""))}`,browseblobtemplate:({domain,user,project,committish,blobpath,path:path3,fragment,hashformat})=>`https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish||"HEAD")}/${path3}${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:path3})=>`https://${domain}/${user}/${project}/raw/${maybeEncode(committish||"HEAD")}/${path3}`,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:path3})=>`https://${maybeJoin(auth,"@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish||"HEAD")}/${path3}`,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:path3,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish||"HEAD"),"/",path3,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 path3=url.pathname.slice(1);if(path3.includes("/-/")||path3.includes("/archive.tar.gz"))return;let segments=path3.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:path3,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path3))}`,browseblobtemplate:({domain,project,committish,path:path3,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path3))}`,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:path3})=>`https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/",maybeEncode(committish))}/${path3}`,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:path3})=>`https://${domain}/${user}/${project}/blob/${maybeEncode(committish)||"HEAD"}/${path3}`,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(),cache=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:",path3=pathname.replace(/\.git$/,"");return`${proto}//${hostname}${path3}`}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(!cache.has(key)){let hostArgs=fromUrl(giturl,opts,{gitHosts:_GitHost.#gitHosts,protocols:_GitHost.#protocols});cache.set(key,hostArgs?new _GitHost(...hostArgs):void 0)}return cache.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(path3,...args){return typeof path3!="string"?this.#fill(this.browsetemplate,path3):typeof args[0]!="string"?this.#fill(this.browsetreetemplate,{...args[0],path:path3}):this.#fill(this.browsetreetemplate,{...args[1],fragment:args[0],path:path3})}browseFile(path3,...args){return typeof args[0]!="string"?this.#fill(this.browseblobtemplate,{...args[0],path:path3}):this.#fill(this.browseblobtemplate,{...args[1],fragment:args[0],path:path3})}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(path3,opts){return this.#fill(this.filetemplate,{...opts,path:path3})}edit(path3,opts){return this.#fill(this.edittemplate,{...opts,path:path3})}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=/^ +$/,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=path3=>{let end=path3.length-1,index=path3.lastIndexOf(SLASH,path3[end]===SLASH?end-1:end);return index<0?path3:path3.slice(index+1)},parentOf=path3=>{if(path3.charCodeAt(0)===SLASH_CODE||path3.indexOf(DOUBLE_SLASH)>=0){let slices=path3.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY}let end=path3.length-1,cut=path3.lastIndexOf(SLASH,path3.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY:path3.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(path3,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename2=shortcut?basenameOf(path3):path3;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?basename2:path3)&&(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=(path3,originalPath,doThrow)=>isString(path3)?path3?checkPath.isNotRelative(path3)?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=path3=>{let first=path3.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path3.length===1)return!0;let second=path3.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path3.length===2||path3.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,cache,checkUnignored){let path3=originalPath&&checkPath.convert(originalPath);return checkPath(path3,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path3,cache,checkUnignored)}checkIgnore(path3){if(path3.charCodeAt(path3.length-1)!==SLASH_CODE)return this.test(path3);let parentPath=parentOf(path3);if(parentPath){let parent=this._t(parentPath,this._testCache,!0);if(parent.ignored)return parent}return this._rules.test(path3,!1,MODE_CHECK_IGNORE)}_t(path3,cache,checkUnignored){if(path3 in cache)return cache[path3];let parentPath=parentOf(path3),parent=parentPath?this._t(parentPath,cache,checkUnignored):UNDEFINED;return cache[path3]=parent&&parent.ignored?parent:this._rules.test(path3,checkUnignored,MODE_IGNORE)}ignores(path3){return this._test(path3,this._ignoreCache,!1).ignored}createFilter(){return path3=>!this.ignores(path3)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path3){return this._test(path3,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path3=>checkPath(path3&&checkPath.convert(path3),path3,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=path3=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path3)||isNotRelative(path3)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});import*as fs from"node:fs";import*as path from"node:path";import{inspect}from"node:util";function redactSensitiveOutput(text){return redactSensitiveTokenValues(text.replace(/\b([A-Z][A-Z0-9_]*(?:API_KEY|SECRET|TOKEN|PASSWORD|AUTH)[A-Z0-9_]*)=([^\s'"]+)/g,"$1=[REDACTED]").replace(/\b(Authorization:\s*Bearer\s+)([^\s'"]+)/gi,"$1[REDACTED]").replace(/\b(Bearer\s+)(sk-[A-Za-z0-9._-]+)/g,"$1[REDACTED]"))}function redactSensitiveTokenValues(text,replacement="[REDACTED]"){return text.replace(/\bghp_[A-Za-z0-9]{20,}\b/g,replacement).replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,replacement)}function appendDebugLogEntry(header,text){let debugLogPath=getDebugLogPath(),prefix=`[${new Date().toISOString()}] ${header}
2
+ import{KeybindingsManager}from"./chunk-ZMFHNH6U.js";import{detectTerminalBackgroundFromEnv,detectTerminalThemeForAuto,initTheme,isStdoutTakenOver,loadThemeFromPath,parseAutoThemeSetting,resolveThemeSetting,setRegisteredThemes,setTheme,theme}from"./chunk-V2ZB62DG.js";import{Container,Input,ProcessTerminal,Spacer,TUI,Text,fuzzyMatch,getKeybindings,setCapabilityOverrides,setKeybindings,truncateToWidth,visibleWidth}from"./chunk-DQZB4GVV.js";import{SettingsManager}from"./chunk-Z4LHCTJ6.js";import{require_semver}from"./chunk-I7YUNMWH.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,PACKAGE_NAME,canonicalizePath,envValue,getAgentDir,getDebugLogPath,getSettingsPath,isLocalPath,markPathIgnoredByCloudSync,resolvePath,spawnProcess,spawnProcessSync,stripBom}from"./chunk-H5RK2RYZ.js";import{__commonJS,__require,__toESM}from"./chunk-VR4X5O2Z.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:path3})=>`https://${domain}/${user}/${project}${maybeJoin("/",editpath,"/",maybeEncode(committish||"HEAD"),"/",path3)}`,browsetemplate:({domain,user,project,committish,treepath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}`,browsetreetemplate:({domain,user,project,committish,treepath,path:path3,fragment,hashformat})=>`https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish||"HEAD")}/${path3}${maybeJoin("#",hashformat(fragment||""))}`,browseblobtemplate:({domain,user,project,committish,blobpath,path:path3,fragment,hashformat})=>`https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish||"HEAD")}/${path3}${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:path3})=>`https://${domain}/${user}/${project}/raw/${maybeEncode(committish||"HEAD")}/${path3}`,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:path3})=>`https://${maybeJoin(auth,"@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish||"HEAD")}/${path3}`,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:path3,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish||"HEAD"),"/",path3,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 path3=url.pathname.slice(1);if(path3.includes("/-/")||path3.includes("/archive.tar.gz"))return;let segments=path3.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:path3,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path3))}`,browseblobtemplate:({domain,project,committish,path:path3,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path3))}`,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:path3})=>`https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/",maybeEncode(committish))}/${path3}`,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:path3})=>`https://${domain}/${user}/${project}/blob/${maybeEncode(committish)||"HEAD"}/${path3}`,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(),cache=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:",path3=pathname.replace(/\.git$/,"");return`${proto}//${hostname}${path3}`}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(!cache.has(key)){let hostArgs=fromUrl(giturl,opts,{gitHosts:_GitHost.#gitHosts,protocols:_GitHost.#protocols});cache.set(key,hostArgs?new _GitHost(...hostArgs):void 0)}return cache.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(path3,...args){return typeof path3!="string"?this.#fill(this.browsetemplate,path3):typeof args[0]!="string"?this.#fill(this.browsetreetemplate,{...args[0],path:path3}):this.#fill(this.browsetreetemplate,{...args[1],fragment:args[0],path:path3})}browseFile(path3,...args){return typeof args[0]!="string"?this.#fill(this.browseblobtemplate,{...args[0],path:path3}):this.#fill(this.browseblobtemplate,{...args[1],fragment:args[0],path:path3})}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(path3,opts){return this.#fill(this.filetemplate,{...opts,path:path3})}edit(path3,opts){return this.#fill(this.edittemplate,{...opts,path:path3})}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=/^ +$/,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=path3=>{let end=path3.length-1,index=path3.lastIndexOf(SLASH,path3[end]===SLASH?end-1:end);return index<0?path3:path3.slice(index+1)},parentOf=path3=>{if(path3.charCodeAt(0)===SLASH_CODE||path3.indexOf(DOUBLE_SLASH)>=0){let slices=path3.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY}let end=path3.length-1,cut=path3.lastIndexOf(SLASH,path3.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY:path3.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(path3,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename2=shortcut?basenameOf(path3):path3;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?basename2:path3)&&(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=(path3,originalPath,doThrow)=>isString(path3)?path3?checkPath.isNotRelative(path3)?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=path3=>{let first=path3.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path3.length===1)return!0;let second=path3.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path3.length===2||path3.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,cache,checkUnignored){let path3=originalPath&&checkPath.convert(originalPath);return checkPath(path3,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path3,cache,checkUnignored)}checkIgnore(path3){if(path3.charCodeAt(path3.length-1)!==SLASH_CODE)return this.test(path3);let parentPath=parentOf(path3);if(parentPath){let parent=this._t(parentPath,this._testCache,!0);if(parent.ignored)return parent}return this._rules.test(path3,!1,MODE_CHECK_IGNORE)}_t(path3,cache,checkUnignored){if(path3 in cache)return cache[path3];let parentPath=parentOf(path3),parent=parentPath?this._t(parentPath,cache,checkUnignored):UNDEFINED;return cache[path3]=parent&&parent.ignored?parent:this._rules.test(path3,checkUnignored,MODE_IGNORE)}ignores(path3){return this._test(path3,this._ignoreCache,!1).ignored}createFilter(){return path3=>!this.ignores(path3)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path3){return this._test(path3,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path3=>checkPath(path3&&checkPath.convert(path3),path3,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=path3=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path3)||isNotRelative(path3)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});import*as fs from"node:fs";import*as path from"node:path";import{inspect}from"node:util";function redactSensitiveOutput(text){return redactSensitiveTokenValues(text.replace(/\b([A-Z][A-Z0-9_]*(?:API_KEY|SECRET|TOKEN|PASSWORD|AUTH)[A-Z0-9_]*)=([^\s'"]+)/g,"$1=[REDACTED]").replace(/\b(Authorization:\s*Bearer\s+)([^\s'"]+)/gi,"$1[REDACTED]").replace(/\b(Bearer\s+)(sk-[A-Za-z0-9._-]+)/g,"$1[REDACTED]"))}function redactSensitiveTokenValues(text,replacement="[REDACTED]"){return text.replace(/\bghp_[A-Za-z0-9]{20,}\b/g,replacement).replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,replacement)}function appendDebugLogEntry(header,text){let debugLogPath=getDebugLogPath(),prefix=`[${new Date().toISOString()}] ${header}
3
3
  `,redactedText=redactSensitiveOutput(text),suffix=redactedText.endsWith(`
4
4
  `)?"":`
5
5
  `;fs.mkdirSync(path.dirname(debugLogPath),{recursive:!0}),fs.appendFileSync(debugLogPath,`${prefix}${redactedText}${suffix}`,{mode:384}),fs.chmodSync(debugLogPath,384)}function appendHiddenTuiStdout(text){text.length!==0&&appendDebugLogEntry("hidden stdout while TUI active",text)}function appendUncaughtCrashLog(origin,error){appendDebugLogEntry(`uncaught crash (${origin})`,describeCrash(error))}function describeCrash(error){if(error instanceof Error){let identity=`${error.name}: ${error.message}`,stack=typeof error.stack=="string"&&error.stack.length>0?error.stack:void 0;return stack===void 0||stack.startsWith(identity)?stack??identity:`${identity}
6
6
  ${stack}`}try{return typeof error=="string"?error:inspect(error,{depth:3})}catch{return"<unprintable crash value>"}}var DynamicBorder=class{constructor(color=str=>theme.fg("border",str)){this.color=color}invalidate(){}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="",path3="",scpLikeMatch=repoWithoutRef.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch)host=scpLikeMatch[1]??"",path3=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,path3=parsed.pathname.replace(/^\/+/,"")}catch{return null}else{let slashIndex=repoWithoutRef.indexOf("/");if(slashIndex<0||(host=repoWithoutRef.slice(0,slashIndex),path3=repoWithoutRef.slice(slashIndex+1),!host.includes(".")&&host!=="localhost"))return null;repo=`https://${repoWithoutRef}`}return buildGitSource({repo,host,path:path3,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}from"node:crypto";import{chmodSync as chmodSync2,existsSync as existsSync2,globSync,mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync3,rmSync,statSync as statSync2,writeFileSync}from"node:fs";import{homedir}from"node:os";var import_ignore2=__toESM(require_ignore(),1);import{basename,dirname as dirname2,join as join2,relative as relative2,resolve,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;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 parseCommaParts(str){if(!str)return[""];let parts=[],m=balanced("{","}",str);if(!m)return str.split(",");let{pre,body,post}=m,p=pre.split(",");p[p.length-1]+="{"+body+"}";let postParts=parseCommaParts(post);return post.length&&(p[p.length-1]+=postParts.shift(),p.push.apply(p,postParts)),parts.push.apply(parts,p),parts}function expand(str,options={}){if(!str)return[];let{max=EXPANSION_MAX,maxLength=EXPANSION_MAX_LENGTH}=options;return str.slice(0,2)==="{}"&&(str="\\{\\}"+str.slice(2)),expand_(escapeBraces(str),max,maxLength,!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,isTop){let acc=[""],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(m.post.match(/,(?!,).*\}/)){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,!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,!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",path2={win32:{sep:"\\"},posix:{sep:"/"}},sep=defaultPlatform==="win32"?path2.win32.sep:path2.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("|"),[open,close]=set.length>1?["(?:",")"]:["",""];re="^"+open+re+close+"$",this.partial&&(re="^(?:\\/|"+open+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}from"node:fs";var RESOURCE_FIELDS=["extensions","skills","prompts","themes","hooks"];function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg=JSON.parse(stripBom(readFileSync(packageJsonPath,"utf-8")));if(!isObject(pkg)||!isObject(pkg.pi))return null;let manifest={};typeof pkg.pi.system=="boolean"&&(manifest.system=pkg.pi.system);for(let field of RESOURCE_FIELDS){let entries=pkg.pi[field];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field]=entries)}return manifest}catch{return null}}var import_ignore=__toESM(require_ignore(),1);import{closeSync,existsSync,fstatSync,openSync,readdirSync,readFileSync as readFileSync2,readSync,statSync}from"node:fs";import{join,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(`
7
- ---`),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=join(dir,filename);if(existsSync(ignorePath))try{let patterns=readFileSync2(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=openSync(filePath,"r");try{let prefix=Buffer.allocUnsafe(SKILL_FRONTMATTER_PREFIX_BYTES),bytesRead=readSync(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=fstatSync(fd).size-bytesRead;if(restSize<=0)return decodeFrontmatterSource(prefixBuf);let rest=Buffer.allocUnsafe(restSize);return readSync(fd,rest,0,restSize,bytesRead),decodeFrontmatterSource(Buffer.concat([prefixBuf,rest]))}finally{closeSync(fd)}}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir){let entries=[];if(!existsSync(dir))return entries;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore.default)();addIgnoreRules(ig,dir,root);try{let dirEntries=readdirSync(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync(fullPath).isFile()}catch{continue}let relPath=toPosixPath(relative(root,fullPath));if(isFile&&!ig.ignores(relPath))return entries.push(fullPath),entries}for(let entry of dirEntries){if(shouldSkipSkillWalkDirectoryName(entry.name))continue;let fullPath=join(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath(relative(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&!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=readFileSync3("/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.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=join2(agentDir,"tmp","extensions");return mkdirSync2(tempFolder,{recursive:!0,mode:448}),chmodSync2(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=join2(dir,filename);if(existsSync2(ignorePath))try{let patterns=readFileSync3(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=>resolve(root,match2)).filter(path3=>relative2(root,path3).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(!existsSync2(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore2.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync2(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync2(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=resolve(startDir);for(;;){if(existsSync2(join2(dir,".git")))return dir;let parent=dirname2(dir);if(parent===dir)return null;dir=parent}}function collectAncestorAgentsSkillDirs(startDir){let skillDirs=[],resolvedStartDir=resolve(startDir),gitRepoRoot=findGitRepoRoot(resolvedStartDir),dir=resolvedStartDir;for(;skillDirs.push(join2(dir,".agents","skills")),!(gitRepoRoot&&dir===gitRepoRoot);){let parent=dirname2(dir);if(parent===dir)break;dir=parent}return skillDirs}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync2(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync2(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(!existsSync2(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync2(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=join2(dir,"package.json");if(existsSync2(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=resolve(dir,extPath);existsSync2(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=join2(dir,"index.ts"),indexJs=join2(dir,"index.js");return existsSync2(indexTs)?[indexTs]:existsSync2(indexJs)?[indexJs]:null}function collectAutoExtensionEntries(dir){let entries=[];if(!existsSync2(dir))return entries;let rootEntries=resolveExtensionEntries(dir);if(rootEntries)return rootEntries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync2(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=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentName=isSkillFile?basename(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath2(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath2(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var DefaultPackageManager=class{constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager}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 path3=this.getNpmInstallPath(parsed,scope);return existsSync2(path3)?path3:void 0}if(parsed.type==="git"){let path3=this.getGitInstallPath(parsed,scope);return existsSync2(path3)?path3:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path3=this.resolvePathFromBase(parsed.path,baseDir);return existsSync2(path3)?path3: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=join2(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)}return this.addAutoDiscoveredResources(accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir),this.toResolvedPaths(accumulator)}async resolveExtensionSources(sources,options){let accumulator=this.createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user",packageSources=sources.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(!existsSync2(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=existsSync2(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!existsSync2(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(!(!existsSync2(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(!existsSync2(installedPath)||!await this.installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync2(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=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(existsSync2(resolved))try{let stats=statSync2(resolved);if(stats.isFile()){metadata.baseDir=dirname2(resolved),this.addResource(accumulator.extensions,resolved,metadata,!0);return}stats.isDirectory()&&(metadata.baseDir=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=join2(installedPath,"package.json");if(existsSync2(packageJsonPath))try{let content=readFileSync3(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(),commandParts=[npmCommand.command,...npmCommand.args],separatorIndex=commandParts.lastIndexOf("--"),packageManagerCommand=separatorIndex>=0?commandParts[separatorIndex+1]:npmCommand.command;return packageManagerCommand?basename(packageManagerCommand).replace(/\.(cmd|exe)$/i,""):""}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}getGitDependencyInstallArgs(){let configuredCommand=this.settingsManager.getNpmCommand();return configuredCommand&&configuredCommand.length>0?["install"]:["install","--omit=dev"]}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(!existsSync2(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(existsSync2(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),mkdirSync2(dirname2(targetDir),{recursive:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join2(targetDir,"package.json");existsSync2(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}catch(error){throw rmSync(targetDir,{recursive:!0,force:!0}),this.pruneEmptyGitParents(targetDir,gitRoot),error}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync2(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=join2(targetDir,"package.json");if(!existsSync2(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync3(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep3}`)?!existsSync2(dependencyPath):!1})}catch{return!1}}async repairMissingGitDependencies(targetDir){this.hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}getGitUpdateMarkerPath(targetDir){return join2(dirname2(targetDir),`.${basename(targetDir)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error}let packageJsonPath=join2(targetDir,"package.json");existsSync2(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir}),rmSync(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),markerPath=this.getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync2(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync(targetDir,{recursive:!0,force:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0}),this.pruneEmptyGitParents(targetDir,this.getGitInstallRoot(scope))}pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve(installRoot),current=dirname2(targetDir);for(;current.startsWith(resolvedRoot)&&current!==resolvedRoot;){if(!existsSync2(current)){current=dirname2(current);continue}if(readdirSync2(current).length>0)break;try{rmSync(current,{recursive:!0,force:!0})}catch{break}current=dirname2(current)}}ensureNpmProject(installRoot){existsSync2(installRoot)||mkdirSync2(installRoot,{recursive:!0}),markPathIgnoredByCloudSync(installRoot),this.ensureGitIgnore(installRoot);let packageJsonPath=join2(installRoot,"package.json");existsSync2(packageJsonPath)||writeFileSync(packageJsonPath,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(dir){existsSync2(dir)||mkdirSync2(dir,{recursive:!0});let ignorePath=join2(dir,".gitignore");existsSync2(ignorePath)||writeFileSync(ignorePath,`*
7
+ ---`),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=join(dir,filename);if(existsSync(ignorePath))try{let patterns=readFileSync2(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=openSync(filePath,"r")}catch{return decodeFrontmatterSource(readFileSync2(filePath))}try{let prefix=Buffer.allocUnsafe(SKILL_FRONTMATTER_PREFIX_BYTES),bytesRead=readSync(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=fstatSync(fd).size-bytesRead;if(restSize<=0)return decodeFrontmatterSource(prefixBuf);let rest=Buffer.allocUnsafe(restSize);return readSync(fd,rest,0,restSize,bytesRead),decodeFrontmatterSource(Buffer.concat([prefixBuf,rest]))}finally{closeSync(fd)}}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir){let entries=[];if(!existsSync(dir))return entries;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore.default)();addIgnoreRules(ig,dir,root);try{let dirEntries=readdirSync(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync(fullPath).isFile()}catch{continue}let relPath=toPosixPath(relative(root,fullPath));if(isFile&&!ig.ignores(relPath))return entries.push(fullPath),entries}for(let entry of dirEntries){if(shouldSkipSkillWalkDirectoryName(entry.name))continue;let fullPath=join(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath(relative(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&!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=readFileSync3("/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.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=join2(agentDir,"tmp","extensions");return mkdirSync2(tempFolder,{recursive:!0,mode:448}),chmodSync2(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=join2(dir,filename);if(existsSync2(ignorePath))try{let patterns=readFileSync3(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=>resolve(root,match2)).filter(path3=>relative2(root,path3).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(!existsSync2(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore2.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync2(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync2(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=resolve(startDir);for(;;){if(existsSync2(join2(dir,".git")))return dir;let parent=dirname2(dir);if(parent===dir)return null;dir=parent}}function collectAncestorAgentsSkillDirs(startDir){let skillDirs=[],resolvedStartDir=resolve(startDir),gitRepoRoot=findGitRepoRoot(resolvedStartDir),dir=resolvedStartDir;for(;skillDirs.push(join2(dir,".agents","skills")),!(gitRepoRoot&&dir===gitRepoRoot);){let parent=dirname2(dir);if(parent===dir)break;dir=parent}return skillDirs}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync2(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync2(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(!existsSync2(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync2(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=join2(dir,"package.json");if(existsSync2(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=resolve(dir,extPath);existsSync2(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=join2(dir,"index.ts"),indexJs=join2(dir,"index.js");return existsSync2(indexTs)?[indexTs]:existsSync2(indexJs)?[indexJs]:null}function collectAutoExtensionEntries(dir){let entries=[];if(!existsSync2(dir))return entries;let rootEntries=resolveExtensionEntries(dir);if(rootEntries)return rootEntries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join2(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync2(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=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentName=isSkillFile?basename(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath2(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath2(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var DefaultPackageManager=class{constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager}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 path3=this.getNpmInstallPath(parsed,scope);return existsSync2(path3)?path3:void 0}if(parsed.type==="git"){let path3=this.getGitInstallPath(parsed,scope);return existsSync2(path3)?path3:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path3=this.resolvePathFromBase(parsed.path,baseDir);return existsSync2(path3)?path3: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=join2(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)}return this.addAutoDiscoveredResources(accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir),this.toResolvedPaths(accumulator)}async resolveExtensionSources(sources,options){let accumulator=this.createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user",packageSources=sources.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(!existsSync2(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=existsSync2(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!existsSync2(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(!(!existsSync2(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(!existsSync2(installedPath)||!await this.installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync2(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=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(existsSync2(resolved))try{let stats=statSync2(resolved);if(stats.isFile()){metadata.baseDir=dirname2(resolved),this.addResource(accumulator.extensions,resolved,metadata,!0);return}stats.isDirectory()&&(metadata.baseDir=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=join2(installedPath,"package.json");if(existsSync2(packageJsonPath))try{let content=readFileSync3(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(),commandParts=[npmCommand.command,...npmCommand.args],separatorIndex=commandParts.lastIndexOf("--"),packageManagerCommand=separatorIndex>=0?commandParts[separatorIndex+1]:npmCommand.command;return packageManagerCommand?basename(packageManagerCommand).replace(/\.(cmd|exe)$/i,""):""}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}getGitDependencyInstallArgs(){let configuredCommand=this.settingsManager.getNpmCommand();return configuredCommand&&configuredCommand.length>0?["install"]:["install","--omit=dev"]}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(!existsSync2(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(existsSync2(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),mkdirSync2(dirname2(targetDir),{recursive:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join2(targetDir,"package.json");existsSync2(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}catch(error){throw rmSync(targetDir,{recursive:!0,force:!0}),this.pruneEmptyGitParents(targetDir,gitRoot),error}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync2(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=join2(targetDir,"package.json");if(!existsSync2(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync3(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep3}`)?!existsSync2(dependencyPath):!1})}catch{return!1}}async repairMissingGitDependencies(targetDir){this.hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}getGitUpdateMarkerPath(targetDir){return join2(dirname2(targetDir),`.${basename(targetDir)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error}let packageJsonPath=join2(targetDir,"package.json");existsSync2(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir}),rmSync(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),markerPath=this.getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync2(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync(targetDir,{recursive:!0,force:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0}),this.pruneEmptyGitParents(targetDir,this.getGitInstallRoot(scope))}pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve(installRoot),current=dirname2(targetDir);for(;current.startsWith(resolvedRoot)&&current!==resolvedRoot;){if(!existsSync2(current)){current=dirname2(current);continue}if(readdirSync2(current).length>0)break;try{rmSync(current,{recursive:!0,force:!0})}catch{break}current=dirname2(current)}}ensureNpmProject(installRoot){existsSync2(installRoot)||mkdirSync2(installRoot,{recursive:!0}),markPathIgnoredByCloudSync(installRoot),this.ensureGitIgnore(installRoot);let packageJsonPath=join2(installRoot,"package.json");existsSync2(packageJsonPath)||writeFileSync(packageJsonPath,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(dir){existsSync2(dir)||mkdirSync2(dir,{recursive:!0});let ignorePath=join2(dir,".gitignore");existsSync2(ignorePath)||writeFileSync(ignorePath,`*
8
8
  !.gitignore
9
9
  `,"utf-8")}getNpmInstallRoot(scope,temporary){return temporary?this.getTemporaryDir("npm"):scope==="project"?(this.assertProjectTrustedForScope(scope),join2(this.cwd,CONFIG_DIR_NAME,"npm")):join2(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=join2(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 path3=entry.dependencies?.[packageName]?.path;if(path3)return path3}}getManagedNpmInstallPath(source,scope){return scope==="temporary"?join2(this.getTemporaryDir("npm"),"node_modules",source.name):scope==="project"?(this.assertProjectTrustedForScope(scope),join2(this.cwd,CONFIG_DIR_NAME,"npm","node_modules",source.name)):join2(this.agentDir,"npm","node_modules",source.name)}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join2(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=this.getManagedNpmInstallPath(source,scope);if(scope!=="user"||existsSync2(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync2(legacyPath)?legacyPath:managedPath}getGitInstallPath(source,scope){if(scope==="temporary")return this.getTemporaryDir(`git-${source.host}`,source.path);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),join2(this.cwd,CONFIG_DIR_NAME,"git")):join2(this.agentDir,"git")}getTemporaryDir(prefix,suffix){let root=this.resolveManagedPath(getExtensionTempFolder(this.agentDir),prefix),hash=createHash("sha256").update(`${prefix}-${suffix??""}`).digest("hex").slice(0,8);return this.resolveManagedPath(root,hash,suffix??"")}resolveManagedPath(root,...parts){let resolvedRoot=resolve(root),resolvedPath=resolve(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),join2(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(join2(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=join2(packageRoot,resourceType);if(existsSync2(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(join2(packageRoot,"package.json"))?.[resourceType];if(entries){this.addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join2(packageRoot,resourceType);if(existsSync2(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(join2(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=join2(packageRoot,resourceType);if(!existsSync2(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):[resolve(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:join2(globalBaseDir,"extensions"),skills:join2(globalBaseDir,"skills"),prompts:join2(globalBaseDir,"prompts"),themes:join2(globalBaseDir,"themes"),hooks:join2(globalBaseDir,"hooks")},projectDirs={extensions:join2(projectBaseDir,"extensions"),skills:join2(projectBaseDir,"skills"),prompts:join2(projectBaseDir,"prompts"),themes:join2(projectBaseDir,"themes"),hooks:join2(projectBaseDir,"hooks")},legacyProjectBaseDir=join2(this.cwd,".pi"),legacyProjectDirs={extensions:join2(legacyProjectBaseDir,"extensions"),skills:join2(legacyProjectBaseDir,"skills"),prompts:join2(legacyProjectBaseDir,"prompts"),themes:join2(legacyProjectBaseDir,"themes"),hooks:join2(legacyProjectBaseDir,"hooks")},userAgentsSkillsDir=join2(getHomeDir(),".agents","skills"),projectTrusted=this.settingsManager.isProjectTrusted(),projectAgentsSkillDirs=projectTrusted?collectAncestorAgentsSkillDirs(this.cwd).filter(dir=>resolve(dir)!==resolve(userAgentsSkillsDir)):[],addResources=(resourceType,paths,metadata,overrides,baseDir)=>{let target=this.getTargetMap(accumulator,resourceType);for(let path3 of paths){let enabled=isEnabledByOverrides(path3,overrides,baseDir);this.addResource(target,path3,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)),resolve(legacyProjectBaseDir)!==resolve(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(existsSync2(p))try{let stats=statSync2(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,path3,metadata,enabled){path3&&(map.has(path3)||map.set(path3,{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(([path3,{metadata,enabled}])=>({path:path3,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})}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})}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});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),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===`
10
10
  `?this.onSubmitCallback(this.input.getValue()):kb.matches(keyData,"tui.select.cancel")?this.onCancelCallback():this.input.handleInput(keyData)}dispose(){this.countdown?.dispose()}};var ExtensionSelectorComponent=class _ExtensionSelectorComponent extends Container{static{this.DEFAULT_MAX_VISIBLE_OPTIONS=10}constructor(title,options,onSelect,onCancel,opts){super(),this.selectedIndex=0,this.options=options,this.onSelectCallback=onSelect,this.onCancelCallback=onCancel,this.onToggleToolsExpanded=opts?.onToggleToolsExpanded,this.baseTitle=title,this.maxVisibleOptions=opts?.tui?Math.max(5,Math.floor(opts.tui.terminal.rows/2)):_ExtensionSelectorComponent.DEFAULT_MAX_VISIBLE_OPTIONS,this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.titleText=new Text(theme.fg("accent",theme.bold(title)),1,0),this.addChild(this.titleText),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",theme.bold(`${this.baseTitle} (${s}s)`))),()=>this.onCancelCallback())),this.listContainer=new Container,this.addChild(this.listContainer),this.addChild(new Spacer(1)),this.addChild(new Text(rawKeyHint("\u2191\u2193","navigate")+" "+keyHint("tui.select.confirm","select")+" "+keyHint("tui.select.cancel","cancel"),1,0)),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder),this.updateList()}updateList(){this.listContainer.clear();let count=this.options.length,startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisibleOptions/2),count-this.maxVisibleOptions)),endIndex=Math.min(startIndex+this.maxVisibleOptions,count);startIndex>0&&this.listContainer.addChild(new Text(theme.fg("muted",` \u2026 ${startIndex} more above`),1,0));for(let i=startIndex;i<endIndex;i++){let text=i===this.selectedIndex?theme.fg("accent","\u2192 ")+theme.fg("accent",this.options[i]):` ${theme.fg("text",this.options[i])}`;this.listContainer.addChild(new Text(text,1,0))}endIndex<count&&this.listContainer.addChild(new Text(theme.fg("muted",` \u2026 ${count-endIndex} more below`),1,0))}handleInput(keyData){let kb=getKeybindings();if(kb.matches(keyData,"app.tools.expand"))this.onToggleToolsExpanded?.();else if(kb.matches(keyData,"tui.select.up")||keyData==="k")this.selectedIndex=Math.max(0,this.selectedIndex-1),this.updateList();else if(kb.matches(keyData,"tui.select.down")||keyData==="j")this.selectedIndex=Math.min(this.options.length-1,this.selectedIndex+1),this.updateList();else if(kb.matches(keyData,"tui.select.confirm")||keyData===`