@code-yeongyu/senpi 2026.10.24-4 → 2026.10.25-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/bundle/chunks/{chunk-IUHU5PEC.js → chunk-7WAJCESX.js} +1 -1
- package/dist/bundle/chunks/{chunk-NQC7MI2G.js → chunk-BTNYLNWZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-UT6AJHPK.js → chunk-EYBDBR7V.js} +1 -1
- package/dist/bundle/chunks/{chunk-HKUXKTFW.js → chunk-J5P2VL3Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-GVJ76VQI.js → chunk-URBJS24R.js} +54 -54
- package/dist/bundle/chunks/{chunk-42OY5SZZ.js → chunk-YDCRA5ES.js} +1 -1
- package/dist/bundle/chunks/{cli-main-UH3MAREK.js → cli-main-TABBP55A.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-R5RCSJ2F.js → interactive-mode-DGQNSXUA.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-YZEMYUFY.js → multi-session-host-M7HVUMRH.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-5FOXDKUA.js → package-manager-cli-FSR5P6YL.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-6K62CZBW.js → rpc-mode-SZAJNKKL.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-54TMCS7Q.js → session-control-endpoint-WEF3XTJR.js} +1 -1
- package/dist/bundle/chunks/{session-picker-P2VUU2MQ.js → session-picker-KQUFWDQC.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +56 -56
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-binding.d.ts +2 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-commit-boundary.d.ts +6 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-commit-boundary.js +18 -7
- package/dist/core/extensions/builtin/anthropic-subscription/session-commit-divergence.d.ts +23 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-commit-divergence.js +107 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-entry-annotations.d.ts +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-entry-annotations.js +3 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-observability.d.ts +3 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-observability.js +4 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-wiring.js +12 -7
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry.d.ts +3 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry.js +3 -2
- package/dist/core/extensions/builtin/anthropic-subscription/session-stream.js +2 -0
- package/dist/core/skill-access.js +15 -3
- package/dist/core/skill-discovery.d.ts +2 -0
- package/dist/core/skill-discovery.js +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2026.10.25-1] - 2026-10-25
|
|
4
|
+
|
|
5
|
+
### Breaking Changes
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- When the Anthropic Subscription commit boundary sees a committed assistant that differs from what the provider streamed, the `assistant_rewritten` record, the continuity log line and the next continuity observation now name the first field that diverged (for example `content[0].arguments.summary`), never its value ([#1975](https://github.com/code-yeongyu/senpi/issues/1975))
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- Skill loading no longer rescans every user root once per discovered skill; project skill containment remains enforced. Thanks to @haifenghan for the report ([#4214](https://github.com/code-yeongyu/senpi/pull/4214)).
|
|
16
|
+
|
|
17
|
+
### Removed
|
|
18
|
+
|
|
3
19
|
## [2026.10.24-4] - 2026-10-24
|
|
4
20
|
|
|
5
21
|
### Breaking Changes
|
|
@@ -1,3 +1,3 @@
|
|
|
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
2
|
import{require_semver}from"./chunk-ZOFZRJSL.js";import{fetchWithRetry}from"./chunk-2SOVDETB.js";import{APP_NAME,BRAND,DISPLAY_VERSION,PACKAGE_NAME,brandProfile,envValue}from"./chunk-7YO7VQZW.js";import{__toESM}from"./chunk-IKOFCODM.js";import{spawnSync}from"node:child_process";import{homedir as osHomedir}from"node:os";import{posix,win32}from"node:path";var RUNTIME_ENV_VAR="SENPI_RUNTIME",MIN_BUN_VERSION="1.4.0";function normalize(path){return path.replaceAll("\\","/")}function paths(options){return options.platform==="win32"?win32:posix}function bunRoot(options){let configured=options.env.BUN_INSTALL;return configured!==void 0&&configured.trim()!==""?configured:paths(options).join(options.homedir,".bun")}function resolveOrSelf(path,options){try{return options.realpath(path)}catch{return path}}function isUnderBunGlobalTree(scriptRealPath,options){let globalRoot=paths(options).join(bunRoot(options),"install","global"),script=normalize(scriptRealPath);for(let candidate of new Set([globalRoot,resolveOrSelf(globalRoot,options)]))if(script.startsWith(`${normalize(candidate)}/`))return!0;return!1}function isInstalledPackageScript(scriptRealPath){return normalize(scriptRealPath).includes("/node_modules/")}function bunVersionSatisfies(version){let actual=/^v?(\d+)\.(\d+)\.(\d+)/.exec(version?.trim()??""),minimum=/^(\d+)\.(\d+)\.(\d+)/.exec(MIN_BUN_VERSION);if(!actual||!minimum)return!1;for(let index=1;index<=3;index++){let difference=Number(actual[index])-Number(minimum[index]);if(difference!==0)return difference>0}return!0}function bunExecutableName(options){return options.platform==="win32"?"bun.exe":"bun"}function pathCandidateNames(options){if(options.platform!=="win32")return["bun"];let extensions=(options.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(extension=>extension.trim()).filter(extension=>extension.length>0);return extensions.length>0?extensions.map(extension=>`bun${extension}`):["bun.exe"]}function findBunBinary(options){let path=paths(options),executable=bunExecutableName(options),rootCandidates=[path.join(bunRoot(options),"bin",executable),path.join(options.homedir,".bun","bin",executable)];for(let candidate of rootCandidates)if(options.exists(candidate))return candidate;let pathValue=options.env.PATH??options.env.Path;if(pathValue===void 0||pathValue==="")return;let names=pathCandidateNames(options);for(let directory of pathValue.split(path.delimiter))if(directory!=="")for(let name of names){let candidate=path.join(directory,name);if(options.exists(candidate))return candidate}}function readRuntimePin(options){let value=options.env[RUNTIME_ENV_VAR];if(value==="node"||value==="bun")return value}function resolveBunReexec(input){if(input.versions.bun!==void 0)return{action:"stay",reason:"already-bun"};let pinned=readRuntimePin(input.options);if(pinned==="node")return{action:"stay",reason:"runtime-pinned-node"};if(input.hasInheritedInspectorOption)return{action:"stay",reason:"inspector"};let trustsInstalledBun=pinned==="bun"||isUnderBunGlobalTree(input.scriptRealPath,input.options);if(!trustsInstalledBun&&!isInstalledPackageScript(input.scriptRealPath))return{action:"stay",reason:"not-bun-install"};let bunPath=findBunBinary(input.options);return bunPath===void 0?{action:"stay",reason:"bun-not-found"}:!trustsInstalledBun&&!bunVersionSatisfies(input.options.bunVersion(bunPath))?{action:"stay",reason:"bun-too-old"}:{action:"reexec",bunPath}}function readBunVersion(bunPath){try{let result=spawnSync(bunPath,["--version"],{encoding:"utf8",timeout:5e3,windowsHide:!0});if(result.status!==0)return;let version=result.stdout.trim();return version===""?void 0:version}catch{return}}function processBunRuntimeOptions(exists,realpath){return{env:process.env,homedir:osHomedir(),platform:process.platform,exists,realpath,bunVersion:readBunVersion}}import{format}from"node:util";var OUTPUT_DELIVERY_LIMIT_MS=3e4,nativeLog=console.log,nativeStdoutWrite=process.stdout.write;async function captureStdout(print){if(console.log!==nativeLog||process.stdout.write!==nativeStdoutWrite)return{result:await print(),output:""};let chunks=[];console.log=(...args)=>{chunks.push(`${format(...args)}
|
|
3
|
-
`)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}function getPiUserAgent(version=DISPLAY_VERSION){let runtime=process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`;return`${BRAND?.userAgent??APP_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`}var modeHandlers=new WeakSet;function markModeCrashHandler(listener){modeHandlers.add(listener)}function hasModeCrashHandler(event){return process.listeners(event).some(listener=>modeHandlers.has(listener))}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var StaleExtensionContextError=class extends Error{constructor(){super(...arguments),this.name="StaleExtensionContextError"}};var STALE_EXTENSION_CONTEXT_ERROR_PREFIX="This extension ctx is stale after session replacement or reload.",STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE="stale extension generation after reload";function isStaleExtensionContextError(error){return error instanceof StaleExtensionContextError?!0:error instanceof Error&&(error.message.startsWith(STALE_EXTENSION_CONTEXT_ERROR_PREFIX)||error.message===STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE)}var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var import_semver=__toESM(require_semver(),1);var REGISTRY_BASE_URL="https://registry.npmjs.org",LATEST_VERSION_URL=`${REGISTRY_BASE_URL}/${encodeURIComponent(PACKAGE_NAME)}/latest`;function latestVersionUrl(channel){return channel?`${REGISTRY_BASE_URL}/-/package/${encodeURIComponent(channel.packageName)}/dist-tags`:LATEST_VERSION_URL}function readAvailableVersion(payload,channel){if(typeof payload!="object"||payload===null)return;let source=payload,raw=channel?source[channel.distTag]:source.version;return typeof raw=="string"&&raw.trim()?raw.trim():void 0}var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4,RELEASE_CHANGELOG_BASE_URL="https://github.com/code-yeongyu/senpi/blob",RELEASE_CHANGELOG_PATH="packages/coding-agent/CHANGELOG.md",SENPI_CALVER_PATTERN=/^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-([2-9]\d*))?$/;function parseSenpiCalVer(version){let match=SENPI_CALVER_PATTERN.exec(version);if(match)return[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??1)]}function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let leftTrimmed=leftVersion.trim(),rightTrimmed=rightVersion.trim(),leftCalVer=parseSenpiCalVer(leftTrimmed),rightCalVer=parseSenpiCalVer(rightTrimmed);if(leftCalVer&&rightCalVer){for(let index=0;index<leftCalVer.length;index++)if(leftCalVer[index]!==rightCalVer[index])return leftCalVer[index]<rightCalVer[index]?-1:1;return 0}let left=(0,import_semver.valid)(leftTrimmed),right=(0,import_semver.valid)(rightTrimmed);if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(candidateVersion,currentVersion);return comparison!==void 0&&comparison>0}function getReleaseChangelogUrl(version){let trimmedVersion=version.trim(),channel=brandProfile()?.update;if(channel?.changelogUrl)return channel.changelogUrl.replace("{version}",trimmedVersion);let tag=trimmedVersion.startsWith("v")?trimmedVersion:`v${trimmedVersion}`;return`${RELEASE_CHANGELOG_BASE_URL}/${tag}/${RELEASE_CHANGELOG_PATH}`}async function getLatestPiRelease(currentVersion,options={}){if(envValue("OFFLINE"))return;let brand=brandProfile(),channel=brand?.update;if(brand&&!channel)return;let response=await fetchWithRetry(latestVersionUrl(channel),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json(),availableVersion=readAvailableVersion(data,channel);if(!availableVersion)return;if(channel)return{version:availableVersion,packageName:channel.packageName};let packageName=typeof data.packageName=="string"&&data.packageName.trim()?data.packageName.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:availableVersion,packageName,note}}async function checkForNewPiVersion(currentVersion){if(!envValue("SKIP_VERSION_CHECK"))try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-
|
|
3
|
+
`)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}function getPiUserAgent(version=DISPLAY_VERSION){let runtime=process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`;return`${BRAND?.userAgent??APP_NAME}/${version} (${process.platform}; ${runtime}; ${process.arch})`}var modeHandlers=new WeakSet;function markModeCrashHandler(listener){modeHandlers.add(listener)}function hasModeCrashHandler(event){return process.listeners(event).some(listener=>modeHandlers.has(listener))}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var StaleExtensionContextError=class extends Error{constructor(){super(...arguments),this.name="StaleExtensionContextError"}};var STALE_EXTENSION_CONTEXT_ERROR_PREFIX="This extension ctx is stale after session replacement or reload.",STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE="stale extension generation after reload";function isStaleExtensionContextError(error){return error instanceof StaleExtensionContextError?!0:error instanceof Error&&(error.message.startsWith(STALE_EXTENSION_CONTEXT_ERROR_PREFIX)||error.message===STALE_EXTENSION_GENERATION_AFTER_RELOAD_MESSAGE)}var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var import_semver=__toESM(require_semver(),1);var REGISTRY_BASE_URL="https://registry.npmjs.org",LATEST_VERSION_URL=`${REGISTRY_BASE_URL}/${encodeURIComponent(PACKAGE_NAME)}/latest`;function latestVersionUrl(channel){return channel?`${REGISTRY_BASE_URL}/-/package/${encodeURIComponent(channel.packageName)}/dist-tags`:LATEST_VERSION_URL}function readAvailableVersion(payload,channel){if(typeof payload!="object"||payload===null)return;let source=payload,raw=channel?source[channel.distTag]:source.version;return typeof raw=="string"&&raw.trim()?raw.trim():void 0}var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4,RELEASE_CHANGELOG_BASE_URL="https://github.com/code-yeongyu/senpi/blob",RELEASE_CHANGELOG_PATH="packages/coding-agent/CHANGELOG.md",SENPI_CALVER_PATTERN=/^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-([2-9]\d*))?$/;function parseSenpiCalVer(version){let match=SENPI_CALVER_PATTERN.exec(version);if(match)return[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??1)]}function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let leftTrimmed=leftVersion.trim(),rightTrimmed=rightVersion.trim(),leftCalVer=parseSenpiCalVer(leftTrimmed),rightCalVer=parseSenpiCalVer(rightTrimmed);if(leftCalVer&&rightCalVer){for(let index=0;index<leftCalVer.length;index++)if(leftCalVer[index]!==rightCalVer[index])return leftCalVer[index]<rightCalVer[index]?-1:1;return 0}let left=(0,import_semver.valid)(leftTrimmed),right=(0,import_semver.valid)(rightTrimmed);if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(candidateVersion,currentVersion);return comparison!==void 0&&comparison>0}function getReleaseChangelogUrl(version){let trimmedVersion=version.trim(),channel=brandProfile()?.update;if(channel?.changelogUrl)return channel.changelogUrl.replace("{version}",trimmedVersion);let tag=trimmedVersion.startsWith("v")?trimmedVersion:`v${trimmedVersion}`;return`${RELEASE_CHANGELOG_BASE_URL}/${tag}/${RELEASE_CHANGELOG_PATH}`}async function getLatestPiRelease(currentVersion,options={}){if(envValue("OFFLINE"))return;let brand=brandProfile(),channel=brand?.update;if(brand&&!channel)return;let response=await fetchWithRetry(latestVersionUrl(channel),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json(),availableVersion=readAvailableVersion(data,channel);if(!availableVersion)return;if(channel)return{version:availableVersion,packageName:channel.packageName};let packageName=typeof data.packageName=="string"&&data.packageName.trim()?data.packageName.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:availableVersion,packageName,note}}async function checkForNewPiVersion(currentVersion){if(!envValue("SKIP_VERSION_CHECK"))try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-FSR5P6YL.js");return await handlePackageCommand(args,runtimeOptions)}async function dispatchConfigCommand(args,runtimeOptions={}){if(args[0]!==CONFIG_COMMAND_ARGV)return!1;let{handleConfigCommand}=await import("./package-manager-cli-FSR5P6YL.js");return await handleConfigCommand(args,runtimeOptions)}async function dispatchHostCommand(args){if(args[0]!==HOST_COMMAND_ARGV)return;if(args[1]==="session"){let{runHostSessionCommand}=await import("./host-session-command-IGB27ZPJ.js");return await runHostSessionCommand(args.slice(2))}let{runHostCommand}=await import("./host-command-OQR4RDTM.js");return await runHostCommand(args.slice(1))}async function dispatchScheduleCommand(args){if(args[0]!==SCHEDULE_COMMAND_ARGV)return;let{runScheduleCommand}=await import("./schedule-command-XBW4EOG5.js");return await runScheduleCommand(args.slice(1))}export{RUNTIME_ENV_VAR,MIN_BUN_VERSION,bunVersionSatisfies,findBunBinary,resolveBunReexec,processBunRuntimeOptions,captureStdout,exitAfterOutput,printThenExit,getPiUserAgent,StaleExtensionContextError,isStaleExtensionContextError,markModeCrashHandler,hasModeCrashHandler,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,formatVersionCheckError,isNewerPackageVersion,getReleaseChangelogUrl,getLatestPiRelease,checkForNewPiVersion,CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv,dispatchPackageCommand,dispatchConfigCommand,dispatchHostCommand,dispatchScheduleCommand};
|
|
@@ -131,7 +131,7 @@ ${value}`,this.eventDataSize=eventDataSize;return}if(isFieldName(line,fieldLengt
|
|
|
131
131
|
`).slice(1).join(`
|
|
132
132
|
`);err.stack=stack?`${stack}
|
|
133
133
|
${captureLines}`:capture.stack}module.exports.fetch=function(init,options=void 0){return fetchImpl(init,options).catch(err=>{throw currentFilename?appendFetchStackTrace(err,currentFilename):err&&typeof err=="object"&&Error.captureStackTrace(err,module.exports.fetch),err})};module.exports.Headers=require_headers().Headers;module.exports.Response=require_response().Response;module.exports.Request=require_request2().Request;module.exports.FormData=require_formdata().FormData;var{setGlobalOrigin,getGlobalOrigin}=require_global();module.exports.setGlobalOrigin=setGlobalOrigin;module.exports.getGlobalOrigin=getGlobalOrigin;var{CacheStorage}=require_cachestorage(),{kConstruct}=require_symbols();module.exports.caches=new CacheStorage(kConstruct);var{deleteCookie,getCookies,getSetCookies,setCookie,parseCookie}=require_cookies();module.exports.deleteCookie=deleteCookie;module.exports.getCookies=getCookies;module.exports.getSetCookies=getSetCookies;module.exports.setCookie=setCookie;module.exports.parseCookie=parseCookie;var{parseMIMEType,serializeAMimeType}=require_data_url();module.exports.parseMIMEType=parseMIMEType;module.exports.serializeAMimeType=serializeAMimeType;var{CloseEvent,ErrorEvent,MessageEvent}=require_events(),{WebSocket,ping}=require_websocket();module.exports.WebSocket=WebSocket;module.exports.CloseEvent=CloseEvent;module.exports.ErrorEvent=ErrorEvent;module.exports.MessageEvent=MessageEvent;module.exports.ping=ping;module.exports.WebSocketStream=require_websocketstream().WebSocketStream;module.exports.WebSocketError=require_websocketerror().WebSocketError;module.exports.request=makeDispatcher(api.request);module.exports.stream=makeDispatcher(api.stream);module.exports.pipeline=makeDispatcher(api.pipeline);module.exports.connect=makeDispatcher(api.connect);module.exports.upgrade=makeDispatcher(api.upgrade);module.exports.MockClient=MockClient;module.exports.MockCallHistory=MockCallHistory;module.exports.MockCallHistoryLog=MockCallHistoryLog;module.exports.MockPool=MockPool;module.exports.MockAgent=MockAgent;module.exports.SnapshotAgent=SnapshotAgent;module.exports.mockErrors=mockErrors;var{EventSource}=require_eventsource();module.exports.EventSource=EventSource;function install2(){globalThis.fetch=module.exports.fetch,globalThis.Headers=module.exports.Headers,globalThis.Response=module.exports.Response,globalThis.Request=module.exports.Request,globalThis.FormData=module.exports.FormData,globalThis.WebSocket=module.exports.WebSocket,globalThis.CloseEvent=module.exports.CloseEvent,globalThis.ErrorEvent=module.exports.ErrorEvent,globalThis.MessageEvent=module.exports.MessageEvent,globalThis.EventSource=module.exports.EventSource}module.exports.install=install2}});var DynamicBorder=class{constructor(color=str=>theme.fg("border",str)){this.revision=nextRenderRevision(),this.color=color}invalidate(){this.revision=nextRenderRevision()}getRenderRevision(){return this.revision}render(width){return[this.color("\u2500".repeat(Math.max(1,width)))]}};var KEY_DISPLAY_ALIASES=new Map([["escape","esc"]]);function formatKeyPart(part,options){let lowerPart=part.toLowerCase(),displayPart=KEY_DISPLAY_ALIASES.get(lowerPart)??(process.platform==="darwin"&&lowerPart==="alt"?"option":part);return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}var import_hosted_git_info=__toESM(require_lib(),1);function splitRef(url){let scpLikeMatch=url.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch){let pathWithMaybeRef2=scpLikeMatch[2]??"",refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:{repo:`git@${scpLikeMatch[1]??""}:${repoPath2}`,ref:ref2}}if(url.includes("://"))try{let parsed=new URL(url),pathWithMaybeRef2=parsed.pathname.replace(/^\/+/,""),refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:(parsed.pathname=`/${repoPath2}`,{repo:parsed.toString().replace(/\/$/,""),ref:ref2})}catch{return{repo:url}}let slashIndex=url.indexOf("/");if(slashIndex<0)return{repo:url};let host=url.slice(0,slashIndex),pathWithMaybeRef=url.slice(slashIndex+1),refSeparator=pathWithMaybeRef.indexOf("@");if(refSeparator<0)return{repo:url};let repoPath=pathWithMaybeRef.slice(0,refSeparator),ref=pathWithMaybeRef.slice(refSeparator+1);return!repoPath||!ref?{repo:url}:{repo:`${host}/${repoPath}`,ref}}function decodeForValidation(value){try{return decodeURIComponent(value)}catch{return null}}function hasUnsafeGitInstallPart(value,allowSlash){let decoded=decodeForValidation(value);if(decoded===null)return!0;let candidates=[value,decoded];for(let candidate of candidates)if(candidate.includes("\0")||candidate.includes("\\")||candidate.startsWith("/")||!allowSlash&&candidate.includes("/")||candidate.split("/").includes(".."))return!0;return!1}function buildGitSource(args){if(args.path.startsWith("/"))return null;let normalizedPath=args.path.replace(/\.git$/,"").replace(/^\/+/,"");return!args.host||!normalizedPath||normalizedPath.split("/").length<2||hasUnsafeGitInstallPart(args.host,!1)||hasUnsafeGitInstallPart(normalizedPath,!0)?null:{type:"git",repo:args.repo,host:args.host,path:normalizedPath,ref:args.ref,pinned:!!args.ref}}function parseGenericGitUrl(url){let{repo:repoWithoutRef,ref}=splitRef(url),repo=repoWithoutRef,host="",path2="",scpLikeMatch=repoWithoutRef.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch)host=scpLikeMatch[1]??"",path2=scpLikeMatch[2]??"";else if(repoWithoutRef.startsWith("https://")||repoWithoutRef.startsWith("http://")||repoWithoutRef.startsWith("ssh://")||repoWithoutRef.startsWith("git://"))try{let parsed=new URL(repoWithoutRef);host=parsed.hostname,path2=parsed.pathname.replace(/^\/+/,"")}catch{return null}else{let slashIndex=repoWithoutRef.indexOf("/");if(slashIndex<0||(host=repoWithoutRef.slice(0,slashIndex),path2=repoWithoutRef.slice(slashIndex+1),!host.includes(".")&&host!=="localhost"))return null;repo=`https://${repoWithoutRef}`}return buildGitSource({repo,host,path:path2,ref})}function parseGitUrl(source){let trimmed=source.trim(),hasGitPrefix=trimmed.startsWith("git:"),url=hasGitPrefix?trimmed.slice(4).trim():trimmed;if(!hasGitPrefix&&!/^(https?|ssh|git):\/\//i.test(url))return null;let split=splitRef(url),hostedCandidates=[split.ref?`${split.repo}#${split.ref}`:void 0,url].filter(value=>!!value);for(let candidate of hostedCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;let useHttpsPrefix=!split.repo.startsWith("http://")&&!split.repo.startsWith("https://")&&!split.repo.startsWith("ssh://")&&!split.repo.startsWith("git://")&&!split.repo.startsWith("git@");return buildGitSource({repo:useHttpsPrefix?`https://${split.repo}`:split.repo,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}let httpsCandidates=[split.ref?`https://${split.repo}#${split.ref}`:void 0,`https://${url}`].filter(value=>!!value);for(let candidate of httpsCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;return buildGitSource({repo:`https://${split.repo}`,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}return parseGenericGitUrl(url)}var stdoutTakeoverState,stderrTakeoverState,visibleStderrObservation;var rawStdoutWriteTail=Promise.resolve();function getRawStdoutWrite(){return stdoutTakeoverState?stdoutTakeoverState.rawStdoutWrite:process.stdout.write.bind(process.stdout)}async function writeRawStdoutChunk(text){for(;;)try{await new Promise((resolve6,reject)=>{try{getRawStdoutWrite()(text,error=>{error?reject(error):resolve6()})}catch(error){reject(error instanceof Error?error:new Error(String(error)))}});return}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),code=writeError.code;if(code!=="ENOBUFS"&&code!=="EAGAIN"&&code!=="EWOULDBLOCK")throw writeError;await new Promise(resolve6=>setTimeout(resolve6,10))}}function takeOverStdout(){if(stdoutTakeoverState)return;let rawStdoutWrite=process.stdout.write.bind(process.stdout),rawStderrWrite=process.stderr.write.bind(process.stderr),originalStdoutWrite=process.stdout.write;process.stdout.write=((chunk,encodingOrCallback,callback)=>typeof encodingOrCallback=="function"?rawStderrWrite(String(chunk),encodingOrCallback):rawStderrWrite(String(chunk),callback)),stdoutTakeoverState={rawStdoutWrite,rawStderrWrite,originalStdoutWrite}}function restoreStdout(){stdoutTakeoverState&&(process.stdout.write=stdoutTakeoverState.originalStdoutWrite,stdoutTakeoverState=void 0)}function stdioChunkToString(chunk,encoding){return typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding)}function normalizeThrownError(error){return error instanceof Error?error:new Error(String(error))}function writeOriginalStderr(state,text){text.length!==0&&state.originalStderrWrite.call(process.stderr,text)}function observeVisibleStderrWrites(listener){if(!visibleStderrObservation){let original=stderrTakeoverState?.originalStderrWrite??process.stderr.write,listeners=new Set,writer=function(...args){for(let notify2 of listeners)notify2();return Reflect.apply(original,this,args)};visibleStderrObservation={original,writer,listeners},stderrTakeoverState?stderrTakeoverState.originalStderrWrite=writer:process.stderr.write=writer}let observation=visibleStderrObservation,notify=()=>listener();return observation.listeners.add(notify),()=>{!observation.listeners.delete(notify)||observation.listeners.size>0||(stderrTakeoverState?.originalStderrWrite===observation.writer&&(stderrTakeoverState.originalStderrWrite=observation.original),process.stderr.write===observation.writer&&(process.stderr.write=observation.original),visibleStderrObservation=void 0)}}function takeOverStderr(onHiddenDiagnostic,formatHiddenDiagnosticFallback){if(stderrTakeoverState)return;let originalStderrWrite=process.stderr.write;process.stderr.write=((chunk,encodingOrCallback,callback)=>{let text=stdioChunkToString(chunk,typeof encodingOrCallback=="string"?encodingOrCallback:void 0);try{stderrTakeoverState?.onHiddenDiagnostic?.(text)}catch(error){let state=stderrTakeoverState;if(state){let fallbackText=state.formatHiddenDiagnosticFallback?.(text)??text;writeOriginalStderr(state,fallbackText)}let writeError=normalizeThrownError(error);return typeof encodingOrCallback=="function"?encodingOrCallback(writeError):callback?.(writeError),!1}return typeof encodingOrCallback=="function"?encodingOrCallback(null):callback?.(null),!0}),stderrTakeoverState={formatHiddenDiagnosticFallback,originalStderrWrite,onHiddenDiagnostic}}function restoreStderr(){stderrTakeoverState&&(process.stderr.write=stderrTakeoverState.originalStderrWrite,stderrTakeoverState=void 0)}function isStdoutTakenOver(){return stdoutTakeoverState!==void 0}function writeRawStdout(text){text.length!==0&&(rawStdoutWriteTail=rawStdoutWriteTail.then(()=>writeRawStdoutChunk(text)),rawStdoutWriteTail.catch(()=>{process.exit(1)}))}async function waitForRawStdoutBackpressure(){for(;;){let tail=rawStdoutWriteTail;if(await tail,tail===rawStdoutWriteTail)return}}async function flushRawStdout(){await waitForRawStdoutBackpressure(),await writeRawStdoutChunk("")}import{createHash as createHash2}from"node:crypto";import{chmodSync,existsSync as existsSync3,globSync,mkdirSync,readdirSync as readdirSync2,readFileSync as readFileSync4,rmSync,statSync as statSync3,writeFileSync}from"node:fs";import{homedir as homedir2}from"node:os";var import_ignore2=__toESM(require_ignore(),1);import{basename,dirname as dirname2,join as join3,relative as relative2,resolve as resolve3,sep as sep4}from"node:path";var balanced=(a,b,str)=>{let ma=a instanceof RegExp?maybeMatch(a,str):a,mb=b instanceof RegExp?maybeMatch(b,str):b,r=ma!==null&&mb!=null&&range(ma,mb,str);return r&&{start:r[0],end:r[1],pre:str.slice(0,r[0]),body:str.slice(r[0]+ma.length,r[1]),post:str.slice(r[1]+mb.length)}},maybeMatch=(reg,str)=>{let m=str.match(reg);return m?m[0]:null},range=(a,b,str)=>{let begs,beg,left,right,result,ai=str.indexOf(a),bi=str.indexOf(b,ai+1),i=ai;if(ai>=0&&bi>0){if(a===b)return[ai,bi];for(begs=[],left=str.length;i>=0&&!result;){if(i===ai)begs.push(i),ai=str.indexOf(a,i+1);else if(begs.length===1){let r=begs.pop();r!==void 0&&(result=[r,bi])}else beg=begs.pop(),beg!==void 0&&beg<left&&(left=beg,right=bi),bi=str.indexOf(b,i+1);i=ai<bi&&ai>=0?ai:bi}begs.length&&right!==void 0&&(result=[left,right])}return result};var escSlash="\0SLASH"+Math.random()+"\0",escOpen="\0OPEN"+Math.random()+"\0",escClose="\0CLOSE"+Math.random()+"\0",escComma="\0COMMA"+Math.random()+"\0",escPeriod="\0PERIOD"+Math.random()+"\0",escSlashPattern=new RegExp(escSlash,"g"),escOpenPattern=new RegExp(escOpen,"g"),escClosePattern=new RegExp(escClose,"g"),escCommaPattern=new RegExp(escComma,"g"),escPeriodPattern=new RegExp(escPeriod,"g"),slashPattern=/\\\\/g,openPattern=/\\{/g,closePattern=/\\}/g,commaPattern=/\\,/g,periodPattern=/\\\./g,EXPANSION_MAX=1e5,EXPANSION_MAX_LENGTH=4e6,EXPANSION_MAX_DEPTH=1e3,EXPANSION_MAX_REWRITES=1e3;function numeric(str){return isNaN(str)?str.charCodeAt(0):parseInt(str,10)}function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function pushAll(target,items){for(let i=0;i<items.length;i++)target.push(items[i])}function parseCommaParts(str){let parts=[],carry="";for(;;){let m=balanced("{","}",str);if(!m){let tail=str.split(",");return tail[0]=carry+tail[0],pushAll(parts,tail),parts}let{pre,body,post}=m,p=pre.split(",");if(p[0]=carry+p[0],p[p.length-1]+="{"+body+"}",!post.length)return pushAll(parts,p),parts;carry=p.pop(),pushAll(parts,p),str=post}}function expand(str,options={}){if(!str)return[];let{max=EXPANSION_MAX,maxLength=EXPANSION_MAX_LENGTH,maxDepth=EXPANSION_MAX_DEPTH,maxRewrites=EXPANSION_MAX_REWRITES}=options;return str.slice(0,2)==="{}"&&(str="\\{\\}"+str.slice(2)),expand_(escapeBraces(str),max,maxLength,maxDepth,0,maxRewrites,!0).map(unescapeBraces)}function embrace(str){return"{"+str+"}"}function isPadded(el){return/^-?0\d/.test(el)}function lte(i,y){return i<=y}function gte(i,y){return i>=y}function combine(acc,pre,values,max,maxLength,dropEmpties){let out=[],length=0;for(let a=0;a<acc.length;a++)for(let v=0;v<values.length;v++){if(out.length>=max)return out;let expansion=acc[a]+pre+values[v];if(!(dropEmpties&&!expansion)){if(length+expansion.length>maxLength)return out;out.push(expansion),length+=expansion.length}}return out}function expandSequence(body,isAlphaSequence,max,maxLength){let n=body.split(/\.\./),N=[];if(n[0]===void 0||n[1]===void 0)return N;let x=numeric(n[0]),y=numeric(n[1]),width=Math.max(n[0].length,n[1].length),incr=n.length===3&&n[2]!==void 0?Math.max(Math.abs(numeric(n[2])),1):1,test=lte;y<x&&(incr*=-1,test=gte);let pad=n.some(isPadded),length=0;for(let i=x;test(i,y)&&N.length<max;i+=incr){let c;if(isAlphaSequence)c=String.fromCharCode(i),c==="\\"&&(c="");else if(c=String(i),pad){let need=width-c.length;if(need>0){let z=new Array(need+1).join("0");i<0?c="-"+z+c.slice(1):c=z+c}}if(length+c.length>maxLength)break;N.push(c),length+=c.length}return N}function expand_(str,max,maxLength,maxDepth,depth,maxRewrites,isTop){if(depth>maxDepth)return[str];let acc=[""],rewrites=0,dropEmpties=!1,firstGroup=!0;for(;;){let m=balanced("{","}",str);if(!m)return combine(acc,str,[""],max,maxLength,dropEmpties);let pre=m.pre;if(/\$$/.test(pre)){if(acc=combine(acc,pre+"{"+m.body+"}",[""],max,maxLength,dropEmpties&&!m.post.length),firstGroup=!1,!m.post.length)break;str=m.post;continue}let isNumericSequence=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body),isAlphaSequence=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body),isSequence=isNumericSequence||isAlphaSequence,isOptions=m.body.indexOf(",")>=0;if(!isSequence&&!isOptions){if(rewrites<maxRewrites&&m.post.match(/,(?!,).*\}/)){rewrites++,str=m.pre+"{"+m.body+escClose+m.post,isTop=!0;continue}return combine(acc,pre+"{"+m.body+"}"+m.post,[""],max,maxLength,dropEmpties)}firstGroup&&(dropEmpties=isTop&&!isSequence,firstGroup=!1);let values;if(isSequence)values=expandSequence(m.body,isAlphaSequence,max,maxLength);else{let n=parseCommaParts(m.body);if(n.length===1&&n[0]!==void 0&&(n=expand_(n[0],max,maxLength,maxDepth,depth+1,maxRewrites,!1).map(embrace),n.length===1)){if(acc=combine(acc,pre+n[0],[""],max,maxLength,dropEmpties&&!m.post.length),!m.post.length)break;str=m.post;continue}let dropsEmpties=dropEmpties&&!m.post.length&&!pre;for(let d=0;dropsEmpties&&d<acc.length;d++)acc[d]&&(dropsEmpties=!1);values=[];let valuesLength=0;outer:for(let j=0;j<n.length;j++){let expanded=expand_(n[j],max,maxLength,maxDepth,depth+1,maxRewrites,!1);for(let k=0;k<expanded.length;k++){let v=expanded[k];if(!(dropsEmpties&&!v)){if(values.length>=max||valuesLength+v.length>maxLength)break outer;values.push(v),valuesLength+=v.length}}}}if(acc=combine(acc,pre,values,max,maxLength,dropEmpties&&!m.post.length),!m.post.length)break;str=m.post}return acc}var assertValidPattern=pattern=>{if(typeof pattern!="string")throw new TypeError("invalid pattern");if(pattern.length>65536)throw new TypeError("pattern is too long")};var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},braceEscape=s=>s.replace(/[[\]\\-]/g,"\\$&"),regexpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),rangesToString=ranges=>ranges.join(""),parseClass=(glob,position)=>{let pos=position;if(glob.charAt(pos)!=="[")throw new Error("not in a brace expression");let ranges=[],negs=[],i=pos+1,sawStart=!1,uflag=!1,escaping=!1,negate=!1,endPos=pos,rangeStart="";WHILE:for(;i<glob.length;){let c=glob.charAt(i);if((c==="!"||c==="^")&&i===pos+1){negate=!0,i++;continue}if(c==="]"&&sawStart&&!escaping){endPos=i+1;break}if(sawStart=!0,c==="\\"&&!escaping){escaping=!0,i++;continue}if(c==="["&&!escaping){for(let[cls,[unip,u,neg]]of Object.entries(posixClasses))if(glob.startsWith(cls,i)){if(rangeStart)return["$.",!1,glob.length-pos,!0];i+=cls.length,neg?negs.push(unip):ranges.push(unip),uflag=uflag||u;continue WHILE}}if(escaping=!1,rangeStart){c>rangeStart?ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c)):c===rangeStart&&ranges.push(braceEscape(c)),rangeStart="",i++;continue}if(glob.startsWith("-]",i+1)){ranges.push(braceEscape(c+"-")),i+=2;continue}if(glob.startsWith("-",i+1)){rangeStart=c,i+=2;continue}ranges.push(braceEscape(c)),i++}if(endPos<i)return["",!1,0,!1];if(!ranges.length&&!negs.length)return["$.",!1,glob.length-pos,!0];if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){let r=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r),!1,endPos-pos,!1]}let sranges="["+(negate?"^":"")+rangesToString(ranges)+"]",snegs="["+(negate?"":"^")+rangesToString(negs)+"]";return[ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs,uflag,endPos-pos,!0]};var unescape=(s,{windowsPathsNoEscape=!1,magicalBraces=!0}={})=>magicalBraces?windowsPathsNoEscape?s.replace(/\[([^/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):windowsPathsNoEscape?s.replace(/\[([^/\\{}])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var _a,types=new Set(["!","?","+","*","@"]),isExtglobType=c=>types.has(c),isExtglobAST=c=>isExtglobType(c.type),adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))",startNoDot="(?!\\.)",addPatternStart=new Set(["[","."]),justDots=new Set(["..","."]),reSpecials=new Set("().*{}+?[]^$\\!"),regExpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),qmark="[^/]",star=qmark+"*?",starNoEmpty=qmark+"+?",ID=0,AST=class{type;#root;#hasMagic;#uflag=!1;#parts=[];#parent;#parentIndex;#negs;#filledNegs=!1;#options;#toString;#emptyExt=!1;id=++ID;get depth(){return(this.#parent?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#root.id,parent:this.#parent?.id,depth:this.depth,partsLength:this.#parts.length,parts:this.#parts}}constructor(type,parent,options={}){this.type=type,type&&(this.#hasMagic=!0),this.#parent=parent,this.#root=this.#parent?this.#parent.#root:this,this.#options=this.#root===this?options:this.#root.#options,this.#negs=this.#root===this?[]:this.#root.#negs,type==="!"&&!this.#root.#filledNegs&&this.#negs.push(this),this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(let p of this.#parts)if(typeof p!="string"&&(p.type||p.hasMagic))return this.#hasMagic=!0;return this.#hasMagic}toString(){return this.#toString!==void 0?this.#toString:this.type?this.#toString=this.type+"("+this.#parts.map(p=>String(p)).join("|")+")":this.#toString=this.#parts.map(p=>String(p)).join("")}#fillNegs(){if(this!==this.#root)throw new Error("should only call on root");if(this.#filledNegs)return this;this.toString(),this.#filledNegs=!0;let n;for(;n=this.#negs.pop();){if(n.type!=="!")continue;let p=n,pp=p.#parent;for(;pp;){for(let i=p.#parentIndex+1;!pp.type&&i<pp.#parts.length;i++)for(let part of n.#parts){if(typeof part=="string")throw new Error("string part in extglob AST??");part.copyIn(pp.#parts[i])}p=pp,pp=p.#parent}}return this}push(...parts){for(let p of parts)if(p!==""){if(typeof p!="string"&&!(p instanceof _a&&p.#parent===this))throw new Error("invalid part: "+p);this.#parts.push(p)}}toJSON(){let ret=this.type===null?this.#parts.slice().map(p=>typeof p=="string"?p:p.toJSON()):[this.type,...this.#parts.map(p=>p.toJSON())];return this.isStart()&&!this.type&&ret.unshift([]),this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type==="!")&&ret.push({}),ret}isStart(){if(this.#root===this)return!0;if(!this.#parent?.isStart())return!1;if(this.#parentIndex===0)return!0;let p=this.#parent;for(let i=0;i<this.#parentIndex;i++){let pp=p.#parts[i];if(!(pp instanceof _a&&pp.type==="!"))return!1}return!0}isEnd(){if(this.#root===this||this.#parent?.type==="!")return!0;if(!this.#parent?.isEnd())return!1;if(!this.type)return this.#parent?.isEnd();let pl=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===pl-1}copyIn(part){typeof part=="string"?this.push(part):this.push(part.clone(this))}clone(parent){let c=new _a(this.type,parent);for(let p of this.#parts)c.copyIn(p);return c}static#parseAST(str,ast,pos,opt,extDepth){let maxDepth=opt.maxExtglobRecursion??2,escaping=!1,inBrace=!1,braceStart=-1,braceNeg=!1;if(ast.type===null){let i2=pos,acc2="";for(;i2<str.length;){let c=str.charAt(i2++);if(escaping||c==="\\"){escaping=!escaping,acc2+=c;continue}if(inBrace){i2===braceStart+1?(c==="^"||c==="!")&&(braceNeg=!0):c==="]"&&!(i2===braceStart+2&&braceNeg)&&(inBrace=!1),acc2+=c;continue}else if(c==="["){inBrace=!0,braceStart=i2,braceNeg=!1,acc2+=c;continue}if(!opt.noext&&isExtglobType(c)&&str.charAt(i2)==="("&&extDepth<=maxDepth){ast.push(acc2),acc2="";let ext2=new _a(c,ast);i2=_a.#parseAST(str,ext2,i2,opt,extDepth+1),ast.push(ext2);continue}acc2+=c}return ast.push(acc2),i2}let i=pos+1,part=new _a(null,ast),parts=[],acc="";for(;i<str.length;){let c=str.charAt(i++);if(escaping||c==="\\"){escaping=!escaping,acc+=c;continue}if(inBrace){i===braceStart+1?(c==="^"||c==="!")&&(braceNeg=!0):c==="]"&&!(i===braceStart+2&&braceNeg)&&(inBrace=!1),acc+=c;continue}else if(c==="["){inBrace=!0,braceStart=i,braceNeg=!1,acc+=c;continue}if(!opt.noext&&isExtglobType(c)&&str.charAt(i)==="("&&(extDepth<=maxDepth||ast&&ast.#canAdoptType(c))){let depthAdd=ast&&ast.#canAdoptType(c)?0:1;part.push(acc),acc="";let ext2=new _a(c,part);part.push(ext2),i=_a.#parseAST(str,ext2,i,opt,extDepth+depthAdd);continue}if(c==="|"){part.push(acc),acc="",parts.push(part),part=new _a(null,ast);continue}if(c===")")return acc===""&&ast.#parts.length===0&&(ast.#emptyExt=!0),part.push(acc),acc="",ast.push(...parts,part),i;acc+=c}return ast.type=null,ast.#hasMagic=void 0,ast.#parts=[str.substring(pos-1)],i}#canAdoptWithSpace(child){return this.#canAdopt(child,adoptionWithSpaceMap)}#canAdopt(child,map=adoptionMap){if(!child||typeof child!="object"||child.type!==null||child.#parts.length!==1||this.type===null)return!1;let gc=child.#parts[0];return!gc||typeof gc!="object"||gc.type===null?!1:this.#canAdoptType(gc.type,map)}#canAdoptType(c,map=adoptionAnyMap){return!!map.get(this.type)?.includes(c)}#adoptWithSpace(child,index){let gc=child.#parts[0],blank=new _a(null,gc,this.options);blank.#parts.push(""),gc.push(blank),this.#adopt(child,index)}#adopt(child,index){let gc=child.#parts[0];this.#parts.splice(index,1,...gc.#parts);for(let p of gc.#parts)typeof p=="object"&&(p.#parent=this);this.#toString=void 0}#canUsurpType(c){return!!usurpMap.get(this.type)?.has(c)}#canUsurp(child){if(!child||typeof child!="object"||child.type!==null||child.#parts.length!==1||this.type===null||this.#parts.length!==1)return!1;let gc=child.#parts[0];return!gc||typeof gc!="object"||gc.type===null?!1:this.#canUsurpType(gc.type)}#usurp(child){let m=usurpMap.get(this.type),gc=child.#parts[0],nt=m?.get(gc.type);if(!nt)return!1;this.#parts=gc.#parts;for(let p of this.#parts)typeof p=="object"&&(p.#parent=this);this.type=nt,this.#toString=void 0,this.#emptyExt=!1}static fromGlob(pattern,options={}){let ast=new _a(null,void 0,options);return _a.#parseAST(pattern,ast,0,options,0),ast}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();let glob=this.toString(),[re,body,hasMagic,uflag]=this.toRegExpSource();if(!(hasMagic||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase()))return body;let flags=(this.#options.nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags),{_src:re,_glob:glob})}get options(){return this.#options}toRegExpSource(allowDot){let dot=allowDot??!!this.#options.dot;if(this.#root===this&&(this.#flatten(),this.#fillNegs()),!isExtglobAST(this)){let noEmpty=this.isStart()&&this.isEnd()&&!this.#parts.some(s=>typeof s!="string"),src=this.#parts.map(p=>{let[re,_,hasMagic,uflag]=typeof p=="string"?_a.#parseGlob(p,this.#hasMagic,noEmpty):p.toRegExpSource(allowDot);return this.#hasMagic=this.#hasMagic||hasMagic,this.#uflag=this.#uflag||uflag,re}).join(""),start2="";if(this.isStart()&&typeof this.#parts[0]=="string"&&!(this.#parts.length===1&&justDots.has(this.#parts[0]))){let aps=addPatternStart,needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4)),needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}let end="";return this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type==="!"&&(end="(?:$|\\/)"),[start2+src+end,unescape(src),this.#hasMagic=!!this.#hasMagic,this.#uflag]}let repeated=this.type==="*"||this.type==="+",start=this.type==="!"?"(?:(?!(?:":"(?:",body=this.#partsToRegExp(dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){let s=this.toString(),me=this;return me.#parts=[s],me.type=null,me.#hasMagic=void 0,[s,unescape(this.toString()),!1,!1]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":this.#partsToRegExp(!0);bodyDotAllowed===body&&(bodyDotAllowed=""),bodyDotAllowed&&(body=`(?:${body})(?:${bodyDotAllowed})*?`);let final="";if(this.type==="!"&&this.#emptyExt)final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty;else{let close=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?")?":`)${this.type}`;final=start+body+close}return[final,unescape(body),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#flatten(){if(isExtglobAST(this)){let iterations=0,done=!1;do{done=!0;for(let i=0;i<this.#parts.length;i++){let c=this.#parts[i];typeof c=="object"&&(c.#flatten(),this.#canAdopt(c)?(done=!1,this.#adopt(c,i)):this.#canAdoptWithSpace(c)?(done=!1,this.#adoptWithSpace(c,i)):this.#canUsurp(c)&&(done=!1,this.#usurp(c)))}}while(!done&&++iterations<10)}else for(let p of this.#parts)typeof p=="object"&&p.#flatten();this.#toString=void 0}#partsToRegExp(dot){return this.#parts.map(p=>{if(typeof p=="string")throw new Error("string type in extglob ast??");let[re,_,_hasMagic,uflag]=p.toRegExpSource(dot);return this.#uflag=this.#uflag||uflag,re}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")}static#parseGlob(glob,hasMagic,noEmpty=!1){let escaping=!1,re="",uflag=!1,inStar=!1;for(let i=0;i<glob.length;i++){let c=glob.charAt(i);if(escaping){escaping=!1,re+=(reSpecials.has(c)?"\\":"")+c;continue}if(c==="*"){if(inStar)continue;inStar=!0,re+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star,hasMagic=!0;continue}else inStar=!1;if(c==="\\"){i===glob.length-1?re+="\\\\":escaping=!0;continue}if(c==="["){let[src,needUflag,consumed,magic]=parseClass(glob,i);if(consumed){re+=src,uflag=uflag||needUflag,i+=consumed-1,hasMagic=hasMagic||magic;continue}}if(c==="?"){re+=qmark,hasMagic=!0;continue}re+=regExpEscape(c)}return[re,unescape(glob),!!hasMagic,uflag]}};_a=AST;var escape=(s,{windowsPathsNoEscape=!1,magicalBraces=!1}={})=>magicalBraces?windowsPathsNoEscape?s.replace(/[?*()[\]{}]/g,"[$&]"):s.replace(/[?*()[\]\\{}]/g,"\\$&"):windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");var minimatch=(p,pattern,options={})=>(assertValidPattern(pattern),!options.nocomment&&pattern.charAt(0)==="#"?!1:new Minimatch(pattern,options).match(p)),starDotExtRE=/^\*+([^+@!?*[(]*)$/,starDotExtTest=ext2=>f=>!f.startsWith(".")&&f.endsWith(ext2),starDotExtTestDot=ext2=>f=>f.endsWith(ext2),starDotExtTestNocase=ext2=>(ext2=ext2.toLowerCase(),f=>!f.startsWith(".")&&f.toLowerCase().endsWith(ext2)),starDotExtTestNocaseDot=ext2=>(ext2=ext2.toLowerCase(),f=>f.toLowerCase().endsWith(ext2)),starDotStarRE=/^\*+\.\*+$/,starDotStarTest=f=>!f.startsWith(".")&&f.includes("."),starDotStarTestDot=f=>f!=="."&&f!==".."&&f.includes("."),dotStarRE=/^\.\*+$/,dotStarTest=f=>f!=="."&&f!==".."&&f.startsWith("."),starRE=/^\*+$/,starTest=f=>f.length!==0&&!f.startsWith("."),starTestDot=f=>f.length!==0&&f!=="."&&f!=="..",qmarksRE=/^\?+([^+@!?*[(]*)?$/,qmarksTestNocase=([$0,ext2=""])=>{let noext=qmarksTestNoExt([$0]);return ext2?(ext2=ext2.toLowerCase(),f=>noext(f)&&f.toLowerCase().endsWith(ext2)):noext},qmarksTestNocaseDot=([$0,ext2=""])=>{let noext=qmarksTestNoExtDot([$0]);return ext2?(ext2=ext2.toLowerCase(),f=>noext(f)&&f.toLowerCase().endsWith(ext2)):noext},qmarksTestDot=([$0,ext2=""])=>{let noext=qmarksTestNoExtDot([$0]);return ext2?f=>noext(f)&&f.endsWith(ext2):noext},qmarksTest=([$0,ext2=""])=>{let noext=qmarksTestNoExt([$0]);return ext2?f=>noext(f)&&f.endsWith(ext2):noext},qmarksTestNoExt=([$0])=>{let len=$0.length;return f=>f.length===len&&!f.startsWith(".")},qmarksTestNoExtDot=([$0])=>{let len=$0.length;return f=>f.length===len&&f!=="."&&f!==".."},defaultPlatform=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",path={win32:{sep:"\\"},posix:{sep:"/"}},sep=defaultPlatform==="win32"?path.win32.sep:path.posix.sep;minimatch.sep=sep;var GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;var qmark2="[^/]",star2=qmark2+"*?",twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?",filter=(pattern,options={})=>p=>minimatch(p,pattern,options);minimatch.filter=filter;var ext=(a,b={})=>Object.assign({},a,b),defaults=def=>{if(!def||typeof def!="object"||!Object.keys(def).length)return minimatch;let orig=minimatch;return Object.assign((p,pattern,options={})=>orig(p,pattern,ext(def,options)),{Minimatch:class extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class extends orig.AST{constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:(s,options={})=>orig.unescape(s,ext(def,options)),escape:(s,options={})=>orig.escape(s,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),makeRe:(pattern,options={})=>orig.makeRe(pattern,ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list,pattern,options={})=>orig.match(list,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;var braceExpand=(pattern,options={})=>(assertValidPattern(pattern),options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)?[pattern]:expand(pattern,{max:options.braceExpandMax}));minimatch.braceExpand=braceExpand;var makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;var match=(list,pattern,options={})=>{let mm=new Minimatch(pattern,options);return list=list.filter(f=>mm.match(f)),mm.options.nonull&&!list.length&&list.push(pattern),list};minimatch.match=match;var globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/,regExpEscape2=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(pattern,options={}){assertValidPattern(pattern),options=options||{},this.options=options,this.maxGlobstarRecursion=options.maxGlobstarRecursion??200,this.pattern=pattern,this.platform=options.platform||defaultPlatform,this.isWindows=this.platform==="win32";let awe="allowWindowsEscape";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options[awe]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!options.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!options.nonegate,this.comment=!1,this.empty=!1,this.partial=!!options.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=options.windowsNoMagicRoot!==void 0?options.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let pattern of this.set)for(let part of pattern)if(typeof part!="string")return!0;return!1}debug(..._){}make(){let pattern=this.pattern,options=this.options;if(!options.nocomment&&pattern.charAt(0)==="#"){this.comment=!0;return}if(!pattern){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],options.debug&&(this.debug=(...args)=>console.error(...args)),this.debug(this.pattern,this.globSet);let rawGlobParts=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(rawGlobParts),this.debug(this.pattern,this.globParts);let set=this.globParts.map((s,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){let isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&!globMagic.test(s[3]),isDrive=/^[a-z]:/i.test(s[0]);if(isUNC)return[...s.slice(0,4),...s.slice(4).map(ss=>this.parse(ss))];if(isDrive)return[s[0],...s.slice(1).map(ss=>this.parse(ss))]}return s.map(ss=>this.parse(ss))});if(this.debug(this.pattern,set),this.set=set.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let p=this.set[i];p[0]===""&&p[1]===""&&this.globParts[i][2]==="?"&&typeof p[3]=="string"&&/^[a-z]:$/i.test(p[3])&&(p[2]="?")}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar)for(let partset of globParts)for(let j=0;j<partset.length;j++)partset[j]==="**"&&(partset[j]="*");let{optimizationLevel=1}=this.options;return optimizationLevel>=2?(globParts=this.firstPhasePreProcess(globParts),globParts=this.secondPhasePreProcess(globParts)):optimizationLevel>=1?globParts=this.levelOneOptimize(globParts):globParts=this.adjascentGlobstarOptimize(globParts),globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs=-1;for(;(gs=parts.indexOf("**",gs+1))!==-1;){let i=gs;for(;parts[i+1]==="**";)i++;i!==gs&&parts.splice(gs,i-gs)}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>(parts=parts.reduce((set,part)=>{let prev=set[set.length-1];return part==="**"&&prev==="**"?set:part===".."&&prev&&prev!==".."&&prev!=="."&&prev!=="**"?(set.pop(),set):(set.push(part),set)},[]),parts.length===0?[""]:parts))}levelTwoFileOptimize(parts){Array.isArray(parts)||(parts=this.slashSplit(parts));let didSomething=!1;do{if(didSomething=!1,!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){let p=parts[i];i===1&&p===""&&parts[0]===""||(p==="."||p==="")&&(didSomething=!0,parts.splice(i,1),i--)}parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")&&(didSomething=!0,parts.pop())}let dd=0;for(;(dd=parts.indexOf("..",dd+1))!==-1;){let p=parts[dd-1];p&&p!=="."&&p!==".."&&p!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(p))&&(didSomething=!0,parts.splice(dd-1,2),dd-=2)}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let didSomething=!1;do{didSomething=!1;for(let parts of globParts){let gs=-1;for(;(gs=parts.indexOf("**",gs+1))!==-1;){let gss=gs;for(;parts[gss+1]==="**";)gss++;gss>gs&&parts.splice(gs+1,gss-gs);let next=parts[gs+1],p=parts[gs+2],p2=parts[gs+3];if(next!==".."||!p||p==="."||p===".."||!p2||p2==="."||p2==="..")continue;didSomething=!0,parts.splice(gs,1);let other=parts.slice(0);other[gs]="**",globParts.push(other),gs--}if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){let p=parts[i];i===1&&p===""&&parts[0]===""||(p==="."||p==="")&&(didSomething=!0,parts.splice(i,1),i--)}parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")&&(didSomething=!0,parts.pop())}let dd=0;for(;(dd=parts.indexOf("..",dd+1))!==-1;){let p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=!0;let splin=dd===1&&parts[dd+1]==="**"?["."]:[];parts.splice(dd-1,2,...splin),parts.length===0&&parts.push(""),dd-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i=0;i<globParts.length-1;i++)for(let j=i+1;j<globParts.length;j++){let matched=this.partsMatch(globParts[i],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i]=[],globParts[j]=matched;break}}return globParts.filter(gs=>gs.length)}partsMatch(a,b,emptyGSMatch=!1){let ai=0,bi=0,result=[],which="";for(;ai<a.length&&bi<b.length;)if(a[ai]===b[bi])result.push(which==="b"?b[bi]:a[ai]),ai++,bi++;else if(emptyGSMatch&&a[ai]==="**"&&b[bi]===a[ai+1])result.push(a[ai]),ai++;else if(emptyGSMatch&&b[bi]==="**"&&a[ai]===b[bi+1])result.push(b[bi]),bi++;else if(a[ai]==="*"&&b[bi]&&(this.options.dot||!b[bi].startsWith("."))&&b[bi]!=="**"){if(which==="b")return!1;which="a",result.push(a[ai]),ai++,bi++}else if(b[bi]==="*"&&a[ai]&&(this.options.dot||!a[ai].startsWith("."))&&a[ai]!=="**"){if(which==="a")return!1;which="b",result.push(b[bi]),ai++,bi++}else return!1;return a.length===b.length&&result}parseNegate(){if(this.nonegate)return;let pattern=this.pattern,negate=!1,negateOffset=0;for(let i=0;i<pattern.length&&pattern.charAt(i)==="!";i++)negate=!negate,negateOffset++;negateOffset&&(this.pattern=pattern.slice(negateOffset)),this.negate=negate}matchOne(file,pattern,partial=!1){let fileStartIndex=0,patternStartIndex=0;if(this.isWindows){let fileDrive=typeof file[0]=="string"&&/^[a-z]:$/i.test(file[0]),fileUNC=!fileDrive&&file[0]===""&&file[1]===""&&file[2]==="?"&&/^[a-z]:$/i.test(file[3]),patternDrive=typeof pattern[0]=="string"&&/^[a-z]:$/i.test(pattern[0]),patternUNC=!patternDrive&&pattern[0]===""&&pattern[1]===""&&pattern[2]==="?"&&typeof pattern[3]=="string"&&/^[a-z]:$/i.test(pattern[3]),fdi=fileUNC?3:fileDrive?0:void 0,pdi=patternUNC?3:patternDrive?0:void 0;if(typeof fdi=="number"&&typeof pdi=="number"){let[fd,pd]=[file[fdi],pattern[pdi]];fd.toLowerCase()===pd.toLowerCase()&&(pattern[pdi]=fd,patternStartIndex=pdi,fileStartIndex=fdi)}}let{optimizationLevel=1}=this.options;return optimizationLevel>=2&&(file=this.levelTwoFileOptimize(file)),pattern.includes(GLOBSTAR)?this.#matchGlobstar(file,pattern,partial,fileStartIndex,patternStartIndex):this.#matchOne(file,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file,pattern,partial,fileIndex,patternIndex){let firstgs=pattern.indexOf(GLOBSTAR,patternIndex),lastgs=pattern.lastIndexOf(GLOBSTAR),[head,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head.length){let fileHead=file.slice(fileIndex,fileIndex+head.length);if(!this.#matchOne(fileHead,head,partial,0,0))return!1;fileIndex+=head.length,patternIndex+=head.length}let fileTailMatch=0;if(tail.length){if(tail.length+fileIndex>file.length)return!1;let tailStart=file.length-tail.length;if(this.#matchOne(file,tail,partial,tailStart,0))fileTailMatch=tail.length;else{if(file[file.length-1]!==""||fileIndex+tail.length===file.length||(tailStart--,!this.#matchOne(file,tail,partial,tailStart,0)))return!1;fileTailMatch=tail.length+1}}if(!body.length){let sawSome=!!fileTailMatch;for(let i2=fileIndex;i2<file.length-fileTailMatch;i2++){let f=String(file[i2]);if(sawSome=!0,f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return partial||sawSome}let bodySegments=[[[],0]],currentBody=bodySegments[0],nonGsParts=0,nonGsPartsSums=[0];for(let b of body)b===GLOBSTAR?(nonGsPartsSums.push(nonGsParts),currentBody=[[],0],bodySegments.push(currentBody)):(currentBody[0].push(b),nonGsParts++);let i=bodySegments.length-1,fileLength=file.length-fileTailMatch;for(let b of bodySegments)b[1]=fileLength-(nonGsPartsSums[i--]+b[0].length);return!!this.#matchGlobStarBodySections(file,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)}#matchGlobStarBodySections(file,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){let bs=bodySegments[bodyIndex];if(!bs){for(let i=fileIndex;i<file.length;i++){sawTail=!0;let f=file[i];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return sawTail}let[body,after]=bs;for(;fileIndex<=after;){if(this.#matchOne(file.slice(0,fileIndex+body.length),body,partial,fileIndex,0)&&globStarDepth<this.maxGlobstarRecursion){let sub=this.#matchGlobStarBodySections(file,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(sub!==!1)return sub}let f=file[fileIndex];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;fileIndex++}return partial||null}#matchOne(file,pattern,partial,fileIndex,patternIndex){let fi,pi,pl,fl;for(fi=fileIndex,pi=patternIndex,fl=file.length,pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){this.debug("matchOne loop");let p=pattern[pi],f=file[fi];if(this.debug(pattern,p,f),p===!1||p===GLOBSTAR)return!1;let hit;if(typeof p=="string"?(hit=f===p,this.debug("string match",p,f,hit)):(hit=p.test(f),this.debug("pattern match",p,f,hit)),!hit)return!1}if(fi===fl&&pi===pl)return!0;if(fi===fl)return partial;if(pi===pl)return fi===fl-1&&file[fi]==="";throw new Error("wtf?")}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);let options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m,fastTest=null;(m=pattern.match(starRE))?fastTest=options.dot?starTestDot:starTest:(m=pattern.match(starDotExtRE))?fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1]):(m=pattern.match(qmarksRE))?fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m):(m=pattern.match(starDotStarRE))?fastTest=options.dot?starDotStarTestDot:starDotStarTest:(m=pattern.match(dotStarRE))&&(fastTest=dotStarTest);let re=AST.fromGlob(pattern,this.options).toMMPattern();return fastTest&&typeof re=="object"&&Reflect.defineProperty(re,"test",{value:fastTest}),re}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let set=this.set;if(!set.length)return this.regexp=!1,this.regexp;let options=this.options,twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot,flags=new Set(options.nocase?["i"]:[]),re=set.map(pattern=>{let pp=pattern.map(p=>{if(p instanceof RegExp)for(let f of p.flags.split(""))flags.add(f);return typeof p=="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp.forEach((p,i)=>{let next=pp[i+1],prev=pp[i-1];p!==GLOBSTAR||prev===GLOBSTAR||(prev===void 0?next!==void 0&&next!==GLOBSTAR?pp[i+1]="(?:\\/|"+twoStar+"\\/)?"+next:pp[i]=twoStar:next===void 0?pp[i-1]=prev+"(?:\\/|\\/"+twoStar+")?":next!==GLOBSTAR&&(pp[i-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next,pp[i+1]=GLOBSTAR))});let filtered=pp.filter(p=>p!==GLOBSTAR);if(this.partial&&filtered.length>=1){let prefixes=[];for(let i=1;i<=filtered.length;i++)prefixes.push(filtered.slice(0,i).join("/"));return"(?:"+prefixes.join("|")+")"}return filtered.join("/")}).join("|"),[open3,close]=set.length>1?["(?:",")"]:["",""];re="^"+open3+re+close+"$",this.partial&&(re="^(?:\\/|"+open3+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}}import{createHash}from"node:crypto";import{closeSync as closeSync2,constants,existsSync as existsSync2,fstatSync as fstatSync2,lstatSync,openSync as openSync2,readFileSync as readFileSync3,realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{lstat,open,readFile,realpath}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join as join2,resolve as resolve2,sep as sep3}from"node:path";var import_ignore=__toESM(require_ignore(),1);import{closeSync,existsSync,fstatSync,openSync,readdirSync,readFileSync as readFileSync2,readSync,realpathSync,statSync}from"node:fs";import{join,relative,resolve,sep as sep2}from"node:path";var SKILL_FRONTMATTER_PREFIX_BYTES=8192,IGNORE_FILE_NAMES=[".gitignore",".ignore",".fdignore"],SKIP_SKILL_WALK_DIRECTORY_NAMES=new Set(["node_modules",".git"]),FRONTMATTER_CLOSE_LF=Buffer.from(`
|
|
134
|
-
---`),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,options={}){let entries=[];if(!existsSync(dir))return entries;let canonical;try{authorizeSkillPath(dir,options.provenance,options.allowedSet,!0),canonical=realpathSync.native(dir)}catch(error){if(error instanceof BlockedSkillLinkError)return[dir];canonical=resolve(dir)}if(options.ancestry?.has(canonical))return entries;let ancestry=new Set(options.ancestry);ancestry.add(canonical),options.onDirectory?.(dir);let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore.default)();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,{...options,ancestry})))}}catch{}return entries}function collectAutoSkillEntries(dir,mode,options){return collectSkillEntries(dir,mode,void 0,void 0,options)}var EMPTY_SKILL_ALLOWED_SET={roots:[],files:[],digest:""};function skillProjectRoot(cwd){let current=resolve2(cwd);for(;;){if(existsSync2(join2(current,".git")))return current;let parent=dirname(current);if(parent===current)return resolve2(cwd);current=parent}}function insideSkillRoot(path2,root){return path2===root||path2.startsWith(root.endsWith(sep3)?root:`${root}${sep3}`)}function buildSkillAllowedSet(sources){let roots=new Set,files=new Set;for(let source of sources)try{let canonical=realpathSync2.native(source);if(statSync2(canonical).isFile()){files.add(canonical);continue}collectSkillEntries(source,"pi",void 0,void 0,{onDirectory:path2=>roots.add(realpathSync2.native(path2))})}catch{}let allowedRoots=[...roots].sort(),allowedFiles=[...files].sort();return{roots:allowedRoots,files:allowedFiles,digest:createHash("sha256").update(JSON.stringify([allowedRoots,allowedFiles])).digest("hex")}}var BlockedSkillLinkError=class extends Error{constructor(path2,target){let display=value=>{let home=homedir();return insideSkillRoot(value,home)?`~${value.slice(home.length)}`:value};super(`Blocked skill link outside the project: ${display(path2)} -> ${display(target)}. Add the target folder to your user skills settings to allow it.`),this.name="BlockedSkillLinkError",this.diagnostic={type:"warning",category:"skill-link-blocked",path:path2,message:this.message}}};function projectRoots(provenance){return[...provenance.projectRoot===void 0?[]:[provenance.projectRoot],...provenance.kind==="project-selected"?[provenance.selectedRoot]:[]]}function contained(canonical,roots,allowed,directory){return[...roots,...allowed.roots].some(root=>insideSkillRoot(canonical,root))||allowed.files.includes(canonical)||directory&&allowed.files.some(file=>insideSkillRoot(file,canonical))}function authorizeSkillPath(path2,provenance,allowed=EMPTY_SKILL_ALLOWED_SET,directory=!1){if(provenance===void 0||provenance.kind==="user")return path2;let canonical;try{canonical=realpathSync2.native(path2);let roots=projectRoots(provenance).map(root=>realpathSync2.native(root));if(contained(canonical,roots,allowed,directory))return canonical}catch{throw new BlockedSkillLinkError(path2,"unresolvable target")}throw new BlockedSkillLinkError(path2,canonical)}async function authorizeSkillPathAsync(path2,provenance,allowed){let canonical;try{canonical=await realpath(path2);let roots=await Promise.all(projectRoots(provenance).map(root=>realpath(root)));if(contained(canonical,roots,allowed,!1))return canonical}catch{throw new BlockedSkillLinkError(path2,"unresolvable target")}throw new BlockedSkillLinkError(path2,canonical)}function readSkillFileCheckedSync(path2,provenance,allowed){if(provenance===void 0||provenance.kind==="user")return readFileSync3(path2,"utf8");let canonical=authorizeSkillPath(path2,provenance,allowed),expected,descriptor;try{if(expected=lstatSync(canonical),!expected.isFile())throw new BlockedSkillLinkError(path2,canonical);descriptor=openSync2(canonical,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch{throw new BlockedSkillLinkError(path2,canonical)}try{let opened=fstatSync2(descriptor);if(!opened.isFile()||opened.dev!==expected.dev||opened.ino!==expected.ino||lstatSync(canonical).isSymbolicLink())throw new BlockedSkillLinkError(path2,canonical);return readFileSync3(descriptor,"utf8")}finally{closeSync2(descriptor)}}async function readSkillFileChecked(path2,provenance,allowed=EMPTY_SKILL_ALLOWED_SET){if(provenance===void 0||provenance.kind==="user")return await readFile(path2,"utf8");let canonical=await authorizeSkillPathAsync(path2,provenance,allowed),expected,handle;try{if(expected=await lstat(canonical),!expected.isFile())throw new BlockedSkillLinkError(path2,canonical);handle=await open(canonical,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch{throw new BlockedSkillLinkError(path2,canonical)}try{let opened=await handle.stat();if(!opened.isFile()||opened.dev!==expected.dev||opened.ino!==expected.ino||(await lstat(canonical)).isSymbolicLink())throw new BlockedSkillLinkError(path2,canonical);return await handle.readFile("utf8")}finally{await handle.close()}}function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync4("/proc/self/environ","utf-8"),env={};for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&(env[entry.slice(0,idx)]=entry.slice(idx+1))}return env}catch{return process.env}}var NETWORK_TIMEOUT_MS=1e4,UPDATE_CHECK_CONCURRENCY=4,GIT_UPDATE_CONCURRENCY=4;function isOfflineModeEnabled(){let value=envValue("OFFLINE");return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}function isExactNpmVersion(version){return(0,import_semver.valid)(version??"")!==null}function getNpmVersionRange(version){return version?(0,import_semver.validRange)(version)??void 0:void 0}function resourcePrecedenceRank(m){return m.source==="builtin"?5:m.origin==="package"?4:(m.scope==="project"?0:2)+(m.source==="local"?0:1)}var RESOURCE_TYPES=["extensions","skills","prompts","themes","hooks"],FILE_PATTERNS={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/,hooks:/\.json$/},IGNORE_FILE_NAMES2=[".gitignore",".ignore",".fdignore"];function toPosixPath2(p){return p.split(sep4).join("/")}function getHomeDir(){return process.env.HOME||homedir2()}function getExtensionTempFolder(agentDir){let tempFolder=join3(agentDir,"tmp","extensions");return mkdirSync(tempFolder,{recursive:!0,mode:448}),chmodSync(tempFolder,448),tempFolder}function prefixIgnorePattern2(line,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=join3(dir,filename);if(existsSync3(ignorePath))try{let patterns=readFileSync4(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function isPattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")||s.includes("*")||s.includes("?")}function isOverridePattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")}function hasGlobPattern(s){return s.includes("*")||s.includes("?")}function expandPackageGlob(pattern,root){return globSync(pattern,{cwd:root}).map(match2=>resolve3(root,match2)).filter(path2=>relative2(root,path2).split(sep4).every(segment=>segment===".."||!segment.startsWith("."))).sort((a,b)=>a<b?-1:a>b?1:0)}function splitPatterns(entries){let plain=[],patterns=[];for(let entry of entries)isPattern(entry)?patterns.push(entry):plain.push(entry);return{plain,patterns}}function collectFiles(dir,filePattern,skipNodeModules=!0,ignoreMatcher,rootDir){let files=[];if(!existsSync3(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore2.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync2(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync3(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath2(relative2(root,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;ig.ignores(ignorePath)||(isDir?files.push(...collectFiles(fullPath,filePattern,skipNodeModules,ig,root)):isFile&&filePattern.test(entry.name)&&files.push(fullPath))}}catch{}return files}function collectAncestorAgentsSkillDirs(startDir){return projectAgentsSkillDirs(startDir)}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync3(fullPath).isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".md")&&entries.push(fullPath)}}catch{}return entries}function collectAutoThemeEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync3(fullPath).isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".json")&&entries.push(fullPath)}}catch{}return entries}function resolveExtensionEntries(dir){let packageJsonPath=join3(dir,"package.json");if(existsSync3(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=resolve3(dir,extPath);existsSync3(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=join3(dir,"index.ts"),indexJs=join3(dir,"index.js");return existsSync3(indexTs)?[indexTs]:existsSync3(indexJs)?[indexJs]:null}function collectAutoExtensionEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let rootEntries=resolveExtensionEntries(dir);if(rootEntries)return rootEntries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync3(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;if(!ig.ignores(ignorePath)){if(isFile&&(entry.name.endsWith(".ts")||entry.name.endsWith(".js")))entries.push(fullPath);else if(isDir){let resolvedEntries=resolveExtensionEntries(fullPath);resolvedEntries&&entries.push(...resolvedEntries)}}}}catch{}return entries}function collectResourceFiles(dir,resourceType,provenance){return resourceType==="skills"?collectSkillEntries(dir,"pi",void 0,void 0,{provenance}):resourceType==="extensions"?collectAutoExtensionEntries(dir):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentName=isSkillFile?basename(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath2(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath2(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var DefaultPackageManager=class{constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager,this.builtinExtensions=options.builtinExtensions??[]}setProgressCallback(callback){this.progressCallback=callback}addSourceToSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],normalizedSource=this.normalizePackageSourceForSettings(source,scope),matchIndex=currentPackages.findIndex(existing=>this.packageSourcesMatch(existing,source,scope));if(matchIndex!==-1){let existing=currentPackages[matchIndex];if(this.getPackageSourceString(existing)===normalizedSource)return!1;let nextPackages2=[...currentPackages];return nextPackages2[matchIndex]=typeof existing=="string"?normalizedSource:{...existing,source:normalizedSource},scope==="project"?this.settingsManager.setProjectPackages(nextPackages2):this.settingsManager.setPackages(nextPackages2),!0}let nextPackages=[...currentPackages,normalizedSource];return scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0}removeSourceFromSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],nextPackages=currentPackages.filter(existing=>!this.packageSourcesMatch(existing,source,scope));return nextPackages.length!==currentPackages.length?(scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0):!1}getInstalledPath(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm"){let path2=this.getNpmInstallPath(parsed,scope);return existsSync3(path2)?path2:void 0}if(parsed.type==="git"){let path2=this.getGitInstallPath(parsed,scope);return existsSync3(path2)?path2:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path2=this.resolvePathFromBase(parsed.path,baseDir);return existsSync3(path2)?path2:void 0}}emitProgress(event){this.progressCallback?.(event)}async withProgress(action,source,message,operation){this.emitProgress({type:"start",action,source,message});try{await operation(),this.emitProgress({type:"complete",action,source})}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw this.emitProgress({type:"error",action,source,message:errorMessage}),error}}async resolve(onMissing){let accumulator=this.createAccumulator(),globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg of projectSettings.packages??[])allPackages.push({pkg,scope:"project"});for(let pkg of globalSettings.packages??[])allPackages.push({pkg,scope:"user"});let packageSources=this.dedupePackages(allPackages);await this.resolvePackageSources(packageSources,accumulator,onMissing);let globalBaseDir=this.agentDir,projectBaseDir=join3(this.cwd,CONFIG_DIR_NAME);for(let resourceType of RESOURCE_TYPES){let target=this.getTargetMap(accumulator,resourceType),globalEntries=globalSettings[resourceType]??[],projectEntries=projectSettings[resourceType]??[];this.resolveLocalEntries(projectEntries,resourceType,target,{source:"local",scope:"project",origin:"top-level"},projectBaseDir),this.resolveLocalEntries(globalEntries,resourceType,target,{source:"local",scope:"user",origin:"top-level"},globalBaseDir)}this.addAutoDiscoveredResources(accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir);for(let name of this.builtinExtensions){let path2=`${BUILTIN_PATH_PREFIX}${name}`,projectEnabled=applyAutoloadDisabledPatterns([path2],getOverridePatterns(projectSettings.extensions??[]),projectBaseDir).get(path2);this.addResource(accumulator.extensions,path2,{source:"builtin",scope:projectEnabled===void 0?"user":"project",origin:"top-level"},projectEnabled??isEnabledByOverrides(path2,globalSettings.extensions??[],globalBaseDir))}return this.toResolvedPaths(accumulator)}async resolveExtensionSources(sources,options){let accumulator=this.createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user";for(let source of sources.filter(source2=>source2.startsWith(BUILTIN_PATH_PREFIX)))this.addResource(accumulator.extensions,source,{source:"builtin",scope,origin:"top-level"},!0);let packageSources=sources.filter(source=>!source.startsWith(BUILTIN_PATH_PREFIX)).map(source=>({pkg:source,scope}));return await this.resolvePackageSources(packageSources,accumulator),this.toResolvedPaths(accumulator)}listConfiguredPackages(){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),configuredPackages=[];for(let pkg of globalSettings.packages??[]){let source=typeof pkg=="string"?pkg:pkg.source;configuredPackages.push({source,scope:"user",filtered:typeof pkg=="object",installedPath:this.getInstalledPath(source,"user")})}for(let pkg of projectSettings.packages??[]){let source=typeof pkg=="string"?pkg:pkg.source;configuredPackages.push({source,scope:"project",filtered:typeof pkg=="object",installedPath:this.getInstalledPath(source,"project")})}return configuredPackages}async install(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";this.assertProjectTrustedForScope(scope),await this.withProgress("install",source,`Installing ${source}...`,async()=>{if(parsed.type==="npm"){await this.installNpm(parsed,scope,!1);return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}if(parsed.type==="local"){let resolved=this.resolvePath(parsed.path);if(!existsSync3(resolved))throw new Error(`Path does not exist: ${resolved}`);return}throw new Error(`Unsupported install source: ${source}`)})}async installAndPersist(source,options){await this.install(source,options),this.addSourceToSettings(source,options)}async remove(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";this.assertProjectTrustedForScope(scope),await this.withProgress("remove",source,`Removing ${source}...`,async()=>{if(parsed.type==="npm"){await this.uninstallNpm(parsed,scope);return}if(parsed.type==="git"){await this.removeGit(parsed,scope);return}if(parsed.type!=="local")throw new Error(`Unsupported remove source: ${source}`)})}async removeAndPersist(source,options){return await this.remove(source,options),this.removeSourceFromSettings(source,options)}async update(source){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),identity=source?this.getPackageIdentity(source):void 0,matched=!1,updateSources=[];for(let pkg of globalSettings.packages??[]){let sourceStr=typeof pkg=="string"?pkg:pkg.source;identity&&this.getPackageIdentity(sourceStr,"user")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"user"}))}for(let pkg of projectSettings.packages??[]){let sourceStr=typeof pkg=="string"?pkg:pkg.source;identity&&this.getPackageIdentity(sourceStr,"project")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"project"}))}if(source&&!matched)throw new Error(this.buildNoMatchingPackageMessage(source,[...globalSettings.packages??[],...projectSettings.packages??[]]));await this.updateConfiguredSources(updateSources)}async updateConfiguredSources(sources){if(isOfflineModeEnabled()||sources.length===0)return;let npmCandidates=[],gitCandidates=[];for(let entry of sources){let parsed=this.parseSource(entry.source);parsed.type==="npm"?parsed.pinned||npmCandidates.push({...entry,parsed}):parsed.type==="git"&&gitCandidates.push({...entry,parsed})}let npmCheckTasks=npmCandidates.map(entry=>async()=>({entry,shouldUpdate:await this.shouldUpdateNpmSource(entry.parsed,entry.scope)})),npmCheckResults=await this.runWithConcurrency(npmCheckTasks,UPDATE_CHECK_CONCURRENCY),userNpmUpdates=[],projectNpmUpdates=[];for(let result of npmCheckResults)result.shouldUpdate&&(result.entry.scope==="user"?userNpmUpdates.push(result.entry):projectNpmUpdates.push(result.entry));let tasks=[];if(userNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(userNpmUpdates,"user")),projectNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(projectNpmUpdates,"project")),gitCandidates.length>0){let gitTasks=gitCandidates.map(entry=>async()=>this.withProgress("update",entry.source,`Updating ${entry.source}...`,async()=>{await this.updateGit(entry.parsed,entry.scope)}));tasks.push(this.runWithConcurrency(gitTasks,GIT_UPDATE_CONCURRENCY).then(()=>{}))}await Promise.all(tasks)}async shouldUpdateNpmSource(source,scope){let installedPath=this.getManagedNpmInstallPath(source,scope),installedVersion=existsSync3(installedPath)?this.getInstalledNpmVersion(installedPath):void 0;if(!installedVersion)return!0;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver.gt)(targetVersion,installedVersion)}catch{return!0}}async updateNpmBatch(sources,scope){if(sources.length===0)return;let sourceLabel=sources.length===1?sources[0].source:`${scope} npm packages`,message=sources.length===1?`Updating ${sources[0].source}...`:`Updating ${scope} npm packages...`,specs=sources.map(entry=>entry.parsed.version?entry.parsed.spec:`${entry.parsed.name}@latest`);await this.withProgress("update",sourceLabel,message,async()=>{await this.installNpmBatch(specs,scope)})}async installNpmBatch(specs,scope){let installRoot=this.getNpmInstallRoot(scope,!1);this.ensureNpmProject(installRoot),await this.runNpmCommand(this.getNpmInstallArgs(specs,installRoot))}async checkForAvailableUpdates(){if(isOfflineModeEnabled())return[];let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg of projectSettings.packages??[])allPackages.push({pkg,scope:"project"});for(let pkg of globalSettings.packages??[])allPackages.push({pkg,scope:"user"});let checks=this.dedupePackages(allPackages).filter(entry=>entry.scope!=="temporary"&&entry.scope!=="system").map(entry=>async()=>{let source=typeof entry.pkg=="string"?entry.pkg:entry.pkg.source,parsed=this.parseSource(source);if(parsed.type==="local"||parsed.pinned)return;if(parsed.type==="npm"){let installedPath2=this.getNpmInstallPath(parsed,entry.scope);return!existsSync3(installedPath2)||!await this.npmHasAvailableUpdate(parsed,installedPath2)?void 0:{source,displayName:parsed.name,type:"npm",scope:entry.scope}}let installedPath=this.getGitInstallPath(parsed,entry.scope);if(!(!existsSync3(installedPath)||!await this.gitHasAvailableUpdate(installedPath)))return{source,displayName:`${parsed.host}/${parsed.path}`,type:"git",scope:entry.scope}});return(await this.runWithConcurrency(checks,UPDATE_CHECK_CONCURRENCY)).filter(result=>result!==void 0)}async resolvePackageSources(sources,accumulator,onMissing){for(let{pkg,scope}of sources){let sourceStr=typeof pkg=="string"?pkg:pkg.source,filter2=typeof pkg=="object"?pkg:void 0,deltaBase=this.findAutoloadDeltaBase(pkg,scope,sources),resolvedSource=deltaBase?.source??sourceStr,resolvedScope=deltaBase?.scope??scope,parsed=this.parseSource(resolvedSource),metadata={source:sourceStr,scope,origin:"package"};if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(resolvedScope);this.resolveLocalExtensionSource(parsed,accumulator,filter2,metadata,baseDir);continue}let installMissing=async()=>{if(isOfflineModeEnabled())return!1;if(!onMissing)return await this.installParsedSource(parsed,resolvedScope),!0;let action=await onMissing(resolvedSource);if(action==="skip")return!1;if(action==="error")throw new Error(`Missing source: ${resolvedSource}`);return await this.installParsedSource(parsed,resolvedScope),!0};if(parsed.type==="npm"){let installedPath=this.getNpmInstallPath(parsed,resolvedScope);if(!existsSync3(installedPath)||!await this.installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,metadata.packageRoot=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync3(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=installedPath,metadata.packageRoot=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata)}}}findAutoloadDeltaBase(pkg,scope,sources){if(scope!=="project"||typeof pkg!="object"||pkg.autoload!==!1)return;let identity=this.getPackageIdentity(pkg.source,scope),userEntry=sources.find(entry=>entry.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(entry.pkg),"user")===identity);return userEntry?{source:this.getPackageSourceString(userEntry.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(source,accumulator,filter2,metadata,baseDir){let resolved=this.resolvePathFromBase(source.path,baseDir);if(existsSync3(resolved))try{let stats=statSync3(resolved);if(stats.isFile()){metadata.baseDir=dirname2(resolved),this.addResource(accumulator.extensions,resolved,metadata,!0);return}stats.isDirectory()&&(metadata.baseDir=resolved,metadata.packageRoot=resolved,this.collectPackageResources(resolved,accumulator,filter2,metadata)||this.addResource(accumulator.extensions,resolved,metadata,!0))}catch{return}}async installParsedSource(parsed,scope){if(parsed.type==="npm"){await this.installNpm(parsed,scope,scope==="temporary");return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}}getPackageSourceString(pkg){return typeof pkg=="string"?pkg:pkg.source}getSourceMatchKeyForInput(source){let parsed=this.parseSource(source);return parsed.type==="npm"?`npm:${parsed.name}`:parsed.type==="git"?`git:${parsed.host}/${parsed.path}`:`local:${this.resolvePath(parsed.path)}`}getSourceMatchKeyForSettings(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;let baseDir=this.getBaseDirForScope(scope);return`local:${this.resolvePathFromBase(parsed.path,baseDir)}`}buildNoMatchingPackageMessage(source,configuredPackages){let suggestion=this.findSuggestedConfiguredSource(source,configuredPackages);return suggestion?`No matching package found for ${source}. Did you mean ${suggestion}?`:`No matching package found for ${source}`}findSuggestedConfiguredSource(source,configuredPackages){let trimmedSource=source.trim(),suggestions=new Set;for(let pkg of configuredPackages){let sourceStr=this.getPackageSourceString(pkg),parsed=this.parseSource(sourceStr);if(parsed.type==="npm"){(trimmedSource===parsed.name||trimmedSource===parsed.spec)&&suggestions.add(sourceStr);continue}if(parsed.type==="git"){let shorthand=`${parsed.host}/${parsed.path}`,shorthandWithRef=parsed.ref?`${shorthand}@${parsed.ref}`:void 0;(trimmedSource===shorthand||shorthandWithRef&&trimmedSource===shorthandWithRef)&&suggestions.add(sourceStr)}}return suggestions.values().next().value}packageSourcesMatch(existing,inputSource,scope){let left=this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing),scope),right=this.getSourceMatchKeyForInput(inputSource);return left===right}normalizePackageSourceForSettings(source,scope){let parsed=this.parseSource(source);if(parsed.type!=="local")return source;let baseDir=this.getBaseDirForScope(scope),resolved=this.resolvePath(parsed.path);return relative2(baseDir,resolved)||"."}parseSource(source){if(source.startsWith("npm:")){let spec=source.slice(4).trim(),{name,version}=this.parseNpmSpec(spec);return{type:"npm",spec,name,version,range:getNpmVersionRange(version),pinned:isExactNpmVersion(version)}}if(isLocalPath(source))return{type:"local",path:source};let gitParsed=parseGitUrl(source);return gitParsed||{type:"local",path:source}}async installedNpmMatchesConfiguredVersion(source,installedPath){let installedVersion=this.getInstalledNpmVersion(installedPath);return installedVersion?source.range?(0,import_semver.satisfies)(installedVersion,source.range):!0:!1}async npmHasAvailableUpdate(source,installedPath){if(isOfflineModeEnabled())return!1;let installedVersion=this.getInstalledNpmVersion(installedPath);if(!installedVersion)return!1;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver.gt)(targetVersion,installedVersion)}catch{return!1}}getInstalledNpmVersion(installedPath){let packageJsonPath=join3(installedPath,"package.json");if(existsSync3(packageJsonPath))try{let content=readFileSync4(packageJsonPath,"utf-8");return JSON.parse(stripBom(content)).version}catch{return}}async getLatestNpmVersion(packageSpec,range2){let npmCommand=this.getNpmCommand(),raw=(await this.runCommandCapture(npmCommand.command,[...npmCommand.args,"view",packageSpec,"version","--json"],{cwd:this.cwd,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!raw)throw new Error("Empty response from npm view");let parsed=JSON.parse(raw);if(typeof parsed=="string")return parsed;if(Array.isArray(parsed)){let versions=parsed.filter(value=>typeof value=="string"&&value.length>0),latest=range2?(0,import_semver.maxSatisfying)(versions,range2):[...versions].sort(import_semver.rcompare)[0];if(latest)return latest}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(installedPath){if(isOfflineModeEnabled())return!1;try{let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),remoteHead=await this.getRemoteGitHead(installedPath);return localHead.trim()!==remoteHead.trim()}catch{return!1}}async getRemoteGitHead(installedPath){let upstreamRef=await this.getGitUpstreamRef(installedPath);if(upstreamRef){let match3=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin",upstreamRef])).match(/^([0-9a-f]{40})\s+/m);if(match3?.[1])return match3[1]}let match2=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!match2?.[1])throw new Error("Failed to determine remote HEAD");return match2[1]}async getLocalGitUpdateTarget(installedPath){try{let trimmedUpstream=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!trimmedUpstream.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`);let branch=trimmedUpstream.slice(7);if(!branch)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:installedPath}).catch(()=>{});let head=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),branch=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return branch?{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}:{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(installedPath){try{let trimmed=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!trimmed.startsWith("origin/"))return;let branch=trimmed.slice(7);return branch?`refs/heads/${branch}`:void 0}catch{return}}runGitRemoteCommand(installedPath,args){return this.runCommandCapture("git",args,{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(tasks,limit){if(tasks.length===0)return[];let results=new Array(tasks.length),nextIndex=0,workerCount=Math.max(1,Math.min(limit,tasks.length)),worker=async()=>{for(;;){let index=nextIndex;if(nextIndex+=1,index>=tasks.length)return;results[index]=await tasks[index]()}};return await Promise.all(Array.from({length:workerCount},()=>worker())),results}getPackageIdentity(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;if(scope){let baseDir=this.getBaseDirForScope(scope);return`local:${this.resolvePathFromBase(parsed.path,baseDir)}`}return`local:${this.resolvePath(parsed.path)}`}dedupePackages(packages){let result=[],seen=new Map;for(let entry of packages){let identity=this.getPackageIdentity(this.getPackageSourceString(entry.pkg),entry.scope),index=seen.get(identity);if(index===void 0){seen.set(identity,result.length),result.push(entry);continue}let existing=result[index];existing?.scope==="project"&&entry.scope==="user"?typeof existing.pkg=="object"&&existing.pkg.autoload===!1&&result.push(entry):entry.scope==="project"&&(result[index]=entry)}return result}parseNpmSpec(spec){let match2=spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!match2)return{name:spec};let name=match2[1]??spec,version=match2[2];return{name,version}}assertProjectTrustedForScope(scope){if(scope==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){let configuredCommand=this.settingsManager.getNpmCommand();if(!configuredCommand||configuredCommand.length===0)return{command:"npm",args:[]};let[command,...args]=configuredCommand;if(!command)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command,args}}getPackageManagerName(){let npmCommand=this.getNpmCommand(),normalizeCommandName=command=>basename(command).replace(/\.(cmd|exe)$/i,""),supportedPackageManagers=new Set(["npm","pnpm","bun"]),directCommand=normalizeCommandName(npmCommand.command),separatorIndex=npmCommand.args.lastIndexOf("--");if(separatorIndex>=0){let wrappedCommand=npmCommand.args[separatorIndex+1];return wrappedCommand?normalizeCommandName(wrappedCommand):directCommand}if(supportedPackageManagers.has(directCommand))return directCommand;let wrappedPackageManagers=[...new Set(npmCommand.args.map(normalizeCommandName).filter(command=>supportedPackageManagers.has(command)))];if(wrappedPackageManagers.length>1)throw new Error(`Ambiguous npmCommand package managers: ${wrappedPackageManagers.join(", ")}`);return wrappedPackageManagers[0]??directCommand}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(args){let npmCommand=this.getNpmCommand();return this.runCommandSync(npmCommand.command,[...npmCommand.args,...args])}getNpmInstallArgs(specs,installRoot){let packageManagerName=this.getPackageManagerName();return packageManagerName==="bun"?["install",...specs,"--cwd",installRoot,"--omit=peer"]:packageManagerName==="pnpm"?["install",...specs,"--prefix",installRoot,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...specs,"--prefix",installRoot,"--legacy-peer-deps"]}async installNpm(source,scope,temporary){let installRoot=this.getNpmInstallRoot(scope,temporary);this.ensureNpmProject(installRoot),await this.runNpmCommand(this.getNpmInstallArgs([source.spec],installRoot))}async uninstallNpm(source,scope){let installRoot=this.getNpmInstallRoot(scope,!1);if(!existsSync3(installRoot))return;let packageManagerName=this.getPackageManagerName();if(packageManagerName==="bun"){await this.runNpmCommand(["uninstall",source.name,"--cwd",installRoot]);return}let args=["uninstall",source.name,"--prefix",installRoot];packageManagerName!=="pnpm"&&args.push("--legacy-peer-deps"),await this.runNpmCommand(args)}async installGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(existsSync3(targetDir)){if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref);return}let gitRoot=this.getGitInstallRoot(scope);gitRoot&&this.ensureGitIgnore(gitRoot),mkdirSync(dirname2(targetDir),{recursive:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join3(targetDir,"package.json");existsSync3(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}catch(error){throw rmSync(targetDir,{recursive:!0,force:!0}),this.pruneEmptyGitParents(targetDir,gitRoot),error}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync3(targetDir)){await this.installGit(source,scope);return}if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref)}hasMissingGitDependencies(targetDir){let packageJsonPath=join3(targetDir,"package.json");if(!existsSync3(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync4(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve3(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve3(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep4}`)?!existsSync3(dependencyPath):!1})}catch{return!1}}async repairMissingGitDependencies(targetDir){this.hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}getGitUpdateMarkerPath(targetDir){return join3(dirname2(targetDir),`.${basename(targetDir)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error}let packageJsonPath=join3(targetDir,"package.json");existsSync3(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir}),rmSync(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),markerPath=this.getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync3(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync(targetDir,{recursive:!0,force:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0}),this.pruneEmptyGitParents(targetDir,this.getGitInstallRoot(scope))}pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve3(installRoot),current=dirname2(targetDir);for(;current.startsWith(resolvedRoot)&¤t!==resolvedRoot;){if(!existsSync3(current)){current=dirname2(current);continue}if(readdirSync2(current).length>0)break;try{rmSync(current,{recursive:!0,force:!0})}catch{break}current=dirname2(current)}}ensureNpmProject(installRoot){existsSync3(installRoot)||mkdirSync(installRoot,{recursive:!0}),markPathIgnoredByCloudSync(installRoot),this.ensureGitIgnore(installRoot);let packageJsonPath=join3(installRoot,"package.json");existsSync3(packageJsonPath)||writeFileSync(packageJsonPath,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(dir){existsSync3(dir)||mkdirSync(dir,{recursive:!0});let ignorePath=join3(dir,".gitignore");existsSync3(ignorePath)||writeFileSync(ignorePath,`*
|
|
134
|
+
---`),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,options={}){let entries=[];if(!existsSync(dir))return entries;let canonical;try{authorizeSkillPath(dir,options.provenance,options.allowedSet,!0),canonical=(options.realpath??realpathSync.native)(dir)}catch(error){if(error instanceof BlockedSkillLinkError)return[dir];canonical=resolve(dir)}if(options.ancestry?.has(canonical))return entries;let ancestry=new Set(options.ancestry);ancestry.add(canonical),options.onDirectory?.(dir);let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore.default)();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,{...options,ancestry})))}}catch{}return entries}function collectAutoSkillEntries(dir,mode,options){return collectSkillEntries(dir,mode,void 0,void 0,options)}var EMPTY_SKILL_ALLOWED_SET={roots:[],files:[],digest:""};function skillProjectRoot(cwd){let current=resolve2(cwd);for(;;){if(existsSync2(join2(current,".git")))return current;let parent=dirname(current);if(parent===current)return resolve2(cwd);current=parent}}function insideSkillRoot(path2,root){return path2===root||path2.startsWith(root.endsWith(sep3)?root:`${root}${sep3}`)}function buildSkillAllowedSet(sources){let roots=new Set,files=new Set,realpaths=new Map,realpath2=path2=>{let canonical=realpaths.get(path2);return canonical===void 0&&(canonical=realpathSync2.native(path2),realpaths.set(path2,canonical)),canonical};for(let source of new Set(sources))try{let canonical=realpath2(source);if(statSync2(canonical).isFile()){files.add(canonical);continue}collectSkillEntries(source,"pi",void 0,void 0,{realpath:realpath2,onDirectory:path2=>roots.add(realpath2(path2))})}catch{}let allowedRoots=[...roots].sort(),allowedFiles=[...files].sort();return{roots:allowedRoots,files:allowedFiles,digest:createHash("sha256").update(JSON.stringify([allowedRoots,allowedFiles])).digest("hex")}}var BlockedSkillLinkError=class extends Error{constructor(path2,target){let display=value=>{let home=homedir();return insideSkillRoot(value,home)?`~${value.slice(home.length)}`:value};super(`Blocked skill link outside the project: ${display(path2)} -> ${display(target)}. Add the target folder to your user skills settings to allow it.`),this.name="BlockedSkillLinkError",this.diagnostic={type:"warning",category:"skill-link-blocked",path:path2,message:this.message}}};function projectRoots(provenance){return[...provenance.projectRoot===void 0?[]:[provenance.projectRoot],...provenance.kind==="project-selected"?[provenance.selectedRoot]:[]]}function contained(canonical,roots,allowed,directory){return[...roots,...allowed.roots].some(root=>insideSkillRoot(canonical,root))||allowed.files.includes(canonical)||directory&&allowed.files.some(file=>insideSkillRoot(file,canonical))}function authorizeSkillPath(path2,provenance,allowed=EMPTY_SKILL_ALLOWED_SET,directory=!1){if(provenance===void 0||provenance.kind==="user")return path2;let canonical;try{canonical=realpathSync2.native(path2);let roots=projectRoots(provenance).map(root=>realpathSync2.native(root));if(contained(canonical,roots,allowed,directory))return canonical}catch{throw new BlockedSkillLinkError(path2,"unresolvable target")}throw new BlockedSkillLinkError(path2,canonical)}async function authorizeSkillPathAsync(path2,provenance,allowed){let canonical;try{canonical=await realpath(path2);let roots=await Promise.all(projectRoots(provenance).map(root=>realpath(root)));if(contained(canonical,roots,allowed,!1))return canonical}catch{throw new BlockedSkillLinkError(path2,"unresolvable target")}throw new BlockedSkillLinkError(path2,canonical)}function readSkillFileCheckedSync(path2,provenance,allowed){if(provenance===void 0||provenance.kind==="user")return readFileSync3(path2,"utf8");let canonical=authorizeSkillPath(path2,provenance,allowed),expected,descriptor;try{if(expected=lstatSync(canonical),!expected.isFile())throw new BlockedSkillLinkError(path2,canonical);descriptor=openSync2(canonical,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch{throw new BlockedSkillLinkError(path2,canonical)}try{let opened=fstatSync2(descriptor);if(!opened.isFile()||opened.dev!==expected.dev||opened.ino!==expected.ino||lstatSync(canonical).isSymbolicLink())throw new BlockedSkillLinkError(path2,canonical);return readFileSync3(descriptor,"utf8")}finally{closeSync2(descriptor)}}async function readSkillFileChecked(path2,provenance,allowed=EMPTY_SKILL_ALLOWED_SET){if(provenance===void 0||provenance.kind==="user")return await readFile(path2,"utf8");let canonical=await authorizeSkillPathAsync(path2,provenance,allowed),expected,handle;try{if(expected=await lstat(canonical),!expected.isFile())throw new BlockedSkillLinkError(path2,canonical);handle=await open(canonical,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch{throw new BlockedSkillLinkError(path2,canonical)}try{let opened=await handle.stat();if(!opened.isFile()||opened.dev!==expected.dev||opened.ino!==expected.ino||(await lstat(canonical)).isSymbolicLink())throw new BlockedSkillLinkError(path2,canonical);return await handle.readFile("utf8")}finally{await handle.close()}}function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync4("/proc/self/environ","utf-8"),env={};for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&(env[entry.slice(0,idx)]=entry.slice(idx+1))}return env}catch{return process.env}}var NETWORK_TIMEOUT_MS=1e4,UPDATE_CHECK_CONCURRENCY=4,GIT_UPDATE_CONCURRENCY=4;function isOfflineModeEnabled(){let value=envValue("OFFLINE");return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}function isExactNpmVersion(version){return(0,import_semver.valid)(version??"")!==null}function getNpmVersionRange(version){return version?(0,import_semver.validRange)(version)??void 0:void 0}function resourcePrecedenceRank(m){return m.source==="builtin"?5:m.origin==="package"?4:(m.scope==="project"?0:2)+(m.source==="local"?0:1)}var RESOURCE_TYPES=["extensions","skills","prompts","themes","hooks"],FILE_PATTERNS={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/,hooks:/\.json$/},IGNORE_FILE_NAMES2=[".gitignore",".ignore",".fdignore"];function toPosixPath2(p){return p.split(sep4).join("/")}function getHomeDir(){return process.env.HOME||homedir2()}function getExtensionTempFolder(agentDir){let tempFolder=join3(agentDir,"tmp","extensions");return mkdirSync(tempFolder,{recursive:!0,mode:448}),chmodSync(tempFolder,448),tempFolder}function prefixIgnorePattern2(line,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=join3(dir,filename);if(existsSync3(ignorePath))try{let patterns=readFileSync4(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function isPattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")||s.includes("*")||s.includes("?")}function isOverridePattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")}function hasGlobPattern(s){return s.includes("*")||s.includes("?")}function expandPackageGlob(pattern,root){return globSync(pattern,{cwd:root}).map(match2=>resolve3(root,match2)).filter(path2=>relative2(root,path2).split(sep4).every(segment=>segment===".."||!segment.startsWith("."))).sort((a,b)=>a<b?-1:a>b?1:0)}function splitPatterns(entries){let plain=[],patterns=[];for(let entry of entries)isPattern(entry)?patterns.push(entry):plain.push(entry);return{plain,patterns}}function collectFiles(dir,filePattern,skipNodeModules=!0,ignoreMatcher,rootDir){let files=[];if(!existsSync3(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore2.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync2(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync3(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath2(relative2(root,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;ig.ignores(ignorePath)||(isDir?files.push(...collectFiles(fullPath,filePattern,skipNodeModules,ig,root)):isFile&&filePattern.test(entry.name)&&files.push(fullPath))}}catch{}return files}function collectAncestorAgentsSkillDirs(startDir){return projectAgentsSkillDirs(startDir)}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync3(fullPath).isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".md")&&entries.push(fullPath)}}catch{}return entries}function collectAutoThemeEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync3(fullPath).isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".json")&&entries.push(fullPath)}}catch{}return entries}function resolveExtensionEntries(dir){let packageJsonPath=join3(dir,"package.json");if(existsSync3(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=resolve3(dir,extPath);existsSync3(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=join3(dir,"index.ts"),indexJs=join3(dir,"index.js");return existsSync3(indexTs)?[indexTs]:existsSync3(indexJs)?[indexJs]:null}function collectAutoExtensionEntries(dir){let entries=[];if(!existsSync3(dir))return entries;let rootEntries=resolveExtensionEntries(dir);if(rootEntries)return rootEntries;let ig=(0,import_ignore2.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync2(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join3(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync3(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath2(relative2(dir,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;if(!ig.ignores(ignorePath)){if(isFile&&(entry.name.endsWith(".ts")||entry.name.endsWith(".js")))entries.push(fullPath);else if(isDir){let resolvedEntries=resolveExtensionEntries(fullPath);resolvedEntries&&entries.push(...resolvedEntries)}}}}catch{}return entries}function collectResourceFiles(dir,resourceType,provenance){return resourceType==="skills"?collectSkillEntries(dir,"pi",void 0,void 0,{provenance}):resourceType==="extensions"?collectAutoExtensionEntries(dir):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentName=isSkillFile?basename(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath2(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath2(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath2(relative2(baseDir,filePath)),name=basename(filePath),filePathPosix=toPosixPath2(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname2(filePath):void 0,parentRel=isSkillFile?toPosixPath2(relative2(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath2(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var DefaultPackageManager=class{constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager,this.builtinExtensions=options.builtinExtensions??[]}setProgressCallback(callback){this.progressCallback=callback}addSourceToSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],normalizedSource=this.normalizePackageSourceForSettings(source,scope),matchIndex=currentPackages.findIndex(existing=>this.packageSourcesMatch(existing,source,scope));if(matchIndex!==-1){let existing=currentPackages[matchIndex];if(this.getPackageSourceString(existing)===normalizedSource)return!1;let nextPackages2=[...currentPackages];return nextPackages2[matchIndex]=typeof existing=="string"?normalizedSource:{...existing,source:normalizedSource},scope==="project"?this.settingsManager.setProjectPackages(nextPackages2):this.settingsManager.setPackages(nextPackages2),!0}let nextPackages=[...currentPackages,normalizedSource];return scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0}removeSourceFromSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],nextPackages=currentPackages.filter(existing=>!this.packageSourcesMatch(existing,source,scope));return nextPackages.length!==currentPackages.length?(scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0):!1}getInstalledPath(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm"){let path2=this.getNpmInstallPath(parsed,scope);return existsSync3(path2)?path2:void 0}if(parsed.type==="git"){let path2=this.getGitInstallPath(parsed,scope);return existsSync3(path2)?path2:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path2=this.resolvePathFromBase(parsed.path,baseDir);return existsSync3(path2)?path2:void 0}}emitProgress(event){this.progressCallback?.(event)}async withProgress(action,source,message,operation){this.emitProgress({type:"start",action,source,message});try{await operation(),this.emitProgress({type:"complete",action,source})}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw this.emitProgress({type:"error",action,source,message:errorMessage}),error}}async resolve(onMissing){let accumulator=this.createAccumulator(),globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg of projectSettings.packages??[])allPackages.push({pkg,scope:"project"});for(let pkg of globalSettings.packages??[])allPackages.push({pkg,scope:"user"});let packageSources=this.dedupePackages(allPackages);await this.resolvePackageSources(packageSources,accumulator,onMissing);let globalBaseDir=this.agentDir,projectBaseDir=join3(this.cwd,CONFIG_DIR_NAME);for(let resourceType of RESOURCE_TYPES){let target=this.getTargetMap(accumulator,resourceType),globalEntries=globalSettings[resourceType]??[],projectEntries=projectSettings[resourceType]??[];this.resolveLocalEntries(projectEntries,resourceType,target,{source:"local",scope:"project",origin:"top-level"},projectBaseDir),this.resolveLocalEntries(globalEntries,resourceType,target,{source:"local",scope:"user",origin:"top-level"},globalBaseDir)}this.addAutoDiscoveredResources(accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir);for(let name of this.builtinExtensions){let path2=`${BUILTIN_PATH_PREFIX}${name}`,projectEnabled=applyAutoloadDisabledPatterns([path2],getOverridePatterns(projectSettings.extensions??[]),projectBaseDir).get(path2);this.addResource(accumulator.extensions,path2,{source:"builtin",scope:projectEnabled===void 0?"user":"project",origin:"top-level"},projectEnabled??isEnabledByOverrides(path2,globalSettings.extensions??[],globalBaseDir))}return this.toResolvedPaths(accumulator)}async resolveExtensionSources(sources,options){let accumulator=this.createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user";for(let source of sources.filter(source2=>source2.startsWith(BUILTIN_PATH_PREFIX)))this.addResource(accumulator.extensions,source,{source:"builtin",scope,origin:"top-level"},!0);let packageSources=sources.filter(source=>!source.startsWith(BUILTIN_PATH_PREFIX)).map(source=>({pkg:source,scope}));return await this.resolvePackageSources(packageSources,accumulator),this.toResolvedPaths(accumulator)}listConfiguredPackages(){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),configuredPackages=[];for(let pkg of globalSettings.packages??[]){let source=typeof pkg=="string"?pkg:pkg.source;configuredPackages.push({source,scope:"user",filtered:typeof pkg=="object",installedPath:this.getInstalledPath(source,"user")})}for(let pkg of projectSettings.packages??[]){let source=typeof pkg=="string"?pkg:pkg.source;configuredPackages.push({source,scope:"project",filtered:typeof pkg=="object",installedPath:this.getInstalledPath(source,"project")})}return configuredPackages}async install(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";this.assertProjectTrustedForScope(scope),await this.withProgress("install",source,`Installing ${source}...`,async()=>{if(parsed.type==="npm"){await this.installNpm(parsed,scope,!1);return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}if(parsed.type==="local"){let resolved=this.resolvePath(parsed.path);if(!existsSync3(resolved))throw new Error(`Path does not exist: ${resolved}`);return}throw new Error(`Unsupported install source: ${source}`)})}async installAndPersist(source,options){await this.install(source,options),this.addSourceToSettings(source,options)}async remove(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";this.assertProjectTrustedForScope(scope),await this.withProgress("remove",source,`Removing ${source}...`,async()=>{if(parsed.type==="npm"){await this.uninstallNpm(parsed,scope);return}if(parsed.type==="git"){await this.removeGit(parsed,scope);return}if(parsed.type!=="local")throw new Error(`Unsupported remove source: ${source}`)})}async removeAndPersist(source,options){return await this.remove(source,options),this.removeSourceFromSettings(source,options)}async update(source){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),identity=source?this.getPackageIdentity(source):void 0,matched=!1,updateSources=[];for(let pkg of globalSettings.packages??[]){let sourceStr=typeof pkg=="string"?pkg:pkg.source;identity&&this.getPackageIdentity(sourceStr,"user")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"user"}))}for(let pkg of projectSettings.packages??[]){let sourceStr=typeof pkg=="string"?pkg:pkg.source;identity&&this.getPackageIdentity(sourceStr,"project")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"project"}))}if(source&&!matched)throw new Error(this.buildNoMatchingPackageMessage(source,[...globalSettings.packages??[],...projectSettings.packages??[]]));await this.updateConfiguredSources(updateSources)}async updateConfiguredSources(sources){if(isOfflineModeEnabled()||sources.length===0)return;let npmCandidates=[],gitCandidates=[];for(let entry of sources){let parsed=this.parseSource(entry.source);parsed.type==="npm"?parsed.pinned||npmCandidates.push({...entry,parsed}):parsed.type==="git"&&gitCandidates.push({...entry,parsed})}let npmCheckTasks=npmCandidates.map(entry=>async()=>({entry,shouldUpdate:await this.shouldUpdateNpmSource(entry.parsed,entry.scope)})),npmCheckResults=await this.runWithConcurrency(npmCheckTasks,UPDATE_CHECK_CONCURRENCY),userNpmUpdates=[],projectNpmUpdates=[];for(let result of npmCheckResults)result.shouldUpdate&&(result.entry.scope==="user"?userNpmUpdates.push(result.entry):projectNpmUpdates.push(result.entry));let tasks=[];if(userNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(userNpmUpdates,"user")),projectNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(projectNpmUpdates,"project")),gitCandidates.length>0){let gitTasks=gitCandidates.map(entry=>async()=>this.withProgress("update",entry.source,`Updating ${entry.source}...`,async()=>{await this.updateGit(entry.parsed,entry.scope)}));tasks.push(this.runWithConcurrency(gitTasks,GIT_UPDATE_CONCURRENCY).then(()=>{}))}await Promise.all(tasks)}async shouldUpdateNpmSource(source,scope){let installedPath=this.getManagedNpmInstallPath(source,scope),installedVersion=existsSync3(installedPath)?this.getInstalledNpmVersion(installedPath):void 0;if(!installedVersion)return!0;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver.gt)(targetVersion,installedVersion)}catch{return!0}}async updateNpmBatch(sources,scope){if(sources.length===0)return;let sourceLabel=sources.length===1?sources[0].source:`${scope} npm packages`,message=sources.length===1?`Updating ${sources[0].source}...`:`Updating ${scope} npm packages...`,specs=sources.map(entry=>entry.parsed.version?entry.parsed.spec:`${entry.parsed.name}@latest`);await this.withProgress("update",sourceLabel,message,async()=>{await this.installNpmBatch(specs,scope)})}async installNpmBatch(specs,scope){let installRoot=this.getNpmInstallRoot(scope,!1);this.ensureNpmProject(installRoot),await this.runNpmCommand(this.getNpmInstallArgs(specs,installRoot))}async checkForAvailableUpdates(){if(isOfflineModeEnabled())return[];let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg of projectSettings.packages??[])allPackages.push({pkg,scope:"project"});for(let pkg of globalSettings.packages??[])allPackages.push({pkg,scope:"user"});let checks=this.dedupePackages(allPackages).filter(entry=>entry.scope!=="temporary"&&entry.scope!=="system").map(entry=>async()=>{let source=typeof entry.pkg=="string"?entry.pkg:entry.pkg.source,parsed=this.parseSource(source);if(parsed.type==="local"||parsed.pinned)return;if(parsed.type==="npm"){let installedPath2=this.getNpmInstallPath(parsed,entry.scope);return!existsSync3(installedPath2)||!await this.npmHasAvailableUpdate(parsed,installedPath2)?void 0:{source,displayName:parsed.name,type:"npm",scope:entry.scope}}let installedPath=this.getGitInstallPath(parsed,entry.scope);if(!(!existsSync3(installedPath)||!await this.gitHasAvailableUpdate(installedPath)))return{source,displayName:`${parsed.host}/${parsed.path}`,type:"git",scope:entry.scope}});return(await this.runWithConcurrency(checks,UPDATE_CHECK_CONCURRENCY)).filter(result=>result!==void 0)}async resolvePackageSources(sources,accumulator,onMissing){for(let{pkg,scope}of sources){let sourceStr=typeof pkg=="string"?pkg:pkg.source,filter2=typeof pkg=="object"?pkg:void 0,deltaBase=this.findAutoloadDeltaBase(pkg,scope,sources),resolvedSource=deltaBase?.source??sourceStr,resolvedScope=deltaBase?.scope??scope,parsed=this.parseSource(resolvedSource),metadata={source:sourceStr,scope,origin:"package"};if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(resolvedScope);this.resolveLocalExtensionSource(parsed,accumulator,filter2,metadata,baseDir);continue}let installMissing=async()=>{if(isOfflineModeEnabled())return!1;if(!onMissing)return await this.installParsedSource(parsed,resolvedScope),!0;let action=await onMissing(resolvedSource);if(action==="skip")return!1;if(action==="error")throw new Error(`Missing source: ${resolvedSource}`);return await this.installParsedSource(parsed,resolvedScope),!0};if(parsed.type==="npm"){let installedPath=this.getNpmInstallPath(parsed,resolvedScope);if(!existsSync3(installedPath)||!await this.installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,metadata.packageRoot=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync3(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=installedPath,metadata.packageRoot=installedPath,this.collectPackageResources(installedPath,accumulator,filter2,metadata)}}}findAutoloadDeltaBase(pkg,scope,sources){if(scope!=="project"||typeof pkg!="object"||pkg.autoload!==!1)return;let identity=this.getPackageIdentity(pkg.source,scope),userEntry=sources.find(entry=>entry.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(entry.pkg),"user")===identity);return userEntry?{source:this.getPackageSourceString(userEntry.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(source,accumulator,filter2,metadata,baseDir){let resolved=this.resolvePathFromBase(source.path,baseDir);if(existsSync3(resolved))try{let stats=statSync3(resolved);if(stats.isFile()){metadata.baseDir=dirname2(resolved),this.addResource(accumulator.extensions,resolved,metadata,!0);return}stats.isDirectory()&&(metadata.baseDir=resolved,metadata.packageRoot=resolved,this.collectPackageResources(resolved,accumulator,filter2,metadata)||this.addResource(accumulator.extensions,resolved,metadata,!0))}catch{return}}async installParsedSource(parsed,scope){if(parsed.type==="npm"){await this.installNpm(parsed,scope,scope==="temporary");return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}}getPackageSourceString(pkg){return typeof pkg=="string"?pkg:pkg.source}getSourceMatchKeyForInput(source){let parsed=this.parseSource(source);return parsed.type==="npm"?`npm:${parsed.name}`:parsed.type==="git"?`git:${parsed.host}/${parsed.path}`:`local:${this.resolvePath(parsed.path)}`}getSourceMatchKeyForSettings(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;let baseDir=this.getBaseDirForScope(scope);return`local:${this.resolvePathFromBase(parsed.path,baseDir)}`}buildNoMatchingPackageMessage(source,configuredPackages){let suggestion=this.findSuggestedConfiguredSource(source,configuredPackages);return suggestion?`No matching package found for ${source}. Did you mean ${suggestion}?`:`No matching package found for ${source}`}findSuggestedConfiguredSource(source,configuredPackages){let trimmedSource=source.trim(),suggestions=new Set;for(let pkg of configuredPackages){let sourceStr=this.getPackageSourceString(pkg),parsed=this.parseSource(sourceStr);if(parsed.type==="npm"){(trimmedSource===parsed.name||trimmedSource===parsed.spec)&&suggestions.add(sourceStr);continue}if(parsed.type==="git"){let shorthand=`${parsed.host}/${parsed.path}`,shorthandWithRef=parsed.ref?`${shorthand}@${parsed.ref}`:void 0;(trimmedSource===shorthand||shorthandWithRef&&trimmedSource===shorthandWithRef)&&suggestions.add(sourceStr)}}return suggestions.values().next().value}packageSourcesMatch(existing,inputSource,scope){let left=this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing),scope),right=this.getSourceMatchKeyForInput(inputSource);return left===right}normalizePackageSourceForSettings(source,scope){let parsed=this.parseSource(source);if(parsed.type!=="local")return source;let baseDir=this.getBaseDirForScope(scope),resolved=this.resolvePath(parsed.path);return relative2(baseDir,resolved)||"."}parseSource(source){if(source.startsWith("npm:")){let spec=source.slice(4).trim(),{name,version}=this.parseNpmSpec(spec);return{type:"npm",spec,name,version,range:getNpmVersionRange(version),pinned:isExactNpmVersion(version)}}if(isLocalPath(source))return{type:"local",path:source};let gitParsed=parseGitUrl(source);return gitParsed||{type:"local",path:source}}async installedNpmMatchesConfiguredVersion(source,installedPath){let installedVersion=this.getInstalledNpmVersion(installedPath);return installedVersion?source.range?(0,import_semver.satisfies)(installedVersion,source.range):!0:!1}async npmHasAvailableUpdate(source,installedPath){if(isOfflineModeEnabled())return!1;let installedVersion=this.getInstalledNpmVersion(installedPath);if(!installedVersion)return!1;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver.gt)(targetVersion,installedVersion)}catch{return!1}}getInstalledNpmVersion(installedPath){let packageJsonPath=join3(installedPath,"package.json");if(existsSync3(packageJsonPath))try{let content=readFileSync4(packageJsonPath,"utf-8");return JSON.parse(stripBom(content)).version}catch{return}}async getLatestNpmVersion(packageSpec,range2){let npmCommand=this.getNpmCommand(),raw=(await this.runCommandCapture(npmCommand.command,[...npmCommand.args,"view",packageSpec,"version","--json"],{cwd:this.cwd,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!raw)throw new Error("Empty response from npm view");let parsed=JSON.parse(raw);if(typeof parsed=="string")return parsed;if(Array.isArray(parsed)){let versions=parsed.filter(value=>typeof value=="string"&&value.length>0),latest=range2?(0,import_semver.maxSatisfying)(versions,range2):[...versions].sort(import_semver.rcompare)[0];if(latest)return latest}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(installedPath){if(isOfflineModeEnabled())return!1;try{let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),remoteHead=await this.getRemoteGitHead(installedPath);return localHead.trim()!==remoteHead.trim()}catch{return!1}}async getRemoteGitHead(installedPath){let upstreamRef=await this.getGitUpstreamRef(installedPath);if(upstreamRef){let match3=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin",upstreamRef])).match(/^([0-9a-f]{40})\s+/m);if(match3?.[1])return match3[1]}let match2=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!match2?.[1])throw new Error("Failed to determine remote HEAD");return match2[1]}async getLocalGitUpdateTarget(installedPath){try{let trimmedUpstream=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!trimmedUpstream.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`);let branch=trimmedUpstream.slice(7);if(!branch)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:installedPath}).catch(()=>{});let head=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}),branch=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return branch?{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}:{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(installedPath){try{let trimmed=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS})).trim();if(!trimmed.startsWith("origin/"))return;let branch=trimmed.slice(7);return branch?`refs/heads/${branch}`:void 0}catch{return}}runGitRemoteCommand(installedPath,args){return this.runCommandCapture("git",args,{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(tasks,limit){if(tasks.length===0)return[];let results=new Array(tasks.length),nextIndex=0,workerCount=Math.max(1,Math.min(limit,tasks.length)),worker=async()=>{for(;;){let index=nextIndex;if(nextIndex+=1,index>=tasks.length)return;results[index]=await tasks[index]()}};return await Promise.all(Array.from({length:workerCount},()=>worker())),results}getPackageIdentity(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;if(scope){let baseDir=this.getBaseDirForScope(scope);return`local:${this.resolvePathFromBase(parsed.path,baseDir)}`}return`local:${this.resolvePath(parsed.path)}`}dedupePackages(packages){let result=[],seen=new Map;for(let entry of packages){let identity=this.getPackageIdentity(this.getPackageSourceString(entry.pkg),entry.scope),index=seen.get(identity);if(index===void 0){seen.set(identity,result.length),result.push(entry);continue}let existing=result[index];existing?.scope==="project"&&entry.scope==="user"?typeof existing.pkg=="object"&&existing.pkg.autoload===!1&&result.push(entry):entry.scope==="project"&&(result[index]=entry)}return result}parseNpmSpec(spec){let match2=spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!match2)return{name:spec};let name=match2[1]??spec,version=match2[2];return{name,version}}assertProjectTrustedForScope(scope){if(scope==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){let configuredCommand=this.settingsManager.getNpmCommand();if(!configuredCommand||configuredCommand.length===0)return{command:"npm",args:[]};let[command,...args]=configuredCommand;if(!command)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command,args}}getPackageManagerName(){let npmCommand=this.getNpmCommand(),normalizeCommandName=command=>basename(command).replace(/\.(cmd|exe)$/i,""),supportedPackageManagers=new Set(["npm","pnpm","bun"]),directCommand=normalizeCommandName(npmCommand.command),separatorIndex=npmCommand.args.lastIndexOf("--");if(separatorIndex>=0){let wrappedCommand=npmCommand.args[separatorIndex+1];return wrappedCommand?normalizeCommandName(wrappedCommand):directCommand}if(supportedPackageManagers.has(directCommand))return directCommand;let wrappedPackageManagers=[...new Set(npmCommand.args.map(normalizeCommandName).filter(command=>supportedPackageManagers.has(command)))];if(wrappedPackageManagers.length>1)throw new Error(`Ambiguous npmCommand package managers: ${wrappedPackageManagers.join(", ")}`);return wrappedPackageManagers[0]??directCommand}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(args){let npmCommand=this.getNpmCommand();return this.runCommandSync(npmCommand.command,[...npmCommand.args,...args])}getNpmInstallArgs(specs,installRoot){let packageManagerName=this.getPackageManagerName();return packageManagerName==="bun"?["install",...specs,"--cwd",installRoot,"--omit=peer"]:packageManagerName==="pnpm"?["install",...specs,"--prefix",installRoot,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...specs,"--prefix",installRoot,"--legacy-peer-deps"]}async installNpm(source,scope,temporary){let installRoot=this.getNpmInstallRoot(scope,temporary);this.ensureNpmProject(installRoot),await this.runNpmCommand(this.getNpmInstallArgs([source.spec],installRoot))}async uninstallNpm(source,scope){let installRoot=this.getNpmInstallRoot(scope,!1);if(!existsSync3(installRoot))return;let packageManagerName=this.getPackageManagerName();if(packageManagerName==="bun"){await this.runNpmCommand(["uninstall",source.name,"--cwd",installRoot]);return}let args=["uninstall",source.name,"--prefix",installRoot];packageManagerName!=="pnpm"&&args.push("--legacy-peer-deps"),await this.runNpmCommand(args)}async installGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(existsSync3(targetDir)){if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref);return}let gitRoot=this.getGitInstallRoot(scope);gitRoot&&this.ensureGitIgnore(gitRoot),mkdirSync(dirname2(targetDir),{recursive:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join3(targetDir,"package.json");existsSync3(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}catch(error){throw rmSync(targetDir,{recursive:!0,force:!0}),this.pruneEmptyGitParents(targetDir,gitRoot),error}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync3(targetDir)){await this.installGit(source,scope);return}if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref)}hasMissingGitDependencies(targetDir){let packageJsonPath=join3(targetDir,"package.json");if(!existsSync3(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync4(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve3(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve3(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep4}`)?!existsSync3(dependencyPath):!1})}catch{return!1}}async repairMissingGitDependencies(targetDir){this.hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir})}getGitUpdateMarkerPath(targetDir){return join3(dirname2(targetDir),`.${basename(targetDir)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error}let packageJsonPath=join3(targetDir,"package.json");existsSync3(packageJsonPath)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:targetDir}),rmSync(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS}),markerPath=this.getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync3(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync(targetDir,{recursive:!0,force:!0}),rmSync(this.getGitUpdateMarkerPath(targetDir),{force:!0}),this.pruneEmptyGitParents(targetDir,this.getGitInstallRoot(scope))}pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve3(installRoot),current=dirname2(targetDir);for(;current.startsWith(resolvedRoot)&¤t!==resolvedRoot;){if(!existsSync3(current)){current=dirname2(current);continue}if(readdirSync2(current).length>0)break;try{rmSync(current,{recursive:!0,force:!0})}catch{break}current=dirname2(current)}}ensureNpmProject(installRoot){existsSync3(installRoot)||mkdirSync(installRoot,{recursive:!0}),markPathIgnoredByCloudSync(installRoot),this.ensureGitIgnore(installRoot);let packageJsonPath=join3(installRoot,"package.json");existsSync3(packageJsonPath)||writeFileSync(packageJsonPath,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(dir){existsSync3(dir)||mkdirSync(dir,{recursive:!0});let ignorePath=join3(dir,".gitignore");existsSync3(ignorePath)||writeFileSync(ignorePath,`*
|
|
135
135
|
!.gitignore
|
|
136
136
|
`,"utf-8")}getNpmInstallRoot(scope,temporary){return temporary?this.getTemporaryDir("npm"):scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME,"npm")):join3(this.agentDir,"npm")}getGlobalNpmRoot(){let npmCommand=this.getNpmCommand(),commandKey=[npmCommand.command,...npmCommand.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===commandKey)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){let binDir=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=join3(dirname2(binDir),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=commandKey,this.globalNpmRoot}getPnpmGlobalPackagePath(packageName){if(this.getPackageManagerName()!=="pnpm")return;let output=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),entries=JSON.parse(output);for(let entry of entries){let path2=entry.dependencies?.[packageName]?.path;if(path2)return path2}}getManagedNpmInstallPath(source,scope){return scope==="temporary"?join3(this.getTemporaryDir("npm"),"node_modules",source.name):scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME,"npm","node_modules",source.name)):join3(this.agentDir,"npm","node_modules",source.name)}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join3(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=this.getManagedNpmInstallPath(source,scope);if(scope!=="user"||existsSync3(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync3(legacyPath)?legacyPath:managedPath}getGitInstallPath(source,scope){if(scope==="temporary")return this.getTemporaryDir(`git-${source.host}`,source.path,source.ref);let installRoot=this.getGitInstallRoot(scope);if(!installRoot)throw new Error("Missing git install root");return this.resolveManagedPath(installRoot,source.host,source.path)}getGitInstallRoot(scope){if(scope!=="temporary")return scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME,"git")):join3(this.agentDir,"git")}getTemporaryDir(prefix,suffix,ref){let root=this.resolveManagedPath(getExtensionTempFolder(this.agentDir),prefix),hash=createHash2("sha256").update(`${prefix}-${suffix??""}${ref?`@${ref}`:""}`).digest("hex").slice(0,8);return this.resolveManagedPath(root,hash,suffix??"")}resolveManagedPath(root,...parts){let resolvedRoot=resolve3(root),resolvedPath=resolve3(resolvedRoot,...parts);if(resolvedPath!==resolvedRoot&&!resolvedPath.startsWith(`${resolvedRoot}${sep4}`))throw new Error(`Refusing to use path outside package install root: ${resolvedPath}`);return resolvedPath}getBaseDirForScope(scope){return scope==="project"?(this.assertProjectTrustedForScope(scope),join3(this.cwd,CONFIG_DIR_NAME)):scope==="user"?this.agentDir:this.cwd}resolvePath(input){return resolvePath(input,this.cwd,{homeDir:getHomeDir(),trim:!0})}resolvePathFromBase(input,baseDir){return resolvePath(input,baseDir,{homeDir:getHomeDir(),trim:!0})}collectPackageResources(packageRoot,accumulator,filter2,metadata){metadata=this.selectSkillRoot(packageRoot,metadata,"project-auto");let manifest=readPiManifest(join3(packageRoot,"package.json"));if(manifest?.system===!0&&metadata.scope==="temporary"&&(metadata.scope="system"),filter2){for(let resourceType of RESOURCE_TYPES){let patterns=filter2[resourceType],target=this.getTargetMap(accumulator,resourceType);filter2.autoload===!1?this.applyPackageDeltaFilter(packageRoot,patterns??[],resourceType,target,metadata):patterns!==void 0?this.applyPackageFilter(packageRoot,patterns,resourceType,target,metadata):this.collectDefaultResources(packageRoot,resourceType,target,metadata)}return!0}if(manifest){for(let resourceType of RESOURCE_TYPES){let entries=manifest[resourceType];this.addManifestEntries(entries,packageRoot,resourceType,this.getTargetMap(accumulator,resourceType),metadata)}return!0}let hasAnyDir=!1;for(let resourceType of RESOURCE_TYPES){let dir=join3(packageRoot,resourceType);if(existsSync3(dir)){let files=collectResourceFiles(dir,resourceType,metadata.skillProvenance);for(let f of files)this.addResource(this.getTargetMap(accumulator,resourceType),f,metadata,!0);hasAnyDir=!0}}return hasAnyDir}collectDefaultResources(packageRoot,resourceType,target,metadata){let entries=readPiManifest(join3(packageRoot,"package.json"))?.[resourceType];if(entries){this.addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join3(packageRoot,resourceType);if(existsSync3(dir)){let files=collectResourceFiles(dir,resourceType,metadata.skillProvenance);for(let f of files)this.addResource(target,f,metadata,!0)}}applyPackageFilter(packageRoot,userPatterns,resourceType,target,metadata){let{allFiles}=this.collectManifestFiles(packageRoot,resourceType,metadata.skillProvenance);if(userPatterns.length===0){for(let f of allFiles)this.addResource(target,f,metadata,!1);return}let enabledByUser=applyPatterns(allFiles,userPatterns,packageRoot);for(let f of allFiles){let enabled=enabledByUser.has(f);this.addResource(target,f,metadata,enabled)}}applyPackageDeltaFilter(packageRoot,userPatterns,resourceType,target,metadata){if(userPatterns.length===0)return;let{allFiles}=this.collectManifestFiles(packageRoot,resourceType,metadata.skillProvenance),enabledByUser=applyAutoloadDisabledPatterns(allFiles,userPatterns,packageRoot);for(let[filePath,enabled]of enabledByUser)this.addResource(target,filePath,metadata,enabled)}collectManifestFiles(packageRoot,resourceType,provenance){let entries=readPiManifest(join3(packageRoot,"package.json"))?.[resourceType];if(entries&&entries.length>0){let allFiles2=this.collectFilesFromManifestEntries(entries,packageRoot,resourceType,provenance),manifestPatterns=entries.filter(isOverridePattern),enabledByManifest=manifestPatterns.length>0?applyPatterns(allFiles2,manifestPatterns,packageRoot):new Set(allFiles2);return{allFiles:Array.from(enabledByManifest),enabledByManifest}}let conventionDir=join3(packageRoot,resourceType);if(!existsSync3(conventionDir))return{allFiles:[],enabledByManifest:new Set};let allFiles=collectResourceFiles(conventionDir,resourceType,provenance);return{allFiles,enabledByManifest:new Set(allFiles)}}addManifestEntries(entries,root,resourceType,target,metadata){if(!entries)return;let allFiles=this.collectFilesFromManifestEntries(entries,root,resourceType,metadata.skillProvenance),patterns=entries.filter(isOverridePattern),enabledPaths=applyPatterns(allFiles,patterns,root);for(let f of allFiles)enabledPaths.has(f)&&this.addResource(target,f,metadata,!0)}collectFilesFromManifestEntries(entries,root,resourceType,provenance){let resolved=entries.filter(entry=>!isOverridePattern(entry)).flatMap(entry=>hasGlobPattern(entry)?expandPackageGlob(entry,root):[resolve3(root,entry)]);return this.collectFilesFromPaths(resolved,resourceType,provenance)}resolveLocalEntries(entries,resourceType,target,metadata,baseDir){if(entries.length===0)return;let{plain,patterns}=splitPatterns(entries),resolvedPlain=plain.map(p=>this.resolvePathFromBase(p,baseDir)),metadataByFile=new Map,allFiles=resolvedPlain.flatMap(path2=>{let selected=resourceType==="skills"?this.selectSkillRoot(path2,metadata,"project-selected"):metadata,files=this.collectFilesFromPaths([path2],resourceType,selected.skillProvenance);for(let file of files)metadataByFile.set(file,selected);return files}),enabledPaths=applyPatterns(allFiles,patterns,baseDir);for(let f of allFiles)this.addResource(target,f,metadataByFile.get(f)??metadata,enabledPaths.has(f))}addAutoDiscoveredResources(accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir){let userMetadata={source:"auto",scope:"user",origin:"top-level",baseDir:globalBaseDir},projectMetadata={source:"auto",scope:"project",origin:"top-level",baseDir:projectBaseDir},userOverrides={extensions:globalSettings.extensions??[],skills:globalSettings.skills??[],prompts:globalSettings.prompts??[],themes:globalSettings.themes??[],hooks:globalSettings.hooks??[]},projectOverrides={extensions:projectSettings.extensions??[],skills:projectSettings.skills??[],prompts:projectSettings.prompts??[],themes:projectSettings.themes??[],hooks:projectSettings.hooks??[]},userDirs={extensions:join3(globalBaseDir,"extensions"),skills:join3(globalBaseDir,"skills"),prompts:join3(globalBaseDir,"prompts"),themes:join3(globalBaseDir,"themes"),hooks:join3(globalBaseDir,"hooks")},projectDirs={extensions:join3(projectBaseDir,"extensions"),skills:join3(projectBaseDir,"skills"),prompts:join3(projectBaseDir,"prompts"),themes:join3(projectBaseDir,"themes"),hooks:join3(projectBaseDir,"hooks")},legacyProjectBaseDir=join3(this.cwd,".pi"),legacyProjectDirs={extensions:join3(legacyProjectBaseDir,"extensions"),skills:join3(legacyProjectBaseDir,"skills"),prompts:join3(legacyProjectBaseDir,"prompts"),themes:join3(legacyProjectBaseDir,"themes"),hooks:join3(legacyProjectBaseDir,"hooks")},userAgentsSkillsDir=join3(getHomeDir(),".agents","skills"),projectTrusted=this.settingsManager.isProjectTrusted(),projectAgentsSkillDirs2=projectTrusted?collectAncestorAgentsSkillDirs(this.cwd):[],addResources=(resourceType,paths,metadata,overrides,baseDir)=>{let target=this.getTargetMap(accumulator,resourceType);for(let path2 of paths){let enabled=isEnabledByOverrides(path2,overrides,baseDir);this.addResource(target,path2,metadata,enabled)}},addSkills=(root,mode,metadata,overrides,base)=>{let selected=this.selectSkillRoot(root,metadata,"project-auto");addResources("skills",collectAutoSkillEntries(root,mode,{provenance:selected.skillProvenance}),selected,overrides,base)};projectTrusted&&(addResources("extensions",collectAutoExtensionEntries(projectDirs.extensions),projectMetadata,projectOverrides.extensions,projectBaseDir),addSkills(projectDirs.skills,"pi",projectMetadata,projectOverrides.skills,projectBaseDir));for(let agentsSkillsDir of projectAgentsSkillDirs2){let agentsBaseDir=dirname2(agentsSkillsDir),agentsMetadata={...projectMetadata,baseDir:agentsBaseDir};addSkills(agentsSkillsDir,"agents",agentsMetadata,projectOverrides.skills,agentsBaseDir)}if(projectTrusted&&(addResources("prompts",collectAutoPromptEntries(projectDirs.prompts),projectMetadata,projectOverrides.prompts,projectBaseDir),addResources("themes",collectAutoThemeEntries(projectDirs.themes),projectMetadata,projectOverrides.themes,projectBaseDir),addResources("hooks",collectFiles(projectDirs.hooks,FILE_PATTERNS.hooks),projectMetadata,projectOverrides.hooks,projectBaseDir)),projectTrusted&&resolve3(legacyProjectBaseDir)!==resolve3(projectBaseDir)){let legacyProjectMetadata={...projectMetadata,baseDir:legacyProjectBaseDir};addResources("extensions",collectAutoExtensionEntries(legacyProjectDirs.extensions),legacyProjectMetadata,projectOverrides.extensions,legacyProjectBaseDir),addSkills(legacyProjectDirs.skills,"pi",legacyProjectMetadata,projectOverrides.skills,legacyProjectBaseDir),addResources("prompts",collectAutoPromptEntries(legacyProjectDirs.prompts),legacyProjectMetadata,projectOverrides.prompts,legacyProjectBaseDir),addResources("themes",collectAutoThemeEntries(legacyProjectDirs.themes),legacyProjectMetadata,projectOverrides.themes,legacyProjectBaseDir),addResources("hooks",collectFiles(legacyProjectDirs.hooks,FILE_PATTERNS.hooks),legacyProjectMetadata,projectOverrides.hooks,legacyProjectBaseDir)}addResources("extensions",collectAutoExtensionEntries(userDirs.extensions),userMetadata,userOverrides.extensions,globalBaseDir),addSkills(userDirs.skills,"pi",userMetadata,userOverrides.skills,globalBaseDir);let userAgentsBaseDir=dirname2(userAgentsSkillsDir),userAgentsMetadata={...userMetadata,baseDir:userAgentsBaseDir};addSkills(userAgentsSkillsDir,"agents",userAgentsMetadata,userOverrides.skills,userAgentsBaseDir),addResources("prompts",collectAutoPromptEntries(userDirs.prompts),userMetadata,userOverrides.prompts,globalBaseDir),addResources("themes",collectAutoThemeEntries(userDirs.themes),userMetadata,userOverrides.themes,globalBaseDir),addResources("hooks",collectFiles(userDirs.hooks,FILE_PATTERNS.hooks),userMetadata,userOverrides.hooks,globalBaseDir)}selectSkillRoot(root,metadata,kind){let repositoryRoot=skillProjectRoot(this.cwd),spelled=resolve3(root),owner=dirname2(dirname2(spelled)),ancestorSkillsDir=basename(spelled)==="skills"&&[".agents",".senpi",".pi"].includes(basename(dirname2(spelled)))&&insideSkillRoot(resolve3(this.cwd),owner),projectRoot=kind==="project-auto"&&ancestorSkillsDir&&!insideSkillRoot(spelled,repositoryRoot)?owner:repositoryRoot;return{...metadata,skillProvenance:{kind:metadata.scope==="project"?kind:"user",selectedRoot:root,projectRoot}}}collectFilesFromPaths(paths,resourceType,provenance){let files=[];for(let p of paths)if(existsSync3(p))try{let stats=statSync3(p);stats.isFile()?files.push(p):stats.isDirectory()&&files.push(...collectResourceFiles(p,resourceType,provenance))}catch{}return files}getTargetMap(accumulator,resourceType){switch(resourceType){case"extensions":return accumulator.extensions;case"skills":return accumulator.skills;case"prompts":return accumulator.prompts;case"themes":return accumulator.themes;case"hooks":return accumulator.hooks;default:throw new Error(`Unknown resource type: ${resourceType}`)}}addResource(map,path2,metadata,enabled){path2&&(map.has(path2)||map.set(path2,{metadata,enabled}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map,hooks:new Map}}toResolvedPaths(accumulator){let mapToResolved=entries=>{let resolved=Array.from(entries.entries()).map(([path2,{metadata,enabled}])=>({path:path2,enabled,metadata}));resolved.sort((a,b)=>resourcePrecedenceRank(a.metadata)-resourcePrecedenceRank(b.metadata));let seen=new Set;return resolved.filter(entry=>{let canonicalPath=canonicalizePath(entry.path);return seen.has(canonicalPath)?!1:(seen.add(canonicalPath),!0)})};return{skillRoots:[...accumulator.skills.values()].filter(entry=>entry.enabled).flatMap(entry=>entry.metadata.skillProvenance===void 0?[]:[entry.metadata.skillProvenance]),extensions:mapToResolved(accumulator.extensions),skills:mapToResolved(accumulator.skills),prompts:mapToResolved(accumulator.prompts),themes:mapToResolved(accumulator.themes),hooks:mapToResolved(accumulator.hooks)}}spawnCommand(command,args,options){let env=getEnv();return spawnProcess(command,args,{cwd:options?.cwd,stdio:isStdoutTakenOver()?["ignore",2,2]:"inherit",env,windowsHide:!0})}spawnCaptureCommand(command,args,options){let baseEnv=getEnv(),env=options?.env?{...baseEnv,...options.env}:baseEnv;return spawnProcess(command,args,{cwd:options?.cwd,stdio:["ignore","pipe","pipe"],env,windowsHide:!0})}runCommandCapture(command,args,options){return new Promise((resolvePromise,reject)=>{let child=this.spawnCaptureCommand(command,args,options),stdout="",stderr="",timedOut=!1,timeout=typeof options?.timeoutMs=="number"?setTimeout(()=>{timedOut=!0,signalSpawnedChild(child)},options.timeoutMs):void 0;child.stdout?.on("data",data=>{stdout+=data.toString()}),child.stderr?.on("data",data=>{stderr+=data.toString()}),child.once("error",error=>{timeout&&clearTimeout(timeout),reject(error)}),child.once("close",(code,signal)=>{if(timeout&&clearTimeout(timeout),timedOut){reject(new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`));return}if(code===0){resolvePromise(stdout.trim());return}let exitStatus=code===null?`signal ${signal??"unknown"}`:`code ${code}`;reject(new Error(`${command} ${args.join(" ")} failed with ${exitStatus}: ${stderr||stdout}`))})})}runCommand(command,args,options){return new Promise((resolvePromise,reject)=>{let child=this.spawnCommand(command,args,options);child.on("error",reject),child.on("exit",code=>{code===0?resolvePromise():reject(new Error(`${command} ${args.join(" ")} failed with code ${code}`))})})}runCommandSync(command,args){let env=getEnv(),result=spawnProcessSync(command,args,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env,windowsHide:!0});if(result.error||result.status!==0)throw new Error(`Failed to run ${command} ${args.join(" ")}: ${result.error?.message||result.stderr||result.stdout}`);return(result.stdout||result.stderr||"").trim()}};var MANUAL_CONTINUE_CUSTOM_TYPE="manual-continue";function isManualContinueSubmission(input){return input.text.trim()==="."&&input.hasMessages&&!input.hasImages}var MANUAL_CONTINUE_DIRECTIVE=`<system-notice>
|
|
137
137
|
Continue.
|
|
@@ -1,2 +1,2 @@
|
|
|
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{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv}from"./chunk-
|
|
2
|
+
import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv}from"./chunk-7WAJCESX.js";import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import*as nodeModule from"node:module";async function enableStartupCompileCache(){let enable=nodeModule.enableCompileCache;if(typeof enable!="function")return;let args=process.argv.slice(2);if(!isPackageCommandArgv(args)&&args[0]!==CONFIG_COMMAND_ARGV&&(args.includes("--version")||args.includes("-v")))return;let scheduleWatch=!1;if(args[0]===SCHEDULE_COMMAND_ARGV&&args[1]==="run")for(let index=2;index<args.length;index++){let arg=args[index];arg==="--watch"?scheduleWatch=!0:["--exec","--poll-seconds","--timeout-seconds","--concurrency"].includes(arg??"")&&index++}if(!(isPackageCommandArgv(args)||args[0]===HOST_COMMAND_ARGV||args[0]===SCHEDULE_COMMAND_ARGV&&!scheduleWatch)){if(!scheduleWatch&&args.some(arg=>["--help","-h","--export","--list-models","--list-tips"].includes(arg)))try{let{parseArgs}=await import("./args-JXULI4EH.js"),parsed=parseArgs(args);if(parsed.version||parsed.export||parsed.listModels!==void 0||parsed.listTips||parsed.help&&!(parsed.mode==="rpc"&&parsed.multiSession))return}catch{}try{let result=enable();result.directory!==void 0&&process.env.NODE_COMPILE_CACHE===void 0&&(process.env.NODE_COMPILE_CACHE=result.directory)}catch{}}}export{enableStartupCompileCache};
|