@draht/coding-agent 2026.11.14-1 → 2026.11.18-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 +6 -0
- package/dist/bundle/chunks/{anthropic-messages-C5ZJVCKX.js → anthropic-messages-AFT3AY2S.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-TNRID5YC.js → azure-openai-responses-A52AJ5P5.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-XWZLYE4L.js → chunk-2XOICIOV.js} +1 -1
- package/dist/bundle/chunks/{chunk-MPJIXESS.js → chunk-5PDANNKW.js} +1 -1
- package/dist/bundle/chunks/{chunk-SXHVGWCU.js → chunk-6EVZEBYO.js} +1 -1
- package/dist/bundle/chunks/{chunk-OUXJRC2W.js → chunk-ACQFXG5D.js} +1 -1
- package/dist/bundle/chunks/{chunk-5WEOWREV.js → chunk-CAOOVEOM.js} +1 -1
- package/dist/bundle/chunks/{chunk-JHKMYVPC.js → chunk-CP35SXCN.js} +7 -8
- package/dist/bundle/chunks/{chunk-5C4MAPF6.js → chunk-CXCOVS2M.js} +1 -1
- package/dist/bundle/chunks/{chunk-O2XYFH2E.js → chunk-HTSLUWLE.js} +3 -3
- package/dist/bundle/chunks/{chunk-RVXTPNXQ.js → chunk-JMYX7QEX.js} +1 -1
- package/dist/bundle/chunks/{chunk-B6S2UR4T.js → chunk-LKMWSNTE.js} +1 -1
- package/dist/bundle/chunks/{chunk-2IQVBLH6.js → chunk-O2P5SYXT.js} +3 -2
- package/dist/bundle/chunks/{chunk-LCTFXH4P.js → chunk-TUIWJI22.js} +1 -1
- package/dist/bundle/chunks/{chunk-YSE3VKKB.js → chunk-YFDWS2SA.js} +1 -1
- package/dist/bundle/chunks/{cli-2QKCAPPD.js → cli-L6U4GJHK.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-UCG6T3XP.js → cloudflare-workers-ai-system-one-KYAP5L2X.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-GPBKPOXA.js → google-generative-ai-WR6OZ27M.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-USZY53NF.js → google-vertex-FUYYVM54.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-7DEQ4ZUF.js → llama-cpp-classify-6LLMLBUC.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-UOGXPDZ3.js → mistral-conversations-WVGS4PN2.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-VUDXQ3EU.js → openai-codex-responses-CTLT3QUI.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-UQOOS7NM.js → openai-completions-V37FD5ZZ.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-24WNXO2R.js → openai-decisions-WTY6DQT4.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-5AF6MZ5L.js → openai-responses-R7W5BVUV.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-OUXVVTYQ.js → openrouter-images-7GGRYAYP.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-DRMOEO6B.js → pi-messages-O7OXMCNL.js} +1 -1
- package/dist/bundle/chunks/{runtime-L23MZBKL.js → runtime-73OLLYOI.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-K63EBJDD.js → typesafe-system-one-FGISCLX2.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-JZV35VDE.js → virtual-modules-JL2BFG57.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +4 -7
- package/dist/extensions/mcp/index.js.map +1 -1
- package/package.json +9 -9
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{Box,CODEMODE_TOOL_NAME,CURSOR_MARKER,CancellableLoader,CodeHighlighter,CombinedAutocompleteProvider,Container,Editor,FS_WATCH_RETRY_DELAY_MS,Image,Input,Key,KeybindingsManager,Loader,Markdown,Marked,MouseRegion,ProcessTerminal,SYSTEM_THEME_NAME,ScrollView,SelectList,SettingsList,Spacer,THEME_TOKENS,TOOL_SEARCH_TOOL_NAME,TUI_KEYBINDINGS,Text,Theme,TruncatedText,TuiAltScreen,TuiMainScreen,VStack,VisualLinePreview,addUsageToTotals,closeWatcher,combineUsage,combinedKeyHint,createCodemodeToolDefinition,createOutputFileStream,createToolDefinitionFromAgentTool,createToolSearchToolDefinition,createUsageTotals,detectCapabilities,foregroundAnsi,formatKeyText,formatReadLineRange,formatToolCallWithArgs,fuzzyFilter,fuzzyMatch,getAvailableThemes,getAvailableThemesWithPaths,getCapabilities,getEditorTheme,getKeybindings,getLanguageFromPath,getMarkdownTheme,getNativeClipboard,getResolvedThemeColors,getSelectListTheme,getSelectPageIndex,getSettingsListTheme,getTerminalColorMode,getTerminalTheme,getTextOutput,getThemeByName,getThemeExportColors,getUsageCostBreakdown,highlightCode,hyperlink,initTheme,invalidArgText,isKeyRelease,isKeyRepeat,isValidUsage,isViewportTUI,keyDisplayText,keyHint,keyText,loadAllHighlightLanguages,loadThemeFromPath,markTerminalColorsPending,matchesKey,mixColors,normalizeDisplayText,onThemeChange,parseAutoThemeSetting,parseColor,rawKeyHint,renderToolPath,replaceControlCharacters,replaceTabs,resolveThemeSetting,setCapabilityOverrides,setImageTranscoder,setKeybindings,setRegisteredThemes,setTerminalColorScheme,setTerminalColors,setTheme,setThemeInstance,setThemeJsonValidator,shortenPath,sliceByColumn,splitIncompleteAnsiSuffix,startToolTimer,stopThemeWatcher,str,stripAnsi,theme,toolTimerText,truncateToVisualLines,truncateToWidth,visibleWidth,watchWithErrorHandler,wrapTextWithAnsi,wrapToolDefinition,writeOutputFile}from"./chunk-GAABJAG4.js";import{CACHE_WARMING_MAX_AGE_MS,CACHE_WARMING_MAX_IDLE_AGE_MS,CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS,Compile,CredentialSynchronizationError,DEFAULT_RADIUS_GATEWAY,InMemoryCodingAgentModelsStore,ModelRuntime,ProjectTrustStore,VIRTUAL_MODEL_STATE_ENTRY,addMcpServerConfig,comparablePath,completeSimple,evaluateCacheWarming,fauxAssistantMessage,fauxProvider,fauxText,fauxToolCall,fetchWithRetry,findLatestResponse,getApiProvider,getBranchSelection,getCacheWarmingDelayMs,getCacheWarmingRequestOptions,getDrahtUserAgent,getModel,getModels,getProjectTrustOptions,getPromptCacheTtlMs,getProviders,getVirtualModelState,hasTrustRequiringProjectResources,isCacheWarmingReplayable,isContextOverflow,isRecoverableLength,isVirtualModel,loadMcpConfig,normalizeRadiusGatewayUrl,openBrowser,questionTerminal,realHomeDir,realPathStrict,resetApiProviders,stream,streamSimple,typesafeSystemOneApi,updateMcpServerConfig,validateToolArguments}from"./chunk-O2XYFH2E.js";import{source_default,typebox_exports}from"./chunk-ITKDPD4D.js";import{AuthStorage,LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,McpServerRegistry,READ_MCP_RESOURCE_TOOL,ReadOnlyAuthStorage,createMcpToolName,createToolNameMatcher,getMcpToolExposure,isMcpToolName,limitMcpContent,mcpNamespace,normalizeMcpInputSchema,raceWithAbortSignal,toLlmContent,validateMcpServerConfig}from"./chunk-2IQVBLH6.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,getShellEnv,killProcessTree,killTrackedDetachedChildren,sanitizeBinaryOutput,sliceHead,trackDetachedChildPid,truncateHead,truncateLine,truncateTail,untrackDetachedChildPid}from"./chunk-4FPBO5KP.js";import{uuidv7}from"./chunk-Y3NLUJYO.js";import{CACHE_WARMING_MODES,DEFAULT_TOOL_NAMES,HTTP_IDLE_TIMEOUT_CHOICES,SettingsManager,applyHttpProxySettings,applyToolModifiers,configureHttpDispatcher,formatHttpIdleTimeoutMs,getToolListError,isToolModifier}from"./chunk-RI7HJ6AF.js";import{SETTINGS_DEFAULTS}from"./chunk-MXA4WY3C.js";import{isRetryableAssistantError,retryAssistantCall,retryDelayMs}from"./chunk-2CHTECAU.js";import{require_proper_lockfile}from"./chunk-2JZLKNZ4.js";import{APP_NAME,APP_TITLE,CONFIG_DIR_NAME,DISPLAY_VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,PACKAGE_NAME,VERSION,detectInstallChange,detectInstallMethod,expandTildePath,formatPathRelativeToCwdOrAbsolute,getAgentDir,getAuthPath,getBinDir,getBundledInteractiveAssetPath,getChangelogPath,getConfiguredSelfUpdateArgv,getCwdRelativePath,getDebugLogPath,getDocsPath,getExamplesPath,getExportTemplateDir,getPackageDir,getPathComparisonKey,getReadmePath,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getSessionsDir,getSettingsPath,getShareViewerUrl,getShippedPromptsDir,getShippedSkillsDir,isBunBinary,isLocalPath,isPathWithin,makeConfiguredSelfUpdateCommand,markPathIgnoredByCloudSync,normalizePath,pathsEqual,resolvePath,shortenHomePath,spawnProcess,spawnProcessSync,splitBom,stripBom,waitForChildProcess}from"./chunk-6M3D4XVD.js";import{cleanupSessionResources}from"./chunk-Y7QE2R34.js";import{ToolCallArgumentsStream}from"./chunk-KFREX3FS.js";import{ModelsError,clampThinkingLevel,createInitialSystemMessage,getCurrentSystemMessage,getCurrentSystemPrompt,getCurrentTools,getSupportedThinkingLevels,getToolStateChanges,isModelType,modelsAreEqual,normalizeContext,supportsMax,supportsXhigh,toToolDeclaration}from"./chunk-YSE3VKKB.js";import{EventStream,createAssistantMessageEventStream}from"./chunk-USCN7R2E.js";import{DRAHT_ATTRIBUTION,contentText,getSystemMessageText,mergeClientIdentity}from"./chunk-XWZLYE4L.js";import{__commonJS,__export,__require,__toESM}from"./chunk-HZ2UHMBT.js";var require_ignore=__commonJS({"node_modules/.bun/ignore@7.0.11/node_modules/ignore/index.js"(exports,module){function makeArray(subject){return Array.isArray(subject)?subject:[subject]}var UNDEFINED=void 0,EMPTY="",SPACE=" ",ESCAPE="\\",REGEX_LITERAL_SPECIAL=/[.*+?()[\]{}^$|\\/]/,REGEX_TEST_BLANK_LINE=/^\uFEFF? *$/,REGEX_INVALID_TRAILING_BACKSLASH=/(?:[^\\]|^)\\$/,REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION=/^\\!/,REGEX_REPLACE_LEADING_EXCAPED_HASH=/^\\#/,REGEX_SPLITALL_CRLF=/\r?\n/g,DOUBLE_SLASH="//",SLASH_CODE=47,DOT_CODE=46,SLASH="/",TMP_KEY_IGNORE="node-ignore";typeof Symbol<"u"&&(TMP_KEY_IGNORE=Symbol.for("node-ignore"));var KEY_IGNORE=TMP_KEY_IGNORE,define=(object,key,value)=>(Object.defineProperty(object,key,{value}),value),RETURN_FALSE=()=>!1,cleanRangeBackSlash=slashes=>{let{length}=slashes;return slashes.slice(0,length-length%2)},POSIX_CLASSES={alnum:"0-9A-Za-z",alpha:"A-Za-z",blank:" \\t",cntrl:"\\x00-\\x1f\\x7f",digit:"0-9",graph:"!-.0-~",lower:"a-z",print:" -.0-~",punct:"!-.:-@\\[-`{-~",space:" \\t\\n\\r",upper:"A-Z",xdigit:"0-9A-Fa-f"},CLASS_MEMBERS_TO_ESCAPE="\\]^-[",escapeMember=char=>CLASS_MEMBERS_TO_ESCAPE.indexOf(char)<0?char:ESCAPE+char,NON_SLASH="(?!\\/)",classSource=(negated,body)=>{if(negated)return`[^\\/${body}]`;let source=`[${body}]`;return new RegExp(source).test("/")?NON_SLASH+source:source},scanBracket=(pattern,start)=>{let{length}=pattern,index=start+1,negated=EMPTY,lead=pattern[index];(lead==="!"||lead==="^")&&(negated="^",index++);let body=EMPTY,prev=EMPTY;for(;;){let char=pattern[index];if(char===UNDEFINED)return null;if(char===ESCAPE){let escaped=pattern[index+1];if(escaped===UNDEFINED)return null;body+=escapeMember(escaped),prev=escaped,index++}else if(char==="-"&&prev&&index+1<length&&pattern[index+1]!=="]"){index++;let to=pattern[index];to===ESCAPE&&(to=pattern[index+=1]),prev<=to&&(body+=`-${escapeMember(to)}`),prev=EMPTY}else if(char==="["&&pattern[index+1]===":"){let nameStart=index+2,end=nameStart;for(;end<length&&pattern[end]!=="]";)end++;if(end===length)return null;if(end>nameStart&&pattern[end-1]===":"){let expanded=POSIX_CLASSES[pattern.slice(nameStart,end-1)];if(expanded===UNDEFINED)return null;body+=expanded,prev=EMPTY,index=end}else body+=escapeMember("["),prev="[",index=nameStart-2}else body+=escapeMember(char),prev=char;if(index++,pattern[index]==="]")return{end:index,source:classSource(negated,body)}}},NEVER_MATCH="[]",PLACEHOLDER="\0",REGEX_RESTORE_PLACEHOLDER=new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,"g"),TRAILING_WILDCARD="\uE000",TRAILING_DOUBLESTAR="\uE001",extractBrackets=pattern=>{let sources=[],hold=source=>`${PLACEHOLDER}${sources.push(source)-1}${PLACEHOLDER}`,{length}=pattern,out=EMPTY,index=0;for(;index<length;){let char=pattern[index];if(char===ESCAPE){let escaped=pattern[index+1];escaped==="*"||escaped==="["||escaped===SPACE||escaped===ESCAPE?out+=pattern.slice(index,index+2):out+=hold(REGEX_LITERAL_SPECIAL.test(escaped)?ESCAPE+escaped:escaped),index+=2}else if(char===PLACEHOLDER)out+=hold(`[${PLACEHOLDER}]`),index++;else if(char==="["){let scanned=scanBracket(pattern,index);scanned===null?(out+=hold(NEVER_MATCH),index=length):(out+=hold(scanned.source),index=scanned.end+1)}else out+=char,index++}return{source:out,sources}},DIRECT=null,REGEX_INNER_SLASH=/\/(?!$)/,REPLACERS=[[/^\uFEFF/,()=>EMPTY,"\uFEFF"],[/[\r\n]+$/,()=>EMPTY],[/((?:\\\\)*?)(\\? +)$/,(_,m1,m2)=>m1+(m2.indexOf("\\")===0?SPACE:EMPTY)],[/(\\+?) /g,(_,m1)=>{let{length}=m1;return m1.slice(0,length-length%2)+SPACE}],[/[\\$.|*+(){^]/g,match2=>`\\${match2}`],[/(?!\\)\?/g,()=>"[^/]","?"],[/^\//,()=>"^",SLASH],[/\//g,()=>"\\/",SLASH],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?","*"],[DIRECT,(source,pattern)=>!source||source[0]==="^"?source:(REGEX_INNER_SLASH.test(pattern)?"^":"(?:^|\\/)")+source],[/\\\/\\\*\\\*(?=\\\/|$)/g,(_,index,str2)=>index+6<str2.length?str2.slice(index+6)==="\\/"?"(?:\\/[^\\/]+)+":"(?:\\/[^\\/]+)*":`\\/${TRAILING_DOUBLESTAR}`,"*"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(_,p1,p2)=>{let unescaped=p2.replace(/\\\*/g,"[^\\/]*");return p1+unescaped},"*"],[/(^|[^\\])((?:\\\\)*)\\\*$/,(match2,p1,p2)=>p2.length/2%2===0?p1+p2+TRAILING_WILDCARD:match2,"*"],[/\\\\\\(?=[$.|*+(){^])/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\\/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\[([^\]/]*?)(\\*)($|\])/g,(match2,range2,endEscape,close)=>`\\[${range2}${cleanRangeBackSlash(endEscape)}${close}`,"["],[DIRECT,source=>{let last=source[source.length-1];return!last||last===TRAILING_WILDCARD||last===TRAILING_DOUBLESTAR?source:last===SLASH?`${source}$`:`${source}(?=$|\\/$)`}]],REGEX_REPLACE_TRAILING_WILDCARD=/(^|\\\/)?\uE000$/,MODE_IGNORE="regex",MODE_CHECK_IGNORE="checkRegex",UNDERSCORE="_",replaceTrailingWildcard=(_,p1)=>`${p1?`${p1}[^/]+`:"[^/]*"}(?=$|\\/$)`,REGEX_REPLACE_TRAILING_DOUBLESTAR=/\uE001$/,replaceTrailingDoublestar=()=>".+(?=$|\\/$)",WILDCARD="[^\\/]*",separatorAfter=(run,at)=>{let separator=EMPTY;for(let index=at+1;index<run.length&&!run[index].wildcard;index++)separator+=run[index].single;return separator},pinWildcards=source=>{if(source.indexOf(WILDCARD)<0)return source;let tokens=[],{length}=source,index=0;for(;index<length;){let char=source[index];if(source.startsWith(WILDCARD,index))tokens.push({wildcard:!0}),index+=WILDCARD.length;else if(char==="["){let end=index+1;for(source[end]==="^"&&end++,source[end]==="]"&&end++;end<length&&source[end]!=="]";)end+=source[end]===ESCAPE?2:1;end++,tokens.push({single:source.slice(index,end)}),index=end}else if(char===ESCAPE)tokens.push({single:source.slice(index,index+2)}),index+=2;else if(char==="("){let depth=0,end=index;do source[end]===ESCAPE?end++:source[end]==="("?depth++:source[end]===")"&&depth--,end++;while(end<length&&depth>0);"*+?".indexOf(source[end])>=0&&end++,tokens.push({boundary:source.slice(index,end)}),index=end}else char==="^"||char==="$"?(tokens.push({boundary:char}),index++):(tokens.push({single:char}),index++)}let out=EMPTY,run=[],flush=()=>{let lastWildcard;run.forEach((token,at)=>{token.wildcard&&(lastWildcard=at)}),run.forEach((token,at)=>{if(!token.wildcard){out+=token.single;return}out+=at===lastWildcard?WILDCARD:`(?:(?!${separatorAfter(run,at)})[^\\/])*`}),run=[]};return tokens.forEach(token=>{if(token.boundary===void 0){run.push(token);return}flush(),out+=token.boundary}),flush(),out},makeRegexPrefix=pattern=>{let{source,sources}=extractBrackets(pattern),replaced=REPLACERS.reduce((prev,[matcher,replacer,required])=>matcher===DIRECT?replacer(prev,pattern):required!==UNDEFINED&&prev.indexOf(required)<0?prev:matcher.test(prev)?prev.replace(matcher,replacer.bind(pattern)):prev,source);return sources.length?replaced.replace(REGEX_RESTORE_PLACEHOLDER,(match2,index)=>sources[index]):replaced},checkSourceOf=(body,prefix)=>{body[body.length-1]===SLASH&&(prefix=makeRegexPrefix(body.slice(0,-1)));let head=prefix.slice(0,-1),last=prefix[prefix.length-1];return last===TRAILING_WILDCARD?`${head}$`:last===TRAILING_DOUBLESTAR?`${head}.*$`:NEVER_MATCH},matchesBasename=body=>{let index=body.indexOf(SLASH);return index<0||index===body.length-1},basenameOf=path20=>{let end=path20.length-1,index=path20.lastIndexOf(SLASH,path20[end]===SLASH?end-1:end);return index<0?path20:path20.slice(index+1)},parentOf=path20=>{if(path20.charCodeAt(0)===SLASH_CODE||path20.indexOf(DOUBLE_SLASH)>=0){let slices=path20.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY}let end=path20.length-1,cut=path20.lastIndexOf(SLASH,path20.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY:path20.slice(0,cut+1)},isString=subject=>typeof subject=="string",checkPattern=pattern=>pattern&&isString(pattern)&&!REGEX_TEST_BLANK_LINE.test(pattern)&&!REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)&&pattern.indexOf("#")!==0,splitPattern=pattern=>pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean),IgnoreRule=class{constructor(pattern,mark,body,ignoreCase,negative,prefix){this.pattern=pattern,this.mark=mark,this.negative=negative,define(this,"body",body),define(this,"ignoreCase",ignoreCase),define(this,"regexPrefix",prefix)}get _basenameOnly(){return define(this,"_basenameOnly",matchesBasename(this.body))}get regex(){let key=UNDERSCORE+MODE_IGNORE;return this[key]?this[key]:this._make(MODE_IGNORE,key)}get checkRegex(){let key=UNDERSCORE+MODE_CHECK_IGNORE;return this[key]?this[key]:this._make(MODE_CHECK_IGNORE,key)}_make(mode,key){let str2=pinWildcards(mode===MODE_IGNORE?this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR,replaceTrailingDoublestar):checkSourceOf(this.body,this.regexPrefix)),regex=this.ignoreCase?new RegExp(str2,"i"):new RegExp(str2);return define(this,key,regex)}},createRule=({pattern,mark},ignoreCase)=>{let negative=!1,body=pattern;body.indexOf("!")===0&&(negative=!0,body=body.substr(1)),body=body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION,"!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH,"#");let regexPrefix=makeRegexPrefix(body);return new IgnoreRule(pattern,mark,body,ignoreCase,negative,regexPrefix)},RuleManager=class{constructor(ignoreCase){this._ignoreCase=ignoreCase,this._rules=[],this._basenameCount=0}_add(pattern){if(pattern&&pattern[KEY_IGNORE]){this._rules=this._rules.concat(pattern._rules._rules),this._basenameCount+=pattern._rules._basenameCount,this._added=!0;return}if(isString(pattern)&&(pattern={pattern}),checkPattern(pattern.pattern)){let rule=createRule(pattern,this._ignoreCase);this._added=!0,this._rules.push(rule),matchesBasename(rule.body)&&this._basenameCount++}}add(pattern){return this._added=!1,makeArray(isString(pattern)?splitPattern(pattern):pattern).forEach(this._add,this),this._added&&(this._literalRules=UNDEFINED),this._added}testLiteral(path20){let rules=this._literalRules||(this._literalRules=this._rules.filter(({body})=>body[body.length-(body[body.length-1]===SLASH?2:1)]==="*")),ignored=!1,unignored=!1,matchedRule;for(let index=rules.length-1;index>=0;index--){let rule=rules[index];if(rule.checkRegex.test(path20)){ignored=!rule.negative,unignored=rule.negative,matchedRule=rule.negative?UNDEFINED:rule;break}}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}test(path20,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename14=shortcut?basenameOf(path20):path20;for(let index=0;index<length;index++){let rule=rules[index],{negative}=rule;!(unignored===negative&&ignored!==unignored||negative&&!ignored&&!unignored&&!checkUnignored)&&rule[mode].test(shortcut&&rule._basenameOnly?basename14:path20)&&(ignored=!negative,unignored=negative,matchedRule=negative?UNDEFINED:rule)}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}},throwError=(message,Ctor)=>{throw new Ctor(message)},checkPath=(path20,originalPath,doThrow)=>isString(path20)?path20?checkPath.isNotRelative(path20)?doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`,RangeError):!0:doThrow("path must not be empty",TypeError):doThrow(`path must be a string, but got \`${originalPath}\``,TypeError),isNotRelative=path20=>{let first=path20.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path20.length===1)return!0;let second=path20.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path20.length===2||path20.charCodeAt(2)===SLASH_CODE};checkPath.isNotRelative=isNotRelative;checkPath.convert=p=>p;var Ignore=class{constructor({ignorecase=!0,ignoreCase=ignorecase,allowRelativePaths=!1}={}){define(this,KEY_IGNORE,!0),this._rules=new RuleManager(ignoreCase),this._strictPathCheck=!allowRelativePaths,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(pattern){return this._rules.add(pattern)&&this._initCache(),this}addPattern(pattern){return this.add(pattern)}_test(originalPath,cache2,checkUnignored){let path20=originalPath&&checkPath.convert(originalPath);return checkPath(path20,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path20,cache2,checkUnignored)}checkIgnore(path20){if(path20.charCodeAt(path20.length-1)!==SLASH_CODE)return this.test(path20);let dir=this._t(path20,this._testCache,!0);if(dir.ignored)return dir;let literal2=this._rules.testLiteral(path20);return literal2.ignored||literal2.unignored?literal2:dir}_t(path20,cache2,checkUnignored){if(path20 in cache2)return cache2[path20];let parentPath=parentOf(path20),parent=parentPath?this._t(parentPath,cache2,checkUnignored):UNDEFINED;return cache2[path20]=parent&&parent.ignored?parent:this._rules.test(path20,checkUnignored,MODE_IGNORE)}ignores(path20){return this._test(path20,this._ignoreCache,!1).ignored}createFilter(){return path20=>!this.ignores(path20)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path20){return this._test(path20,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path20=>checkPath(path20&&checkPath.convert(path20),path20,RETURN_FALSE),setupWindows=()=>{let makePosix=str2=>/^\\\\\?\\/.test(str2)||/["<>|\u0000-\u001F]+/u.test(str2)?str2:str2.replace(/\\/g,"/");checkPath.convert=makePosix;let REGEX_TEST_WINDOWS_PATH_ABSOLUTE=/^[a-z]:\//i;checkPath.isNotRelative=path20=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path20)||isNotRelative(path20)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});var require_constants=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/constants.js"(exports,module){"use strict";var SEMVER_SPEC_VERSION="2.0.0",MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH=16,MAX_SAFE_BUILD_LENGTH=250,RELEASE_TYPES=["major","premajor","minor","preminor","patch","prepatch","prerelease"];module.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH,MAX_SAFE_INTEGER,RELEASE_TYPES,SEMVER_SPEC_VERSION,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}});var require_debug=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/debug.js"(exports,module){"use strict";var debug=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...args)=>console.error("SEMVER",...args):()=>{};module.exports=debug}});var require_re=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/re.js"(exports,module){"use strict";var{MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH,MAX_LENGTH}=require_constants(),debug=require_debug();exports=module.exports={};var re=exports.re=[],safeRe=exports.safeRe=[],src=exports.src=[],safeSrc=exports.safeSrc=[],t=exports.t={},R2=0,LETTERDASHNUMBER="[a-zA-Z0-9-]",safeRegexReplacements=[["\\s",1],["\\d",MAX_LENGTH],[LETTERDASHNUMBER,MAX_SAFE_BUILD_LENGTH]],makeSafeRegex=value=>{for(let[token,max]of safeRegexReplacements)value=value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);return value},createToken=(name,value,isGlobal)=>{let safe=makeSafeRegex(value),index=R2++;debug(name,index,value),t[name]=index,src[index]=value,safeSrc[index]=safe,re[index]=new RegExp(value,isGlobal?"g":void 0),safeRe[index]=new RegExp(safe,isGlobal?"g":void 0)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);createToken("MAINVERSION",`(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASE",`(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${LETTERDASHNUMBER}+`);createToken("BUILD",`(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);createToken("FULL",`^${src[t.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);createToken("LOOSE",`^${src[t.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);createToken("XRANGE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`(^|[^\\d])(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);createToken("COERCE",`${src[t.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",src[t.COERCEPLAIN]+`(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);createToken("COERCERTL",src[t.COERCE],!0);createToken("COERCERTLFULL",src[t.COERCEFULL],!0);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${src[t.LONETILDE]}\\s+`,!0);exports.tildeTrimReplace="$1~";createToken("TILDE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${src[t.LONECARET]}\\s+`,!0);exports.caretTrimReplace="$1^";createToken("CARET",`^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`,!0);exports.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}});var require_parse_options=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/parse-options.js"(exports,module){"use strict";var looseOption=Object.freeze({loose:!0}),emptyOpts=Object.freeze({}),parseOptions=options=>options?typeof options!="object"?looseOption:options:emptyOpts;module.exports=parseOptions}});var require_identifiers=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/identifiers.js"(exports,module){"use strict";var numeric2=/^[0-9]+$/,compareIdentifiers=(a,b)=>{if(typeof a=="number"&&typeof b=="number")return a===b?0:a<b?-1:1;let anum=numeric2.test(a),bnum=numeric2.test(b);return anum&&bnum&&(a=+a,b=+b),a===b?0:anum&&!bnum?-1:bnum&&!anum?1:a<b?-1:1},rcompareIdentifiers=(a,b)=>compareIdentifiers(b,a);module.exports={compareIdentifiers,rcompareIdentifiers}}});var require_semver=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/classes/semver.js"(exports,module){"use strict";var debug=require_debug(),{MAX_LENGTH,MAX_SAFE_INTEGER}=require_constants(),{safeRe:re,t}=require_re(),parseOptions=require_parse_options(),{compareIdentifiers}=require_identifiers(),isPrereleaseIdentifier=(prerelease,identifier)=>{let identifiers=identifier.split(".");if(identifiers.length>prerelease.length)return!1;for(let i=0;i<identifiers.length;i++)if(compareIdentifiers(prerelease[i],identifiers[i])!==0)return!1;return!0},SemVer=class _SemVer{constructor(version2,options){if(options=parseOptions(options),version2 instanceof _SemVer){if(version2.loose===!!options.loose&&version2.includePrerelease===!!options.includePrerelease)return version2;version2=version2.version}else if(typeof version2!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`);if(version2.length>MAX_LENGTH)throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);debug("SemVer",version2,options),this.options=options,this.loose=!!options.loose,this.includePrerelease=!!options.includePrerelease;let m=version2.trim().match(options.loose?re[t.LOOSE]:re[t.FULL]);if(!m)throw new TypeError(`Invalid Version: ${version2}`);if(this.raw=version2,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>MAX_SAFE_INTEGER||this.major<0)throw new TypeError("Invalid major version");if(this.minor>MAX_SAFE_INTEGER||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>MAX_SAFE_INTEGER||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(id=>{if(/^[0-9]+$/.test(id)){let num=+id;if(num>=0&&num<MAX_SAFE_INTEGER)return num}return id}):this.prerelease=[],this.build=m[5]?m[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(other){if(debug("SemVer.compare",this.version,this.options,other),!(other instanceof _SemVer)){if(typeof other=="string"&&other===this.version)return 0;other=new _SemVer(other,this.options)}return other.version===this.version?0:this.compareMain(other)||this.comparePre(other)}compareMain(other){return other instanceof _SemVer||(other=new _SemVer(other,this.options)),this.major<other.major?-1:this.major>other.major?1:this.minor<other.minor?-1:this.minor>other.minor?1:this.patch<other.patch?-1:this.patch>other.patch?1:0}comparePre(other){if(other instanceof _SemVer||(other=new _SemVer(other,this.options)),this.prerelease.length&&!other.prerelease.length)return-1;if(!this.prerelease.length&&other.prerelease.length)return 1;if(!this.prerelease.length&&!other.prerelease.length)return 0;let i=0;do{let a=this.prerelease[i],b=other.prerelease[i];if(debug("prerelease compare",i,a,b),a===void 0&&b===void 0)return 0;if(b===void 0)return 1;if(a===void 0)return-1;if(a===b)continue;return compareIdentifiers(a,b)}while(++i)}compareBuild(other){other instanceof _SemVer||(other=new _SemVer(other,this.options));let i=0;do{let a=this.build[i],b=other.build[i];if(debug("build compare",i,a,b),a===void 0&&b===void 0)return 0;if(b===void 0)return 1;if(a===void 0)return-1;if(a===b)continue;return compareIdentifiers(a,b)}while(++i)}inc(release2,identifier,identifierBase){if(release2.startsWith("pre")){if(!identifier&&identifierBase===!1)throw new Error("invalid increment argument: identifier is empty");if(identifier){let match2=`-${identifier}`.match(this.options.loose?re[t.PRERELEASELOOSE]:re[t.PRERELEASE]);if(!match2||match2[1]!==identifier)throw new Error(`invalid identifier: ${identifier}`)}}switch(release2){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",identifier,identifierBase);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",identifier,identifierBase);break;case"prepatch":this.prerelease.length=0,this.inc("patch",identifier,identifierBase),this.inc("pre",identifier,identifierBase);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",identifier,identifierBase),this.inc("pre",identifier,identifierBase);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let base=Number(identifierBase)?1:0;if(this.prerelease.length===0)this.prerelease=[base];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(identifier===this.prerelease.join(".")&&identifierBase===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(base)}}if(identifier){let prerelease=[identifier,base];if(identifierBase===!1&&(prerelease=[identifier]),isPrereleaseIdentifier(this.prerelease,identifier)){let prereleaseBase=this.prerelease[identifier.split(".").length];isNaN(prereleaseBase)&&(this.prerelease=prerelease)}else this.prerelease=prerelease}break}default:throw new Error(`invalid increment argument: ${release2}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};module.exports=SemVer}});var require_parse=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/parse.js"(exports,module){"use strict";var SemVer=require_semver(),parse4=(version2,options,throwErrors=!1)=>{if(version2 instanceof SemVer)return version2;try{return new SemVer(version2,options)}catch(er2){if(!throwErrors)return null;throw er2}};module.exports=parse4}});var require_valid=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/valid.js"(exports,module){"use strict";var parse4=require_parse(),valid3=(version2,options)=>{let v=parse4(version2,options);return v?v.version:null};module.exports=valid3}});var require_clean=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/clean.js"(exports,module){"use strict";var parse4=require_parse(),clean2=(version2,options)=>{let s=parse4(version2.trim().replace(/^[=v]+/,""),options);return s?s.version:null};module.exports=clean2}});var require_inc=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/inc.js"(exports,module){"use strict";var SemVer=require_semver(),inc=(version2,release2,options,identifier,identifierBase)=>{typeof options=="string"&&(identifierBase=identifier,identifier=options,options=void 0);try{return new SemVer(version2 instanceof SemVer?version2.version:version2,options).inc(release2,identifier,identifierBase).version}catch{return null}};module.exports=inc}});var require_diff=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/diff.js"(exports,module){"use strict";var parse4=require_parse(),diff=(version1,version2)=>{let v1=parse4(version1,null,!0),v2=parse4(version2,null,!0),comparison=v1.compare(v2);if(comparison===0)return null;let v1Higher=comparison>0,highVersion=v1Higher?v1:v2,lowVersion=v1Higher?v2:v1,highHasPre=!!highVersion.prerelease.length;if(!!lowVersion.prerelease.length&&!highHasPre){if(!lowVersion.patch&&!lowVersion.minor)return"major";if(lowVersion.compareMain(highVersion)===0)return lowVersion.minor&&!lowVersion.patch?"minor":"patch"}let prefix=highHasPre?"pre":"";return v1.major!==v2.major?prefix+"major":v1.minor!==v2.minor?prefix+"minor":v1.patch!==v2.patch?prefix+"patch":"prerelease"};module.exports=diff}});var require_major=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/major.js"(exports,module){"use strict";var SemVer=require_semver(),major=(a,loose)=>new SemVer(a,loose).major;module.exports=major}});var require_minor=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/minor.js"(exports,module){"use strict";var SemVer=require_semver(),minor=(a,loose)=>new SemVer(a,loose).minor;module.exports=minor}});var require_patch=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/patch.js"(exports,module){"use strict";var SemVer=require_semver(),patch=(a,loose)=>new SemVer(a,loose).patch;module.exports=patch}});var require_prerelease=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/prerelease.js"(exports,module){"use strict";var parse4=require_parse(),prerelease=(version2,options)=>{let parsed=parse4(version2,options);return parsed&&parsed.prerelease.length?parsed.prerelease:null};module.exports=prerelease}});var require_compare=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/compare.js"(exports,module){"use strict";var SemVer=require_semver(),compare2=(a,b,loose)=>new SemVer(a,loose).compare(new SemVer(b,loose));module.exports=compare2}});var require_rcompare=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/rcompare.js"(exports,module){"use strict";var compare2=require_compare(),rcompare2=(a,b,loose)=>compare2(b,a,loose);module.exports=rcompare2}});var require_compare_loose=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/compare-loose.js"(exports,module){"use strict";var compare2=require_compare(),compareLoose=(a,b)=>compare2(a,b,!0);module.exports=compareLoose}});var require_compare_build=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/compare-build.js"(exports,module){"use strict";var SemVer=require_semver(),compareBuild=(a,b,loose)=>{let versionA=new SemVer(a,loose),versionB=new SemVer(b,loose);return versionA.compare(versionB)||versionA.compareBuild(versionB)};module.exports=compareBuild}});var require_sort=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/sort.js"(exports,module){"use strict";var compareBuild=require_compare_build(),sort=(list,loose)=>list.sort((a,b)=>compareBuild(a,b,loose));module.exports=sort}});var require_rsort=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/rsort.js"(exports,module){"use strict";var compareBuild=require_compare_build(),rsort=(list,loose)=>list.sort((a,b)=>compareBuild(b,a,loose));module.exports=rsort}});var require_gt=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/gt.js"(exports,module){"use strict";var compare2=require_compare(),gt2=(a,b,loose)=>compare2(a,b,loose)>0;module.exports=gt2}});var require_lt=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/lt.js"(exports,module){"use strict";var compare2=require_compare(),lt=(a,b,loose)=>compare2(a,b,loose)<0;module.exports=lt}});var require_eq=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/eq.js"(exports,module){"use strict";var compare2=require_compare(),eq=(a,b,loose)=>compare2(a,b,loose)===0;module.exports=eq}});var require_neq=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/neq.js"(exports,module){"use strict";var compare2=require_compare(),neq=(a,b,loose)=>compare2(a,b,loose)!==0;module.exports=neq}});var require_gte=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/gte.js"(exports,module){"use strict";var compare2=require_compare(),gte2=(a,b,loose)=>compare2(a,b,loose)>=0;module.exports=gte2}});var require_lte=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/lte.js"(exports,module){"use strict";var compare2=require_compare(),lte2=(a,b,loose)=>compare2(a,b,loose)<=0;module.exports=lte2}});var require_cmp=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/cmp.js"(exports,module){"use strict";var eq=require_eq(),neq=require_neq(),gt2=require_gt(),gte2=require_gte(),lt=require_lt(),lte2=require_lte(),cmp=(a,op,b,loose)=>{switch(op){case"===":return typeof a=="object"&&(a=a.version),typeof b=="object"&&(b=b.version),a===b;case"!==":return typeof a=="object"&&(a=a.version),typeof b=="object"&&(b=b.version),a!==b;case"":case"=":case"==":return eq(a,b,loose);case"!=":return neq(a,b,loose);case">":return gt2(a,b,loose);case">=":return gte2(a,b,loose);case"<":return lt(a,b,loose);case"<=":return lte2(a,b,loose);default:throw new TypeError(`Invalid operator: ${op}`)}};module.exports=cmp}});var require_coerce=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/coerce.js"(exports,module){"use strict";var SemVer=require_semver(),parse4=require_parse(),{safeRe:re,t}=require_re(),coerce=(version2,options)=>{if(version2 instanceof SemVer)return version2;if(typeof version2=="number"&&(version2=String(version2)),typeof version2!="string")return null;options=options||{};let match2=null;if(!options.rtl)match2=version2.match(options.includePrerelease?re[t.COERCEFULL]:re[t.COERCE]);else{let coerceRtlRegex=options.includePrerelease?re[t.COERCERTLFULL]:re[t.COERCERTL],next;for(;(next=coerceRtlRegex.exec(version2))&&(!match2||match2.index+match2[0].length!==version2.length);)(!match2||next.index+next[0].length!==match2.index+match2[0].length)&&(match2=next),coerceRtlRegex.lastIndex=next.index+next[1].length+next[2].length;coerceRtlRegex.lastIndex=-1}if(match2===null)return null;let major=match2[2],minor=match2[3]||"0",patch=match2[4]||"0",prerelease=options.includePrerelease&&match2[5]?`-${match2[5]}`:"",build2=options.includePrerelease&&match2[6]?`+${match2[6]}`:"";return parse4(`${major}.${minor}.${patch}${prerelease}${build2}`,options)};module.exports=coerce}});var require_truncate=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/truncate.js"(exports,module){"use strict";var parse4=require_parse(),constants9=require_constants(),SemVer=require_semver(),truncate3=(version2,truncation,options)=>{if(!constants9.RELEASE_TYPES.includes(truncation))return null;let clonedVersion=cloneInputVersion(version2,options);return clonedVersion&&doTruncation(clonedVersion,truncation)},cloneInputVersion=(version2,options)=>{let versionStringToParse=version2 instanceof SemVer?version2.version:version2;return parse4(versionStringToParse,options)},doTruncation=(version2,truncation)=>{if(isPrerelease(truncation))return version2.version;switch(version2.prerelease=[],truncation){case"major":version2.minor=0,version2.patch=0;break;case"minor":version2.patch=0;break}return version2.format()},isPrerelease=type=>type.startsWith("pre");module.exports=truncate3}});var require_lrucache=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/lrucache.js"(exports,module){"use strict";var LRUCache=class{constructor(){this.max=1e3,this.map=new Map}get(key){let value=this.map.get(key);if(value!==void 0)return this.map.delete(key),this.map.set(key,value),value}delete(key){return this.map.delete(key)}set(key,value){if(!this.delete(key)&&value!==void 0){if(this.map.size>=this.max){let firstKey=this.map.keys().next().value;this.delete(firstKey)}this.map.set(key,value)}return this}};module.exports=LRUCache}});var require_range=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/classes/range.js"(exports,module){"use strict";var SPACE_CHARACTERS=/\s+/g,Range=class _Range{constructor(range2,options){if(options=parseOptions(options),range2 instanceof _Range)return range2.loose===!!options.loose&&range2.includePrerelease===!!options.includePrerelease?range2:new _Range(range2.raw,options);if(range2 instanceof Comparator)return this.raw=range2.value,this.set=[[range2]],this.formatted=void 0,this;if(this.options=options,this.loose=!!options.loose,this.includePrerelease=!!options.includePrerelease,this.raw=range2.trim().replace(SPACE_CHARACTERS," "),this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(c=>c.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let first=this.set[0];if(this.set=this.set.filter(c=>!isNullSet(c[0])),this.set.length===0)this.set=[first];else if(this.set.length>1){for(let c of this.set)if(c.length===1&&isAny(c[0])){this.set=[c];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let i=0;i<this.set.length;i++){i>0&&(this.formatted+="||");let comps=this.set[i];for(let k=0;k<comps.length;k++)k>0&&(this.formatted+=" "),this.formatted+=comps[k].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(range2){range2=range2.replace(BUILDSTRIPRE,"");let memoKey=((this.options.includePrerelease&&FLAG_INCLUDE_PRERELEASE)|(this.options.loose&&FLAG_LOOSE))+":"+range2,cached=cache2.get(memoKey);if(cached)return cached;let loose=this.options.loose,hr=loose?re[t.HYPHENRANGELOOSE]:re[t.HYPHENRANGE];range2=range2.replace(hr,hyphenReplace(this.options.includePrerelease)),debug("hyphen replace",range2),range2=range2.replace(re[t.COMPARATORTRIM],comparatorTrimReplace),debug("comparator trim",range2),range2=range2.replace(re[t.TILDETRIM],tildeTrimReplace),debug("tilde trim",range2),range2=range2.replace(re[t.CARETTRIM],caretTrimReplace),debug("caret trim",range2);let rangeList=range2.split(" ").map(comp=>parseComparator(comp,this.options)).join(" ").split(/\s+/).map(comp=>replaceGTE0(comp,this.options));loose&&(rangeList=rangeList.filter(comp=>(debug("loose invalid filter",comp,this.options),!!comp.match(re[t.COMPARATORLOOSE])))),debug("range list",rangeList);let rangeMap=new Map,comparators=rangeList.map(comp=>new Comparator(comp,this.options));for(let comp of comparators){if(isNullSet(comp))return[comp];rangeMap.set(comp.value,comp)}rangeMap.size>1&&rangeMap.has("")&&rangeMap.delete("");let result=[...rangeMap.values()];return cache2.set(memoKey,result),result}intersects(range2,options){if(!(range2 instanceof _Range))throw new TypeError("a Range is required");return this.set.some(thisComparators=>isSatisfiable(thisComparators,options)&&range2.set.some(rangeComparators=>isSatisfiable(rangeComparators,options)&&thisComparators.every(thisComparator=>rangeComparators.every(rangeComparator=>thisComparator.intersects(rangeComparator,options)))))}test(version2){if(!version2)return!1;if(typeof version2=="string")try{version2=new SemVer(version2,this.options)}catch{return!1}for(let i=0;i<this.set.length;i++)if(testSet(this.set[i],version2,this.options))return!0;return!1}};module.exports=Range;var LRU=require_lrucache(),cache2=new LRU,parseOptions=require_parse_options(),Comparator=require_comparator(),debug=require_debug(),SemVer=require_semver(),{safeRe:re,src,t,comparatorTrimReplace,tildeTrimReplace,caretTrimReplace}=require_re(),{FLAG_INCLUDE_PRERELEASE,FLAG_LOOSE}=require_constants(),BUILDSTRIPRE=new RegExp(src[t.BUILD],"g"),isNullSet=c=>c.value==="<0.0.0-0",isAny=c=>c.value==="",isSatisfiable=(comparators,options)=>{let result=!0,remainingComparators=comparators.slice(),testComparator=remainingComparators.pop();for(;result&&remainingComparators.length;)result=remainingComparators.every(otherComparator=>testComparator.intersects(otherComparator,options)),testComparator=remainingComparators.pop();return result},parseComparator=(comp,options)=>(comp=comp.replace(re[t.BUILD],""),debug("comp",comp,options),comp=replaceCarets(comp,options),debug("caret",comp),comp=replaceTildes(comp,options),debug("tildes",comp),comp=replaceXRanges(comp,options),debug("xrange",comp),comp=replaceStars(comp,options),debug("stars",comp),comp),isX=id=>!id||id.toLowerCase()==="x"||id==="*",invalidXRangeOrder=(M,m,p)=>isX(M)&&!isX(m)||isX(m)&&p&&!isX(p),replaceTildes=(comp,options)=>comp.trim().split(/\s+/).map(c=>replaceTilde(c,options)).join(" "),replaceTilde=(comp,options)=>{let r=options.loose?re[t.TILDELOOSE]:re[t.TILDE],z=options.includePrerelease?"-0":"";return comp.replace(r,(_,M,m,p,pr)=>{debug("tilde",comp,_,M,m,p,pr);let ret;return isX(M)?ret="":isX(m)?ret=`>=${M}.0.0${z} <${+M+1}.0.0-0`:isX(p)?ret=`>=${M}.${m}.0${z} <${M}.${+m+1}.0-0`:pr?(debug("replaceTilde pr",pr),ret=`>=${M}.${m}.${p}-${pr} <${M}.${+m+1}.0-0`):ret=`>=${M}.${m}.${p} <${M}.${+m+1}.0-0`,debug("tilde return",ret),ret})},replaceCarets=(comp,options)=>comp.trim().split(/\s+/).map(c=>replaceCaret(c,options)).join(" "),replaceCaret=(comp,options)=>{debug("caret",comp,options);let r=options.loose?re[t.CARETLOOSE]:re[t.CARET],z=options.includePrerelease?"-0":"";return comp.replace(r,(_,M,m,p,pr)=>{debug("caret",comp,_,M,m,p,pr);let ret;return isX(M)?ret="":isX(m)?ret=`>=${M}.0.0${z} <${+M+1}.0.0-0`:isX(p)?M==="0"?ret=`>=${M}.${m}.0${z} <${M}.${+m+1}.0-0`:ret=`>=${M}.${m}.0${z} <${+M+1}.0.0-0`:pr?(debug("replaceCaret pr",pr),M==="0"?m==="0"?ret=`>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p+1}-0`:ret=`>=${M}.${m}.${p}-${pr} <${M}.${+m+1}.0-0`:ret=`>=${M}.${m}.${p}-${pr} <${+M+1}.0.0-0`):(debug("no pr"),M==="0"?m==="0"?ret=`>=${M}.${m}.${p} <${M}.${m}.${+p+1}-0`:ret=`>=${M}.${m}.${p} <${M}.${+m+1}.0-0`:ret=`>=${M}.${m}.${p} <${+M+1}.0.0-0`),debug("caret return",ret),ret})},replaceXRanges=(comp,options)=>(debug("replaceXRanges",comp,options),comp.split(/\s+/).map(c=>replaceXRange(c,options)).join(" ")),replaceXRange=(comp,options)=>{comp=comp.trim();let r=options.loose?re[t.XRANGELOOSE]:re[t.XRANGE];return comp.replace(r,(ret,gtlt,M,m,p,pr)=>{if(debug("xRange",comp,ret,gtlt,M,m,p,pr),invalidXRangeOrder(M,m,p))return comp;let xM=isX(M),xm=xM||isX(m),xp=xm||isX(p),anyX=xp;return gtlt==="="&&anyX&&(gtlt=""),pr=options.includePrerelease?"-0":"",xM?gtlt===">"||gtlt==="<"?ret="<0.0.0-0":ret="*":gtlt&&anyX?(xm&&(m=0),p=0,gtlt===">"?(gtlt=">=",xm?(M=+M+1,m=0,p=0):(m=+m+1,p=0)):gtlt==="<="&&(gtlt="<",xm?M=+M+1:m=+m+1),gtlt==="<"&&(pr="-0"),ret=`${gtlt+M}.${m}.${p}${pr}`):xm?ret=`>=${M}.0.0${pr} <${+M+1}.0.0-0`:xp&&(ret=`>=${M}.${m}.0${pr} <${M}.${+m+1}.0-0`),debug("xRange return",ret),ret})},replaceStars=(comp,options)=>(debug("replaceStars",comp,options),comp.trim().replace(re[t.STAR],"")),replaceGTE0=(comp,options)=>(debug("replaceGTE0",comp,options),comp.trim().replace(re[options.includePrerelease?t.GTE0PRE:t.GTE0],"")),hyphenReplace=incPr=>($0,from,fM,fm,fp,fpr,fb,to,tM,tm,tp,tpr)=>(isX(fM)?from="":isX(fm)?from=`>=${fM}.0.0${incPr?"-0":""}`:isX(fp)?from=`>=${fM}.${fm}.0${incPr?"-0":""}`:fpr?from=`>=${from}`:from=`>=${from}${incPr?"-0":""}`,isX(tM)?to="":isX(tm)?to=`<${+tM+1}.0.0-0`:isX(tp)?to=`<${tM}.${+tm+1}.0-0`:tpr?to=`<=${tM}.${tm}.${tp}-${tpr}`:incPr?to=`<${tM}.${tm}.${+tp+1}-0`:to=`<=${to}`,`${from} ${to}`.trim()),testSet=(set,version2,options)=>{for(let i=0;i<set.length;i++)if(!set[i].test(version2))return!1;if(version2.prerelease.length&&!options.includePrerelease){for(let i=0;i<set.length;i++)if(debug(set[i].semver),set[i].semver!==Comparator.ANY&&set[i].semver.prerelease.length>0){let allowed=set[i].semver;if(allowed.major===version2.major&&allowed.minor===version2.minor&&allowed.patch===version2.patch)return!0}return!1}return!0}}});var require_comparator=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/classes/comparator.js"(exports,module){"use strict";var ANY=Symbol("SemVer ANY"),Comparator=class _Comparator{static get ANY(){return ANY}constructor(comp,options){if(options=parseOptions(options),comp instanceof _Comparator){if(comp.loose===!!options.loose)return comp;comp=comp.value}comp=comp.trim().split(/\s+/).join(" "),debug("comparator",comp,options),this.options=options,this.loose=!!options.loose,this.parse(comp),this.semver===ANY?this.value="":this.value=this.operator+this.semver.version,debug("comp",this)}parse(comp){let r=this.options.loose?re[t.COMPARATORLOOSE]:re[t.COMPARATOR],m=comp.match(r);if(!m)throw new TypeError(`Invalid comparator: ${comp}`);this.operator=m[1]!==void 0?m[1]:"",this.operator==="="&&(this.operator=""),m[2]?this.semver=new SemVer(m[2],this.options.loose):this.semver=ANY}toString(){return this.value}test(version2){if(debug("Comparator.test",version2,this.options.loose),this.semver===ANY||version2===ANY)return!0;if(typeof version2=="string")try{version2=new SemVer(version2,this.options)}catch{return!1}return cmp(version2,this.operator,this.semver,this.options)}intersects(comp,options){if(!(comp instanceof _Comparator))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Range(comp.value,options).test(this.value):comp.operator===""?comp.value===""?!0:new Range(this.value,options).test(comp.semver):(options=parseOptions(options),options.includePrerelease&&(this.value==="<0.0.0-0"||comp.value==="<0.0.0-0")||!options.includePrerelease&&(this.value.startsWith("<0.0.0")||comp.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&comp.operator.startsWith(">")||this.operator.startsWith("<")&&comp.operator.startsWith("<")||this.semver.version===comp.semver.version&&this.operator.includes("=")&&comp.operator.includes("=")||cmp(this.semver,"<",comp.semver,options)&&this.operator.startsWith(">")&&comp.operator.startsWith("<")||cmp(this.semver,">",comp.semver,options)&&this.operator.startsWith("<")&&comp.operator.startsWith(">")))}};module.exports=Comparator;var parseOptions=require_parse_options(),{safeRe:re,t}=require_re(),cmp=require_cmp(),debug=require_debug(),SemVer=require_semver(),Range=require_range()}});var require_satisfies=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/satisfies.js"(exports,module){"use strict";var Range=require_range(),satisfies2=(version2,range2,options)=>{try{range2=new Range(range2,options)}catch{return!1}return range2.test(version2)};module.exports=satisfies2}});var require_to_comparators=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/to-comparators.js"(exports,module){"use strict";var Range=require_range(),toComparators=(range2,options)=>new Range(range2,options).set.map(comp=>comp.map(c=>c.value).join(" ").trim().split(" "));module.exports=toComparators}});var require_max_satisfying=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js"(exports,module){"use strict";var SemVer=require_semver(),Range=require_range(),maxSatisfying2=(versions,range2,options)=>{let max=null,maxSV=null,rangeObj=null;try{rangeObj=new Range(range2,options)}catch{return null}return versions.forEach(v=>{rangeObj.test(v)&&(!max||maxSV.compare(v)===-1)&&(max=v,maxSV=new SemVer(max,options))}),max};module.exports=maxSatisfying2}});var require_min_satisfying=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js"(exports,module){"use strict";var SemVer=require_semver(),Range=require_range(),minSatisfying=(versions,range2,options)=>{let min=null,minSV=null,rangeObj=null;try{rangeObj=new Range(range2,options)}catch{return null}return versions.forEach(v=>{rangeObj.test(v)&&(!min||minSV.compare(v)===1)&&(min=v,minSV=new SemVer(min,options))}),min};module.exports=minSatisfying}});var require_min_version=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/min-version.js"(exports,module){"use strict";var SemVer=require_semver(),Range=require_range(),gt2=require_gt(),minVersion=(range2,loose)=>{range2=new Range(range2,loose);let minver=new SemVer("0.0.0");if(range2.test(minver)||(minver=new SemVer("0.0.0-0"),range2.test(minver)))return minver;minver=null;for(let i=0;i<range2.set.length;++i){let comparators=range2.set[i],setMin=null;comparators.forEach(comparator=>{let compver=new SemVer(comparator.semver.version);switch(comparator.operator){case">":compver.prerelease.length===0?compver.patch++:compver.prerelease.push(0),compver.raw=compver.format();case"":case">=":(!setMin||gt2(compver,setMin))&&(setMin=compver);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${comparator.operator}`)}}),setMin&&(!minver||gt2(minver,setMin))&&(minver=setMin)}return minver&&range2.test(minver)?minver:null};module.exports=minVersion}});var require_valid2=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/valid.js"(exports,module){"use strict";var Range=require_range(),validRange2=(range2,options)=>{try{return new Range(range2,options).range||"*"}catch{return null}};module.exports=validRange2}});var require_outside=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/outside.js"(exports,module){"use strict";var SemVer=require_semver(),Comparator=require_comparator(),{ANY}=Comparator,Range=require_range(),satisfies2=require_satisfies(),gt2=require_gt(),lt=require_lt(),lte2=require_lte(),gte2=require_gte(),outside=(version2,range2,hilo,options)=>{version2=new SemVer(version2,options),range2=new Range(range2,options);let gtfn,ltefn,ltfn,comp,ecomp;switch(hilo){case">":gtfn=gt2,ltefn=lte2,ltfn=lt,comp=">",ecomp=">=";break;case"<":gtfn=lt,ltefn=gte2,ltfn=gt2,comp="<",ecomp="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(satisfies2(version2,range2,options))return!1;for(let i=0;i<range2.set.length;++i){let comparators=range2.set[i],high=null,low=null;if(comparators.forEach(comparator=>{comparator.semver===ANY&&(comparator=new Comparator(">=0.0.0")),high=high||comparator,low=low||comparator,gtfn(comparator.semver,high.semver,options)?high=comparator:ltfn(comparator.semver,low.semver,options)&&(low=comparator)}),high.operator===comp||high.operator===ecomp||(!low.operator||low.operator===comp)&<efn(version2,low.semver))return!1;if(low.operator===ecomp&<fn(version2,low.semver))return!1}return!0};module.exports=outside}});var require_gtr=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/gtr.js"(exports,module){"use strict";var outside=require_outside(),gtr=(version2,range2,options)=>outside(version2,range2,">",options);module.exports=gtr}});var require_ltr=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/ltr.js"(exports,module){"use strict";var outside=require_outside(),ltr=(version2,range2,options)=>outside(version2,range2,"<",options);module.exports=ltr}});var require_intersects=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/intersects.js"(exports,module){"use strict";var Range=require_range(),intersects=(r1,r2,options)=>(r1=new Range(r1,options),r2=new Range(r2,options),r1.intersects(r2,options));module.exports=intersects}});var require_simplify=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/simplify.js"(exports,module){"use strict";var satisfies2=require_satisfies(),compare2=require_compare();module.exports=(versions,range2,options)=>{let set=[],first=null,prev=null,v=versions.sort((a,b)=>compare2(a,b,options));for(let version2 of v)satisfies2(version2,range2,options)?(prev=version2,first||(first=version2)):(prev&&set.push([first,prev]),prev=null,first=null);first&&set.push([first,null]);let ranges=[];for(let[min,max]of set)min===max?ranges.push(min):!max&&min===v[0]?ranges.push("*"):max?min===v[0]?ranges.push(`<=${max}`):ranges.push(`${min} - ${max}`):ranges.push(`>=${min}`);let simplified=ranges.join(" || "),original=typeof range2.raw=="string"?range2.raw:String(range2);return simplified.length<original.length?simplified:range2}}});var require_subset=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/subset.js"(exports,module){"use strict";var Range=require_range(),Comparator=require_comparator(),{ANY}=Comparator,satisfies2=require_satisfies(),compare2=require_compare(),subset=(sub,dom,options={})=>{if(sub===dom)return!0;sub=new Range(sub,options),dom=new Range(dom,options);let sawNonNull=!1;OUTER:for(let simpleSub of sub.set){for(let simpleDom of dom.set){let isSub=simpleSubset(simpleSub,simpleDom,options);if(sawNonNull=sawNonNull||isSub!==null,isSub)continue OUTER}if(sawNonNull)return!1}return!0},minimumVersionWithPreRelease=[new Comparator(">=0.0.0-0")],minimumVersion=[new Comparator(">=0.0.0")],simpleSubset=(sub,dom,options)=>{if(sub===dom)return!0;if(sub.length===1&&sub[0].semver===ANY){if(dom.length===1&&dom[0].semver===ANY)return!0;options.includePrerelease?sub=minimumVersionWithPreRelease:sub=minimumVersion}if(dom.length===1&&dom[0].semver===ANY){if(options.includePrerelease)return!0;dom=minimumVersion}let eqSet=new Set,gt2,lt;for(let c of sub)c.operator===">"||c.operator===">="?gt2=higherGT(gt2,c,options):c.operator==="<"||c.operator==="<="?lt=lowerLT(lt,c,options):eqSet.add(c.semver);if(eqSet.size>1)return null;let gtltComp;if(gt2&<){if(gtltComp=compare2(gt2.semver,lt.semver,options),gtltComp>0)return null;if(gtltComp===0&&(gt2.operator!==">="||lt.operator!=="<="))return null}for(let eq of eqSet){if(gt2&&!satisfies2(eq,String(gt2),options)||lt&&!satisfies2(eq,String(lt),options))return null;for(let c of dom)if(!satisfies2(eq,String(c),options))return!1;return!0}let higher,lower,hasDomLT,hasDomGT,needDomLTPre=lt&&!options.includePrerelease&<.semver.prerelease.length?lt.semver:!1,needDomGTPre=gt2&&!options.includePrerelease&>2.semver.prerelease.length?gt2.semver:!1;needDomLTPre&&needDomLTPre.prerelease.length===1&<.operator==="<"&&needDomLTPre.prerelease[0]===0&&(needDomLTPre=!1);for(let c of dom){if(hasDomGT=hasDomGT||c.operator===">"||c.operator===">=",hasDomLT=hasDomLT||c.operator==="<"||c.operator==="<=",gt2){if(needDomGTPre&&c.semver.prerelease&&c.semver.prerelease.length&&c.semver.major===needDomGTPre.major&&c.semver.minor===needDomGTPre.minor&&c.semver.patch===needDomGTPre.patch&&(needDomGTPre=!1),c.operator===">"||c.operator===">="){if(higher=higherGT(gt2,c,options),higher===c&&higher!==gt2)return!1}else if(gt2.operator===">="&&!c.test(gt2.semver))return!1}if(lt){if(needDomLTPre&&c.semver.prerelease&&c.semver.prerelease.length&&c.semver.major===needDomLTPre.major&&c.semver.minor===needDomLTPre.minor&&c.semver.patch===needDomLTPre.patch&&(needDomLTPre=!1),c.operator==="<"||c.operator==="<="){if(lower=lowerLT(lt,c,options),lower===c&&lower!==lt)return!1}else if(lt.operator==="<="&&!c.test(lt.semver))return!1}if(!c.operator&&(lt||gt2)&>ltComp!==0)return!1}return!(gt2&&hasDomLT&&!lt&>ltComp!==0||lt&&hasDomGT&&!gt2&>ltComp!==0||needDomGTPre||needDomLTPre)},higherGT=(a,b,options)=>{if(!a)return b;let comp=compare2(a.semver,b.semver,options);return comp>0?a:comp<0||b.operator===">"&&a.operator===">="?b:a},lowerLT=(a,b,options)=>{if(!a)return b;let comp=compare2(a.semver,b.semver,options);return comp<0?a:comp>0||b.operator==="<"&&a.operator==="<="?b:a};module.exports=subset}});var require_semver2=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/index.js"(exports,module){"use strict";var internalRe=require_re(),constants9=require_constants(),SemVer=require_semver(),identifiers=require_identifiers(),parse4=require_parse(),valid3=require_valid(),clean2=require_clean(),inc=require_inc(),diff=require_diff(),major=require_major(),minor=require_minor(),patch=require_patch(),prerelease=require_prerelease(),compare2=require_compare(),rcompare2=require_rcompare(),compareLoose=require_compare_loose(),compareBuild=require_compare_build(),sort=require_sort(),rsort=require_rsort(),gt2=require_gt(),lt=require_lt(),eq=require_eq(),neq=require_neq(),gte2=require_gte(),lte2=require_lte(),cmp=require_cmp(),coerce=require_coerce(),truncate3=require_truncate(),Comparator=require_comparator(),Range=require_range(),satisfies2=require_satisfies(),toComparators=require_to_comparators(),maxSatisfying2=require_max_satisfying(),minSatisfying=require_min_satisfying(),minVersion=require_min_version(),validRange2=require_valid2(),outside=require_outside(),gtr=require_gtr(),ltr=require_ltr(),intersects=require_intersects(),simplifyRange=require_simplify(),subset=require_subset();module.exports={parse:parse4,valid:valid3,clean:clean2,inc,diff,major,minor,patch,prerelease,compare:compare2,rcompare:rcompare2,compareLoose,compareBuild,sort,rsort,gt:gt2,lt,eq,neq,gte:gte2,lte:lte2,cmp,coerce,truncate:truncate3,Comparator,Range,satisfies:satisfies2,toComparators,maxSatisfying:maxSatisfying2,minSatisfying,minVersion,validRange:validRange2,outside,gtr,ltr,intersects,simplifyRange,subset,SemVer,re:internalRe.re,src:internalRe.src,tokens:internalRe.t,SEMVER_SPEC_VERSION:constants9.SEMVER_SPEC_VERSION,RELEASE_TYPES:constants9.RELEASE_TYPES,compareIdentifiers:identifiers.compareIdentifiers,rcompareIdentifiers:identifiers.rcompareIdentifiers}}});var require_index_min=__commonJS({"node_modules/.bun/lru-cache@11.2.6/node_modules/lru-cache/dist/commonjs/index.min.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var x=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,U2=new Set,R2=typeof process=="object"&&process?process:{},I=(a,t,e,i)=>{typeof R2.emitWarning=="function"?R2.emitWarning(a,t,e,i):console.error(`[${e}] ${t}: ${a}`)},C=globalThis.AbortController,L2=globalThis.AbortSignal;if(typeof C>"u"){L2=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,s){this._onabort.push(s)}},C=class{constructor(){t()}signal=new L2;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i)}}};let a=R2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{a&&(a=!1,I("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var G=a=>!U2.has(a),y=a=>a&&a===Math.floor(a)&&a>0&&isFinite(a),M=a=>y(a)?a<=Math.pow(2,8)?Uint8Array:a<=Math.pow(2,16)?Uint16Array:a<=Math.pow(2,32)?Uint32Array:a<=Number.MAX_SAFE_INTEGER?z:null:null,z=class extends Array{constructor(t){super(t),this.fill(0)}},W=class a{heap;length;static#o=!1;static create(t){let e=M(t);if(!e)return[];a.#o=!0;let i=new a(t,e);return a.#o=!1,i}constructor(t,e){if(!a.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},D2=class a{#o;#c;#w;#C;#S;#L;#U;#m;get perf(){return this.#m}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#_;#s;#i;#t;#a;#u;#l;#h;#b;#r;#y;#A;#d;#g;#T;#v;#f;#I;static unsafeExposeInternals(t){return{starts:t.#A,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#a,prev:t.#u,get head(){return t.#l},get tail(){return t.#h},free:t.#b,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,h)=>t.#G(e,i,s,h),moveToTail:e=>t.#D(e),indexes:e=>t.#F(e),rindexes:e=>t.#O(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#_}get size(){return this.#n}get fetchMethod(){return this.#L}get memoMethod(){return this.#U}get dispose(){return this.#w}get onInsert(){return this.#C}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:h,updateAgeOnGet:n,updateAgeOnHas:o,allowStale:r,dispose:f,onInsert:m,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:g,maxSize:A=0,maxEntrySize:p=0,sizeCalculation:_,fetchMethod:l,memoMethod:w,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:T,ignoreFetchAbort:F,perf:v}=t;if(v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#m=v??x,e!==0&&!y(e))throw new TypeError("max option must be a nonnegative integer");let O=e?M(e):Array;if(!O)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=A,this.maxEntrySize=p||this.#c,this.sizeCalculation=_,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#U=w,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#L=l,this.#v=!!l,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#a=new O(e),this.#u=new O(e),this.#l=0,this.#h=0,this.#b=W.create(e),this.#n=0,this.#_=0,typeof f=="function"&&(this.#w=f),typeof m=="function"&&(this.#C=m),typeof c=="function"?(this.#S=c,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#w,this.#I=!!this.#C,this.#f=!!this.#S,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!u,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(this.#c!==0&&!y(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!y(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!n,this.updateAgeOnHas=!!o,this.ttlResolution=y(s)||s===0?s:1,this.ttlAutopurge=!!h,this.ttl=i||0,this.ttl){if(!y(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let E="LRU_CACHE_UNBOUNDED";G(E)&&(U2.add(E),I("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",E,a))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#j(){let t=new z(this.#o),e=new z(this.#o);this.#d=t,this.#A=e;let i=this.ttlAutopurge?new Array(this.#o):void 0;this.#g=i,this.#N=(n,o,r=this.#m.now())=>{if(e[n]=o!==0?r:0,t[n]=o,i?.[n]&&(clearTimeout(i[n]),i[n]=void 0),o!==0&&i){let f=setTimeout(()=>{this.#p(n)&&this.#E(this.#i[n],"expire")},o+1);f.unref&&f.unref(),i[n]=f}},this.#R=n=>{e[n]=t[n]!==0?this.#m.now():0},this.#z=(n,o)=>{if(t[o]){let r=t[o],f=e[o];if(!r||!f)return;n.ttl=r,n.start=f,n.now=s||h();let m=n.now-f;n.remainingTTL=r-m}};let s=0,h=()=>{let n=this.#m.now();if(this.ttlResolution>0){s=n;let o=setTimeout(()=>s=0,this.ttlResolution);o.unref&&o.unref()}return n};this.getRemainingTTL=n=>{let o=this.#s.get(n);if(o===void 0)return 0;let r=t[o],f=e[o];if(!r||!f)return 1/0;let m=(s||h())-f;return r-m},this.#p=n=>{let o=e[n],r=t[n];return!!r&&!!o&&(s||h())-o>r}}#R=()=>{};#z=()=>{};#N=()=>{};#p=()=>!1;#B(){let t=new z(this.#o);this.#_=0,this.#y=t,this.#W=e=>{this.#_-=t[e],t[e]=0},this.#P=(e,i,s,h)=>{if(this.#e(i))return 0;if(!y(s))if(h){if(typeof h!="function")throw new TypeError("sizeCalculation must be a function");if(s=h(i,e),!y(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#M=(e,i,s)=>{if(t[e]=i,this.#c){let h=this.#c-t[e];for(;this.#_>h;)this.#x(!0)}this.#_+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#_)}}#W=t=>{};#M=(t,e,i)=>{};#P=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#F({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;!(!this.#H(e)||((t||!this.#p(e))&&(yield e),e===this.#l));)e=this.#u[e]}*#O({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#l;!(!this.#H(e)||((t||!this.#p(e))&&(yield e),e===this.#h));)e=this.#a[e]}#H(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#F())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#O())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#F()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#O()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#F())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#O())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#F()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;if(h!==void 0&&t(h,this.#i[i],this))return this.get(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#F()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;h!==void 0&&t.call(e,h,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#O()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;h!==void 0&&t.call(e,h,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#O({allowStale:!0}))this.#p(e)&&(this.#E(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let h={value:s};if(this.#d&&this.#A){let n=this.#d[e],o=this.#A[e];if(n&&o){let r=n-(this.#m.now()-o);h.ttl=r,h.start=Date.now()}}return this.#y&&(h.size=this.#y[e]),h}dump(){let t=[];for(let e of this.#F({allowStale:!0})){let i=this.#i[e],s=this.#t[e],h=this.#e(s)?s.__staleWhileFetching:s;if(h===void 0||i===void 0)continue;let n={value:h};if(this.#d&&this.#A){n.ttl=this.#d[e];let o=this.#m.now()-this.#A[e];n.start=Math.floor(Date.now()-o)}this.#y&&(n.size=this.#y[e]),t.unshift([i,n])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#m.now()-s}this.set(e,i.value,i)}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:h,noDisposeOnSet:n=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:r}=i,{noUpdateTTL:f=this.noUpdateTTL}=i,m=this.#P(t,e,i.size||0,o);if(this.maxEntrySize&&m>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.#E(t,"set"),this;let c=this.#n===0?void 0:this.#s.get(t);if(c===void 0)c=this.#n===0?this.#h:this.#b.length!==0?this.#b.pop():this.#n===this.#o?this.#x(!1):this.#n,this.#i[c]=t,this.#t[c]=e,this.#s.set(t,c),this.#a[this.#h]=c,this.#u[c]=this.#h,this.#h=c,this.#n++,this.#M(c,m,r),r&&(r.set="add"),f=!1,this.#I&&this.#C?.(e,t,"add");else{this.#D(c);let d=this.#t[c];if(e!==d){if(this.#v&&this.#e(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:g}=d;g!==void 0&&!n&&(this.#T&&this.#w?.(g,t,"set"),this.#f&&this.#r?.push([g,t,"set"]))}else n||(this.#T&&this.#w?.(d,t,"set"),this.#f&&this.#r?.push([d,t,"set"]));if(this.#W(c),this.#M(c,m,r),this.#t[c]=e,r){r.set="replace";let g=d&&this.#e(d)?d.__staleWhileFetching:d;g!==void 0&&(r.oldValue=g)}}else r&&(r.set="update");this.#I&&this.onInsert?.(e,t,e===d?"update":"replace")}if(s!==0&&!this.#d&&this.#j(),this.#d&&(f||this.#N(c,s,h),r&&this.#z(r,c)),!n&&this.#f&&this.#r){let d=this.#r,g;for(;g=d?.shift();)this.#S?.(...g)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#l];if(this.#x(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#x(t){let e=this.#l,i=this.#i[e],s=this.#t[e];return this.#v&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#T||this.#f)&&(this.#T&&this.#w?.(s,i,"evict"),this.#f&&this.#r?.push([s,i,"evict"])),this.#W(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#b.push(e)),this.#n===1?(this.#l=this.#h=0,this.#b.length=0):this.#l=this.#a[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,h=this.#s.get(t);if(h!==void 0){let n=this.#t[h];if(this.#e(n)&&n.__staleWhileFetching===void 0)return!1;if(this.#p(h))s&&(s.has="stale",this.#z(s,h));else return i&&this.#R(h),s&&(s.has="hit",this.#z(s,h)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,s=this.#s.get(t);if(s===void 0||!i&&this.#p(s))return;let h=this.#t[s];return this.#e(h)?h.__staleWhileFetching:h}#G(t,e,i,s){let h=e===void 0?void 0:this.#t[e];if(this.#e(h))return h;let n=new C,{signal:o}=i;o?.addEventListener("abort",()=>n.abort(o.reason),{signal:n.signal});let r={signal:n.signal,options:i,context:s},f=(p,_=!1)=>{let{aborted:l}=n.signal,w=i.ignoreFetchAbort&&p!==void 0,b=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&p!==void 0);if(i.status&&(l&&!_?(i.status.fetchAborted=!0,i.status.fetchError=n.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!w&&!_)return c(n.signal.reason,b);let S=g,u=this.#t[e];return(u===g||w&&_&&u===void 0)&&(p===void 0?S.__staleWhileFetching!==void 0?this.#t[e]=S.__staleWhileFetching:this.#E(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,p,r.options))),p},m=p=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=p),c(p,!1)),c=(p,_)=>{let{aborted:l}=n.signal,w=l&&i.allowStaleOnFetchAbort,b=w||i.allowStaleOnFetchRejection,S=b||i.noDeleteOnFetchRejection,u=g;if(this.#t[e]===g&&(!S||!_&&u.__staleWhileFetching===void 0?this.#E(t,"fetch"):w||(this.#t[e]=u.__staleWhileFetching)),b)return i.status&&u.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw p},d=(p,_)=>{let l=this.#L?.(t,h,r);l&&l instanceof Promise&&l.then(w=>p(w===void 0?void 0:w),_),n.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(p(void 0),i.allowStaleOnFetchAbort&&(p=w=>f(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let g=new Promise(d).then(f,m),A=Object.assign(g,{__abortController:n,__staleWhileFetching:h,__returned:void 0});return e===void 0?(this.set(t,A,{...r.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=A,A}#e(t){if(!this.#v)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof C}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:h=this.noDeleteOnStaleGet,ttl:n=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:r=0,sizeCalculation:f=this.sizeCalculation,noUpdateTTL:m=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:p,forceRefresh:_=!1,status:l,signal:w}=e;if(!this.#v)return l&&(l.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:h,status:l});let b={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:h,ttl:n,noDisposeOnSet:o,size:r,sizeCalculation:f,noUpdateTTL:m,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:A,ignoreFetchAbort:g,status:l,signal:w},S=this.#s.get(t);if(S===void 0){l&&(l.fetch="miss");let u=this.#G(t,S,b,p);return u.__returned=u}else{let u=this.#t[S];if(this.#e(u)){let E=i&&u.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",E&&(l.returnedStale=!0)),E?u.__staleWhileFetching:u.__returned=u}let T=this.#p(S);if(!_&&!T)return l&&(l.fetch="hit"),this.#D(S),s&&this.#R(S),l&&this.#z(l,S),u;let F=this.#G(t,S,b,p),O=F.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=T?"stale":"refresh",O&&T&&(l.returnedStale=!0)),O?F.__staleWhileFetching:F.__returned=F}}async forceFetch(t,e={}){let i=await this.fetch(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let i=this.#U;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:h,...n}=e,o=this.get(t,n);if(!h&&o!==void 0)return o;let r=i(t,o,{options:n,context:s});return this.set(t,r,n),r}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:h=this.noDeleteOnStaleGet,status:n}=e,o=this.#s.get(t);if(o!==void 0){let r=this.#t[o],f=this.#e(r);return n&&this.#z(n,o),this.#p(o)?(n&&(n.get="stale"),f?(n&&i&&r.__staleWhileFetching!==void 0&&(n.returnedStale=!0),i?r.__staleWhileFetching:void 0):(h||this.#E(t,"expire"),n&&i&&(n.returnedStale=!0),i?r:void 0)):(n&&(n.get="hit"),f?r.__staleWhileFetching:(this.#D(o),s&&this.#R(o),r))}else n&&(n.get="miss")}#k(t,e){this.#u[e]=t,this.#a[t]=e}#D(t){t!==this.#h&&(t===this.#l?this.#l=this.#a[t]:this.#k(this.#u[t],this.#a[t]),this.#k(this.#h,t),this.#h=t)}delete(t){return this.#E(t,"delete")}#E(t,e){let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#V(e);else{this.#W(s);let h=this.#t[s];if(this.#e(h)?h.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#w?.(h,t,e),this.#f&&this.#r?.push([h,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#l)this.#l=this.#a[s];else{let n=this.#u[s];this.#a[n]=this.#a[s];let o=this.#a[s];this.#u[o]=this.#u[s]}this.#n--,this.#b.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,h;for(;h=s?.shift();)this.#S?.(...h)}return i}clear(){return this.#V("delete")}#V(t){for(let e of this.#O({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#w?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#A){this.#d.fill(0),this.#A.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#l=0,this.#h=0,this.#b.length=0,this.#_=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=D2}});var require_hosts=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/hosts.js"(exports,module){"use strict";var maybeJoin=(...args)=>args.every(arg=>arg)?args.join(""):"",maybeEncode=arg=>arg?encodeURIComponent(arg):"",formatHashFragment=f=>f.toLowerCase().replace(/^\W+/g,"").replace(/(?<!\W)\W+$/,"").replace(/\//g,"").replace(/\W+/g,"-"),defaults2={sshtemplate:({domain,user,project,committish})=>`git@${domain}:${user}/${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,user,project,committish})=>`git+ssh://git@${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath,path:path20})=>`https://${domain}/${user}/${project}${maybeJoin("/",editpath,"/",maybeEncode(committish||"HEAD"),"/",path20)}`,browsetemplate:({domain,user,project,committish,treepath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}`,browsetreetemplate:({domain,user,project,committish,treepath,path:path20,fragment,hashformat})=>`https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish||"HEAD")}/${path20}${maybeJoin("#",hashformat(fragment||""))}`,browseblobtemplate:({domain,user,project,committish,blobpath,path:path20,fragment,hashformat})=>`https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish||"HEAD")}/${path20}${maybeJoin("#",hashformat(fragment||""))}`,docstemplate:({domain,user,project,treepath,committish})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}#readme`,httpstemplate:({auth,domain,user,project,committish})=>`git+https://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({domain,user,project,committish,path:path20})=>`https://${domain}/${user}/${project}/raw/${maybeEncode(committish||"HEAD")}/${path20}`,shortcuttemplate:({type,user,project,committish})=>`${type}:${user}/${project}${maybeJoin("#",committish)}`,pathtemplate:({user,project,committish})=>`${user}/${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,user,project})=>`https://${domain}/${user}/${project}/issues`,hashformat:formatHashFragment},hosts={};hosts.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth,user,project,committish,path:path20})=>`https://${maybeJoin(auth,"@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish||"HEAD")}/${path20}`,gittemplate:({auth,domain,user,project,committish})=>`git://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,type,committish]=url.pathname.split("/",5);if(!(type&&type!=="tree")&&(type||(committish=url.hash.slice(1)),project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish}}};hosts.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain,user,project,committish,treepath,path:path20,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish||"HEAD"),"/",path20,editpath)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/get/${maybeEncode(committish||"HEAD")}.tar.gz`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["get"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};hosts.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish||"HEAD")}`,extract:url=>{let path20=url.pathname.slice(1);if(path20.includes("/-/")||path20.includes("/archive.tar.gz"))return;let segments=path20.split("/"),project=segments.pop();project.endsWith(".git")&&(project=project.slice(0,-4));let user=segments.join("/");if(!(!user||!project))return{user,project,committish:url.hash.slice(1)}}};hosts.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain,project,committish})=>`git@${domain}:${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,project,committish})=>`git+ssh://git@${domain}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",maybeEncode(committish))}/${editpath}`,browsetemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,browsetreetemplate:({domain,project,committish,path:path20,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path20))}`,browseblobtemplate:({domain,project,committish,path:path20,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path20))}`,docstemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,httpstemplate:({domain,project,committish})=>`git+https://${domain}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({user,project,committish,path:path20})=>`https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/",maybeEncode(committish))}/${path20}`,shortcuttemplate:({type,project,committish})=>`${type}:${project}${maybeJoin("#",committish)}`,pathtemplate:({project,committish})=>`${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,project})=>`https://${domain}/${project}`,gittemplate:({domain,project,committish})=>`git://${domain}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({project,committish})=>`https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(aux!=="raw"){if(!project){if(!user)return;project=user,user=null}return project.endsWith(".git")&&(project=project.slice(0,-4)),{user,project,committish:url.hash.slice(1)}}},hashformat:function(fragment){return fragment&&"file-"+formatHashFragment(fragment)}};hosts.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain,user,project,committish,path:path20})=>`https://${domain}/${user}/${project}/blob/${maybeEncode(committish)||"HEAD"}/${path20}`,httpstemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/archive/${maybeEncode(committish)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["archive"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};for(let[name,host]of Object.entries(hosts))hosts[name]=Object.assign({},defaults2,host);module.exports=hosts}});var require_parse_url=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/parse-url.js"(exports,module){var url=__require("url"),lastIndexOfBefore=(str2,char,beforeChar)=>{let startPosition=str2.indexOf(beforeChar);return str2.lastIndexOf(char,startPosition>-1?startPosition:1/0)},safeUrl=u=>{try{return new url.URL(u)}catch{}},correctProtocol=(arg,protocols)=>{let firstColon=arg.indexOf(":"),proto=arg.slice(0,firstColon+1);if(Object.prototype.hasOwnProperty.call(protocols,proto)||arg.substr(firstColon,3)==="://")return arg;let firstAt=arg.indexOf("@");return firstAt>-1?firstAt>firstColon?`git+ssh://${arg}`:arg:`${arg.slice(0,firstColon+1)}//${arg.slice(firstColon+1)}`},correctUrl=giturl=>{let firstAt=lastIndexOfBefore(giturl,"@","#"),lastColonBeforeHash=lastIndexOfBefore(giturl,":","#");return lastColonBeforeHash>firstAt&&(giturl=giturl.slice(0,lastColonBeforeHash)+"/"+giturl.slice(lastColonBeforeHash+1)),lastIndexOfBefore(giturl,":","#")===-1&&giturl.indexOf("//")===-1&&(giturl=`git+ssh://${giturl}`),giturl};module.exports=(giturl,protocols)=>{let withProtocol=protocols?correctProtocol(giturl,protocols):giturl;return safeUrl(withProtocol)||safeUrl(correctUrl(withProtocol))}}});var require_from_url=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/from-url.js"(exports,module){"use strict";var parseUrl=require_parse_url(),isGitHubShorthand=arg=>{let firstHash=arg.indexOf("#"),firstSlash=arg.indexOf("/"),secondSlash=arg.indexOf("/",firstSlash+1),firstColon=arg.indexOf(":"),firstSpace=/\s/.exec(arg),firstAt=arg.indexOf("@"),spaceOnlyAfterHash=!firstSpace||firstHash>-1&&firstSpace.index>firstHash,atOnlyAfterHash=firstAt===-1||firstHash>-1&&firstAt>firstHash,colonOnlyAfterHash=firstColon===-1||firstHash>-1&&firstColon>firstHash,secondSlashOnlyAfterHash=secondSlash===-1||firstHash>-1&&secondSlash>firstHash,hasSlash=firstSlash>0,doesNotEndWithSlash=firstHash>-1?arg[firstHash-1]!=="/":!arg.endsWith("/"),doesNotStartWithDot=!arg.startsWith(".");return spaceOnlyAfterHash&&hasSlash&&doesNotEndWithSlash&&doesNotStartWithDot&&atOnlyAfterHash&&colonOnlyAfterHash&&secondSlashOnlyAfterHash};module.exports=(giturl,opts,{gitHosts,protocols})=>{if(!giturl)return;let correctedUrl=isGitHubShorthand(giturl)?`github:${giturl}`:giturl,parsed=parseUrl(correctedUrl,protocols);if(!parsed)return;let gitHostShortcut=gitHosts.byShortcut[parsed.protocol],gitHostDomain=gitHosts.byDomain[parsed.hostname.startsWith("www.")?parsed.hostname.slice(4):parsed.hostname],gitHostName=gitHostShortcut||gitHostDomain;if(!gitHostName)return;let gitHostInfo=gitHosts[gitHostShortcut||gitHostDomain],auth=null;protocols[parsed.protocol]?.auth&&(parsed.username||parsed.password)&&(auth=`${parsed.username}${parsed.password?":"+parsed.password:""}`);let committish=null,user=null,project=null,defaultRepresentation=null;try{if(gitHostShortcut){let pathname=parsed.pathname.startsWith("/")?parsed.pathname.slice(1):parsed.pathname,firstAt=pathname.indexOf("@");firstAt>-1&&(pathname=pathname.slice(firstAt+1));let lastSlash=pathname.lastIndexOf("/");lastSlash>-1?(user=decodeURIComponent(pathname.slice(0,lastSlash)),user||(user=null),project=decodeURIComponent(pathname.slice(lastSlash+1))):project=decodeURIComponent(pathname),project.endsWith(".git")&&(project=project.slice(0,-4)),parsed.hash&&(committish=decodeURIComponent(parsed.hash.slice(1))),defaultRepresentation="shortcut"}else{if(!gitHostInfo.protocols.includes(parsed.protocol))return;let segments=gitHostInfo.extract(parsed);if(!segments)return;user=segments.user&&decodeURIComponent(segments.user),project=decodeURIComponent(segments.project),committish=decodeURIComponent(segments.committish),defaultRepresentation=protocols[parsed.protocol]?.name||parsed.protocol.slice(0,-1)}}catch(err){if(err instanceof URIError)return;throw err}return[gitHostName,user,auth,project,committish,defaultRepresentation,opts]}}});var require_lib=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/index.js"(exports,module){"use strict";var{LRUCache}=require_index_min(),hosts=require_hosts(),fromUrl=require_from_url(),parseUrl=require_parse_url(),cache2=new LRUCache({max:1e3});function unknownHostedUrl(url){try{let{protocol,hostname,pathname}=new URL(url);if(!hostname)return null;let proto=/(?:git\+)http:$/.test(protocol)?"http:":"https:",path20=pathname.replace(/\.git$/,"");return`${proto}//${hostname}${path20}`}catch{return null}}var GitHost=class _GitHost{constructor(type,user,auth,project,committish,defaultRepresentation,opts={}){Object.assign(this,_GitHost.#gitHosts[type],{type,user,auth,project,committish,default:defaultRepresentation,opts})}static#gitHosts={byShortcut:{},byDomain:{}};static#protocols={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(name,host){_GitHost.#gitHosts[name]=host,_GitHost.#gitHosts.byDomain[host.domain]=name,_GitHost.#gitHosts.byShortcut[`${name}:`]=name,_GitHost.#protocols[`${name}:`]={name}}static fromUrl(giturl,opts){if(typeof giturl!="string")return;let key=giturl+JSON.stringify(opts||{});if(!cache2.has(key)){let hostArgs=fromUrl(giturl,opts,{gitHosts:_GitHost.#gitHosts,protocols:_GitHost.#protocols});cache2.set(key,hostArgs?new _GitHost(...hostArgs):void 0)}return cache2.get(key)}static fromManifest(manifest,opts={}){if(!manifest||typeof manifest!="object")return;let r=manifest.repository,rurl=r&&(typeof r=="string"?r:typeof r=="object"&&typeof r.url=="string"?r.url:null);if(!rurl)throw new Error("no repository");let info=rurl&&_GitHost.fromUrl(rurl.replace(/^git\+/,""),opts)||null;if(info)return info;let unk=unknownHostedUrl(rurl);return _GitHost.fromUrl(unk,opts)||unk}static parseUrl(url){return parseUrl(url)}#fill(template,opts){if(typeof template!="function")return null;let options={...this,...this.opts,...opts};options.path||(options.path=""),options.path.startsWith("/")&&(options.path=options.path.slice(1)),options.noCommittish&&(options.committish=null);let result=template(options);return options.noGitPlus&&result.startsWith("git+")?result.slice(4):result}hash(){return this.committish?`#${this.committish}`:""}ssh(opts){return this.#fill(this.sshtemplate,opts)}sshurl(opts){return this.#fill(this.sshurltemplate,opts)}browse(path20,...args){return typeof path20!="string"?this.#fill(this.browsetemplate,path20):typeof args[0]!="string"?this.#fill(this.browsetreetemplate,{...args[0],path:path20}):this.#fill(this.browsetreetemplate,{...args[1],fragment:args[0],path:path20})}browseFile(path20,...args){return typeof args[0]!="string"?this.#fill(this.browseblobtemplate,{...args[0],path:path20}):this.#fill(this.browseblobtemplate,{...args[1],fragment:args[0],path:path20})}docs(opts){return this.#fill(this.docstemplate,opts)}bugs(opts){return this.#fill(this.bugstemplate,opts)}https(opts){return this.#fill(this.httpstemplate,opts)}git(opts){return this.#fill(this.gittemplate,opts)}shortcut(opts){return this.#fill(this.shortcuttemplate,opts)}path(opts){return this.#fill(this.pathtemplate,opts)}tarball(opts){return this.#fill(this.tarballtemplate,{...opts,noCommittish:!1})}file(path20,opts){return this.#fill(this.filetemplate,{...opts,path:path20})}edit(path20,opts){return this.#fill(this.edittemplate,{...opts,path:path20})}getDefaultRepresentation(){return this.default}toString(opts){return this.default&&typeof this[this.default]=="function"?this[this.default](opts):this.sshurl(opts)}};for(let[name,host]of Object.entries(hosts))GitHost.addHost(name,host);module.exports=GitHost}});var require_identity=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js"(exports){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias2=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,isDocument=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,isMap=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,isPair=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,isScalar2=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,isSeq=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ;function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}function isNode(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}var hasAnchor=node=>(isScalar2(node)||isCollection(node))&&!!node.anchor;exports.ALIAS=ALIAS;exports.DOC=DOC;exports.MAP=MAP;exports.NODE_TYPE=NODE_TYPE;exports.PAIR=PAIR;exports.SCALAR=SCALAR;exports.SEQ=SEQ;exports.hasAnchor=hasAnchor;exports.isAlias=isAlias2;exports.isCollection=isCollection;exports.isDocument=isDocument;exports.isMap=isMap;exports.isNode=isNode;exports.isPair=isPair;exports.isScalar=isScalar2;exports.isSeq=isSeq}});var require_visit=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/visit.js"(exports){"use strict";var identity=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;function visit_(key,node,visitor,path20){let ctrl=callVisitor(key,node,visitor,path20);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path20,ctrl),visit_(key,ctrl,visitor,path20);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path20=Object.freeze(path20.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path20);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path20=Object.freeze(path20.concat(node));let ck=visit_("key",node.key,visitor,path20);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path20);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path20){let ctrl=await callVisitor(key,node,visitor,path20);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path20,ctrl),visitAsync_(key,ctrl,visitor,path20);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path20=Object.freeze(path20.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path20);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path20=Object.freeze(path20.concat(node));let ck=await visitAsync_("key",node.key,visitor,path20);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path20);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}function callVisitor(key,node,visitor,path20){if(typeof visitor=="function")return visitor(key,node,path20);if(identity.isMap(node))return visitor.Map?.(key,node,path20);if(identity.isSeq(node))return visitor.Seq?.(key,node,path20);if(identity.isPair(node))return visitor.Pair?.(key,node,path20);if(identity.isScalar(node))return visitor.Scalar?.(key,node,path20);if(identity.isAlias(node))return visitor.Alias?.(key,node,path20)}function replaceNode(key,path20,node){let parent=path20[path20.length-1];if(identity.isCollection(parent))parent.items[key]=node;else if(identity.isPair(parent))key==="key"?parent.key=node:parent.value=node;else if(identity.isDocument(parent))parent.contents=node;else{let pt=identity.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt} parent`)}}exports.visit=visit;exports.visitAsync=visitAsync}});var require_directives=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js"(exports){"use strict";var identity=require_identity(),visit=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),Directives=class _Directives{constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version2]=parts;if(version2==="1.1"||version2==="1.2")return this.yaml.version=version2,!0;{let isValid=/^\d+\.\d+$/.test(version2);return onError(6,`Unsupported YAML version ${version2}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity.isNode(doc.contents)){let tags={};visit.visit(doc.contents,(_key,node)=>{identity.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
2
|
+
import{Box,CODEMODE_TOOL_NAME,CURSOR_MARKER,CancellableLoader,CodeHighlighter,CombinedAutocompleteProvider,Container,Editor,FS_WATCH_RETRY_DELAY_MS,Image,Input,Key,KeybindingsManager,Loader,Markdown,Marked,MouseRegion,ProcessTerminal,SYSTEM_THEME_NAME,ScrollView,SelectList,SettingsList,Spacer,THEME_TOKENS,TOOL_SEARCH_TOOL_NAME,TUI_KEYBINDINGS,Text,Theme,TruncatedText,TuiAltScreen,TuiMainScreen,VStack,VisualLinePreview,addUsageToTotals,closeWatcher,combineUsage,combinedKeyHint,createCodemodeToolDefinition,createOutputFileStream,createToolDefinitionFromAgentTool,createToolSearchToolDefinition,createUsageTotals,detectCapabilities,foregroundAnsi,formatKeyText,formatReadLineRange,formatToolCallWithArgs,fuzzyFilter,fuzzyMatch,getAvailableThemes,getAvailableThemesWithPaths,getCapabilities,getEditorTheme,getKeybindings,getLanguageFromPath,getMarkdownTheme,getNativeClipboard,getResolvedThemeColors,getSelectListTheme,getSelectPageIndex,getSettingsListTheme,getTerminalColorMode,getTerminalTheme,getTextOutput,getThemeByName,getThemeExportColors,getUsageCostBreakdown,highlightCode,hyperlink,initTheme,invalidArgText,isKeyRelease,isKeyRepeat,isValidUsage,isViewportTUI,keyDisplayText,keyHint,keyText,loadAllHighlightLanguages,loadThemeFromPath,markTerminalColorsPending,matchesKey,mixColors,normalizeDisplayText,onThemeChange,parseAutoThemeSetting,parseColor,rawKeyHint,renderToolPath,replaceControlCharacters,replaceTabs,resolveThemeSetting,setCapabilityOverrides,setImageTranscoder,setKeybindings,setRegisteredThemes,setTerminalColorScheme,setTerminalColors,setTheme,setThemeInstance,setThemeJsonValidator,shortenPath,sliceByColumn,splitIncompleteAnsiSuffix,startToolTimer,stopThemeWatcher,str,stripAnsi,theme,toolTimerText,truncateToVisualLines,truncateToWidth,visibleWidth,watchWithErrorHandler,wrapTextWithAnsi,wrapToolDefinition,writeOutputFile}from"./chunk-GAABJAG4.js";import{CACHE_WARMING_MAX_AGE_MS,CACHE_WARMING_MAX_IDLE_AGE_MS,CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS,Compile,CredentialSynchronizationError,DEFAULT_RADIUS_GATEWAY,InMemoryCodingAgentModelsStore,ModelRuntime,ProjectTrustStore,VIRTUAL_MODEL_STATE_ENTRY,addMcpServerConfig,comparablePath,completeSimple,evaluateCacheWarming,fauxAssistantMessage,fauxProvider,fauxText,fauxToolCall,fetchWithRetry,findLatestResponse,getApiProvider,getBranchSelection,getCacheWarmingDelayMs,getCacheWarmingRequestOptions,getDrahtUserAgent,getModel,getModels,getProjectTrustOptions,getPromptCacheTtlMs,getProviders,getVirtualModelState,hasTrustRequiringProjectResources,isCacheWarmingReplayable,isContextOverflow,isRecoverableLength,isVirtualModel,loadMcpConfig,normalizeRadiusGatewayUrl,openBrowser,questionTerminal,realHomeDir,realPathStrict,resetApiProviders,stream,streamSimple,typesafeSystemOneApi,updateMcpServerConfig,validateToolArguments}from"./chunk-HTSLUWLE.js";import{source_default,typebox_exports}from"./chunk-ITKDPD4D.js";import{AuthStorage,LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,McpServerRegistry,READ_MCP_RESOURCE_TOOL,ReadOnlyAuthStorage,createMcpToolName,createToolNameMatcher,getMcpToolExposure,isMcpToolName,limitMcpContent,mcpNamespace,mcpServerSummary,normalizeMcpInputSchema,raceWithAbortSignal,toLlmContent,validateMcpServerConfig}from"./chunk-O2P5SYXT.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,getShellEnv,killProcessTree,killTrackedDetachedChildren,sanitizeBinaryOutput,sliceHead,trackDetachedChildPid,truncateHead,truncateLine,truncateTail,untrackDetachedChildPid}from"./chunk-4FPBO5KP.js";import{uuidv7}from"./chunk-Y3NLUJYO.js";import{CACHE_WARMING_MODES,DEFAULT_TOOL_NAMES,HTTP_IDLE_TIMEOUT_CHOICES,SettingsManager,applyHttpProxySettings,applyToolModifiers,configureHttpDispatcher,formatHttpIdleTimeoutMs,getToolListError,isToolModifier}from"./chunk-RI7HJ6AF.js";import{SETTINGS_DEFAULTS}from"./chunk-MXA4WY3C.js";import{isRetryableAssistantError,retryAssistantCall,retryDelayMs}from"./chunk-2CHTECAU.js";import{require_proper_lockfile}from"./chunk-2JZLKNZ4.js";import{APP_NAME,APP_TITLE,CONFIG_DIR_NAME,DISPLAY_VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,PACKAGE_NAME,VERSION,detectInstallChange,detectInstallMethod,expandTildePath,formatPathRelativeToCwdOrAbsolute,getAgentDir,getAuthPath,getBinDir,getBundledInteractiveAssetPath,getChangelogPath,getConfiguredSelfUpdateArgv,getCwdRelativePath,getDebugLogPath,getDocsPath,getExamplesPath,getExportTemplateDir,getPackageDir,getPathComparisonKey,getReadmePath,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getSessionsDir,getSettingsPath,getShareViewerUrl,getShippedPromptsDir,getShippedSkillsDir,isBunBinary,isLocalPath,isPathWithin,makeConfiguredSelfUpdateCommand,markPathIgnoredByCloudSync,normalizePath,pathsEqual,resolvePath,shortenHomePath,spawnProcess,spawnProcessSync,splitBom,stripBom,waitForChildProcess}from"./chunk-6M3D4XVD.js";import{cleanupSessionResources}from"./chunk-Y7QE2R34.js";import{ToolCallArgumentsStream}from"./chunk-KFREX3FS.js";import{ModelsError,clampThinkingLevel,createInitialSystemMessage,getCurrentSystemMessage,getCurrentSystemPrompt,getCurrentTools,getSupportedThinkingLevels,getToolStateChanges,isModelType,modelsAreEqual,normalizeContext,supportsMax,supportsXhigh,toToolDeclaration}from"./chunk-YFDWS2SA.js";import{EventStream,createAssistantMessageEventStream}from"./chunk-USCN7R2E.js";import{DRAHT_ATTRIBUTION,contentText,getSystemMessageText,mergeClientIdentity}from"./chunk-2XOICIOV.js";import{__commonJS,__export,__require,__toESM}from"./chunk-HZ2UHMBT.js";var require_ignore=__commonJS({"node_modules/.bun/ignore@7.0.11/node_modules/ignore/index.js"(exports,module){function makeArray(subject){return Array.isArray(subject)?subject:[subject]}var UNDEFINED=void 0,EMPTY="",SPACE=" ",ESCAPE="\\",REGEX_LITERAL_SPECIAL=/[.*+?()[\]{}^$|\\/]/,REGEX_TEST_BLANK_LINE=/^\uFEFF? *$/,REGEX_INVALID_TRAILING_BACKSLASH=/(?:[^\\]|^)\\$/,REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION=/^\\!/,REGEX_REPLACE_LEADING_EXCAPED_HASH=/^\\#/,REGEX_SPLITALL_CRLF=/\r?\n/g,DOUBLE_SLASH="//",SLASH_CODE=47,DOT_CODE=46,SLASH="/",TMP_KEY_IGNORE="node-ignore";typeof Symbol<"u"&&(TMP_KEY_IGNORE=Symbol.for("node-ignore"));var KEY_IGNORE=TMP_KEY_IGNORE,define=(object,key,value)=>(Object.defineProperty(object,key,{value}),value),RETURN_FALSE=()=>!1,cleanRangeBackSlash=slashes=>{let{length}=slashes;return slashes.slice(0,length-length%2)},POSIX_CLASSES={alnum:"0-9A-Za-z",alpha:"A-Za-z",blank:" \\t",cntrl:"\\x00-\\x1f\\x7f",digit:"0-9",graph:"!-.0-~",lower:"a-z",print:" -.0-~",punct:"!-.:-@\\[-`{-~",space:" \\t\\n\\r",upper:"A-Z",xdigit:"0-9A-Fa-f"},CLASS_MEMBERS_TO_ESCAPE="\\]^-[",escapeMember=char=>CLASS_MEMBERS_TO_ESCAPE.indexOf(char)<0?char:ESCAPE+char,NON_SLASH="(?!\\/)",classSource=(negated,body)=>{if(negated)return`[^\\/${body}]`;let source=`[${body}]`;return new RegExp(source).test("/")?NON_SLASH+source:source},scanBracket=(pattern,start)=>{let{length}=pattern,index=start+1,negated=EMPTY,lead=pattern[index];(lead==="!"||lead==="^")&&(negated="^",index++);let body=EMPTY,prev=EMPTY;for(;;){let char=pattern[index];if(char===UNDEFINED)return null;if(char===ESCAPE){let escaped=pattern[index+1];if(escaped===UNDEFINED)return null;body+=escapeMember(escaped),prev=escaped,index++}else if(char==="-"&&prev&&index+1<length&&pattern[index+1]!=="]"){index++;let to=pattern[index];to===ESCAPE&&(to=pattern[index+=1]),prev<=to&&(body+=`-${escapeMember(to)}`),prev=EMPTY}else if(char==="["&&pattern[index+1]===":"){let nameStart=index+2,end=nameStart;for(;end<length&&pattern[end]!=="]";)end++;if(end===length)return null;if(end>nameStart&&pattern[end-1]===":"){let expanded=POSIX_CLASSES[pattern.slice(nameStart,end-1)];if(expanded===UNDEFINED)return null;body+=expanded,prev=EMPTY,index=end}else body+=escapeMember("["),prev="[",index=nameStart-2}else body+=escapeMember(char),prev=char;if(index++,pattern[index]==="]")return{end:index,source:classSource(negated,body)}}},NEVER_MATCH="[]",PLACEHOLDER="\0",REGEX_RESTORE_PLACEHOLDER=new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,"g"),TRAILING_WILDCARD="\uE000",TRAILING_DOUBLESTAR="\uE001",extractBrackets=pattern=>{let sources=[],hold=source=>`${PLACEHOLDER}${sources.push(source)-1}${PLACEHOLDER}`,{length}=pattern,out=EMPTY,index=0;for(;index<length;){let char=pattern[index];if(char===ESCAPE){let escaped=pattern[index+1];escaped==="*"||escaped==="["||escaped===SPACE||escaped===ESCAPE?out+=pattern.slice(index,index+2):out+=hold(REGEX_LITERAL_SPECIAL.test(escaped)?ESCAPE+escaped:escaped),index+=2}else if(char===PLACEHOLDER)out+=hold(`[${PLACEHOLDER}]`),index++;else if(char==="["){let scanned=scanBracket(pattern,index);scanned===null?(out+=hold(NEVER_MATCH),index=length):(out+=hold(scanned.source),index=scanned.end+1)}else out+=char,index++}return{source:out,sources}},DIRECT=null,REGEX_INNER_SLASH=/\/(?!$)/,REPLACERS=[[/^\uFEFF/,()=>EMPTY,"\uFEFF"],[/[\r\n]+$/,()=>EMPTY],[/((?:\\\\)*?)(\\? +)$/,(_,m1,m2)=>m1+(m2.indexOf("\\")===0?SPACE:EMPTY)],[/(\\+?) /g,(_,m1)=>{let{length}=m1;return m1.slice(0,length-length%2)+SPACE}],[/[\\$.|*+(){^]/g,match2=>`\\${match2}`],[/(?!\\)\?/g,()=>"[^/]","?"],[/^\//,()=>"^",SLASH],[/\//g,()=>"\\/",SLASH],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?","*"],[DIRECT,(source,pattern)=>!source||source[0]==="^"?source:(REGEX_INNER_SLASH.test(pattern)?"^":"(?:^|\\/)")+source],[/\\\/\\\*\\\*(?=\\\/|$)/g,(_,index,str2)=>index+6<str2.length?str2.slice(index+6)==="\\/"?"(?:\\/[^\\/]+)+":"(?:\\/[^\\/]+)*":`\\/${TRAILING_DOUBLESTAR}`,"*"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(_,p1,p2)=>{let unescaped=p2.replace(/\\\*/g,"[^\\/]*");return p1+unescaped},"*"],[/(^|[^\\])((?:\\\\)*)\\\*$/,(match2,p1,p2)=>p2.length/2%2===0?p1+p2+TRAILING_WILDCARD:match2,"*"],[/\\\\\\(?=[$.|*+(){^])/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\\/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\[([^\]/]*?)(\\*)($|\])/g,(match2,range2,endEscape,close)=>`\\[${range2}${cleanRangeBackSlash(endEscape)}${close}`,"["],[DIRECT,source=>{let last=source[source.length-1];return!last||last===TRAILING_WILDCARD||last===TRAILING_DOUBLESTAR?source:last===SLASH?`${source}$`:`${source}(?=$|\\/$)`}]],REGEX_REPLACE_TRAILING_WILDCARD=/(^|\\\/)?\uE000$/,MODE_IGNORE="regex",MODE_CHECK_IGNORE="checkRegex",UNDERSCORE="_",replaceTrailingWildcard=(_,p1)=>`${p1?`${p1}[^/]+`:"[^/]*"}(?=$|\\/$)`,REGEX_REPLACE_TRAILING_DOUBLESTAR=/\uE001$/,replaceTrailingDoublestar=()=>".+(?=$|\\/$)",WILDCARD="[^\\/]*",separatorAfter=(run,at)=>{let separator=EMPTY;for(let index=at+1;index<run.length&&!run[index].wildcard;index++)separator+=run[index].single;return separator},pinWildcards=source=>{if(source.indexOf(WILDCARD)<0)return source;let tokens=[],{length}=source,index=0;for(;index<length;){let char=source[index];if(source.startsWith(WILDCARD,index))tokens.push({wildcard:!0}),index+=WILDCARD.length;else if(char==="["){let end=index+1;for(source[end]==="^"&&end++,source[end]==="]"&&end++;end<length&&source[end]!=="]";)end+=source[end]===ESCAPE?2:1;end++,tokens.push({single:source.slice(index,end)}),index=end}else if(char===ESCAPE)tokens.push({single:source.slice(index,index+2)}),index+=2;else if(char==="("){let depth=0,end=index;do source[end]===ESCAPE?end++:source[end]==="("?depth++:source[end]===")"&&depth--,end++;while(end<length&&depth>0);"*+?".indexOf(source[end])>=0&&end++,tokens.push({boundary:source.slice(index,end)}),index=end}else char==="^"||char==="$"?(tokens.push({boundary:char}),index++):(tokens.push({single:char}),index++)}let out=EMPTY,run=[],flush=()=>{let lastWildcard;run.forEach((token,at)=>{token.wildcard&&(lastWildcard=at)}),run.forEach((token,at)=>{if(!token.wildcard){out+=token.single;return}out+=at===lastWildcard?WILDCARD:`(?:(?!${separatorAfter(run,at)})[^\\/])*`}),run=[]};return tokens.forEach(token=>{if(token.boundary===void 0){run.push(token);return}flush(),out+=token.boundary}),flush(),out},makeRegexPrefix=pattern=>{let{source,sources}=extractBrackets(pattern),replaced=REPLACERS.reduce((prev,[matcher,replacer,required])=>matcher===DIRECT?replacer(prev,pattern):required!==UNDEFINED&&prev.indexOf(required)<0?prev:matcher.test(prev)?prev.replace(matcher,replacer.bind(pattern)):prev,source);return sources.length?replaced.replace(REGEX_RESTORE_PLACEHOLDER,(match2,index)=>sources[index]):replaced},checkSourceOf=(body,prefix)=>{body[body.length-1]===SLASH&&(prefix=makeRegexPrefix(body.slice(0,-1)));let head=prefix.slice(0,-1),last=prefix[prefix.length-1];return last===TRAILING_WILDCARD?`${head}$`:last===TRAILING_DOUBLESTAR?`${head}.*$`:NEVER_MATCH},matchesBasename=body=>{let index=body.indexOf(SLASH);return index<0||index===body.length-1},basenameOf=path20=>{let end=path20.length-1,index=path20.lastIndexOf(SLASH,path20[end]===SLASH?end-1:end);return index<0?path20:path20.slice(index+1)},parentOf=path20=>{if(path20.charCodeAt(0)===SLASH_CODE||path20.indexOf(DOUBLE_SLASH)>=0){let slices=path20.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY}let end=path20.length-1,cut=path20.lastIndexOf(SLASH,path20.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY:path20.slice(0,cut+1)},isString=subject=>typeof subject=="string",checkPattern=pattern=>pattern&&isString(pattern)&&!REGEX_TEST_BLANK_LINE.test(pattern)&&!REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)&&pattern.indexOf("#")!==0,splitPattern=pattern=>pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean),IgnoreRule=class{constructor(pattern,mark,body,ignoreCase,negative,prefix){this.pattern=pattern,this.mark=mark,this.negative=negative,define(this,"body",body),define(this,"ignoreCase",ignoreCase),define(this,"regexPrefix",prefix)}get _basenameOnly(){return define(this,"_basenameOnly",matchesBasename(this.body))}get regex(){let key=UNDERSCORE+MODE_IGNORE;return this[key]?this[key]:this._make(MODE_IGNORE,key)}get checkRegex(){let key=UNDERSCORE+MODE_CHECK_IGNORE;return this[key]?this[key]:this._make(MODE_CHECK_IGNORE,key)}_make(mode,key){let str2=pinWildcards(mode===MODE_IGNORE?this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR,replaceTrailingDoublestar):checkSourceOf(this.body,this.regexPrefix)),regex=this.ignoreCase?new RegExp(str2,"i"):new RegExp(str2);return define(this,key,regex)}},createRule=({pattern,mark},ignoreCase)=>{let negative=!1,body=pattern;body.indexOf("!")===0&&(negative=!0,body=body.substr(1)),body=body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION,"!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH,"#");let regexPrefix=makeRegexPrefix(body);return new IgnoreRule(pattern,mark,body,ignoreCase,negative,regexPrefix)},RuleManager=class{constructor(ignoreCase){this._ignoreCase=ignoreCase,this._rules=[],this._basenameCount=0}_add(pattern){if(pattern&&pattern[KEY_IGNORE]){this._rules=this._rules.concat(pattern._rules._rules),this._basenameCount+=pattern._rules._basenameCount,this._added=!0;return}if(isString(pattern)&&(pattern={pattern}),checkPattern(pattern.pattern)){let rule=createRule(pattern,this._ignoreCase);this._added=!0,this._rules.push(rule),matchesBasename(rule.body)&&this._basenameCount++}}add(pattern){return this._added=!1,makeArray(isString(pattern)?splitPattern(pattern):pattern).forEach(this._add,this),this._added&&(this._literalRules=UNDEFINED),this._added}testLiteral(path20){let rules=this._literalRules||(this._literalRules=this._rules.filter(({body})=>body[body.length-(body[body.length-1]===SLASH?2:1)]==="*")),ignored=!1,unignored=!1,matchedRule;for(let index=rules.length-1;index>=0;index--){let rule=rules[index];if(rule.checkRegex.test(path20)){ignored=!rule.negative,unignored=rule.negative,matchedRule=rule.negative?UNDEFINED:rule;break}}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}test(path20,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename14=shortcut?basenameOf(path20):path20;for(let index=0;index<length;index++){let rule=rules[index],{negative}=rule;!(unignored===negative&&ignored!==unignored||negative&&!ignored&&!unignored&&!checkUnignored)&&rule[mode].test(shortcut&&rule._basenameOnly?basename14:path20)&&(ignored=!negative,unignored=negative,matchedRule=negative?UNDEFINED:rule)}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}},throwError=(message,Ctor)=>{throw new Ctor(message)},checkPath=(path20,originalPath,doThrow)=>isString(path20)?path20?checkPath.isNotRelative(path20)?doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`,RangeError):!0:doThrow("path must not be empty",TypeError):doThrow(`path must be a string, but got \`${originalPath}\``,TypeError),isNotRelative=path20=>{let first=path20.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path20.length===1)return!0;let second=path20.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path20.length===2||path20.charCodeAt(2)===SLASH_CODE};checkPath.isNotRelative=isNotRelative;checkPath.convert=p=>p;var Ignore=class{constructor({ignorecase=!0,ignoreCase=ignorecase,allowRelativePaths=!1}={}){define(this,KEY_IGNORE,!0),this._rules=new RuleManager(ignoreCase),this._strictPathCheck=!allowRelativePaths,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(pattern){return this._rules.add(pattern)&&this._initCache(),this}addPattern(pattern){return this.add(pattern)}_test(originalPath,cache2,checkUnignored){let path20=originalPath&&checkPath.convert(originalPath);return checkPath(path20,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path20,cache2,checkUnignored)}checkIgnore(path20){if(path20.charCodeAt(path20.length-1)!==SLASH_CODE)return this.test(path20);let dir=this._t(path20,this._testCache,!0);if(dir.ignored)return dir;let literal2=this._rules.testLiteral(path20);return literal2.ignored||literal2.unignored?literal2:dir}_t(path20,cache2,checkUnignored){if(path20 in cache2)return cache2[path20];let parentPath=parentOf(path20),parent=parentPath?this._t(parentPath,cache2,checkUnignored):UNDEFINED;return cache2[path20]=parent&&parent.ignored?parent:this._rules.test(path20,checkUnignored,MODE_IGNORE)}ignores(path20){return this._test(path20,this._ignoreCache,!1).ignored}createFilter(){return path20=>!this.ignores(path20)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path20){return this._test(path20,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path20=>checkPath(path20&&checkPath.convert(path20),path20,RETURN_FALSE),setupWindows=()=>{let makePosix=str2=>/^\\\\\?\\/.test(str2)||/["<>|\u0000-\u001F]+/u.test(str2)?str2:str2.replace(/\\/g,"/");checkPath.convert=makePosix;let REGEX_TEST_WINDOWS_PATH_ABSOLUTE=/^[a-z]:\//i;checkPath.isNotRelative=path20=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path20)||isNotRelative(path20)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});var require_constants=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/constants.js"(exports,module){"use strict";var SEMVER_SPEC_VERSION="2.0.0",MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH=16,MAX_SAFE_BUILD_LENGTH=250,RELEASE_TYPES=["major","premajor","minor","preminor","patch","prepatch","prerelease"];module.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH,MAX_SAFE_INTEGER,RELEASE_TYPES,SEMVER_SPEC_VERSION,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}});var require_debug=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/debug.js"(exports,module){"use strict";var debug=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...args)=>console.error("SEMVER",...args):()=>{};module.exports=debug}});var require_re=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/re.js"(exports,module){"use strict";var{MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH,MAX_LENGTH}=require_constants(),debug=require_debug();exports=module.exports={};var re=exports.re=[],safeRe=exports.safeRe=[],src=exports.src=[],safeSrc=exports.safeSrc=[],t=exports.t={},R2=0,LETTERDASHNUMBER="[a-zA-Z0-9-]",safeRegexReplacements=[["\\s",1],["\\d",MAX_LENGTH],[LETTERDASHNUMBER,MAX_SAFE_BUILD_LENGTH]],makeSafeRegex=value=>{for(let[token,max]of safeRegexReplacements)value=value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);return value},createToken=(name,value,isGlobal)=>{let safe=makeSafeRegex(value),index=R2++;debug(name,index,value),t[name]=index,src[index]=value,safeSrc[index]=safe,re[index]=new RegExp(value,isGlobal?"g":void 0),safeRe[index]=new RegExp(safe,isGlobal?"g":void 0)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);createToken("MAINVERSION",`(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASE",`(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${LETTERDASHNUMBER}+`);createToken("BUILD",`(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);createToken("FULL",`^${src[t.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);createToken("LOOSE",`^${src[t.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);createToken("XRANGE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`(^|[^\\d])(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);createToken("COERCE",`${src[t.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",src[t.COERCEPLAIN]+`(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);createToken("COERCERTL",src[t.COERCE],!0);createToken("COERCERTLFULL",src[t.COERCEFULL],!0);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${src[t.LONETILDE]}\\s+`,!0);exports.tildeTrimReplace="$1~";createToken("TILDE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${src[t.LONECARET]}\\s+`,!0);exports.caretTrimReplace="$1^";createToken("CARET",`^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`,!0);exports.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}});var require_parse_options=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/parse-options.js"(exports,module){"use strict";var looseOption=Object.freeze({loose:!0}),emptyOpts=Object.freeze({}),parseOptions=options=>options?typeof options!="object"?looseOption:options:emptyOpts;module.exports=parseOptions}});var require_identifiers=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/identifiers.js"(exports,module){"use strict";var numeric2=/^[0-9]+$/,compareIdentifiers=(a,b)=>{if(typeof a=="number"&&typeof b=="number")return a===b?0:a<b?-1:1;let anum=numeric2.test(a),bnum=numeric2.test(b);return anum&&bnum&&(a=+a,b=+b),a===b?0:anum&&!bnum?-1:bnum&&!anum?1:a<b?-1:1},rcompareIdentifiers=(a,b)=>compareIdentifiers(b,a);module.exports={compareIdentifiers,rcompareIdentifiers}}});var require_semver=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/classes/semver.js"(exports,module){"use strict";var debug=require_debug(),{MAX_LENGTH,MAX_SAFE_INTEGER}=require_constants(),{safeRe:re,t}=require_re(),parseOptions=require_parse_options(),{compareIdentifiers}=require_identifiers(),isPrereleaseIdentifier=(prerelease,identifier)=>{let identifiers=identifier.split(".");if(identifiers.length>prerelease.length)return!1;for(let i=0;i<identifiers.length;i++)if(compareIdentifiers(prerelease[i],identifiers[i])!==0)return!1;return!0},SemVer=class _SemVer{constructor(version2,options){if(options=parseOptions(options),version2 instanceof _SemVer){if(version2.loose===!!options.loose&&version2.includePrerelease===!!options.includePrerelease)return version2;version2=version2.version}else if(typeof version2!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`);if(version2.length>MAX_LENGTH)throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);debug("SemVer",version2,options),this.options=options,this.loose=!!options.loose,this.includePrerelease=!!options.includePrerelease;let m=version2.trim().match(options.loose?re[t.LOOSE]:re[t.FULL]);if(!m)throw new TypeError(`Invalid Version: ${version2}`);if(this.raw=version2,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>MAX_SAFE_INTEGER||this.major<0)throw new TypeError("Invalid major version");if(this.minor>MAX_SAFE_INTEGER||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>MAX_SAFE_INTEGER||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(id=>{if(/^[0-9]+$/.test(id)){let num=+id;if(num>=0&&num<MAX_SAFE_INTEGER)return num}return id}):this.prerelease=[],this.build=m[5]?m[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(other){if(debug("SemVer.compare",this.version,this.options,other),!(other instanceof _SemVer)){if(typeof other=="string"&&other===this.version)return 0;other=new _SemVer(other,this.options)}return other.version===this.version?0:this.compareMain(other)||this.comparePre(other)}compareMain(other){return other instanceof _SemVer||(other=new _SemVer(other,this.options)),this.major<other.major?-1:this.major>other.major?1:this.minor<other.minor?-1:this.minor>other.minor?1:this.patch<other.patch?-1:this.patch>other.patch?1:0}comparePre(other){if(other instanceof _SemVer||(other=new _SemVer(other,this.options)),this.prerelease.length&&!other.prerelease.length)return-1;if(!this.prerelease.length&&other.prerelease.length)return 1;if(!this.prerelease.length&&!other.prerelease.length)return 0;let i=0;do{let a=this.prerelease[i],b=other.prerelease[i];if(debug("prerelease compare",i,a,b),a===void 0&&b===void 0)return 0;if(b===void 0)return 1;if(a===void 0)return-1;if(a===b)continue;return compareIdentifiers(a,b)}while(++i)}compareBuild(other){other instanceof _SemVer||(other=new _SemVer(other,this.options));let i=0;do{let a=this.build[i],b=other.build[i];if(debug("build compare",i,a,b),a===void 0&&b===void 0)return 0;if(b===void 0)return 1;if(a===void 0)return-1;if(a===b)continue;return compareIdentifiers(a,b)}while(++i)}inc(release2,identifier,identifierBase){if(release2.startsWith("pre")){if(!identifier&&identifierBase===!1)throw new Error("invalid increment argument: identifier is empty");if(identifier){let match2=`-${identifier}`.match(this.options.loose?re[t.PRERELEASELOOSE]:re[t.PRERELEASE]);if(!match2||match2[1]!==identifier)throw new Error(`invalid identifier: ${identifier}`)}}switch(release2){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",identifier,identifierBase);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",identifier,identifierBase);break;case"prepatch":this.prerelease.length=0,this.inc("patch",identifier,identifierBase),this.inc("pre",identifier,identifierBase);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",identifier,identifierBase),this.inc("pre",identifier,identifierBase);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let base=Number(identifierBase)?1:0;if(this.prerelease.length===0)this.prerelease=[base];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(identifier===this.prerelease.join(".")&&identifierBase===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(base)}}if(identifier){let prerelease=[identifier,base];if(identifierBase===!1&&(prerelease=[identifier]),isPrereleaseIdentifier(this.prerelease,identifier)){let prereleaseBase=this.prerelease[identifier.split(".").length];isNaN(prereleaseBase)&&(this.prerelease=prerelease)}else this.prerelease=prerelease}break}default:throw new Error(`invalid increment argument: ${release2}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};module.exports=SemVer}});var require_parse=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/parse.js"(exports,module){"use strict";var SemVer=require_semver(),parse4=(version2,options,throwErrors=!1)=>{if(version2 instanceof SemVer)return version2;try{return new SemVer(version2,options)}catch(er2){if(!throwErrors)return null;throw er2}};module.exports=parse4}});var require_valid=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/valid.js"(exports,module){"use strict";var parse4=require_parse(),valid3=(version2,options)=>{let v=parse4(version2,options);return v?v.version:null};module.exports=valid3}});var require_clean=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/clean.js"(exports,module){"use strict";var parse4=require_parse(),clean2=(version2,options)=>{let s=parse4(version2.trim().replace(/^[=v]+/,""),options);return s?s.version:null};module.exports=clean2}});var require_inc=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/inc.js"(exports,module){"use strict";var SemVer=require_semver(),inc=(version2,release2,options,identifier,identifierBase)=>{typeof options=="string"&&(identifierBase=identifier,identifier=options,options=void 0);try{return new SemVer(version2 instanceof SemVer?version2.version:version2,options).inc(release2,identifier,identifierBase).version}catch{return null}};module.exports=inc}});var require_diff=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/diff.js"(exports,module){"use strict";var parse4=require_parse(),diff=(version1,version2)=>{let v1=parse4(version1,null,!0),v2=parse4(version2,null,!0),comparison=v1.compare(v2);if(comparison===0)return null;let v1Higher=comparison>0,highVersion=v1Higher?v1:v2,lowVersion=v1Higher?v2:v1,highHasPre=!!highVersion.prerelease.length;if(!!lowVersion.prerelease.length&&!highHasPre){if(!lowVersion.patch&&!lowVersion.minor)return"major";if(lowVersion.compareMain(highVersion)===0)return lowVersion.minor&&!lowVersion.patch?"minor":"patch"}let prefix=highHasPre?"pre":"";return v1.major!==v2.major?prefix+"major":v1.minor!==v2.minor?prefix+"minor":v1.patch!==v2.patch?prefix+"patch":"prerelease"};module.exports=diff}});var require_major=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/major.js"(exports,module){"use strict";var SemVer=require_semver(),major=(a,loose)=>new SemVer(a,loose).major;module.exports=major}});var require_minor=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/minor.js"(exports,module){"use strict";var SemVer=require_semver(),minor=(a,loose)=>new SemVer(a,loose).minor;module.exports=minor}});var require_patch=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/patch.js"(exports,module){"use strict";var SemVer=require_semver(),patch=(a,loose)=>new SemVer(a,loose).patch;module.exports=patch}});var require_prerelease=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/prerelease.js"(exports,module){"use strict";var parse4=require_parse(),prerelease=(version2,options)=>{let parsed=parse4(version2,options);return parsed&&parsed.prerelease.length?parsed.prerelease:null};module.exports=prerelease}});var require_compare=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/compare.js"(exports,module){"use strict";var SemVer=require_semver(),compare2=(a,b,loose)=>new SemVer(a,loose).compare(new SemVer(b,loose));module.exports=compare2}});var require_rcompare=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/rcompare.js"(exports,module){"use strict";var compare2=require_compare(),rcompare2=(a,b,loose)=>compare2(b,a,loose);module.exports=rcompare2}});var require_compare_loose=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/compare-loose.js"(exports,module){"use strict";var compare2=require_compare(),compareLoose=(a,b)=>compare2(a,b,!0);module.exports=compareLoose}});var require_compare_build=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/compare-build.js"(exports,module){"use strict";var SemVer=require_semver(),compareBuild=(a,b,loose)=>{let versionA=new SemVer(a,loose),versionB=new SemVer(b,loose);return versionA.compare(versionB)||versionA.compareBuild(versionB)};module.exports=compareBuild}});var require_sort=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/sort.js"(exports,module){"use strict";var compareBuild=require_compare_build(),sort=(list,loose)=>list.sort((a,b)=>compareBuild(a,b,loose));module.exports=sort}});var require_rsort=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/rsort.js"(exports,module){"use strict";var compareBuild=require_compare_build(),rsort=(list,loose)=>list.sort((a,b)=>compareBuild(b,a,loose));module.exports=rsort}});var require_gt=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/gt.js"(exports,module){"use strict";var compare2=require_compare(),gt2=(a,b,loose)=>compare2(a,b,loose)>0;module.exports=gt2}});var require_lt=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/lt.js"(exports,module){"use strict";var compare2=require_compare(),lt=(a,b,loose)=>compare2(a,b,loose)<0;module.exports=lt}});var require_eq=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/eq.js"(exports,module){"use strict";var compare2=require_compare(),eq=(a,b,loose)=>compare2(a,b,loose)===0;module.exports=eq}});var require_neq=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/neq.js"(exports,module){"use strict";var compare2=require_compare(),neq=(a,b,loose)=>compare2(a,b,loose)!==0;module.exports=neq}});var require_gte=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/gte.js"(exports,module){"use strict";var compare2=require_compare(),gte2=(a,b,loose)=>compare2(a,b,loose)>=0;module.exports=gte2}});var require_lte=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/lte.js"(exports,module){"use strict";var compare2=require_compare(),lte2=(a,b,loose)=>compare2(a,b,loose)<=0;module.exports=lte2}});var require_cmp=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/cmp.js"(exports,module){"use strict";var eq=require_eq(),neq=require_neq(),gt2=require_gt(),gte2=require_gte(),lt=require_lt(),lte2=require_lte(),cmp=(a,op,b,loose)=>{switch(op){case"===":return typeof a=="object"&&(a=a.version),typeof b=="object"&&(b=b.version),a===b;case"!==":return typeof a=="object"&&(a=a.version),typeof b=="object"&&(b=b.version),a!==b;case"":case"=":case"==":return eq(a,b,loose);case"!=":return neq(a,b,loose);case">":return gt2(a,b,loose);case">=":return gte2(a,b,loose);case"<":return lt(a,b,loose);case"<=":return lte2(a,b,loose);default:throw new TypeError(`Invalid operator: ${op}`)}};module.exports=cmp}});var require_coerce=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/coerce.js"(exports,module){"use strict";var SemVer=require_semver(),parse4=require_parse(),{safeRe:re,t}=require_re(),coerce=(version2,options)=>{if(version2 instanceof SemVer)return version2;if(typeof version2=="number"&&(version2=String(version2)),typeof version2!="string")return null;options=options||{};let match2=null;if(!options.rtl)match2=version2.match(options.includePrerelease?re[t.COERCEFULL]:re[t.COERCE]);else{let coerceRtlRegex=options.includePrerelease?re[t.COERCERTLFULL]:re[t.COERCERTL],next;for(;(next=coerceRtlRegex.exec(version2))&&(!match2||match2.index+match2[0].length!==version2.length);)(!match2||next.index+next[0].length!==match2.index+match2[0].length)&&(match2=next),coerceRtlRegex.lastIndex=next.index+next[1].length+next[2].length;coerceRtlRegex.lastIndex=-1}if(match2===null)return null;let major=match2[2],minor=match2[3]||"0",patch=match2[4]||"0",prerelease=options.includePrerelease&&match2[5]?`-${match2[5]}`:"",build2=options.includePrerelease&&match2[6]?`+${match2[6]}`:"";return parse4(`${major}.${minor}.${patch}${prerelease}${build2}`,options)};module.exports=coerce}});var require_truncate=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/truncate.js"(exports,module){"use strict";var parse4=require_parse(),constants9=require_constants(),SemVer=require_semver(),truncate3=(version2,truncation,options)=>{if(!constants9.RELEASE_TYPES.includes(truncation))return null;let clonedVersion=cloneInputVersion(version2,options);return clonedVersion&&doTruncation(clonedVersion,truncation)},cloneInputVersion=(version2,options)=>{let versionStringToParse=version2 instanceof SemVer?version2.version:version2;return parse4(versionStringToParse,options)},doTruncation=(version2,truncation)=>{if(isPrerelease(truncation))return version2.version;switch(version2.prerelease=[],truncation){case"major":version2.minor=0,version2.patch=0;break;case"minor":version2.patch=0;break}return version2.format()},isPrerelease=type=>type.startsWith("pre");module.exports=truncate3}});var require_lrucache=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/internal/lrucache.js"(exports,module){"use strict";var LRUCache=class{constructor(){this.max=1e3,this.map=new Map}get(key){let value=this.map.get(key);if(value!==void 0)return this.map.delete(key),this.map.set(key,value),value}delete(key){return this.map.delete(key)}set(key,value){if(!this.delete(key)&&value!==void 0){if(this.map.size>=this.max){let firstKey=this.map.keys().next().value;this.delete(firstKey)}this.map.set(key,value)}return this}};module.exports=LRUCache}});var require_range=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/classes/range.js"(exports,module){"use strict";var SPACE_CHARACTERS=/\s+/g,Range=class _Range{constructor(range2,options){if(options=parseOptions(options),range2 instanceof _Range)return range2.loose===!!options.loose&&range2.includePrerelease===!!options.includePrerelease?range2:new _Range(range2.raw,options);if(range2 instanceof Comparator)return this.raw=range2.value,this.set=[[range2]],this.formatted=void 0,this;if(this.options=options,this.loose=!!options.loose,this.includePrerelease=!!options.includePrerelease,this.raw=range2.trim().replace(SPACE_CHARACTERS," "),this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(c=>c.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let first=this.set[0];if(this.set=this.set.filter(c=>!isNullSet(c[0])),this.set.length===0)this.set=[first];else if(this.set.length>1){for(let c of this.set)if(c.length===1&&isAny(c[0])){this.set=[c];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let i=0;i<this.set.length;i++){i>0&&(this.formatted+="||");let comps=this.set[i];for(let k=0;k<comps.length;k++)k>0&&(this.formatted+=" "),this.formatted+=comps[k].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(range2){range2=range2.replace(BUILDSTRIPRE,"");let memoKey=((this.options.includePrerelease&&FLAG_INCLUDE_PRERELEASE)|(this.options.loose&&FLAG_LOOSE))+":"+range2,cached=cache2.get(memoKey);if(cached)return cached;let loose=this.options.loose,hr=loose?re[t.HYPHENRANGELOOSE]:re[t.HYPHENRANGE];range2=range2.replace(hr,hyphenReplace(this.options.includePrerelease)),debug("hyphen replace",range2),range2=range2.replace(re[t.COMPARATORTRIM],comparatorTrimReplace),debug("comparator trim",range2),range2=range2.replace(re[t.TILDETRIM],tildeTrimReplace),debug("tilde trim",range2),range2=range2.replace(re[t.CARETTRIM],caretTrimReplace),debug("caret trim",range2);let rangeList=range2.split(" ").map(comp=>parseComparator(comp,this.options)).join(" ").split(/\s+/).map(comp=>replaceGTE0(comp,this.options));loose&&(rangeList=rangeList.filter(comp=>(debug("loose invalid filter",comp,this.options),!!comp.match(re[t.COMPARATORLOOSE])))),debug("range list",rangeList);let rangeMap=new Map,comparators=rangeList.map(comp=>new Comparator(comp,this.options));for(let comp of comparators){if(isNullSet(comp))return[comp];rangeMap.set(comp.value,comp)}rangeMap.size>1&&rangeMap.has("")&&rangeMap.delete("");let result=[...rangeMap.values()];return cache2.set(memoKey,result),result}intersects(range2,options){if(!(range2 instanceof _Range))throw new TypeError("a Range is required");return this.set.some(thisComparators=>isSatisfiable(thisComparators,options)&&range2.set.some(rangeComparators=>isSatisfiable(rangeComparators,options)&&thisComparators.every(thisComparator=>rangeComparators.every(rangeComparator=>thisComparator.intersects(rangeComparator,options)))))}test(version2){if(!version2)return!1;if(typeof version2=="string")try{version2=new SemVer(version2,this.options)}catch{return!1}for(let i=0;i<this.set.length;i++)if(testSet(this.set[i],version2,this.options))return!0;return!1}};module.exports=Range;var LRU=require_lrucache(),cache2=new LRU,parseOptions=require_parse_options(),Comparator=require_comparator(),debug=require_debug(),SemVer=require_semver(),{safeRe:re,src,t,comparatorTrimReplace,tildeTrimReplace,caretTrimReplace}=require_re(),{FLAG_INCLUDE_PRERELEASE,FLAG_LOOSE}=require_constants(),BUILDSTRIPRE=new RegExp(src[t.BUILD],"g"),isNullSet=c=>c.value==="<0.0.0-0",isAny=c=>c.value==="",isSatisfiable=(comparators,options)=>{let result=!0,remainingComparators=comparators.slice(),testComparator=remainingComparators.pop();for(;result&&remainingComparators.length;)result=remainingComparators.every(otherComparator=>testComparator.intersects(otherComparator,options)),testComparator=remainingComparators.pop();return result},parseComparator=(comp,options)=>(comp=comp.replace(re[t.BUILD],""),debug("comp",comp,options),comp=replaceCarets(comp,options),debug("caret",comp),comp=replaceTildes(comp,options),debug("tildes",comp),comp=replaceXRanges(comp,options),debug("xrange",comp),comp=replaceStars(comp,options),debug("stars",comp),comp),isX=id=>!id||id.toLowerCase()==="x"||id==="*",invalidXRangeOrder=(M,m,p)=>isX(M)&&!isX(m)||isX(m)&&p&&!isX(p),replaceTildes=(comp,options)=>comp.trim().split(/\s+/).map(c=>replaceTilde(c,options)).join(" "),replaceTilde=(comp,options)=>{let r=options.loose?re[t.TILDELOOSE]:re[t.TILDE],z=options.includePrerelease?"-0":"";return comp.replace(r,(_,M,m,p,pr)=>{debug("tilde",comp,_,M,m,p,pr);let ret;return isX(M)?ret="":isX(m)?ret=`>=${M}.0.0${z} <${+M+1}.0.0-0`:isX(p)?ret=`>=${M}.${m}.0${z} <${M}.${+m+1}.0-0`:pr?(debug("replaceTilde pr",pr),ret=`>=${M}.${m}.${p}-${pr} <${M}.${+m+1}.0-0`):ret=`>=${M}.${m}.${p} <${M}.${+m+1}.0-0`,debug("tilde return",ret),ret})},replaceCarets=(comp,options)=>comp.trim().split(/\s+/).map(c=>replaceCaret(c,options)).join(" "),replaceCaret=(comp,options)=>{debug("caret",comp,options);let r=options.loose?re[t.CARETLOOSE]:re[t.CARET],z=options.includePrerelease?"-0":"";return comp.replace(r,(_,M,m,p,pr)=>{debug("caret",comp,_,M,m,p,pr);let ret;return isX(M)?ret="":isX(m)?ret=`>=${M}.0.0${z} <${+M+1}.0.0-0`:isX(p)?M==="0"?ret=`>=${M}.${m}.0${z} <${M}.${+m+1}.0-0`:ret=`>=${M}.${m}.0${z} <${+M+1}.0.0-0`:pr?(debug("replaceCaret pr",pr),M==="0"?m==="0"?ret=`>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p+1}-0`:ret=`>=${M}.${m}.${p}-${pr} <${M}.${+m+1}.0-0`:ret=`>=${M}.${m}.${p}-${pr} <${+M+1}.0.0-0`):(debug("no pr"),M==="0"?m==="0"?ret=`>=${M}.${m}.${p} <${M}.${m}.${+p+1}-0`:ret=`>=${M}.${m}.${p} <${M}.${+m+1}.0-0`:ret=`>=${M}.${m}.${p} <${+M+1}.0.0-0`),debug("caret return",ret),ret})},replaceXRanges=(comp,options)=>(debug("replaceXRanges",comp,options),comp.split(/\s+/).map(c=>replaceXRange(c,options)).join(" ")),replaceXRange=(comp,options)=>{comp=comp.trim();let r=options.loose?re[t.XRANGELOOSE]:re[t.XRANGE];return comp.replace(r,(ret,gtlt,M,m,p,pr)=>{if(debug("xRange",comp,ret,gtlt,M,m,p,pr),invalidXRangeOrder(M,m,p))return comp;let xM=isX(M),xm=xM||isX(m),xp=xm||isX(p),anyX=xp;return gtlt==="="&&anyX&&(gtlt=""),pr=options.includePrerelease?"-0":"",xM?gtlt===">"||gtlt==="<"?ret="<0.0.0-0":ret="*":gtlt&&anyX?(xm&&(m=0),p=0,gtlt===">"?(gtlt=">=",xm?(M=+M+1,m=0,p=0):(m=+m+1,p=0)):gtlt==="<="&&(gtlt="<",xm?M=+M+1:m=+m+1),gtlt==="<"&&(pr="-0"),ret=`${gtlt+M}.${m}.${p}${pr}`):xm?ret=`>=${M}.0.0${pr} <${+M+1}.0.0-0`:xp&&(ret=`>=${M}.${m}.0${pr} <${M}.${+m+1}.0-0`),debug("xRange return",ret),ret})},replaceStars=(comp,options)=>(debug("replaceStars",comp,options),comp.trim().replace(re[t.STAR],"")),replaceGTE0=(comp,options)=>(debug("replaceGTE0",comp,options),comp.trim().replace(re[options.includePrerelease?t.GTE0PRE:t.GTE0],"")),hyphenReplace=incPr=>($0,from,fM,fm,fp,fpr,fb,to,tM,tm,tp,tpr)=>(isX(fM)?from="":isX(fm)?from=`>=${fM}.0.0${incPr?"-0":""}`:isX(fp)?from=`>=${fM}.${fm}.0${incPr?"-0":""}`:fpr?from=`>=${from}`:from=`>=${from}${incPr?"-0":""}`,isX(tM)?to="":isX(tm)?to=`<${+tM+1}.0.0-0`:isX(tp)?to=`<${tM}.${+tm+1}.0-0`:tpr?to=`<=${tM}.${tm}.${tp}-${tpr}`:incPr?to=`<${tM}.${tm}.${+tp+1}-0`:to=`<=${to}`,`${from} ${to}`.trim()),testSet=(set,version2,options)=>{for(let i=0;i<set.length;i++)if(!set[i].test(version2))return!1;if(version2.prerelease.length&&!options.includePrerelease){for(let i=0;i<set.length;i++)if(debug(set[i].semver),set[i].semver!==Comparator.ANY&&set[i].semver.prerelease.length>0){let allowed=set[i].semver;if(allowed.major===version2.major&&allowed.minor===version2.minor&&allowed.patch===version2.patch)return!0}return!1}return!0}}});var require_comparator=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/classes/comparator.js"(exports,module){"use strict";var ANY=Symbol("SemVer ANY"),Comparator=class _Comparator{static get ANY(){return ANY}constructor(comp,options){if(options=parseOptions(options),comp instanceof _Comparator){if(comp.loose===!!options.loose)return comp;comp=comp.value}comp=comp.trim().split(/\s+/).join(" "),debug("comparator",comp,options),this.options=options,this.loose=!!options.loose,this.parse(comp),this.semver===ANY?this.value="":this.value=this.operator+this.semver.version,debug("comp",this)}parse(comp){let r=this.options.loose?re[t.COMPARATORLOOSE]:re[t.COMPARATOR],m=comp.match(r);if(!m)throw new TypeError(`Invalid comparator: ${comp}`);this.operator=m[1]!==void 0?m[1]:"",this.operator==="="&&(this.operator=""),m[2]?this.semver=new SemVer(m[2],this.options.loose):this.semver=ANY}toString(){return this.value}test(version2){if(debug("Comparator.test",version2,this.options.loose),this.semver===ANY||version2===ANY)return!0;if(typeof version2=="string")try{version2=new SemVer(version2,this.options)}catch{return!1}return cmp(version2,this.operator,this.semver,this.options)}intersects(comp,options){if(!(comp instanceof _Comparator))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Range(comp.value,options).test(this.value):comp.operator===""?comp.value===""?!0:new Range(this.value,options).test(comp.semver):(options=parseOptions(options),options.includePrerelease&&(this.value==="<0.0.0-0"||comp.value==="<0.0.0-0")||!options.includePrerelease&&(this.value.startsWith("<0.0.0")||comp.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&comp.operator.startsWith(">")||this.operator.startsWith("<")&&comp.operator.startsWith("<")||this.semver.version===comp.semver.version&&this.operator.includes("=")&&comp.operator.includes("=")||cmp(this.semver,"<",comp.semver,options)&&this.operator.startsWith(">")&&comp.operator.startsWith("<")||cmp(this.semver,">",comp.semver,options)&&this.operator.startsWith("<")&&comp.operator.startsWith(">")))}};module.exports=Comparator;var parseOptions=require_parse_options(),{safeRe:re,t}=require_re(),cmp=require_cmp(),debug=require_debug(),SemVer=require_semver(),Range=require_range()}});var require_satisfies=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/functions/satisfies.js"(exports,module){"use strict";var Range=require_range(),satisfies2=(version2,range2,options)=>{try{range2=new Range(range2,options)}catch{return!1}return range2.test(version2)};module.exports=satisfies2}});var require_to_comparators=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/to-comparators.js"(exports,module){"use strict";var Range=require_range(),toComparators=(range2,options)=>new Range(range2,options).set.map(comp=>comp.map(c=>c.value).join(" ").trim().split(" "));module.exports=toComparators}});var require_max_satisfying=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js"(exports,module){"use strict";var SemVer=require_semver(),Range=require_range(),maxSatisfying2=(versions,range2,options)=>{let max=null,maxSV=null,rangeObj=null;try{rangeObj=new Range(range2,options)}catch{return null}return versions.forEach(v=>{rangeObj.test(v)&&(!max||maxSV.compare(v)===-1)&&(max=v,maxSV=new SemVer(max,options))}),max};module.exports=maxSatisfying2}});var require_min_satisfying=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js"(exports,module){"use strict";var SemVer=require_semver(),Range=require_range(),minSatisfying=(versions,range2,options)=>{let min=null,minSV=null,rangeObj=null;try{rangeObj=new Range(range2,options)}catch{return null}return versions.forEach(v=>{rangeObj.test(v)&&(!min||minSV.compare(v)===1)&&(min=v,minSV=new SemVer(min,options))}),min};module.exports=minSatisfying}});var require_min_version=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/min-version.js"(exports,module){"use strict";var SemVer=require_semver(),Range=require_range(),gt2=require_gt(),minVersion=(range2,loose)=>{range2=new Range(range2,loose);let minver=new SemVer("0.0.0");if(range2.test(minver)||(minver=new SemVer("0.0.0-0"),range2.test(minver)))return minver;minver=null;for(let i=0;i<range2.set.length;++i){let comparators=range2.set[i],setMin=null;comparators.forEach(comparator=>{let compver=new SemVer(comparator.semver.version);switch(comparator.operator){case">":compver.prerelease.length===0?compver.patch++:compver.prerelease.push(0),compver.raw=compver.format();case"":case">=":(!setMin||gt2(compver,setMin))&&(setMin=compver);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${comparator.operator}`)}}),setMin&&(!minver||gt2(minver,setMin))&&(minver=setMin)}return minver&&range2.test(minver)?minver:null};module.exports=minVersion}});var require_valid2=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/valid.js"(exports,module){"use strict";var Range=require_range(),validRange2=(range2,options)=>{try{return new Range(range2,options).range||"*"}catch{return null}};module.exports=validRange2}});var require_outside=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/outside.js"(exports,module){"use strict";var SemVer=require_semver(),Comparator=require_comparator(),{ANY}=Comparator,Range=require_range(),satisfies2=require_satisfies(),gt2=require_gt(),lt=require_lt(),lte2=require_lte(),gte2=require_gte(),outside=(version2,range2,hilo,options)=>{version2=new SemVer(version2,options),range2=new Range(range2,options);let gtfn,ltefn,ltfn,comp,ecomp;switch(hilo){case">":gtfn=gt2,ltefn=lte2,ltfn=lt,comp=">",ecomp=">=";break;case"<":gtfn=lt,ltefn=gte2,ltfn=gt2,comp="<",ecomp="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(satisfies2(version2,range2,options))return!1;for(let i=0;i<range2.set.length;++i){let comparators=range2.set[i],high=null,low=null;if(comparators.forEach(comparator=>{comparator.semver===ANY&&(comparator=new Comparator(">=0.0.0")),high=high||comparator,low=low||comparator,gtfn(comparator.semver,high.semver,options)?high=comparator:ltfn(comparator.semver,low.semver,options)&&(low=comparator)}),high.operator===comp||high.operator===ecomp||(!low.operator||low.operator===comp)&<efn(version2,low.semver))return!1;if(low.operator===ecomp&<fn(version2,low.semver))return!1}return!0};module.exports=outside}});var require_gtr=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/gtr.js"(exports,module){"use strict";var outside=require_outside(),gtr=(version2,range2,options)=>outside(version2,range2,">",options);module.exports=gtr}});var require_ltr=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/ltr.js"(exports,module){"use strict";var outside=require_outside(),ltr=(version2,range2,options)=>outside(version2,range2,"<",options);module.exports=ltr}});var require_intersects=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/intersects.js"(exports,module){"use strict";var Range=require_range(),intersects=(r1,r2,options)=>(r1=new Range(r1,options),r2=new Range(r2,options),r1.intersects(r2,options));module.exports=intersects}});var require_simplify=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/simplify.js"(exports,module){"use strict";var satisfies2=require_satisfies(),compare2=require_compare();module.exports=(versions,range2,options)=>{let set=[],first=null,prev=null,v=versions.sort((a,b)=>compare2(a,b,options));for(let version2 of v)satisfies2(version2,range2,options)?(prev=version2,first||(first=version2)):(prev&&set.push([first,prev]),prev=null,first=null);first&&set.push([first,null]);let ranges=[];for(let[min,max]of set)min===max?ranges.push(min):!max&&min===v[0]?ranges.push("*"):max?min===v[0]?ranges.push(`<=${max}`):ranges.push(`${min} - ${max}`):ranges.push(`>=${min}`);let simplified=ranges.join(" || "),original=typeof range2.raw=="string"?range2.raw:String(range2);return simplified.length<original.length?simplified:range2}}});var require_subset=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/ranges/subset.js"(exports,module){"use strict";var Range=require_range(),Comparator=require_comparator(),{ANY}=Comparator,satisfies2=require_satisfies(),compare2=require_compare(),subset=(sub,dom,options={})=>{if(sub===dom)return!0;sub=new Range(sub,options),dom=new Range(dom,options);let sawNonNull=!1;OUTER:for(let simpleSub of sub.set){for(let simpleDom of dom.set){let isSub=simpleSubset(simpleSub,simpleDom,options);if(sawNonNull=sawNonNull||isSub!==null,isSub)continue OUTER}if(sawNonNull)return!1}return!0},minimumVersionWithPreRelease=[new Comparator(">=0.0.0-0")],minimumVersion=[new Comparator(">=0.0.0")],simpleSubset=(sub,dom,options)=>{if(sub===dom)return!0;if(sub.length===1&&sub[0].semver===ANY){if(dom.length===1&&dom[0].semver===ANY)return!0;options.includePrerelease?sub=minimumVersionWithPreRelease:sub=minimumVersion}if(dom.length===1&&dom[0].semver===ANY){if(options.includePrerelease)return!0;dom=minimumVersion}let eqSet=new Set,gt2,lt;for(let c of sub)c.operator===">"||c.operator===">="?gt2=higherGT(gt2,c,options):c.operator==="<"||c.operator==="<="?lt=lowerLT(lt,c,options):eqSet.add(c.semver);if(eqSet.size>1)return null;let gtltComp;if(gt2&<){if(gtltComp=compare2(gt2.semver,lt.semver,options),gtltComp>0)return null;if(gtltComp===0&&(gt2.operator!==">="||lt.operator!=="<="))return null}for(let eq of eqSet){if(gt2&&!satisfies2(eq,String(gt2),options)||lt&&!satisfies2(eq,String(lt),options))return null;for(let c of dom)if(!satisfies2(eq,String(c),options))return!1;return!0}let higher,lower,hasDomLT,hasDomGT,needDomLTPre=lt&&!options.includePrerelease&<.semver.prerelease.length?lt.semver:!1,needDomGTPre=gt2&&!options.includePrerelease&>2.semver.prerelease.length?gt2.semver:!1;needDomLTPre&&needDomLTPre.prerelease.length===1&<.operator==="<"&&needDomLTPre.prerelease[0]===0&&(needDomLTPre=!1);for(let c of dom){if(hasDomGT=hasDomGT||c.operator===">"||c.operator===">=",hasDomLT=hasDomLT||c.operator==="<"||c.operator==="<=",gt2){if(needDomGTPre&&c.semver.prerelease&&c.semver.prerelease.length&&c.semver.major===needDomGTPre.major&&c.semver.minor===needDomGTPre.minor&&c.semver.patch===needDomGTPre.patch&&(needDomGTPre=!1),c.operator===">"||c.operator===">="){if(higher=higherGT(gt2,c,options),higher===c&&higher!==gt2)return!1}else if(gt2.operator===">="&&!c.test(gt2.semver))return!1}if(lt){if(needDomLTPre&&c.semver.prerelease&&c.semver.prerelease.length&&c.semver.major===needDomLTPre.major&&c.semver.minor===needDomLTPre.minor&&c.semver.patch===needDomLTPre.patch&&(needDomLTPre=!1),c.operator==="<"||c.operator==="<="){if(lower=lowerLT(lt,c,options),lower===c&&lower!==lt)return!1}else if(lt.operator==="<="&&!c.test(lt.semver))return!1}if(!c.operator&&(lt||gt2)&>ltComp!==0)return!1}return!(gt2&&hasDomLT&&!lt&>ltComp!==0||lt&&hasDomGT&&!gt2&>ltComp!==0||needDomGTPre||needDomLTPre)},higherGT=(a,b,options)=>{if(!a)return b;let comp=compare2(a.semver,b.semver,options);return comp>0?a:comp<0||b.operator===">"&&a.operator===">="?b:a},lowerLT=(a,b,options)=>{if(!a)return b;let comp=compare2(a.semver,b.semver,options);return comp<0?a:comp>0||b.operator==="<"&&a.operator==="<="?b:a};module.exports=subset}});var require_semver2=__commonJS({"node_modules/.bun/semver@7.8.5/node_modules/semver/index.js"(exports,module){"use strict";var internalRe=require_re(),constants9=require_constants(),SemVer=require_semver(),identifiers=require_identifiers(),parse4=require_parse(),valid3=require_valid(),clean2=require_clean(),inc=require_inc(),diff=require_diff(),major=require_major(),minor=require_minor(),patch=require_patch(),prerelease=require_prerelease(),compare2=require_compare(),rcompare2=require_rcompare(),compareLoose=require_compare_loose(),compareBuild=require_compare_build(),sort=require_sort(),rsort=require_rsort(),gt2=require_gt(),lt=require_lt(),eq=require_eq(),neq=require_neq(),gte2=require_gte(),lte2=require_lte(),cmp=require_cmp(),coerce=require_coerce(),truncate3=require_truncate(),Comparator=require_comparator(),Range=require_range(),satisfies2=require_satisfies(),toComparators=require_to_comparators(),maxSatisfying2=require_max_satisfying(),minSatisfying=require_min_satisfying(),minVersion=require_min_version(),validRange2=require_valid2(),outside=require_outside(),gtr=require_gtr(),ltr=require_ltr(),intersects=require_intersects(),simplifyRange=require_simplify(),subset=require_subset();module.exports={parse:parse4,valid:valid3,clean:clean2,inc,diff,major,minor,patch,prerelease,compare:compare2,rcompare:rcompare2,compareLoose,compareBuild,sort,rsort,gt:gt2,lt,eq,neq,gte:gte2,lte:lte2,cmp,coerce,truncate:truncate3,Comparator,Range,satisfies:satisfies2,toComparators,maxSatisfying:maxSatisfying2,minSatisfying,minVersion,validRange:validRange2,outside,gtr,ltr,intersects,simplifyRange,subset,SemVer,re:internalRe.re,src:internalRe.src,tokens:internalRe.t,SEMVER_SPEC_VERSION:constants9.SEMVER_SPEC_VERSION,RELEASE_TYPES:constants9.RELEASE_TYPES,compareIdentifiers:identifiers.compareIdentifiers,rcompareIdentifiers:identifiers.rcompareIdentifiers}}});var require_index_min=__commonJS({"node_modules/.bun/lru-cache@11.2.6/node_modules/lru-cache/dist/commonjs/index.min.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var x=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,U2=new Set,R2=typeof process=="object"&&process?process:{},I=(a,t,e,i)=>{typeof R2.emitWarning=="function"?R2.emitWarning(a,t,e,i):console.error(`[${e}] ${t}: ${a}`)},C=globalThis.AbortController,L2=globalThis.AbortSignal;if(typeof C>"u"){L2=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,s){this._onabort.push(s)}},C=class{constructor(){t()}signal=new L2;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i)}}};let a=R2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{a&&(a=!1,I("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var G=a=>!U2.has(a),y=a=>a&&a===Math.floor(a)&&a>0&&isFinite(a),M=a=>y(a)?a<=Math.pow(2,8)?Uint8Array:a<=Math.pow(2,16)?Uint16Array:a<=Math.pow(2,32)?Uint32Array:a<=Number.MAX_SAFE_INTEGER?z:null:null,z=class extends Array{constructor(t){super(t),this.fill(0)}},W=class a{heap;length;static#o=!1;static create(t){let e=M(t);if(!e)return[];a.#o=!0;let i=new a(t,e);return a.#o=!1,i}constructor(t,e){if(!a.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},D2=class a{#o;#c;#w;#C;#S;#L;#U;#m;get perf(){return this.#m}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#_;#s;#i;#t;#a;#u;#l;#h;#b;#r;#y;#A;#d;#g;#T;#v;#f;#I;static unsafeExposeInternals(t){return{starts:t.#A,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#a,prev:t.#u,get head(){return t.#l},get tail(){return t.#h},free:t.#b,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,h)=>t.#G(e,i,s,h),moveToTail:e=>t.#D(e),indexes:e=>t.#F(e),rindexes:e=>t.#O(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#_}get size(){return this.#n}get fetchMethod(){return this.#L}get memoMethod(){return this.#U}get dispose(){return this.#w}get onInsert(){return this.#C}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:h,updateAgeOnGet:n,updateAgeOnHas:o,allowStale:r,dispose:f,onInsert:m,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:g,maxSize:A=0,maxEntrySize:p=0,sizeCalculation:_,fetchMethod:l,memoMethod:w,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:T,ignoreFetchAbort:F,perf:v}=t;if(v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#m=v??x,e!==0&&!y(e))throw new TypeError("max option must be a nonnegative integer");let O=e?M(e):Array;if(!O)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=A,this.maxEntrySize=p||this.#c,this.sizeCalculation=_,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#U=w,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#L=l,this.#v=!!l,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#a=new O(e),this.#u=new O(e),this.#l=0,this.#h=0,this.#b=W.create(e),this.#n=0,this.#_=0,typeof f=="function"&&(this.#w=f),typeof m=="function"&&(this.#C=m),typeof c=="function"?(this.#S=c,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#w,this.#I=!!this.#C,this.#f=!!this.#S,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!u,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(this.#c!==0&&!y(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!y(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!n,this.updateAgeOnHas=!!o,this.ttlResolution=y(s)||s===0?s:1,this.ttlAutopurge=!!h,this.ttl=i||0,this.ttl){if(!y(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let E="LRU_CACHE_UNBOUNDED";G(E)&&(U2.add(E),I("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",E,a))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#j(){let t=new z(this.#o),e=new z(this.#o);this.#d=t,this.#A=e;let i=this.ttlAutopurge?new Array(this.#o):void 0;this.#g=i,this.#N=(n,o,r=this.#m.now())=>{if(e[n]=o!==0?r:0,t[n]=o,i?.[n]&&(clearTimeout(i[n]),i[n]=void 0),o!==0&&i){let f=setTimeout(()=>{this.#p(n)&&this.#E(this.#i[n],"expire")},o+1);f.unref&&f.unref(),i[n]=f}},this.#R=n=>{e[n]=t[n]!==0?this.#m.now():0},this.#z=(n,o)=>{if(t[o]){let r=t[o],f=e[o];if(!r||!f)return;n.ttl=r,n.start=f,n.now=s||h();let m=n.now-f;n.remainingTTL=r-m}};let s=0,h=()=>{let n=this.#m.now();if(this.ttlResolution>0){s=n;let o=setTimeout(()=>s=0,this.ttlResolution);o.unref&&o.unref()}return n};this.getRemainingTTL=n=>{let o=this.#s.get(n);if(o===void 0)return 0;let r=t[o],f=e[o];if(!r||!f)return 1/0;let m=(s||h())-f;return r-m},this.#p=n=>{let o=e[n],r=t[n];return!!r&&!!o&&(s||h())-o>r}}#R=()=>{};#z=()=>{};#N=()=>{};#p=()=>!1;#B(){let t=new z(this.#o);this.#_=0,this.#y=t,this.#W=e=>{this.#_-=t[e],t[e]=0},this.#P=(e,i,s,h)=>{if(this.#e(i))return 0;if(!y(s))if(h){if(typeof h!="function")throw new TypeError("sizeCalculation must be a function");if(s=h(i,e),!y(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#M=(e,i,s)=>{if(t[e]=i,this.#c){let h=this.#c-t[e];for(;this.#_>h;)this.#x(!0)}this.#_+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#_)}}#W=t=>{};#M=(t,e,i)=>{};#P=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#F({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;!(!this.#H(e)||((t||!this.#p(e))&&(yield e),e===this.#l));)e=this.#u[e]}*#O({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#l;!(!this.#H(e)||((t||!this.#p(e))&&(yield e),e===this.#h));)e=this.#a[e]}#H(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#F())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#O())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#F()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#O()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#F())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#O())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#F()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;if(h!==void 0&&t(h,this.#i[i],this))return this.get(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#F()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;h!==void 0&&t.call(e,h,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#O()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;h!==void 0&&t.call(e,h,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#O({allowStale:!0}))this.#p(e)&&(this.#E(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let h={value:s};if(this.#d&&this.#A){let n=this.#d[e],o=this.#A[e];if(n&&o){let r=n-(this.#m.now()-o);h.ttl=r,h.start=Date.now()}}return this.#y&&(h.size=this.#y[e]),h}dump(){let t=[];for(let e of this.#F({allowStale:!0})){let i=this.#i[e],s=this.#t[e],h=this.#e(s)?s.__staleWhileFetching:s;if(h===void 0||i===void 0)continue;let n={value:h};if(this.#d&&this.#A){n.ttl=this.#d[e];let o=this.#m.now()-this.#A[e];n.start=Math.floor(Date.now()-o)}this.#y&&(n.size=this.#y[e]),t.unshift([i,n])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#m.now()-s}this.set(e,i.value,i)}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:h,noDisposeOnSet:n=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:r}=i,{noUpdateTTL:f=this.noUpdateTTL}=i,m=this.#P(t,e,i.size||0,o);if(this.maxEntrySize&&m>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.#E(t,"set"),this;let c=this.#n===0?void 0:this.#s.get(t);if(c===void 0)c=this.#n===0?this.#h:this.#b.length!==0?this.#b.pop():this.#n===this.#o?this.#x(!1):this.#n,this.#i[c]=t,this.#t[c]=e,this.#s.set(t,c),this.#a[this.#h]=c,this.#u[c]=this.#h,this.#h=c,this.#n++,this.#M(c,m,r),r&&(r.set="add"),f=!1,this.#I&&this.#C?.(e,t,"add");else{this.#D(c);let d=this.#t[c];if(e!==d){if(this.#v&&this.#e(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:g}=d;g!==void 0&&!n&&(this.#T&&this.#w?.(g,t,"set"),this.#f&&this.#r?.push([g,t,"set"]))}else n||(this.#T&&this.#w?.(d,t,"set"),this.#f&&this.#r?.push([d,t,"set"]));if(this.#W(c),this.#M(c,m,r),this.#t[c]=e,r){r.set="replace";let g=d&&this.#e(d)?d.__staleWhileFetching:d;g!==void 0&&(r.oldValue=g)}}else r&&(r.set="update");this.#I&&this.onInsert?.(e,t,e===d?"update":"replace")}if(s!==0&&!this.#d&&this.#j(),this.#d&&(f||this.#N(c,s,h),r&&this.#z(r,c)),!n&&this.#f&&this.#r){let d=this.#r,g;for(;g=d?.shift();)this.#S?.(...g)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#l];if(this.#x(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#x(t){let e=this.#l,i=this.#i[e],s=this.#t[e];return this.#v&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#T||this.#f)&&(this.#T&&this.#w?.(s,i,"evict"),this.#f&&this.#r?.push([s,i,"evict"])),this.#W(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#b.push(e)),this.#n===1?(this.#l=this.#h=0,this.#b.length=0):this.#l=this.#a[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,h=this.#s.get(t);if(h!==void 0){let n=this.#t[h];if(this.#e(n)&&n.__staleWhileFetching===void 0)return!1;if(this.#p(h))s&&(s.has="stale",this.#z(s,h));else return i&&this.#R(h),s&&(s.has="hit",this.#z(s,h)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,s=this.#s.get(t);if(s===void 0||!i&&this.#p(s))return;let h=this.#t[s];return this.#e(h)?h.__staleWhileFetching:h}#G(t,e,i,s){let h=e===void 0?void 0:this.#t[e];if(this.#e(h))return h;let n=new C,{signal:o}=i;o?.addEventListener("abort",()=>n.abort(o.reason),{signal:n.signal});let r={signal:n.signal,options:i,context:s},f=(p,_=!1)=>{let{aborted:l}=n.signal,w=i.ignoreFetchAbort&&p!==void 0,b=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&p!==void 0);if(i.status&&(l&&!_?(i.status.fetchAborted=!0,i.status.fetchError=n.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),l&&!w&&!_)return c(n.signal.reason,b);let S=g,u=this.#t[e];return(u===g||w&&_&&u===void 0)&&(p===void 0?S.__staleWhileFetching!==void 0?this.#t[e]=S.__staleWhileFetching:this.#E(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,p,r.options))),p},m=p=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=p),c(p,!1)),c=(p,_)=>{let{aborted:l}=n.signal,w=l&&i.allowStaleOnFetchAbort,b=w||i.allowStaleOnFetchRejection,S=b||i.noDeleteOnFetchRejection,u=g;if(this.#t[e]===g&&(!S||!_&&u.__staleWhileFetching===void 0?this.#E(t,"fetch"):w||(this.#t[e]=u.__staleWhileFetching)),b)return i.status&&u.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw p},d=(p,_)=>{let l=this.#L?.(t,h,r);l&&l instanceof Promise&&l.then(w=>p(w===void 0?void 0:w),_),n.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(p(void 0),i.allowStaleOnFetchAbort&&(p=w=>f(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let g=new Promise(d).then(f,m),A=Object.assign(g,{__abortController:n,__staleWhileFetching:h,__returned:void 0});return e===void 0?(this.set(t,A,{...r.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=A,A}#e(t){if(!this.#v)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof C}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:h=this.noDeleteOnStaleGet,ttl:n=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:r=0,sizeCalculation:f=this.sizeCalculation,noUpdateTTL:m=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:p,forceRefresh:_=!1,status:l,signal:w}=e;if(!this.#v)return l&&(l.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:h,status:l});let b={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:h,ttl:n,noDisposeOnSet:o,size:r,sizeCalculation:f,noUpdateTTL:m,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:A,ignoreFetchAbort:g,status:l,signal:w},S=this.#s.get(t);if(S===void 0){l&&(l.fetch="miss");let u=this.#G(t,S,b,p);return u.__returned=u}else{let u=this.#t[S];if(this.#e(u)){let E=i&&u.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",E&&(l.returnedStale=!0)),E?u.__staleWhileFetching:u.__returned=u}let T=this.#p(S);if(!_&&!T)return l&&(l.fetch="hit"),this.#D(S),s&&this.#R(S),l&&this.#z(l,S),u;let F=this.#G(t,S,b,p),O=F.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=T?"stale":"refresh",O&&T&&(l.returnedStale=!0)),O?F.__staleWhileFetching:F.__returned=F}}async forceFetch(t,e={}){let i=await this.fetch(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let i=this.#U;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:h,...n}=e,o=this.get(t,n);if(!h&&o!==void 0)return o;let r=i(t,o,{options:n,context:s});return this.set(t,r,n),r}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:h=this.noDeleteOnStaleGet,status:n}=e,o=this.#s.get(t);if(o!==void 0){let r=this.#t[o],f=this.#e(r);return n&&this.#z(n,o),this.#p(o)?(n&&(n.get="stale"),f?(n&&i&&r.__staleWhileFetching!==void 0&&(n.returnedStale=!0),i?r.__staleWhileFetching:void 0):(h||this.#E(t,"expire"),n&&i&&(n.returnedStale=!0),i?r:void 0)):(n&&(n.get="hit"),f?r.__staleWhileFetching:(this.#D(o),s&&this.#R(o),r))}else n&&(n.get="miss")}#k(t,e){this.#u[e]=t,this.#a[t]=e}#D(t){t!==this.#h&&(t===this.#l?this.#l=this.#a[t]:this.#k(this.#u[t],this.#a[t]),this.#k(this.#h,t),this.#h=t)}delete(t){return this.#E(t,"delete")}#E(t,e){let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#V(e);else{this.#W(s);let h=this.#t[s];if(this.#e(h)?h.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#w?.(h,t,e),this.#f&&this.#r?.push([h,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#l)this.#l=this.#a[s];else{let n=this.#u[s];this.#a[n]=this.#a[s];let o=this.#a[s];this.#u[o]=this.#u[s]}this.#n--,this.#b.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,h;for(;h=s?.shift();)this.#S?.(...h)}return i}clear(){return this.#V("delete")}#V(t){for(let e of this.#O({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#T&&this.#w?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#A){this.#d.fill(0),this.#A.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#l=0,this.#h=0,this.#b.length=0,this.#_=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=D2}});var require_hosts=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/hosts.js"(exports,module){"use strict";var maybeJoin=(...args)=>args.every(arg=>arg)?args.join(""):"",maybeEncode=arg=>arg?encodeURIComponent(arg):"",formatHashFragment=f=>f.toLowerCase().replace(/^\W+/g,"").replace(/(?<!\W)\W+$/,"").replace(/\//g,"").replace(/\W+/g,"-"),defaults2={sshtemplate:({domain,user,project,committish})=>`git@${domain}:${user}/${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,user,project,committish})=>`git+ssh://git@${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath,path:path20})=>`https://${domain}/${user}/${project}${maybeJoin("/",editpath,"/",maybeEncode(committish||"HEAD"),"/",path20)}`,browsetemplate:({domain,user,project,committish,treepath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}`,browsetreetemplate:({domain,user,project,committish,treepath,path:path20,fragment,hashformat})=>`https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish||"HEAD")}/${path20}${maybeJoin("#",hashformat(fragment||""))}`,browseblobtemplate:({domain,user,project,committish,blobpath,path:path20,fragment,hashformat})=>`https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish||"HEAD")}/${path20}${maybeJoin("#",hashformat(fragment||""))}`,docstemplate:({domain,user,project,treepath,committish})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish))}#readme`,httpstemplate:({auth,domain,user,project,committish})=>`git+https://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({domain,user,project,committish,path:path20})=>`https://${domain}/${user}/${project}/raw/${maybeEncode(committish||"HEAD")}/${path20}`,shortcuttemplate:({type,user,project,committish})=>`${type}:${user}/${project}${maybeJoin("#",committish)}`,pathtemplate:({user,project,committish})=>`${user}/${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,user,project})=>`https://${domain}/${user}/${project}/issues`,hashformat:formatHashFragment},hosts={};hosts.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth,user,project,committish,path:path20})=>`https://${maybeJoin(auth,"@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish||"HEAD")}/${path20}`,gittemplate:({auth,domain,user,project,committish})=>`git://${maybeJoin(auth,"@")}${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,type,committish]=url.pathname.split("/",5);if(!(type&&type!=="tree")&&(type||(committish=url.hash.slice(1)),project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish}}};hosts.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain,user,project,committish,treepath,path:path20,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",treepath,"/",maybeEncode(committish||"HEAD"),"/",path20,editpath)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/get/${maybeEncode(committish||"HEAD")}.tar.gz`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["get"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};hosts.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish||"HEAD")}`,extract:url=>{let path20=url.pathname.slice(1);if(path20.includes("/-/")||path20.includes("/archive.tar.gz"))return;let segments=path20.split("/"),project=segments.pop();project.endsWith(".git")&&(project=project.slice(0,-4));let user=segments.join("/");if(!(!user||!project))return{user,project,committish:url.hash.slice(1)}}};hosts.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain,project,committish})=>`git@${domain}:${project}.git${maybeJoin("#",committish)}`,sshurltemplate:({domain,project,committish})=>`git+ssh://git@${domain}/${project}.git${maybeJoin("#",committish)}`,edittemplate:({domain,user,project,committish,editpath})=>`https://${domain}/${user}/${project}${maybeJoin("/",maybeEncode(committish))}/${editpath}`,browsetemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,browsetreetemplate:({domain,project,committish,path:path20,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path20))}`,browseblobtemplate:({domain,project,committish,path:path20,hashformat})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}${maybeJoin("#",hashformat(path20))}`,docstemplate:({domain,project,committish})=>`https://${domain}/${project}${maybeJoin("/",maybeEncode(committish))}`,httpstemplate:({domain,project,committish})=>`git+https://${domain}/${project}.git${maybeJoin("#",committish)}`,filetemplate:({user,project,committish,path:path20})=>`https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/",maybeEncode(committish))}/${path20}`,shortcuttemplate:({type,project,committish})=>`${type}:${project}${maybeJoin("#",committish)}`,pathtemplate:({project,committish})=>`${project}${maybeJoin("#",committish)}`,bugstemplate:({domain,project})=>`https://${domain}/${project}`,gittemplate:({domain,project,committish})=>`git://${domain}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({project,committish})=>`https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish||"HEAD")}`,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(aux!=="raw"){if(!project){if(!user)return;project=user,user=null}return project.endsWith(".git")&&(project=project.slice(0,-4)),{user,project,committish:url.hash.slice(1)}}},hashformat:function(fragment){return fragment&&"file-"+formatHashFragment(fragment)}};hosts.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain,user,project,committish,path:path20})=>`https://${domain}/${user}/${project}/blob/${maybeEncode(committish)||"HEAD"}/${path20}`,httpstemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}.git${maybeJoin("#",committish)}`,tarballtemplate:({domain,user,project,committish})=>`https://${domain}/${user}/${project}/archive/${maybeEncode(committish)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:url=>{let[,user,project,aux]=url.pathname.split("/",4);if(!["archive"].includes(aux)&&(project&&project.endsWith(".git")&&(project=project.slice(0,-4)),!(!user||!project)))return{user,project,committish:url.hash.slice(1)}}};for(let[name,host]of Object.entries(hosts))hosts[name]=Object.assign({},defaults2,host);module.exports=hosts}});var require_parse_url=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/parse-url.js"(exports,module){var url=__require("url"),lastIndexOfBefore=(str2,char,beforeChar)=>{let startPosition=str2.indexOf(beforeChar);return str2.lastIndexOf(char,startPosition>-1?startPosition:1/0)},safeUrl=u=>{try{return new url.URL(u)}catch{}},correctProtocol=(arg,protocols)=>{let firstColon=arg.indexOf(":"),proto=arg.slice(0,firstColon+1);if(Object.prototype.hasOwnProperty.call(protocols,proto)||arg.substr(firstColon,3)==="://")return arg;let firstAt=arg.indexOf("@");return firstAt>-1?firstAt>firstColon?`git+ssh://${arg}`:arg:`${arg.slice(0,firstColon+1)}//${arg.slice(firstColon+1)}`},correctUrl=giturl=>{let firstAt=lastIndexOfBefore(giturl,"@","#"),lastColonBeforeHash=lastIndexOfBefore(giturl,":","#");return lastColonBeforeHash>firstAt&&(giturl=giturl.slice(0,lastColonBeforeHash)+"/"+giturl.slice(lastColonBeforeHash+1)),lastIndexOfBefore(giturl,":","#")===-1&&giturl.indexOf("//")===-1&&(giturl=`git+ssh://${giturl}`),giturl};module.exports=(giturl,protocols)=>{let withProtocol=protocols?correctProtocol(giturl,protocols):giturl;return safeUrl(withProtocol)||safeUrl(correctUrl(withProtocol))}}});var require_from_url=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/from-url.js"(exports,module){"use strict";var parseUrl=require_parse_url(),isGitHubShorthand=arg=>{let firstHash=arg.indexOf("#"),firstSlash=arg.indexOf("/"),secondSlash=arg.indexOf("/",firstSlash+1),firstColon=arg.indexOf(":"),firstSpace=/\s/.exec(arg),firstAt=arg.indexOf("@"),spaceOnlyAfterHash=!firstSpace||firstHash>-1&&firstSpace.index>firstHash,atOnlyAfterHash=firstAt===-1||firstHash>-1&&firstAt>firstHash,colonOnlyAfterHash=firstColon===-1||firstHash>-1&&firstColon>firstHash,secondSlashOnlyAfterHash=secondSlash===-1||firstHash>-1&&secondSlash>firstHash,hasSlash=firstSlash>0,doesNotEndWithSlash=firstHash>-1?arg[firstHash-1]!=="/":!arg.endsWith("/"),doesNotStartWithDot=!arg.startsWith(".");return spaceOnlyAfterHash&&hasSlash&&doesNotEndWithSlash&&doesNotStartWithDot&&atOnlyAfterHash&&colonOnlyAfterHash&&secondSlashOnlyAfterHash};module.exports=(giturl,opts,{gitHosts,protocols})=>{if(!giturl)return;let correctedUrl=isGitHubShorthand(giturl)?`github:${giturl}`:giturl,parsed=parseUrl(correctedUrl,protocols);if(!parsed)return;let gitHostShortcut=gitHosts.byShortcut[parsed.protocol],gitHostDomain=gitHosts.byDomain[parsed.hostname.startsWith("www.")?parsed.hostname.slice(4):parsed.hostname],gitHostName=gitHostShortcut||gitHostDomain;if(!gitHostName)return;let gitHostInfo=gitHosts[gitHostShortcut||gitHostDomain],auth=null;protocols[parsed.protocol]?.auth&&(parsed.username||parsed.password)&&(auth=`${parsed.username}${parsed.password?":"+parsed.password:""}`);let committish=null,user=null,project=null,defaultRepresentation=null;try{if(gitHostShortcut){let pathname=parsed.pathname.startsWith("/")?parsed.pathname.slice(1):parsed.pathname,firstAt=pathname.indexOf("@");firstAt>-1&&(pathname=pathname.slice(firstAt+1));let lastSlash=pathname.lastIndexOf("/");lastSlash>-1?(user=decodeURIComponent(pathname.slice(0,lastSlash)),user||(user=null),project=decodeURIComponent(pathname.slice(lastSlash+1))):project=decodeURIComponent(pathname),project.endsWith(".git")&&(project=project.slice(0,-4)),parsed.hash&&(committish=decodeURIComponent(parsed.hash.slice(1))),defaultRepresentation="shortcut"}else{if(!gitHostInfo.protocols.includes(parsed.protocol))return;let segments=gitHostInfo.extract(parsed);if(!segments)return;user=segments.user&&decodeURIComponent(segments.user),project=decodeURIComponent(segments.project),committish=decodeURIComponent(segments.committish),defaultRepresentation=protocols[parsed.protocol]?.name||parsed.protocol.slice(0,-1)}}catch(err){if(err instanceof URIError)return;throw err}return[gitHostName,user,auth,project,committish,defaultRepresentation,opts]}}});var require_lib=__commonJS({"node_modules/.bun/hosted-git-info@9.0.2/node_modules/hosted-git-info/lib/index.js"(exports,module){"use strict";var{LRUCache}=require_index_min(),hosts=require_hosts(),fromUrl=require_from_url(),parseUrl=require_parse_url(),cache2=new LRUCache({max:1e3});function unknownHostedUrl(url){try{let{protocol,hostname,pathname}=new URL(url);if(!hostname)return null;let proto=/(?:git\+)http:$/.test(protocol)?"http:":"https:",path20=pathname.replace(/\.git$/,"");return`${proto}//${hostname}${path20}`}catch{return null}}var GitHost=class _GitHost{constructor(type,user,auth,project,committish,defaultRepresentation,opts={}){Object.assign(this,_GitHost.#gitHosts[type],{type,user,auth,project,committish,default:defaultRepresentation,opts})}static#gitHosts={byShortcut:{},byDomain:{}};static#protocols={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(name,host){_GitHost.#gitHosts[name]=host,_GitHost.#gitHosts.byDomain[host.domain]=name,_GitHost.#gitHosts.byShortcut[`${name}:`]=name,_GitHost.#protocols[`${name}:`]={name}}static fromUrl(giturl,opts){if(typeof giturl!="string")return;let key=giturl+JSON.stringify(opts||{});if(!cache2.has(key)){let hostArgs=fromUrl(giturl,opts,{gitHosts:_GitHost.#gitHosts,protocols:_GitHost.#protocols});cache2.set(key,hostArgs?new _GitHost(...hostArgs):void 0)}return cache2.get(key)}static fromManifest(manifest,opts={}){if(!manifest||typeof manifest!="object")return;let r=manifest.repository,rurl=r&&(typeof r=="string"?r:typeof r=="object"&&typeof r.url=="string"?r.url:null);if(!rurl)throw new Error("no repository");let info=rurl&&_GitHost.fromUrl(rurl.replace(/^git\+/,""),opts)||null;if(info)return info;let unk=unknownHostedUrl(rurl);return _GitHost.fromUrl(unk,opts)||unk}static parseUrl(url){return parseUrl(url)}#fill(template,opts){if(typeof template!="function")return null;let options={...this,...this.opts,...opts};options.path||(options.path=""),options.path.startsWith("/")&&(options.path=options.path.slice(1)),options.noCommittish&&(options.committish=null);let result=template(options);return options.noGitPlus&&result.startsWith("git+")?result.slice(4):result}hash(){return this.committish?`#${this.committish}`:""}ssh(opts){return this.#fill(this.sshtemplate,opts)}sshurl(opts){return this.#fill(this.sshurltemplate,opts)}browse(path20,...args){return typeof path20!="string"?this.#fill(this.browsetemplate,path20):typeof args[0]!="string"?this.#fill(this.browsetreetemplate,{...args[0],path:path20}):this.#fill(this.browsetreetemplate,{...args[1],fragment:args[0],path:path20})}browseFile(path20,...args){return typeof args[0]!="string"?this.#fill(this.browseblobtemplate,{...args[0],path:path20}):this.#fill(this.browseblobtemplate,{...args[1],fragment:args[0],path:path20})}docs(opts){return this.#fill(this.docstemplate,opts)}bugs(opts){return this.#fill(this.bugstemplate,opts)}https(opts){return this.#fill(this.httpstemplate,opts)}git(opts){return this.#fill(this.gittemplate,opts)}shortcut(opts){return this.#fill(this.shortcuttemplate,opts)}path(opts){return this.#fill(this.pathtemplate,opts)}tarball(opts){return this.#fill(this.tarballtemplate,{...opts,noCommittish:!1})}file(path20,opts){return this.#fill(this.filetemplate,{...opts,path:path20})}edit(path20,opts){return this.#fill(this.edittemplate,{...opts,path:path20})}getDefaultRepresentation(){return this.default}toString(opts){return this.default&&typeof this[this.default]=="function"?this[this.default](opts):this.sshurl(opts)}};for(let[name,host]of Object.entries(hosts))GitHost.addHost(name,host);module.exports=GitHost}});var require_identity=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js"(exports){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias2=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,isDocument=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,isMap=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,isPair=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,isScalar2=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,isSeq=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ;function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}function isNode(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}var hasAnchor=node=>(isScalar2(node)||isCollection(node))&&!!node.anchor;exports.ALIAS=ALIAS;exports.DOC=DOC;exports.MAP=MAP;exports.NODE_TYPE=NODE_TYPE;exports.PAIR=PAIR;exports.SCALAR=SCALAR;exports.SEQ=SEQ;exports.hasAnchor=hasAnchor;exports.isAlias=isAlias2;exports.isCollection=isCollection;exports.isDocument=isDocument;exports.isMap=isMap;exports.isNode=isNode;exports.isPair=isPair;exports.isScalar=isScalar2;exports.isSeq=isSeq}});var require_visit=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/visit.js"(exports){"use strict";var identity=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;function visit_(key,node,visitor,path20){let ctrl=callVisitor(key,node,visitor,path20);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path20,ctrl),visit_(key,ctrl,visitor,path20);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path20=Object.freeze(path20.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path20);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path20=Object.freeze(path20.concat(node));let ck=visit_("key",node.key,visitor,path20);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path20);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path20){let ctrl=await callVisitor(key,node,visitor,path20);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path20,ctrl),visitAsync_(key,ctrl,visitor,path20);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path20=Object.freeze(path20.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path20);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path20=Object.freeze(path20.concat(node));let ck=await visitAsync_("key",node.key,visitor,path20);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path20);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}function callVisitor(key,node,visitor,path20){if(typeof visitor=="function")return visitor(key,node,path20);if(identity.isMap(node))return visitor.Map?.(key,node,path20);if(identity.isSeq(node))return visitor.Seq?.(key,node,path20);if(identity.isPair(node))return visitor.Pair?.(key,node,path20);if(identity.isScalar(node))return visitor.Scalar?.(key,node,path20);if(identity.isAlias(node))return visitor.Alias?.(key,node,path20)}function replaceNode(key,path20,node){let parent=path20[path20.length-1];if(identity.isCollection(parent))parent.items[key]=node;else if(identity.isPair(parent))key==="key"?parent.key=node:parent.value=node;else if(identity.isDocument(parent))parent.contents=node;else{let pt=identity.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt} parent`)}}exports.visit=visit;exports.visitAsync=visitAsync}});var require_directives=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js"(exports){"use strict";var identity=require_identity(),visit=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),Directives=class _Directives{constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version2]=parts;if(version2==="1.1"||version2==="1.2")return this.yaml.version=version2,!0;{let isValid=/^\d+\.\d+$/.test(version2);return onError(6,`Unsupported YAML version ${version2}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity.isNode(doc.contents)){let tags={};visit.visit(doc.contents,(_key,node)=>{identity.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
3
3
|
`)}};Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports.Directives=Directives}});var require_anchors=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/doc/anchors.js"(exports){"use strict";var identity=require_identity(),visit=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw new Error(msg)}return!0}function anchorNames(root){let anchors=new Set;return visit.visit(root,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:source=>{aliasObjects.push(source),prevAnchors??(prevAnchors=anchorNames(doc));let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},setAnchors:()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref=="object"&&ref.anchor&&(identity.isScalar(ref.node)||identity.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=new Error("Failed to resolve repeated object (this should not happen)");throw error.source=source,error}}},sourceObjects}}exports.anchorIsValid=anchorIsValid;exports.anchorNames=anchorNames;exports.createNodeAnchors=createNodeAnchors;exports.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/doc/applyReviver.js"(exports){"use strict";function applyReviver(reviver,obj,key,val){if(val&&typeof val=="object")if(Array.isArray(val))for(let i=0,len=val.length;i<len;++i){let v0=val[i],v1=applyReviver(reviver,val,String(i),v0);v1===void 0?delete val[i]:v1!==v0&&(val[i]=v1)}else if(val instanceof Map)for(let k of Array.from(val.keys())){let v0=val.get(k),v1=applyReviver(reviver,val,k,v0);v1===void 0?val.delete(k):v1!==v0&&val.set(k,v1)}else if(val instanceof Set)for(let v0 of Array.from(val)){let v1=applyReviver(reviver,val,v0,v0);v1===void 0?val.delete(v0):v1!==v0&&(val.delete(v0),val.add(v1))}else for(let[k,v0]of Object.entries(val)){let v1=applyReviver(reviver,val,k,v0);v1===void 0?delete val[k]:v1!==v0&&(val[k]=v1)}return reviver.call(obj,key,val)}exports.applyReviver=applyReviver}});var require_toJS=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/nodes/toJS.js"(exports){"use strict";var identity=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON=="function"){if(!ctx||!identity.hasAnchor(value))return value.toJSON(arg,ctx);let data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data),ctx.onCreate=res2=>{data.res=res2,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value=="bigint"&&!ctx?.keep?Number(value):value}exports.toJS=toJS}});var require_Node=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/nodes/Node.js"(exports){"use strict";var applyReviver=require_applyReviver(),identity=require_identity(),toJS=require_toJS(),NodeBase=class{constructor(type){Object.defineProperty(this,identity.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity.isDocument(doc))throw new TypeError("A document argument is required");let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this,"",ctx);if(typeof onAnchor=="function")for(let{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver=="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports.NodeBase=NodeBase}});var require_Alias=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/nodes/Alias.js"(exports){"use strict";var anchors=require_anchors(),visit=require_visit(),identity=require_identity(),Node=require_Node(),toJS=require_toJS(),Alias=class extends Node.NodeBase{constructor(source){super(identity.ALIAS),this.source=source,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){if(ctx?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit.visit(doc,{Node:(_key,node)=>{(identity.isAlias(node)||identity.hasAnchor(node))&&nodes.push(node)}}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let{anchors:anchors2,doc,maxAliasCount}=ctx,source=this.resolve(doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data=anchors2.get(source);if(data||(toJS.toJS(source,null,ctx),data=anchors2.get(source)),data?.res===void 0){let msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0&&(data.count+=1,data.aliasCount===0&&(data.aliasCount=getAliasCount(doc,source,anchors2)),data.count*data.aliasCount>maxAliasCount)){let msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}return data.res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity.isAlias(node)){let source=node.resolve(doc),anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity.isCollection(node)){let count=0;for(let item of node.items){let c=getAliasCount(doc,item,anchors2);c>count&&(count=c)}return count}else if(identity.isPair(node)){let kc=getAliasCount(doc,node.key,anchors2),vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}exports.Alias=Alias}});var require_Scalar=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/nodes/Scalar.js"(exports){"use strict";var identity=require_identity(),Node=require_Node(),toJS=require_toJS(),isScalarValue=value=>!value||typeof value!="function"&&typeof value!="object",Scalar=class extends Node.NodeBase{constructor(value){super(identity.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports.Scalar=Scalar;exports.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/doc/createNode.js"(exports){"use strict";var Alias=require_Alias(),identity=require_identity(),Scalar=require_Scalar(),defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){let match2=tags.filter(t=>t.tag===tagName),tagObj=match2.find(t=>!t.format)??match2[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t=>t.identify?.(value)&&!t.format)}function createNode(value,tagName,ctx){if(identity.isDocument(value)&&(value=value.contents),identity.isNode(value))return value;if(identity.isPair(value)){let map=ctx.schema[identity.MAP].createNode?.(ctx.schema,null,ctx);return map.items.push(value),map}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<"u"&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value=="object"){if(ref=sourceObjects.get(value),ref)return ref.anchor??(ref.anchor=onAnchor(value)),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith("!!")&&(tagName=defaultTagPrefix+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON=="function"&&(value=value.toJSON()),!value||typeof value!="object"){let node2=new Scalar.Scalar(value);return ref&&(ref.node=node2),node2}tagObj=value instanceof Map?schema[identity.MAP]:Symbol.iterator in Object(value)?schema[identity.SEQ]:schema[identity.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from=="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}exports.createNode=createNode}});var require_Collection=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/nodes/Collection.js"(exports){"use strict";var createNode=require_createNode(),identity=require_identity(),Node=require_Node();function collectionFromPath(schema,path20,value){let v=value;for(let i=path20.length-1;i>=0;--i){let k=path20[i];if(typeof k=="number"&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema,sourceObjects:new Map})}var isEmptyPath=path20=>path20==null||typeof path20=="object"&&!!path20[Symbol.iterator]().next().done,Collection=class extends Node.NodeBase{constructor(type,schema){super(type),Object.defineProperty(this,"schema",{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it=>identity.isNode(it)||identity.isPair(it)?it.clone(schema):it),this.range&&(copy.range=this.range.slice()),copy}addIn(path20,value){if(isEmptyPath(path20))this.add(value);else{let[key,...rest]=path20,node=this.get(key,!0);if(identity.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path20){let[key,...rest]=path20;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity.isCollection(node))return node.deleteIn(rest);throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path20,keepScalar){let[key,...rest]=path20,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity.isScalar(node)?node.value:node:identity.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path20){let[key,...rest]=path20;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity.isCollection(node)?node.hasIn(rest):!1}setIn(path20,value){let[key,...rest]=path20;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports.Collection=Collection;exports.collectionFromPath=collectionFromPath;exports.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"node_modules/.bun/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyComment.js"(exports){"use strict";var stringifyComment=str2=>str2.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}var lineComment=(str2,indent,comment)=>str2.endsWith(`
|
|
4
4
|
`)?indentComment(comment,indent):comment.includes(`
|
|
5
5
|
`)?`
|
|
@@ -614,7 +614,7 @@ ${conversationText}
|
|
|
614
614
|
|
|
615
615
|
${instructions}`}],timestamp:Date.now()}],context=normalizeContext({systemPrompt:SUMMARIZATION_SYSTEM_PROMPT,messages:summarizationMessages}),requestOptions={apiKey,headers,env,signal};model.reasoning&&thinkingLevel&&thinkingLevel!=="off"&&(requestOptions.reasoning=thinkingLevel);let response=await completeSummarization(model,context,requestOptions,streamFn,retry,callbacks);if(response.stopReason==="aborted")return{aborted:!0};let failure2=getSummarizationFailure(response,"Branch summarization");if(failure2)return{error:failure2};if(response.content.some(block=>block.type==="toolCall"))return{error:"Branch summarization attempted to call a tool"};let summary=contentText(response.content);summary=BRANCH_SUMMARY_PREAMBLE+summary;let{readFiles,modifiedFiles}=computeFileLists(fileOps);return summary+=formatFileOperations(readFiles,modifiedFiles),{summary:summary||"No summary generated",usage:response.usage,readFiles,modifiedFiles}}function wrapRegisteredTool(registeredTool,runner){return wrapToolDefinition(registeredTool.definition,(toolCallId,signal)=>runner.createToolContext(toolCallId,signal))}function wrapRegisteredTools(registeredTools,runner){return registeredTools.map(tool=>wrapRegisteredTool(tool,runner))}import*as fs2 from"node:fs";import{createRequire as createRequire2}from"node:module";import*as path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{constants as bufferConstants}from"node:buffer";import{spawn}from"node:child_process";import{constants as osConstants}from"node:os";import{StringDecoder as StringDecoder2}from"node:string_decoder";var DEFAULT_EXEC_MAX_BUFFER=Math.min(256*1024*1024,bufferConstants.MAX_STRING_LENGTH),FORCE_KILL_DELAY_MS=5e3;async function execCommand(command,args,cwd,options){let maxBuffer=options?.maxBuffer??DEFAULT_EXEC_MAX_BUFFER;if(!Number.isInteger(maxBuffer)||maxBuffer<0||maxBuffer>bufferConstants.MAX_STRING_LENGTH)throw new RangeError(`maxBuffer must be an integer between 0 and ${bufferConstants.MAX_STRING_LENGTH} bytes`);let proc=spawn(command,args,{cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),stdout="",stderr="",stdoutDecoder=new StringDecoder2("utf8"),stderrDecoder=new StringDecoder2("utf8"),outputBytes=0,truncated=!1,killed=!1,timeoutId,forceKillId,killProcess=()=>{killed||(killed=!0,proc.kill("SIGTERM"),forceKillId=setTimeout(()=>{proc.exitCode===null&&proc.signalCode===null&&proc.kill("SIGKILL")},FORCE_KILL_DELAY_MS))};options?.signal&&(options.signal.aborted?killProcess():options.signal.addEventListener("abort",killProcess,{once:!0})),options?.timeout&&options.timeout>0&&(timeoutId=setTimeout(killProcess,options.timeout));let takeWithinCap=data=>{if(truncated)return;let remaining=maxBuffer-outputBytes;return data.length<=remaining?(outputBytes+=data.length,data):(truncated=!0,proc.stdout?.destroy(),proc.stderr?.destroy(),killProcess(),remaining>0?data.subarray(0,remaining):void 0)};proc.stdout?.on("data",data=>{let chunk=takeWithinCap(data);chunk&&(stdout+=stdoutDecoder.write(chunk))}),proc.stderr?.on("data",data=>{let chunk=takeWithinCap(data);chunk&&(stderr+=stderrDecoder.write(chunk))});let code;try{code=await waitForChildProcess(proc)}catch(error){if(!(error instanceof Error))throw error;code=1,stderr||(stderr=error.message)}finally{clearTimeout(timeoutId),clearTimeout(forceKillId),options?.signal?.removeEventListener("abort",killProcess)}truncated||(stdout+=stdoutDecoder.end(),stderr+=stderrDecoder.end());let exitCode=code??(proc.signalCode?128+(osConstants.signals[proc.signalCode]??0):1);return{stdout,stderr,code:truncated&&exitCode===0?1:exitCode,killed,truncated}}var ENABLED=process.env.DRAHT_TIMING==="1",timingNamespaces=new Map;function resetTimings(namespace="main"){ENABLED&&timingNamespaces.set(namespace,{timings:[],lastTime:Date.now()})}function time(label,namespace="main"){if(!ENABLED)return;let now=Date.now();timingNamespaces.has(namespace)||resetTimings(namespace);let timingNamespace=timingNamespaces.get(namespace);timingNamespace.timings.push({label,ms:now-timingNamespace.lastTime}),timingNamespace.lastTime=now}function printTimingGroup(title,timings){let printableTimings=timings.filter(timing=>timing.ms>=0);if(printableTimings.length!==0){console.error(`
|
|
616
616
|
--- ${title} ---`);for(let t of printableTimings)console.error(` ${t.label}: ${t.ms}ms`);console.error(` TOTAL: ${printableTimings.reduce((a,b)=>a+b.ms,0)}ms`),console.error(`${"-".repeat(title.length+8)}
|
|
617
|
-
`)}}function printTimings(){if(ENABLED)for(let[namespace,timingNamespace]of timingNamespaces)printTimingGroup(`Startup Timings: ${namespace}`,timingNamespace.timings)}var CHECKPOINTS_UNAVAILABLE="checkpoints are unavailable for this session",require3=createRequire2(import.meta.url),isNodeSeaBinary="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,isBundledNode=!0,isTypeScriptSourceRuntime=!isBunBinary&&path3.extname(fileURLToPath2(import.meta.url))===".ts",usesEmbeddedModules=isBunBinary||isNodeSeaBinary||isBundledNode,createJitiPromise;function getCreateJiti(){return createJitiPromise??=import("./jiti-loader-RKXLMQV2.js").then(module=>module.createJiti),createJitiPromise}var virtualModulesPromise;function getVirtualModules(){return virtualModulesPromise??=import("./virtual-modules-JZV35VDE.js").then(module=>module.VIRTUAL_MODULES),virtualModulesPromise}var _aliases=null;function getAliases(){if(_aliases)return _aliases;let __dirname=path3.dirname(fileURLToPath2(import.meta.url)),packageIndex=path3.resolve(__dirname,"../..","index.js"),legacyTypeboxRoot=require3.resolve("@sinclair/typebox").replace(/[\\/]build[\\/]cjs[\\/]index\.js$/,""),typeboxEntry=require3.resolve("typebox"),typeboxCompileEntry=require3.resolve("typebox/compile"),typeboxValueEntry=require3.resolve("typebox/value"),packagesRoot=path3.resolve(__dirname,"../../../../"),resolveWorkspaceOrImport=(workspaceRelativePath,specifier)=>{let workspacePath=path3.join(packagesRoot,workspaceRelativePath);return fs2.existsSync(workspacePath)?workspacePath:fileURLToPath2(import.meta.resolve(specifier))},piCodingAgentEntry=packageIndex,piAgentCoreEntry=resolveWorkspaceOrImport("agent/dist/index.js","@draht/agent-core"),piTuiEntry=resolveWorkspaceOrImport("tui/dist/index.js","@draht/tui"),piAiCompatEntry=path3.resolve(__dirname,"ai-extension-view.js"),piAiModelsEntry=resolveWorkspaceOrImport("ai/dist/models.js","@draht/ai/models"),piAiOauthEntry=resolveWorkspaceOrImport("ai/dist/oauth.js","@draht/ai/oauth"),piAiProvidersEntry=resolveWorkspaceOrImport("ai/dist/providers/all.js","@draht/ai/providers/all"),piAiProvidersFauxEntry=resolveWorkspaceOrImport("ai/dist/providers/faux.js","@draht/ai/providers/faux");return _aliases={"@draht/coding-agent":piCodingAgentEntry,"@draht/agent-core":piAgentCoreEntry,"@draht/tui":piTuiEntry,"@draht/ai/providers/all":piAiProvidersEntry,"@draht/ai/providers/faux":piAiProvidersFauxEntry,"@draht/ai/compat":piAiCompatEntry,"@draht/ai/models":piAiModelsEntry,"@draht/ai/oauth":piAiOauthEntry,"@draht/ai":piAiCompatEntry,"typebox/compile":typeboxCompileEntry,"typebox/value":typeboxValueEntry,typebox:typeboxEntry,"@sinclair/typebox":legacyTypeboxRoot},_aliases}var extensionCacheCwd,extensionCacheGeneration=0,extensionCache=new Map;function clearExtensionCache(){extensionCache.clear(),extensionCacheCwd=void 0,extensionCacheGeneration++}function useExtensionCacheCwd(cwd){let resolvedCwd=resolvePath(cwd);return extensionCacheCwd!==void 0&&!pathsEqual(extensionCacheCwd,resolvedCwd)&&clearExtensionCache(),extensionCacheCwd=resolvedCwd,{cwd:resolvedCwd,generation:extensionCacheGeneration}}function createExtensionRuntime(){let notInitialized=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},state2={},eventBusUnsubscribers=new Set,assertActive=()=>{if(state2.staleMessage)throw new Error(state2.staleMessage)},runtime={sendMessage:notInitialized,sendUserMessage:notInitialized,appendEntry:notInitialized,appendUsage:notInitialized,setSessionName:notInitialized,getSessionName:notInitialized,setLabel:notInitialized,getActiveTools:notInitialized,getAllTools:notInitialized,getSettings:notInitialized,setActiveTools:notInitialized,refreshTools:()=>{},getCommands:notInitialized,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:notInitialized,setThinkingLevel:notInitialized,getCheckpointManager:()=>{},flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new McpServerRegistry,pendingVirtualModelRegistrations:[],createContext:notInitialized,assertActive,invalidate:message=>{if(!state2.staleMessage){state2.staleMessage=message??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let unsubscribe of eventBusUnsubscribers)unsubscribe();eventBusUnsubscribers.clear()}},trackEventBusSubscription:unsubscribe=>{let active=!0,trackedUnsubscribe=()=>{active&&(active=!1,eventBusUnsubscribers.delete(trackedUnsubscribe),unsubscribe())};return eventBusUnsubscribers.add(trackedUnsubscribe),trackedUnsubscribe},registerProvider:(name,config,extensionPath="<unknown>")=>{runtime.pendingProviderRegistrations.push({name,config,extensionPath})},registerNativeProvider:(provider,extensionPath="<unknown>")=>{runtime.pendingNativeProviderRegistrations.push({provider,extensionPath})},unregisterProvider:name=>{runtime.pendingProviderRegistrations=runtime.pendingProviderRegistrations.filter(r=>r.name!==name),runtime.pendingNativeProviderRegistrations=runtime.pendingNativeProviderRegistrations.filter(r=>r.provider.id!==name)},registerVirtualModel:(definition,extensionPath="<unknown>")=>{runtime.pendingVirtualModelRegistrations.push({definition,extensionPath})},unregisterVirtualModel:(provider,id)=>{runtime.pendingVirtualModelRegistrations=runtime.pendingVirtualModelRegistrations.filter(({definition})=>definition.provider!==provider||definition.id!==id)}};return runtime}var DEFAULT_MARKDOWN_MESSAGE_TYPES=["user","assistant","assistant-thinking"];function createExtensionAPI(extension,runtime,cwd,eventBus){let pendingFlagValues=new Map,pendingRuntimeChanges=[],loadingUnsubscribers=[],state2="loading",assertActive=()=>{if(state2==="failed")throw new Error(`Extension "${extension.path}" failed to load and its API is no longer active.`);runtime.assertActive()},applyRuntimeChange=change=>{state2==="loading"?pendingRuntimeChanges.push(change):change()},clearPending=()=>{pendingFlagValues.clear(),pendingRuntimeChanges.length=0,loadingUnsubscribers.length=0};return{api:{on(event,handler){assertActive();let registeredHandler=(...args)=>handler(...args),list=extension.handlers.get(event)??[];return list.push(registeredHandler),extension.handlers.set(event,list),()=>{let handlers=extension.handlers.get(event);if(!handlers)return;let handlerIndex=handlers.indexOf(registeredHandler);handlerIndex!==-1&&(handlers.splice(handlerIndex,1),handlers.length===0&&extension.handlers.delete(event))}},registerTool(tool){if(assertActive(),typeof tool.parameters!="object"||tool.parameters===null||Array.isArray(tool.parameters))throw new Error(`Tool "${tool.name}" registered by extension "${extension.path}" must define an object parameter schema.`);extension.tools.set(tool.name,{definition:tool,sourceInfo:extension.sourceInfo}),runtime.refreshTools()},registerCommand(name,options){if(assertActive(),typeof name!="string"||name.length===0)throw new Error(`Command registered by extension "${extension.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof options?.handler!="function")throw new Error(`Command "/${name}" registered by extension "${extension.path}" must define handler().`);extension.commands.set(name,{name,sourceInfo:extension.sourceInfo,...options})},registerShortcut(shortcut,options){assertActive(),extension.shortcuts.set(shortcut,{shortcut,extensionPath:extension.path,...options})},registerFlag(name,options){if(assertActive(),options.default!==void 0&&typeof options.default!==options.type)throw new Error(`Invalid default for flag "${name}": expected ${options.type}, got ${typeof options.default}`);extension.flags.set(name,{name,extensionPath:extension.path,...options}),options.default!==void 0&&!runtime.flagValues.has(name)&&(state2==="loading"?pendingFlagValues.has(name)||pendingFlagValues.set(name,options.default):runtime.flagValues.set(name,options.default))},registerMessageRenderer(customType,renderer){assertActive(),extension.messageRenderers.set(customType,renderer)},registerMarkdownTransformer(transformer,options){assertActive(),extension.markdownTransformer={transformer,messageTypes:new Set(options?.messageTypes??DEFAULT_MARKDOWN_MESSAGE_TYPES)}},registerEntryRenderer(customType,renderer){extension.entryRenderers??=new Map,extension.entryRenderers.set(customType,renderer)},registerToolRenderer(resolver){assertActive(),extension.toolRenderers??=[],extension.toolRenderers.push(resolver)},getFlag(name){if(assertActive(),!!extension.flags.has(name))return runtime.flagValues.has(name)?runtime.flagValues.get(name):pendingFlagValues.get(name)},sendMessage(message,options){assertActive(),runtime.sendMessage(message,options)},sendUserMessage(content,options){assertActive(),runtime.sendUserMessage(content,options)},appendEntry(customType,data){assertActive(),runtime.appendEntry(customType,data)},appendUsage(kind,provider,model,usage,note){assertActive();for(let[name,value]of[["kind",kind],["provider",provider],["model",model]])if(typeof value!="string"||value.length===0)throw new Error(`pi.appendUsage: ${name} must be a non-empty string`);if(note!==void 0&&typeof note!="string")throw new Error("pi.appendUsage: note must be a string");if(!isValidUsage(usage))throw new Error("pi.appendUsage: usage must carry finite token counts and a finite cost breakdown");runtime.appendUsage(kind,provider,model,usage,note)},setSessionName(name){assertActive(),runtime.setSessionName(name)},getSessionName(){return assertActive(),runtime.getSessionName()},setLabel(entryId,label){assertActive(),runtime.setLabel(entryId,label)},exec(command,args,options){return assertActive(),execCommand(command,args,options?.cwd??cwd,options)},getActiveTools(){return assertActive(),runtime.getActiveTools()},getAllTools(){return assertActive(),runtime.getAllTools()},getSettings(){return assertActive(),runtime.getSettings()},setActiveTools(toolNames){assertActive(),runtime.setActiveTools(toolNames)},getCommands(){return assertActive(),runtime.getCommands()},setModel(model,options){return assertActive(),runtime.setModel(model,options)},getThinkingLevel(){return assertActive(),runtime.getThinkingLevel()},setThinkingLevel(level,options){assertActive(),runtime.setThinkingLevel(level,options)},registerProvider(providerOrName,config){if(assertActive(),typeof providerOrName=="string"){if(!config)throw new Error("Provider config is required when registering by name");applyRuntimeChange(()=>runtime.registerProvider(providerOrName,config,extension.path));return}applyRuntimeChange(()=>runtime.registerNativeProvider(providerOrName,extension.path))},unregisterProvider(name){assertActive(),applyRuntimeChange(()=>runtime.unregisterProvider(name,extension.path))},registerMcpServer(name,config){assertActive();let validated=validateMcpServerConfig(name,config);if(typeof validated=="string")throw new Error(`Invalid MCP server registered by extension "${extension.path}": ${validated}`);let owner=runtime.mcpServers.get(name)?.extensionPath;if(owner!==void 0&&owner!==extension.path)throw new Error(`MCP server "${name}" is already registered by extension "${owner}"`);let clash=runtime.mcpServers.list().find(server2=>server2.name!==name&&mcpNamespace(server2.name)===mcpNamespace(name));if(clash)throw new Error(`MCP server "${name}" conflicts with registered server "${clash.name}"`);let server={name,config:structuredClone(validated),extensionPath:extension.path,get extensionScope(){return extension.sourceInfo.scope}};applyRuntimeChange(()=>runtime.mcpServers.register(server))},unregisterMcpServer(name){assertActive(),applyRuntimeChange(()=>runtime.mcpServers.unregister(name,extension.path))},getMcpServers(){return assertActive(),runtime.mcpServers.list()},registerVirtualModel(model){assertActive();let definition={...model,route:request=>model.route(request,runtime.createContext())};applyRuntimeChange(()=>runtime.registerVirtualModel(definition,extension.path))},unregisterVirtualModel(provider,id){assertActive(),applyRuntimeChange(()=>runtime.unregisterVirtualModel(provider,id))},events:{emit(channel,data){assertActive(),eventBus.emit(channel,data)},on(channel,handler){assertActive();let unsubscribe=runtime.trackEventBusSubscription(eventBus.on(channel,handler));return state2==="loading"&&loadingUnsubscribers.push(unsubscribe),unsubscribe}},checkpoints:{list(){return assertActive(),runtime.getCheckpointManager()?.list()??[]},get(entryId){return assertActive(),runtime.getCheckpointManager()?.get(entryId)},async restore(options){assertActive();let manager=runtime.getCheckpointManager();return manager?manager.restore(options):{status:"disabled",restored:[],deleted:[],reason:CHECKPOINTS_UNAVAILABLE}},async capture(entryId){assertActive();let manager=runtime.getCheckpointManager();return manager?manager.captureIfChanged(entryId):{status:"disabled",reason:CHECKPOINTS_UNAVAILABLE}}}},commit:()=>{if(state2==="loading"){runtime.assertActive();for(let[name,value]of pendingFlagValues)runtime.flagValues.has(name)||runtime.flagValues.set(name,value);for(let apply of pendingRuntimeChanges)apply();state2="active",clearPending()}},discard:()=>{if(state2==="loading"){state2="failed";for(let unsubscribe of loadingUnsubscribers)unsubscribe();clearPending()}}}}function isCurrentCacheToken(cacheToken){return cacheToken!==void 0&&extensionCacheCwd===cacheToken.cwd&&extensionCacheGeneration===cacheToken.generation}async function loadExtensionModule(extensionPath,cacheToken){if(isCurrentCacheToken(cacheToken)){let cachedFactory=extensionCache.get(extensionPath);if(cachedFactory)return cachedFactory}let createJitiImpl=await getCreateJiti(),resolutionOptions=usesEmbeddedModules?{virtualModules:await getVirtualModules(),tryNative:!1}:isTypeScriptSourceRuntime?{virtualModules:await getVirtualModules(),tsconfigPaths:!0}:{alias:getAliases()},factory=await createJitiImpl(import.meta.url,{moduleCache:!1,...resolutionOptions}).import(realPathStrict(extensionPath)??extensionPath,{default:!0});if(typeof factory=="function")return isCurrentCacheToken(cacheToken)&&extensionCache.set(extensionPath,factory),factory}function createExtension(extensionPath,resolvedPath){let source=getSyntheticPathSource(extensionPath)??"local",baseDir=isSyntheticPath(extensionPath)?void 0:path3.dirname(resolvedPath);return{path:extensionPath,resolvedPath,sourceInfo:createSyntheticSourceInfo(extensionPath,{source,baseDir}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}async function initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime){let extension=createExtension(extensionPath,resolvedPath),load=createExtensionAPI(extension,runtime,cwd,eventBus);try{await factory(load.api),load.commit()}catch(error){throw load.discard(),error}return time(`${extensionPath} factory`,"extensions"),extension}async function loadExtension(extensionPath,cwd,eventBus,runtime,cacheToken){let resolvedPath=resolvePath(extensionPath,cwd,{normalizeUnicodeSpaces:!0});try{let factory=await loadExtensionModule(resolvedPath,cacheToken);return time(`${extensionPath} module import`,"extensions"),factory?{extension:await initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${extensionPath}`}}catch(err){return{extension:null,error:`Failed to load extension: ${err instanceof Error?err.message:String(err)}`}}}async function loadExtensionFromFactory(factory,cwd,eventBus,runtime,extensionPath="<inline>"){let resolvedCwd=resolvePath(cwd);return initializeExtension(factory,extensionPath,extensionPath,resolvedCwd,eventBus,runtime)}async function loadExtensionsInternal(paths,cwd,eventBus,runtime,useCache=!1){let extensions=[],errors=[],warnings=[],cacheToken=useCache?useExtensionCacheCwd(cwd):void 0,resolvedCwd=cacheToken?.cwd??resolvePath(cwd),resolvedEventBus=eventBus??createEventBus(),resolvedRuntime=runtime??createExtensionRuntime();for(let extPath of paths){let{extension,error}=await loadExtension(extPath,resolvedCwd,resolvedEventBus,resolvedRuntime,cacheToken);if(error){errors.push({path:extPath,error});continue}extension&&extensions.push(extension)}return{extensions,errors,warnings,runtime:resolvedRuntime}}async function loadExtensions(paths,cwd,eventBus,runtime){return loadExtensionsInternal(paths,cwd,eventBus,runtime)}async function loadExtensionsCached(paths,cwd,eventBus,runtime){return loadExtensionsInternal(paths,cwd,eventBus,runtime,!0)}function isExtensionFile(name){return name.endsWith(".ts")||name.endsWith(".js")}function resolveExtensionEntries2(dir){let packageJsonPath=path3.join(dir,"package.json");if(fs2.existsSync(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=path3.resolve(dir,extPath);fs2.existsSync(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=path3.join(dir,"index.ts"),indexJs=path3.join(dir,"index.js");return fs2.existsSync(indexTs)?[indexTs]:fs2.existsSync(indexJs)?[indexJs]:null}function discoverExtensionsInDir(dir){if(!fs2.existsSync(dir))return[];let discovered=[];try{let entries=fs2.readdirSync(dir,{withFileTypes:!0});for(let entry of entries){let entryPath=path3.join(dir,entry.name);if((entry.isFile()||entry.isSymbolicLink())&&isExtensionFile(entry.name)){discovered.push(entryPath);continue}if(entry.isDirectory()||entry.isSymbolicLink()){let entries2=resolveExtensionEntries2(entryPath);entries2&&discovered.push(...entries2)}}}catch{return[]}return discovered}async function discoverAndLoadExtensions(configuredPaths,cwd,agentDir=getAgentDir(),eventBus){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),allPaths=[],seen=new Set,addPaths=paths=>{for(let p of paths){let resolved=path3.resolve(p);seen.has(resolved)||(seen.add(resolved),allPaths.push(p))}},localExtDir=path3.join(resolvedCwd,CONFIG_DIR_NAME,"extensions");addPaths(discoverExtensionsInDir(localExtDir));let globalExtDir=path3.join(resolvedAgentDir,"extensions");addPaths(discoverExtensionsInDir(globalExtDir));for(let p of configuredPaths){let resolved=resolvePath(p,resolvedCwd,{normalizeUnicodeSpaces:!0});if(fs2.existsSync(resolved)&&fs2.statSync(resolved).isDirectory()){let entries=resolveExtensionEntries2(resolved);if(entries){addPaths(entries);continue}addPaths(discoverExtensionsInDir(resolved));continue}addPaths([resolved])}let result=await loadExtensions(allPaths,resolvedCwd,eventBus),isUnder=(file,dir)=>{let relative11=path3.relative(dir,path3.resolve(file));return!relative11.startsWith("..")&&!path3.isAbsolute(relative11)};for(let extension of result.extensions){let scope=isUnder(extension.resolvedPath,localExtDir)?"project":isUnder(extension.resolvedPath,globalExtDir)?"user":void 0;if(scope!==void 0){extension.sourceInfo={...extension.sourceInfo,scope};for(let tool of extension.tools.values())tool.sourceInfo=extension.sourceInfo;for(let command of extension.commands.values())command.sourceInfo=extension.sourceInfo}}return result}var ModelRegistry=class{runtime;constructor(runtime){this.runtime=runtime}refresh(options){return this.runtime.refresh(options)}getError(){return this.runtime.getError()}getAll(){return[...this.runtime.getModels()]}getAvailable(){return[...this.runtime.getAvailableSnapshot()]}find(provider,modelId){return this.runtime.getModel(provider,modelId)}findOfType(type,provider,modelId){return this.runtime.getModelOfType(type,provider,modelId)}hasConfiguredAuth(model){return this.runtime.hasConfiguredAuth(model.provider)}async getApiKeyAndHeaders(model){try{let resolution=await this.runtime.getAuth(model);if(!resolution){let compatibility=this.runtime.getCompatibilityRequestConfig(model);return compatibility.authHeader?{ok:!1,error:`No API key found for "${model.provider}"`}:{ok:!0,headers:compatibility.headers}}return{ok:!0,apiKey:resolution.auth.apiKey,headers:resolution.auth.headers,...resolution.auth.baseUrl?{baseUrl:resolution.auth.baseUrl}:{},env:resolution.env}}catch(error){let cause=error instanceof Error?error.cause:void 0,message=cause instanceof Error?cause.message:error instanceof Error?error.message:String(error);return{ok:!1,error:message==="authHeader requires a resolved API key"?`No API key found for "${model.provider}"`:message}}}getProviderAuthStatus(provider){return this.runtime.getProviderAuthStatus(provider)}getProvider(provider){return this.runtime.getProvider(provider)}stream(model,context,options){return this.runtime.stream(model,context,options)}streamSimple(model,context,options){return this.runtime.streamSimple(model,context,options)}complete(model,context,options){return this.runtime.complete(model,context,options)}getModelsOfType(type,provider){return this.runtime.getModelsOfType(type,provider)}getAvailableOfType(type,provider,options){return this.runtime.getAvailableOfType(type,provider,options)}getModelOfType(type,provider,modelId){return this.runtime.getModelOfType(type,provider,modelId)}classify(model,context,options){return this.runtime.classify(model,context,options)}generateImages(model,context,options){return this.runtime.generateImages(model,context,options)}getProviderDisplayName(provider){return this.runtime.getProvider(provider)?.name??provider}getProviderAuth(provider){return this.runtime.getAuth(provider)}async getApiKeyForProvider(provider){try{return(await this.runtime.getAuth(provider))?.auth.apiKey}catch{return}}isUsingOAuth(model){return this.runtime.isUsingOAuth(model.provider)}registerProvider(providerOrName,config){if(typeof providerOrName=="string"){if(!config)throw new Error("Provider config is required when registering by name");this.runtime.registerProvider(providerOrName,config);return}this.runtime.registerNativeProvider(providerOrName)}unregisterProvider(providerName){this.runtime.unregisterProvider(providerName)}registerVirtualModel(definition){this.runtime.registerVirtualModel(definition)}unregisterVirtualModel(providerName,id){this.runtime.unregisterVirtualModel(providerName,id)}getRegisteredProviderConfig(providerName){return this.runtime.getRegisteredProviderConfig(providerName)}getRegisteredNativeProvider(providerName){return this.runtime.getRegisteredNativeProvider(providerName)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}};import{constants as constants3}from"node:fs";import{access as fsAccess}from"node:fs/promises";import{constants as osConstants2}from"node:os";import{spawn as spawn2}from"child_process";import{open as open2}from"node:fs/promises";function byteLength(text){return Buffer.byteLength(text,"utf-8")}var OutputAccumulator=class{maxLines;maxBytes;maxRollingBytes;tempFilePrefix;decoder=new TextDecoder;rawChunks=[];tailText="";tailBytes=0;tailStartsAtLineBoundary=!0;totalRawBytes=0;totalDecodedBytes=0;completedLines=0;totalLines=0;currentLineBytes=0;hasOpenLine=!1;finished=!1;tempFilePath;tempFileStream;constructor(options={}){this.maxLines=options.maxLines??2e3,this.maxBytes=options.maxBytes??51200,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=options.tempFilePrefix??"pi-output"}append(data){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=data.length,this.appendDecodedText(this.decoder.decode(data,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(data)):data.length>0&&this.rawChunks.push(data)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(options={}){let snapshotText=this.getSnapshotText()||this.tailText,tailTruncation=truncateTail(snapshotText,{maxLines:this.maxLines,maxBytes:this.maxBytes}),truncated=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,truncatedBy=truncated?tailTruncation.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,truncation={...tailTruncation,truncated,truncatedBy,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return options.persistIfTruncated&&truncation.truncated&&this.ensureTempFile(),{content:truncation.content,truncation,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;let stream2=this.tempFileStream;this.tempFileStream=void 0,await new Promise((resolve20,reject)=>{let onError=error=>{stream2.off("finish",onFinish),reject(error)},onFinish=()=>{stream2.off("error",onError),resolve20()};stream2.once("error",onError),stream2.once("finish",onFinish),stream2.end()})}async readFullOutput(maxBytes){if(!this.tempFilePath)return{content:new TextDecoder().decode(Buffer.concat(this.rawChunks)),truncated:!1};let file=await open2(this.tempFilePath,"r");try{let size=(await file.stat()).size;if(size<=maxBytes)return{content:new TextDecoder().decode(await file.readFile()),truncated:!1};let headBytes=Math.floor(maxBytes/2),tailBytes=maxBytes-headBytes,head=Buffer.alloc(headBytes),tail=Buffer.alloc(tailBytes);await file.read(head,0,headBytes,0),await file.read(tail,0,tailBytes,size-tailBytes);let headText=new TextDecoder().decode(head,{stream:!0}),tailStart=0;for(;tailStart<tail.length&&(tail[tailStart]&192)===128;)tailStart++;let tailText=new TextDecoder().decode(tail.subarray(tailStart)),omitted=size-headBytes-tailBytes;return{content:`${headText}
|
|
617
|
+
`)}}function printTimings(){if(ENABLED)for(let[namespace,timingNamespace]of timingNamespaces)printTimingGroup(`Startup Timings: ${namespace}`,timingNamespace.timings)}var CHECKPOINTS_UNAVAILABLE="checkpoints are unavailable for this session",require3=createRequire2(import.meta.url),isNodeSeaBinary="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,isBundledNode=!0,isTypeScriptSourceRuntime=!isBunBinary&&path3.extname(fileURLToPath2(import.meta.url))===".ts",usesEmbeddedModules=isBunBinary||isNodeSeaBinary||isBundledNode,createJitiPromise;function getCreateJiti(){return createJitiPromise??=import("./jiti-loader-RKXLMQV2.js").then(module=>module.createJiti),createJitiPromise}var virtualModulesPromise;function getVirtualModules(){return virtualModulesPromise??=import("./virtual-modules-JL2BFG57.js").then(module=>module.VIRTUAL_MODULES),virtualModulesPromise}var _aliases=null;function getAliases(){if(_aliases)return _aliases;let __dirname=path3.dirname(fileURLToPath2(import.meta.url)),packageIndex=path3.resolve(__dirname,"../..","index.js"),legacyTypeboxRoot=require3.resolve("@sinclair/typebox").replace(/[\\/]build[\\/]cjs[\\/]index\.js$/,""),typeboxEntry=require3.resolve("typebox"),typeboxCompileEntry=require3.resolve("typebox/compile"),typeboxValueEntry=require3.resolve("typebox/value"),packagesRoot=path3.resolve(__dirname,"../../../../"),resolveWorkspaceOrImport=(workspaceRelativePath,specifier)=>{let workspacePath=path3.join(packagesRoot,workspaceRelativePath);return fs2.existsSync(workspacePath)?workspacePath:fileURLToPath2(import.meta.resolve(specifier))},piCodingAgentEntry=packageIndex,piAgentCoreEntry=resolveWorkspaceOrImport("agent/dist/index.js","@draht/agent-core"),piTuiEntry=resolveWorkspaceOrImport("tui/dist/index.js","@draht/tui"),piAiCompatEntry=path3.resolve(__dirname,"ai-extension-view.js"),piAiModelsEntry=resolveWorkspaceOrImport("ai/dist/models.js","@draht/ai/models"),piAiOauthEntry=resolveWorkspaceOrImport("ai/dist/oauth.js","@draht/ai/oauth"),piAiProvidersEntry=resolveWorkspaceOrImport("ai/dist/providers/all.js","@draht/ai/providers/all"),piAiProvidersFauxEntry=resolveWorkspaceOrImport("ai/dist/providers/faux.js","@draht/ai/providers/faux");return _aliases={"@draht/coding-agent":piCodingAgentEntry,"@draht/agent-core":piAgentCoreEntry,"@draht/tui":piTuiEntry,"@draht/ai/providers/all":piAiProvidersEntry,"@draht/ai/providers/faux":piAiProvidersFauxEntry,"@draht/ai/compat":piAiCompatEntry,"@draht/ai/models":piAiModelsEntry,"@draht/ai/oauth":piAiOauthEntry,"@draht/ai":piAiCompatEntry,"typebox/compile":typeboxCompileEntry,"typebox/value":typeboxValueEntry,typebox:typeboxEntry,"@sinclair/typebox":legacyTypeboxRoot},_aliases}var extensionCacheCwd,extensionCacheGeneration=0,extensionCache=new Map;function clearExtensionCache(){extensionCache.clear(),extensionCacheCwd=void 0,extensionCacheGeneration++}function useExtensionCacheCwd(cwd){let resolvedCwd=resolvePath(cwd);return extensionCacheCwd!==void 0&&!pathsEqual(extensionCacheCwd,resolvedCwd)&&clearExtensionCache(),extensionCacheCwd=resolvedCwd,{cwd:resolvedCwd,generation:extensionCacheGeneration}}function createExtensionRuntime(){let notInitialized=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},state2={},eventBusUnsubscribers=new Set,assertActive=()=>{if(state2.staleMessage)throw new Error(state2.staleMessage)},runtime={sendMessage:notInitialized,sendUserMessage:notInitialized,appendEntry:notInitialized,appendUsage:notInitialized,setSessionName:notInitialized,getSessionName:notInitialized,setLabel:notInitialized,getActiveTools:notInitialized,getAllTools:notInitialized,getSettings:notInitialized,setActiveTools:notInitialized,refreshTools:()=>{},getCommands:notInitialized,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:notInitialized,setThinkingLevel:notInitialized,getCheckpointManager:()=>{},flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new McpServerRegistry,pendingVirtualModelRegistrations:[],createContext:notInitialized,assertActive,invalidate:message=>{if(!state2.staleMessage){state2.staleMessage=message??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let unsubscribe of eventBusUnsubscribers)unsubscribe();eventBusUnsubscribers.clear()}},trackEventBusSubscription:unsubscribe=>{let active=!0,trackedUnsubscribe=()=>{active&&(active=!1,eventBusUnsubscribers.delete(trackedUnsubscribe),unsubscribe())};return eventBusUnsubscribers.add(trackedUnsubscribe),trackedUnsubscribe},registerProvider:(name,config,extensionPath="<unknown>")=>{runtime.pendingProviderRegistrations.push({name,config,extensionPath})},registerNativeProvider:(provider,extensionPath="<unknown>")=>{runtime.pendingNativeProviderRegistrations.push({provider,extensionPath})},unregisterProvider:name=>{runtime.pendingProviderRegistrations=runtime.pendingProviderRegistrations.filter(r=>r.name!==name),runtime.pendingNativeProviderRegistrations=runtime.pendingNativeProviderRegistrations.filter(r=>r.provider.id!==name)},registerVirtualModel:(definition,extensionPath="<unknown>")=>{runtime.pendingVirtualModelRegistrations.push({definition,extensionPath})},unregisterVirtualModel:(provider,id)=>{runtime.pendingVirtualModelRegistrations=runtime.pendingVirtualModelRegistrations.filter(({definition})=>definition.provider!==provider||definition.id!==id)}};return runtime}var DEFAULT_MARKDOWN_MESSAGE_TYPES=["user","assistant","assistant-thinking"];function createExtensionAPI(extension,runtime,cwd,eventBus){let pendingFlagValues=new Map,pendingRuntimeChanges=[],loadingUnsubscribers=[],state2="loading",assertActive=()=>{if(state2==="failed")throw new Error(`Extension "${extension.path}" failed to load and its API is no longer active.`);runtime.assertActive()},applyRuntimeChange=change=>{state2==="loading"?pendingRuntimeChanges.push(change):change()},clearPending=()=>{pendingFlagValues.clear(),pendingRuntimeChanges.length=0,loadingUnsubscribers.length=0};return{api:{on(event,handler){assertActive();let registeredHandler=(...args)=>handler(...args),list=extension.handlers.get(event)??[];return list.push(registeredHandler),extension.handlers.set(event,list),()=>{let handlers=extension.handlers.get(event);if(!handlers)return;let handlerIndex=handlers.indexOf(registeredHandler);handlerIndex!==-1&&(handlers.splice(handlerIndex,1),handlers.length===0&&extension.handlers.delete(event))}},registerTool(tool){if(assertActive(),typeof tool.parameters!="object"||tool.parameters===null||Array.isArray(tool.parameters))throw new Error(`Tool "${tool.name}" registered by extension "${extension.path}" must define an object parameter schema.`);extension.tools.set(tool.name,{definition:tool,sourceInfo:extension.sourceInfo}),runtime.refreshTools()},registerCommand(name,options){if(assertActive(),typeof name!="string"||name.length===0)throw new Error(`Command registered by extension "${extension.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof options?.handler!="function")throw new Error(`Command "/${name}" registered by extension "${extension.path}" must define handler().`);extension.commands.set(name,{name,sourceInfo:extension.sourceInfo,...options})},registerShortcut(shortcut,options){assertActive(),extension.shortcuts.set(shortcut,{shortcut,extensionPath:extension.path,...options})},registerFlag(name,options){if(assertActive(),options.default!==void 0&&typeof options.default!==options.type)throw new Error(`Invalid default for flag "${name}": expected ${options.type}, got ${typeof options.default}`);extension.flags.set(name,{name,extensionPath:extension.path,...options}),options.default!==void 0&&!runtime.flagValues.has(name)&&(state2==="loading"?pendingFlagValues.has(name)||pendingFlagValues.set(name,options.default):runtime.flagValues.set(name,options.default))},registerMessageRenderer(customType,renderer){assertActive(),extension.messageRenderers.set(customType,renderer)},registerMarkdownTransformer(transformer,options){assertActive(),extension.markdownTransformer={transformer,messageTypes:new Set(options?.messageTypes??DEFAULT_MARKDOWN_MESSAGE_TYPES)}},registerEntryRenderer(customType,renderer){extension.entryRenderers??=new Map,extension.entryRenderers.set(customType,renderer)},registerToolRenderer(resolver){assertActive(),extension.toolRenderers??=[],extension.toolRenderers.push(resolver)},getFlag(name){if(assertActive(),!!extension.flags.has(name))return runtime.flagValues.has(name)?runtime.flagValues.get(name):pendingFlagValues.get(name)},sendMessage(message,options){assertActive(),runtime.sendMessage(message,options)},sendUserMessage(content,options){assertActive(),runtime.sendUserMessage(content,options)},appendEntry(customType,data){assertActive(),runtime.appendEntry(customType,data)},appendUsage(kind,provider,model,usage,note){assertActive();for(let[name,value]of[["kind",kind],["provider",provider],["model",model]])if(typeof value!="string"||value.length===0)throw new Error(`pi.appendUsage: ${name} must be a non-empty string`);if(note!==void 0&&typeof note!="string")throw new Error("pi.appendUsage: note must be a string");if(!isValidUsage(usage))throw new Error("pi.appendUsage: usage must carry finite token counts and a finite cost breakdown");runtime.appendUsage(kind,provider,model,usage,note)},setSessionName(name){assertActive(),runtime.setSessionName(name)},getSessionName(){return assertActive(),runtime.getSessionName()},setLabel(entryId,label){assertActive(),runtime.setLabel(entryId,label)},exec(command,args,options){return assertActive(),execCommand(command,args,options?.cwd??cwd,options)},getActiveTools(){return assertActive(),runtime.getActiveTools()},getAllTools(){return assertActive(),runtime.getAllTools()},getSettings(){return assertActive(),runtime.getSettings()},setActiveTools(toolNames){assertActive(),runtime.setActiveTools(toolNames)},getCommands(){return assertActive(),runtime.getCommands()},setModel(model,options){return assertActive(),runtime.setModel(model,options)},getThinkingLevel(){return assertActive(),runtime.getThinkingLevel()},setThinkingLevel(level,options){assertActive(),runtime.setThinkingLevel(level,options)},registerProvider(providerOrName,config){if(assertActive(),typeof providerOrName=="string"){if(!config)throw new Error("Provider config is required when registering by name");applyRuntimeChange(()=>runtime.registerProvider(providerOrName,config,extension.path));return}applyRuntimeChange(()=>runtime.registerNativeProvider(providerOrName,extension.path))},unregisterProvider(name){assertActive(),applyRuntimeChange(()=>runtime.unregisterProvider(name,extension.path))},registerMcpServer(name,config){assertActive();let validated=validateMcpServerConfig(name,config);if(typeof validated=="string")throw new Error(`Invalid MCP server registered by extension "${extension.path}": ${validated}`);let owner=runtime.mcpServers.get(name)?.extensionPath;if(owner!==void 0&&owner!==extension.path)throw new Error(`MCP server "${name}" is already registered by extension "${owner}"`);let clash=runtime.mcpServers.list().find(server2=>server2.name!==name&&mcpNamespace(server2.name)===mcpNamespace(name));if(clash)throw new Error(`MCP server "${name}" conflicts with registered server "${clash.name}"`);let server={name,config:structuredClone(validated),extensionPath:extension.path,get extensionScope(){return extension.sourceInfo.scope}};applyRuntimeChange(()=>runtime.mcpServers.register(server))},unregisterMcpServer(name){assertActive(),applyRuntimeChange(()=>runtime.mcpServers.unregister(name,extension.path))},getMcpServers(){return assertActive(),runtime.mcpServers.list()},registerVirtualModel(model){assertActive();let definition={...model,route:request=>model.route(request,runtime.createContext())};applyRuntimeChange(()=>runtime.registerVirtualModel(definition,extension.path))},unregisterVirtualModel(provider,id){assertActive(),applyRuntimeChange(()=>runtime.unregisterVirtualModel(provider,id))},events:{emit(channel,data){assertActive(),eventBus.emit(channel,data)},on(channel,handler){assertActive();let unsubscribe=runtime.trackEventBusSubscription(eventBus.on(channel,handler));return state2==="loading"&&loadingUnsubscribers.push(unsubscribe),unsubscribe}},checkpoints:{list(){return assertActive(),runtime.getCheckpointManager()?.list()??[]},get(entryId){return assertActive(),runtime.getCheckpointManager()?.get(entryId)},async restore(options){assertActive();let manager=runtime.getCheckpointManager();return manager?manager.restore(options):{status:"disabled",restored:[],deleted:[],reason:CHECKPOINTS_UNAVAILABLE}},async capture(entryId){assertActive();let manager=runtime.getCheckpointManager();return manager?manager.captureIfChanged(entryId):{status:"disabled",reason:CHECKPOINTS_UNAVAILABLE}}}},commit:()=>{if(state2==="loading"){runtime.assertActive();for(let[name,value]of pendingFlagValues)runtime.flagValues.has(name)||runtime.flagValues.set(name,value);for(let apply of pendingRuntimeChanges)apply();state2="active",clearPending()}},discard:()=>{if(state2==="loading"){state2="failed";for(let unsubscribe of loadingUnsubscribers)unsubscribe();clearPending()}}}}function isCurrentCacheToken(cacheToken){return cacheToken!==void 0&&extensionCacheCwd===cacheToken.cwd&&extensionCacheGeneration===cacheToken.generation}async function loadExtensionModule(extensionPath,cacheToken){if(isCurrentCacheToken(cacheToken)){let cachedFactory=extensionCache.get(extensionPath);if(cachedFactory)return cachedFactory}let createJitiImpl=await getCreateJiti(),resolutionOptions=usesEmbeddedModules?{virtualModules:await getVirtualModules(),tryNative:!1}:isTypeScriptSourceRuntime?{virtualModules:await getVirtualModules(),tsconfigPaths:!0}:{alias:getAliases()},factory=await createJitiImpl(import.meta.url,{moduleCache:!1,...resolutionOptions}).import(realPathStrict(extensionPath)??extensionPath,{default:!0});if(typeof factory=="function")return isCurrentCacheToken(cacheToken)&&extensionCache.set(extensionPath,factory),factory}function createExtension(extensionPath,resolvedPath){let source=getSyntheticPathSource(extensionPath)??"local",baseDir=isSyntheticPath(extensionPath)?void 0:path3.dirname(resolvedPath);return{path:extensionPath,resolvedPath,sourceInfo:createSyntheticSourceInfo(extensionPath,{source,baseDir}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}async function initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime){let extension=createExtension(extensionPath,resolvedPath),load=createExtensionAPI(extension,runtime,cwd,eventBus);try{await factory(load.api),load.commit()}catch(error){throw load.discard(),error}return time(`${extensionPath} factory`,"extensions"),extension}async function loadExtension(extensionPath,cwd,eventBus,runtime,cacheToken){let resolvedPath=resolvePath(extensionPath,cwd,{normalizeUnicodeSpaces:!0});try{let factory=await loadExtensionModule(resolvedPath,cacheToken);return time(`${extensionPath} module import`,"extensions"),factory?{extension:await initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${extensionPath}`}}catch(err){return{extension:null,error:`Failed to load extension: ${err instanceof Error?err.message:String(err)}`}}}async function loadExtensionFromFactory(factory,cwd,eventBus,runtime,extensionPath="<inline>"){let resolvedCwd=resolvePath(cwd);return initializeExtension(factory,extensionPath,extensionPath,resolvedCwd,eventBus,runtime)}async function loadExtensionsInternal(paths,cwd,eventBus,runtime,useCache=!1){let extensions=[],errors=[],warnings=[],cacheToken=useCache?useExtensionCacheCwd(cwd):void 0,resolvedCwd=cacheToken?.cwd??resolvePath(cwd),resolvedEventBus=eventBus??createEventBus(),resolvedRuntime=runtime??createExtensionRuntime();for(let extPath of paths){let{extension,error}=await loadExtension(extPath,resolvedCwd,resolvedEventBus,resolvedRuntime,cacheToken);if(error){errors.push({path:extPath,error});continue}extension&&extensions.push(extension)}return{extensions,errors,warnings,runtime:resolvedRuntime}}async function loadExtensions(paths,cwd,eventBus,runtime){return loadExtensionsInternal(paths,cwd,eventBus,runtime)}async function loadExtensionsCached(paths,cwd,eventBus,runtime){return loadExtensionsInternal(paths,cwd,eventBus,runtime,!0)}function isExtensionFile(name){return name.endsWith(".ts")||name.endsWith(".js")}function resolveExtensionEntries2(dir){let packageJsonPath=path3.join(dir,"package.json");if(fs2.existsSync(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=path3.resolve(dir,extPath);fs2.existsSync(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=path3.join(dir,"index.ts"),indexJs=path3.join(dir,"index.js");return fs2.existsSync(indexTs)?[indexTs]:fs2.existsSync(indexJs)?[indexJs]:null}function discoverExtensionsInDir(dir){if(!fs2.existsSync(dir))return[];let discovered=[];try{let entries=fs2.readdirSync(dir,{withFileTypes:!0});for(let entry of entries){let entryPath=path3.join(dir,entry.name);if((entry.isFile()||entry.isSymbolicLink())&&isExtensionFile(entry.name)){discovered.push(entryPath);continue}if(entry.isDirectory()||entry.isSymbolicLink()){let entries2=resolveExtensionEntries2(entryPath);entries2&&discovered.push(...entries2)}}}catch{return[]}return discovered}async function discoverAndLoadExtensions(configuredPaths,cwd,agentDir=getAgentDir(),eventBus){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),allPaths=[],seen=new Set,addPaths=paths=>{for(let p of paths){let resolved=path3.resolve(p);seen.has(resolved)||(seen.add(resolved),allPaths.push(p))}},localExtDir=path3.join(resolvedCwd,CONFIG_DIR_NAME,"extensions");addPaths(discoverExtensionsInDir(localExtDir));let globalExtDir=path3.join(resolvedAgentDir,"extensions");addPaths(discoverExtensionsInDir(globalExtDir));for(let p of configuredPaths){let resolved=resolvePath(p,resolvedCwd,{normalizeUnicodeSpaces:!0});if(fs2.existsSync(resolved)&&fs2.statSync(resolved).isDirectory()){let entries=resolveExtensionEntries2(resolved);if(entries){addPaths(entries);continue}addPaths(discoverExtensionsInDir(resolved));continue}addPaths([resolved])}let result=await loadExtensions(allPaths,resolvedCwd,eventBus),isUnder=(file,dir)=>{let relative11=path3.relative(dir,path3.resolve(file));return!relative11.startsWith("..")&&!path3.isAbsolute(relative11)};for(let extension of result.extensions){let scope=isUnder(extension.resolvedPath,localExtDir)?"project":isUnder(extension.resolvedPath,globalExtDir)?"user":void 0;if(scope!==void 0){extension.sourceInfo={...extension.sourceInfo,scope};for(let tool of extension.tools.values())tool.sourceInfo=extension.sourceInfo;for(let command of extension.commands.values())command.sourceInfo=extension.sourceInfo}}return result}var ModelRegistry=class{runtime;constructor(runtime){this.runtime=runtime}refresh(options){return this.runtime.refresh(options)}getError(){return this.runtime.getError()}getAll(){return[...this.runtime.getModels()]}getAvailable(){return[...this.runtime.getAvailableSnapshot()]}find(provider,modelId){return this.runtime.getModel(provider,modelId)}findOfType(type,provider,modelId){return this.runtime.getModelOfType(type,provider,modelId)}hasConfiguredAuth(model){return this.runtime.hasConfiguredAuth(model.provider)}async getApiKeyAndHeaders(model){try{let resolution=await this.runtime.getAuth(model);if(!resolution){let compatibility=this.runtime.getCompatibilityRequestConfig(model);return compatibility.authHeader?{ok:!1,error:`No API key found for "${model.provider}"`}:{ok:!0,headers:compatibility.headers}}return{ok:!0,apiKey:resolution.auth.apiKey,headers:resolution.auth.headers,...resolution.auth.baseUrl?{baseUrl:resolution.auth.baseUrl}:{},env:resolution.env}}catch(error){let cause=error instanceof Error?error.cause:void 0,message=cause instanceof Error?cause.message:error instanceof Error?error.message:String(error);return{ok:!1,error:message==="authHeader requires a resolved API key"?`No API key found for "${model.provider}"`:message}}}getProviderAuthStatus(provider){return this.runtime.getProviderAuthStatus(provider)}getProvider(provider){return this.runtime.getProvider(provider)}stream(model,context,options){return this.runtime.stream(model,context,options)}streamSimple(model,context,options){return this.runtime.streamSimple(model,context,options)}complete(model,context,options){return this.runtime.complete(model,context,options)}getModelsOfType(type,provider){return this.runtime.getModelsOfType(type,provider)}getAvailableOfType(type,provider,options){return this.runtime.getAvailableOfType(type,provider,options)}getModelOfType(type,provider,modelId){return this.runtime.getModelOfType(type,provider,modelId)}classify(model,context,options){return this.runtime.classify(model,context,options)}generateImages(model,context,options){return this.runtime.generateImages(model,context,options)}getProviderDisplayName(provider){return this.runtime.getProvider(provider)?.name??provider}getProviderAuth(provider){return this.runtime.getAuth(provider)}async getApiKeyForProvider(provider){try{return(await this.runtime.getAuth(provider))?.auth.apiKey}catch{return}}isUsingOAuth(model){return this.runtime.isUsingOAuth(model.provider)}registerProvider(providerOrName,config){if(typeof providerOrName=="string"){if(!config)throw new Error("Provider config is required when registering by name");this.runtime.registerProvider(providerOrName,config);return}this.runtime.registerNativeProvider(providerOrName)}unregisterProvider(providerName){this.runtime.unregisterProvider(providerName)}registerVirtualModel(definition){this.runtime.registerVirtualModel(definition)}unregisterVirtualModel(providerName,id){this.runtime.unregisterVirtualModel(providerName,id)}getRegisteredProviderConfig(providerName){return this.runtime.getRegisteredProviderConfig(providerName)}getRegisteredNativeProvider(providerName){return this.runtime.getRegisteredNativeProvider(providerName)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}};import{constants as constants3}from"node:fs";import{access as fsAccess}from"node:fs/promises";import{constants as osConstants2}from"node:os";import{spawn as spawn2}from"child_process";import{open as open2}from"node:fs/promises";function byteLength(text){return Buffer.byteLength(text,"utf-8")}var OutputAccumulator=class{maxLines;maxBytes;maxRollingBytes;tempFilePrefix;decoder=new TextDecoder;rawChunks=[];tailText="";tailBytes=0;tailStartsAtLineBoundary=!0;totalRawBytes=0;totalDecodedBytes=0;completedLines=0;totalLines=0;currentLineBytes=0;hasOpenLine=!1;finished=!1;tempFilePath;tempFileStream;constructor(options={}){this.maxLines=options.maxLines??2e3,this.maxBytes=options.maxBytes??51200,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=options.tempFilePrefix??"pi-output"}append(data){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=data.length,this.appendDecodedText(this.decoder.decode(data,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(data)):data.length>0&&this.rawChunks.push(data)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(options={}){let snapshotText=this.getSnapshotText()||this.tailText,tailTruncation=truncateTail(snapshotText,{maxLines:this.maxLines,maxBytes:this.maxBytes}),truncated=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,truncatedBy=truncated?tailTruncation.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,truncation={...tailTruncation,truncated,truncatedBy,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return options.persistIfTruncated&&truncation.truncated&&this.ensureTempFile(),{content:truncation.content,truncation,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;let stream2=this.tempFileStream;this.tempFileStream=void 0,await new Promise((resolve20,reject)=>{let onError=error=>{stream2.off("finish",onFinish),reject(error)},onFinish=()=>{stream2.off("error",onError),resolve20()};stream2.once("error",onError),stream2.once("finish",onFinish),stream2.end()})}async readFullOutput(maxBytes){if(!this.tempFilePath)return{content:new TextDecoder().decode(Buffer.concat(this.rawChunks)),truncated:!1};let file=await open2(this.tempFilePath,"r");try{let size=(await file.stat()).size;if(size<=maxBytes)return{content:new TextDecoder().decode(await file.readFile()),truncated:!1};let headBytes=Math.floor(maxBytes/2),tailBytes=maxBytes-headBytes,head=Buffer.alloc(headBytes),tail=Buffer.alloc(tailBytes);await file.read(head,0,headBytes,0),await file.read(tail,0,tailBytes,size-tailBytes);let headText=new TextDecoder().decode(head,{stream:!0}),tailStart=0;for(;tailStart<tail.length&&(tail[tailStart]&192)===128;)tailStart++;let tailText=new TextDecoder().decode(tail.subarray(tailStart)),omitted=size-headBytes-tailBytes;return{content:`${headText}
|
|
618
618
|
|
|
619
619
|
[... ${omitted} bytes omitted ...]
|
|
620
620
|
|
|
@@ -980,10 +980,9 @@ Session file: ${issue.sessionFile}`:"";return`Stored session working directory d
|
|
|
980
980
|
Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`Session cwd does not exist: ${issue.sessionCwd}`}function getMissingSessionCwdOptions(issue){return[{label:`Continue in ${issue.fallbackCwd} (asks again next time)`,value:"continue"},{label:`Fork into ${issue.fallbackCwd} (new session ID, original kept)`,value:"fork"},{label:"Cancel",value:void 0}]}var MissingSessionCwdError=class extends Error{issue;constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}import{join as join22}from"node:path";function applyExtensionFlagValues(resourceLoader,extensionFlagValues){if(!extensionFlagValues)return[];let diagnostics=[],extensionsResult=resourceLoader.getExtensions(),registeredFlags=new Map;for(let extension of extensionsResult.extensions)for(let[name,flag]of extension.flags)registeredFlags.set(name,{type:flag.type});let unknownFlags=[];for(let[name,value]of extensionFlagValues){let flag=registeredFlags.get(name);if(!flag){unknownFlags.push(name);continue}if(flag.type==="boolean"){extensionsResult.runtime.flagValues.set(name,!0);continue}if(typeof value=="string"){extensionsResult.runtime.flagValues.set(name,value);continue}diagnostics.push({type:"error",message:`Extension flag "--${name}" requires a value`})}return unknownFlags.length>0&&diagnostics.push({type:"error",message:`Unknown option${unknownFlags.length===1?"":"s"}: ${unknownFlags.map(name=>`--${name}`).join(", ")}`}),diagnostics}async function createAgentSessionServices(options){let cwd=resolvePath(options.cwd),agentDir=options.agentDir?resolvePath(options.agentDir):getAgentDir(),modelRuntime=options.modelRuntime??await ModelRuntime.create({authPath:join22(agentDir,"auth.json"),modelsPath:join22(agentDir,"models.json"),signal:options.modelRuntimeSignal}),settingsManager=options.settingsManager??SettingsManager.create(cwd,agentDir),resourceLoader=new DefaultResourceLoader({...options.resourceLoaderOptions??{},cwd,cwdSpelling:options.cwd,agentDir,settingsManager,extensionFactories:[...CORE_BUILTIN_EXTENSIONS,...options.resourceLoaderOptions?.extensionFactories??[]]});await resourceLoader.reload(options.resourceLoaderReloadOptions);let diagnostics=[],extensionsResult=resourceLoader.getExtensions();for(let{name,config,extensionPath}of extensionsResult.runtime.pendingProviderRegistrations)try{modelRuntime.registerProvider(name,config)}catch(error){let message=error instanceof Error?error.message:String(error);diagnostics.push({type:"error",message:`Extension "${extensionPath}" error: ${message}`})}extensionsResult.runtime.pendingProviderRegistrations=[];for(let{provider,extensionPath}of extensionsResult.runtime.pendingNativeProviderRegistrations)try{modelRuntime.registerNativeProvider(provider)}catch(error){let message=error instanceof Error?error.message:String(error);diagnostics.push({type:"error",message:`Extension "${extensionPath}" error: ${message}`})}extensionsResult.runtime.pendingNativeProviderRegistrations=[];for(let{definition,extensionPath}of extensionsResult.runtime.pendingVirtualModelRegistrations)try{modelRuntime.registerVirtualModel(definition)}catch(error){let message=error instanceof Error?error.message:String(error);diagnostics.push({type:"error",message:`Extension "${extensionPath}" error: ${message}`})}return extensionsResult.runtime.pendingVirtualModelRegistrations=[],await modelRuntime.refresh({allowNetwork:!1}),diagnostics.push(...applyExtensionFlagValues(resourceLoader,options.extensionFlagValues)),{cwd,agentDir,modelRuntime,settingsManager,resourceLoader,diagnostics}}async function createAgentSessionFromServices(options){return createAgentSession({cwd:options.services.cwd,agentDir:options.services.agentDir,modelRuntime:options.services.modelRuntime,settingsManager:options.services.settingsManager,resourceLoader:options.services.resourceLoader,sessionManager:options.sessionManager,model:options.model,thinkingLevel:options.thinkingLevel,scopedModels:options.scopedModels,tools:options.tools,excludeTools:options.excludeTools,noTools:options.noTools,customTools:options.customTools,sessionStartEvent:options.sessionStartEvent})}var SessionImportFileNotFoundError=class extends Error{filePath;constructor(filePath){super(`File not found: ${filePath}`),this.name="SessionImportFileNotFoundError",this.filePath=filePath}};function extractUserMessageText(content){return typeof content=="string"?content:content.filter(part=>part.type==="text"&&typeof part.text=="string").map(part=>part.text).join("")}function cwdSpellingDivergence(spelling,cwd){let physical=realPathStrict(spelling),operating=realPathStrict(cwd);if(!(physical===void 0||operating===void 0||physical===operating))return{type:"warning",message:`cwd ${JSON.stringify(spelling)} resolves to ${JSON.stringify(operating)} once \`..\` is collapsed but to ${JSON.stringify(physical)} on disk. Tools run in the first; project context and skills are read from the second, and the first's own AGENTS.md is not loaded.`}}var AgentSessionRuntime=class{rebindSession;sessionReplacedListeners=new Set;beforeSessionInvalidate;_session;_services;_cwdSpelling;createRuntime;_diagnostics;_modelFallbackMessage;constructor(_session,_services,createRuntime,_diagnostics=[],_modelFallbackMessage,_cwdSpelling=_services.cwd){this._session=_session,this._services=_services,this._cwdSpelling=_cwdSpelling,this.createRuntime=createRuntime,this._diagnostics=_diagnostics,this._modelFallbackMessage=_modelFallbackMessage,this.reportCwdSpellingDivergence()}reportCwdSpellingDivergence(){let diagnostic=cwdSpellingDivergence(this._cwdSpelling,this._services.cwd);diagnostic&&(this._diagnostics=[...this._diagnostics,diagnostic])}get services(){return this._services}get session(){return this._session}get cwd(){return this._services.cwd}get cwdSpelling(){return this._cwdSpelling}get diagnostics(){return this._diagnostics}get modelFallbackMessage(){return this._modelFallbackMessage}setRebindSession(rebindSession){this.rebindSession=rebindSession}addSessionReplacedListener(listener){return this.sessionReplacedListeners.add(listener),()=>{this.sessionReplacedListeners.delete(listener)}}setBeforeSessionInvalidate(beforeSessionInvalidate){this.beforeSessionInvalidate=beforeSessionInvalidate}async emitBeforeSwitch(reason,targetSessionFile){let runner=this.session.extensionRunner;return runner.hasHandlers("session_before_switch")?{cancelled:(await runner.emit({type:"session_before_switch",reason,targetSessionFile}))?.cancel===!0}:{cancelled:!1}}async emitBeforeFork(entryId,options){let runner=this.session.extensionRunner;return runner.hasHandlers("session_before_fork")?{cancelled:(await runner.emit({type:"session_before_fork",entryId,...options}))?.cancel===!0}:{cancelled:!1}}async teardownCurrent(reason,targetSessionFile){await emitSessionShutdownEvent(this.session.extensionRunner,{type:"session_shutdown",reason,targetSessionFile}),this.beforeSessionInvalidate?.(),this.session.dispose()}apply(result){this._session=result.session,this._services=result.services,this._diagnostics=result.diagnostics,this._modelFallbackMessage=result.modelFallbackMessage}async applyNewRuntime(options){this.apply(await this.createRuntime({...options,agentDir:this.services.agentDir})),this._cwdSpelling=options.cwd,this.reportCwdSpellingDivergence()}async finishSessionReplacement(withSession){this.rebindSession&&await this.rebindSession(this.session);for(let listener of this.sessionReplacedListeners)await listener(this.session);withSession&&await withSession(this.session.createReplacedSessionContext())}async switchSession(sessionPath,options){let beforeResult=await this.emitBeforeSwitch("resume",sessionPath);if(beforeResult.cancelled)return beforeResult;let previousSessionFile=this.session.sessionFile,sessionManager=SessionManager.open(sessionPath,void 0,options?.cwdOverride);return assertSessionCwdExists(sessionManager,this.cwd),await this.teardownCurrent("resume",sessionManager.getSessionFile()),await this.applyNewRuntime({cwd:sessionManager.getCwd(),sessionManager,sessionStartEvent:{type:"session_start",reason:"resume",previousSessionFile},projectTrustContext:options?.projectTrustContextFactory?.(sessionManager.getCwd())}),await this.finishSessionReplacement(options?.withSession),{cancelled:!1}}async newSession(options){let beforeResult=await this.emitBeforeSwitch("new");if(beforeResult.cancelled)return beforeResult;let previousSessionFile=this.session.sessionFile,sessionDir=this.session.sessionManager.getSessionDir(),sessionManager=this.session.sessionManager.isPersisted()?SessionManager.create(this.cwd,sessionDir):SessionManager.inMemory(this.cwd);return options?.parentSession&&sessionManager.newSession({parentSession:options.parentSession}),await this.teardownCurrent("new",sessionManager.getSessionFile()),await this.applyNewRuntime({cwd:this.cwdSpelling,sessionManager,sessionStartEvent:{type:"session_start",reason:"new",previousSessionFile}}),options?.setup&&(await options.setup(this.session.sessionManager),this.session.refreshContext()),await this.finishSessionReplacement(options?.withSession),{cancelled:!1}}async fork(entryId,options){let position=options?.position??"before";if((await this.emitBeforeFork(entryId,{position})).cancelled)return{cancelled:!0};let targetLeafId,selectedText,selectedEntry=this.session.sessionManager.getEntry(entryId);if(!selectedEntry)throw new Error("Invalid entry ID for forking");if(position==="at")targetLeafId=selectedEntry.id;else{if(selectedEntry.type!=="message"||selectedEntry.message.role!=="user")throw new Error("Invalid entry ID for forking");targetLeafId=selectedEntry.parentId,selectedText=extractUserMessageText(selectedEntry.message.content)}let previousSessionFile=this.session.sessionFile;if(this.session.sessionManager.isPersisted()){let currentSessionFile=this.session.sessionFile;if(!currentSessionFile)throw new Error("Persisted session is missing a session file");let sessionDir=this.session.sessionManager.getSessionDir();if(!targetLeafId){let sessionManager3=SessionManager.create(this.cwd,sessionDir);return sessionManager3.newSession({parentSession:currentSessionFile}),await this.teardownCurrent("fork",sessionManager3.getSessionFile()),await this.applyNewRuntime({cwd:this.cwdSpelling,sessionManager:sessionManager3,sessionStartEvent:{type:"session_start",reason:"fork",previousSessionFile}}),await this.finishSessionReplacement(options?.withSession),{cancelled:!1,selectedText}}if(!existsSync18(currentSessionFile))throw new Error("This session has not been saved yet. Send a message before cloning or forking it.");let sessionManager2=SessionManager.open(currentSessionFile,sessionDir);if(!sessionManager2.createBranchedSession(targetLeafId))throw new Error("Failed to create forked session");return await this.teardownCurrent("fork",sessionManager2.getSessionFile()),await this.applyNewRuntime({cwd:sessionManager2.getCwd(),sessionManager:sessionManager2,sessionStartEvent:{type:"session_start",reason:"fork",previousSessionFile}}),await this.finishSessionReplacement(options?.withSession),{cancelled:!1,selectedText}}let sessionManager=this.session.sessionManager;return await this.teardownCurrent("fork",sessionManager.getSessionFile()),targetLeafId?sessionManager.createBranchedSession(targetLeafId):sessionManager.newSession({parentSession:previousSessionFile}),await this.applyNewRuntime({cwd:this.cwdSpelling,sessionManager,sessionStartEvent:{type:"session_start",reason:"fork",previousSessionFile}}),await this.finishSessionReplacement(options?.withSession),{cancelled:!1,selectedText}}async importFromJsonl(inputPath,cwdOverride){let resolvedPath=resolvePath(inputPath);if(!existsSync18(resolvedPath))throw new SessionImportFileNotFoundError(resolvedPath);let sessionDir=this.session.sessionManager.getSessionDir();existsSync18(sessionDir)||mkdirSync7(sessionDir,{recursive:!0});let destinationPath=join23(sessionDir,basename10(resolvedPath)),sourceAlreadyStored=pathsEqual(destinationPath,resolvedPath);if(!sourceAlreadyStored){let{name,ext:ext2}=parse3(destinationPath),suffix=1;for(;existsSync18(destinationPath);)destinationPath=join23(sessionDir,`${name}-${suffix++}${ext2}`)}let beforeResult=await this.emitBeforeSwitch("resume",destinationPath);if(beforeResult.cancelled)return beforeResult;let previousSessionFile=this.session.sessionFile;sourceAlreadyStored||copyFileSync2(resolvedPath,destinationPath,constants8.COPYFILE_EXCL);let sessionManager=SessionManager.open(destinationPath,sessionDir,cwdOverride);try{assertSessionCwdExists(sessionManager,this.cwd)}catch(error){throw sourceAlreadyStored||rmSync6(destinationPath,{force:!0}),error}return await this.teardownCurrent("resume",sessionManager.getSessionFile()),await this.applyNewRuntime({cwd:sessionManager.getCwd(),sessionManager,sessionStartEvent:{type:"session_start",reason:"resume",previousSessionFile}}),await this.finishSessionReplacement(),{cancelled:!1}}async dispose(){await this.session.abort(),await emitSessionShutdownEvent(this.session.extensionRunner,{type:"session_shutdown",reason:"quit"}),this.beforeSessionInvalidate?.(),this.session.dispose(),await this.services.modelRuntime.settleCredentialWrites()}};async function createAgentSessionRuntime(createRuntime,options){assertSessionCwdExists(options.sessionManager,options.cwd);let result=await createRuntime(options);return new AgentSessionRuntime(result.session,result.services,createRuntime,result.diagnostics,result.modelFallbackMessage,options.cwd)}setDefaultStreamFn(streamSimple);function getDefaultAgentDir(){return getAgentDir()}async function createAgentSession(options={}){let cwdSpelling=options.cwd??options.sessionManager?.getCwd()??process.cwd(),cwd=resolvePath(cwdSpelling),agentDir=options.agentDir?resolvePath(options.agentDir):getDefaultAgentDir(),resourceLoader=options.resourceLoader,authPath=options.agentDir?join24(agentDir,"auth.json"):void 0,modelsPath=options.agentDir?join24(agentDir,"models.json"):void 0,modelRuntime=options.modelRuntime??await ModelRuntime.create({authPath,modelsPath}),settingsManager=options.settingsManager??SettingsManager.create(cwd,agentDir),sessionManager=options.sessionManager??SessionManager.create(cwd,getDefaultSessionDir(cwd,agentDir));resourceLoader||(resourceLoader=new DefaultResourceLoader({cwd,cwdSpelling,agentDir,settingsManager,extensionFactories:[...CORE_BUILTIN_EXTENSIONS]}),await resourceLoader.reload(),time("resourceLoader.reload"));let existingSession=sessionManager.buildSessionContext(),hasExistingSession=existingSession.messages.length>0,hasThinkingEntry=sessionManager.getBranch().some(entry=>entry.type==="thinking_level_change"),model=options.model,modelFallbackMessage,sessionModel=getBranchSelection(sessionManager.getBranch(),(provider,modelId)=>modelRuntime.getModel(provider,modelId));if(!model&&hasExistingSession&&sessionModel){let restoredModel=modelRuntime.getModel(sessionModel.provider,sessionModel.modelId);restoredModel&&modelRuntime.hasConfiguredAuth(restoredModel.provider)&&(model=applyContextWindow(restoredModel,existingSession.model?.contextWindow)),model||(modelFallbackMessage=`Could not restore model ${sessionModel.provider}/${sessionModel.modelId}`)}model||(model=(await findInitialModel({scopedModels:[],isContinuing:hasExistingSession,defaultProvider:settingsManager.getDefaultProvider(),defaultModelId:settingsManager.getDefaultModel(),defaultThinkingLevel:settingsManager.getDefaultThinkingLevel(),modelThinkingLevels:settingsManager.getAllModelThinkingLevels(),modelRuntime})).model,model?modelFallbackMessage&&(modelFallbackMessage+=`. Using ${model.provider}/${model.id}`):modelFallbackMessage=formatNoModelsAvailableMessage());let thinkingLevel=options.thinkingLevel;if(thinkingLevel===void 0&&hasExistingSession&&(thinkingLevel=hasThinkingEntry?existingSession.thinkingLevel:settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),thinkingLevel===void 0&&model){let perModel=settingsManager.getModelThinkingLevel(model.provider,model.id);perModel&&(thinkingLevel=perModel)}thinkingLevel===void 0&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),model?thinkingLevel=clampThinkingLevel(model,thinkingLevel):thinkingLevel="off";let toolListError=options.tools?getToolListError(options.tools):void 0;if(toolListError)throw new Error(`Invalid tools option: ${toolListError}`);let defaultToolNames=options.noTools?[]:settingsManager.getDefaultTools()??DEFAULT_TOOL_NAMES,toolModifiers=options.tools?.some(isToolModifier)?options.tools:void 0,selectedToolNames=toolModifiers?applyToolModifiers(defaultToolNames,toolModifiers):options.tools,allowedToolNames=toolModifiers?options.noTools==="all"?selectedToolNames:void 0:options.tools??(options.noTools==="all"?[]:void 0),excludedToolNames=options.excludeTools,isExcludedTool=excludedToolNames?createToolNameMatcher(excludedToolNames):void 0,initialActiveToolNames=(selectedToolNames??defaultToolNames).filter(name=>!isExcludedTool?.(name)),convertToLlmWithBlockImages=messages=>{let converted=convertToLlm(messages);return settingsManager.getBlockImages()?converted.map(msg=>{if(msg.role==="user"||msg.role==="toolResult"){let content=msg.content;if(Array.isArray(content)&&content.some(c=>c.type==="image")){let filteredContent=content.map(c=>c.type==="image"?{type:"text",text:"Image reading is disabled."}:c).filter((c,i,arr)=>!(c.type==="text"&&c.text==="Image reading is disabled."&&i>0&&arr[i-1].type==="text"&&arr[i-1].text==="Image reading is disabled."));return{...msg,content:filteredContent}}}return msg}):converted},extensionRunnerRef={},cacheWarmer=new CacheWarmer(modelRuntime,sessionManager,()=>settingsManager.getCacheWarmingMode(),async event=>extensionRunnerRef.current?.emitCacheWarmingDecision(event)??event.action),buildRequestOptions=(options2={})=>{let providerRetrySettings=settingsManager.getProviderRetrySettings(),httpIdleTimeoutMs=settingsManager.getHttpIdleTimeoutMs(),effectiveTimeoutMs=httpIdleTimeoutMs===0?2147483647:httpIdleTimeoutMs,headerRunner=extensionRunnerRef.current;return{...options2,timeoutMs:options2.timeoutMs??providerRetrySettings.timeoutMs??effectiveTimeoutMs,websocketConnectTimeoutMs:options2.websocketConnectTimeoutMs??settingsManager.getWebSocketConnectTimeoutMs(),maxRetries:options2.maxRetries??providerRetrySettings.maxRetries,maxRetryDelayMs:options2.maxRetryDelayMs??providerRetrySettings.maxRetryDelayMs,identity:getClientIdentity(settingsManager),transformHeaders:async headers=>headerRunner?.hasHandlers("before_provider_headers")?headerRunner.emitBeforeProviderHeaders(headers):headers}},cacheContextIsCurrent=requestModel=>{let messages=agent.state.messages;return()=>{let currentModel=agent.state.model,currentMessages=agent.state.messages;return currentModel.provider===requestModel.provider&¤tModel.id===requestModel.id&&messages.length<=currentMessages.length&&messages.every((message,index)=>currentMessages[index]===message)}},transformProviderPayload=async payload=>{let runner=extensionRunnerRef.current;return runner?.hasHandlers("before_provider_request")?runner.emitBeforeProviderRequest(payload):payload},handleProviderResponse=async response=>{let runner=extensionRunnerRef.current;runner?.hasHandlers("after_provider_response")&&await runner.emit({type:"after_provider_response",status:response.status,headers:response.headers})},handleProviderStreamEvent=async(data,model2)=>{let runner=extensionRunnerRef.current;runner?.hasHandlers("provider_stream_event")&&await runner.emit({data,type:"provider_stream_event",provider:model2.provider,api:model2.api,model:model2.id})},agent=new Agent({initialState:{systemPrompt:"",model,thinkingLevel,tools:[],messages:existingSession.messages},convertToLlm:convertToLlmWithBlockImages,streamFn:async(model2,context,options2)=>{let requestOptions=buildRequestOptions(options2);return options2?.sessionId===sessionManager.getSessionId()&&cacheWarmer.start({model:model2,context,options:requestOptions},cacheContextIsCurrent(model2)),modelRuntime.streamSimple(model2,context,requestOptions)},onPayload:transformProviderPayload,onResponse:handleProviderResponse,onProviderStreamEvent:handleProviderStreamEvent,sessionId:sessionManager.getSessionId(),transformContext:async messages=>{let runner=extensionRunnerRef.current;return runner?runner.emitContext(messages):messages},steeringMode:settingsManager.getSteeringMode(),followUpMode:settingsManager.getFollowUpMode(),transport:settingsManager.getTransport(),thinkingBudgets:settingsManager.getThinkingBudgets(),maxRetryDelayMs:settingsManager.getProviderRetrySettings().maxRetryDelayMs});markRuntimeStreamFunction(agent.streamFunction,modelRuntime),hasExistingSession?hasThinkingEntry||sessionManager.appendThinkingLevelChange(thinkingLevel):(model&&sessionManager.appendModelChange(model.provider,model.id,model.contextWindow),sessionManager.appendThinkingLevelChange(thinkingLevel));let session=new AgentSession({agent,sessionManager,settingsManager,cwd,scopedModels:options.scopedModels,resourceLoader,customTools:options.customTools,modelRuntime,cacheWarmer,initialActiveToolNames,usesDefaultTools:(options.tools===void 0||toolModifiers!==void 0)&&!options.noTools,defaultToolModifiers:toolModifiers,allowedToolNames,excludedToolNames,extensionRunnerRef,sessionStartEvent:options.sessionStartEvent}),extensionsResult=resourceLoader.getExtensions();return{session,extensionsResult,modelFallbackMessage}}function readMode(pi){return pi.getSettings().codemode?.mode==="only"?"only":SETTINGS_DEFAULTS.codemode.mode}function readInlineBudget(pi){let budget=pi.getSettings().codemode?.inlineBudget;return typeof budget=="number"&&Number.isFinite(budget)&&budget>=0?budget:void 0}function createCodemodeExtension(options={}){return pi=>{pi.registerTool({...createCodemodeToolDefinition({appendEntry:(customType,data)=>pi.appendEntry(customType,data),models:options.models??!0,getToolNamespace:name=>pi.getAllTools().find(tool=>tool.name===name)?.namespace,getToolGuidelines:()=>new Map(pi.getAllTools().map(tool=>[tool.name,tool.promptGuidelines??[]])),getMode:()=>options.mode??readMode(pi),getInlineBudget:()=>options.inlineBudget??readInlineBudget(pi)}),defaultActive:!1})}}var codemode_default=createCodemodeExtension();import{randomUUID as randomUUID8}from"node:crypto";import{unlinkSync,writeFileSync as writeFileSync8}from"node:fs";import{platform as platform2,tmpdir as tmpdir3}from"node:os";import{join as join25}from"node:path";import{spawn as spawn6}from"node:child_process";function runClipboardCommand(command,args,options){return new Promise(resolve20=>{let child=spawn6(command,args,{stdio:["pipe",options?.input===void 0?"pipe":"ignore","ignore"],cwd:"/",detached:process.platform!=="win32",windowsHide:!0}),chunks=[],length=0,settled=!1,finish=result=>{settled||(settled=!0,clearTimeout(timer),resolve20(result))},abort=()=>{child.kill("SIGKILL"),child.stdout?.destroy(),child.stdin?.destroy(),finish(void 0)},timer=setTimeout(abort,options?.timeoutMs??3e3);child.on("error",()=>finish(void 0)),child.on("close",code=>{settled||finish(code===0?Buffer.concat(chunks,length):void 0)}),child.stdout?.on("data",chunk=>{settled||(length+=chunk.length,length>(options?.maxBufferBytes??50*1024*1024)?abort():chunks.push(chunk))}),child.stdin?.on("error",()=>{}),child.stdin?.end(options?.input)})}import{readFileSync as readFileSync16}from"node:fs";function isWSL(env=process.env){if(env.WSL_DISTRO_NAME||env.WSLENV)return!0;try{let release2=readFileSync16("/proc/version","utf-8");return/microsoft|wsl/i.test(release2)}catch{return!1}}var MAX_OSC52_ENCODED_LENGTH=1e5;function isRemoteSession(env){return!!(env.SSH_CONNECTION||env.SSH_CLIENT||env.MOSH_CONNECTION||env.DRAHT_CLIPBOARD_OSC52==="1")}function emitOsc52(text){let encoded=Buffer.from(text).toString("base64");return encoded.length>MAX_OSC52_ENCODED_LENGTH?!1:(process.stdout.write(`\x1B]52;c;${encoded}\x07`),!0)}async function copyViaWindowsClipboard(text){let tmpFile=join25(tmpdir3(),`draht-wsl-clip-${randomUUID8()}.txt`);try{writeFileSync8(tmpFile,text,{encoding:"utf8",mode:384});let winPath=(await runClipboardCommand("wslpath",["-w",tmpFile],{timeoutMs:1e3}))?.toString("utf8").trim();if(!winPath)return!1;let script=`Set-Clipboard -Value ([System.IO.File]::ReadAllText('${winPath.replaceAll("'","''")}', [System.Text.Encoding]::UTF8))`;return await runClipboardCommand("powershell.exe",["-NoProfile","-Command",script],{timeoutMs:5e3})!==void 0}catch{return!1}finally{try{unlinkSync(tmpFile)}catch{}}}async function readClipboardText(){let commands=[];process.env.TERMUX_VERSION&&commands.push(["termux-clipboard-get",[]]),platform2()==="linux"&&(process.env.WAYLAND_DISPLAY&&commands.push(["wl-paste",["--no-newline","--type","text"]]),process.env.DISPLAY&&commands.push(["xclip",["-selection","clipboard","-out"]],["xsel",["--clipboard","--output"]]));for(let[command,args]of commands){let bytes=await runClipboardCommand(command,args,{timeoutMs:5e3});if(bytes!==void 0)return bytes.toString("utf8")||null}try{return await getNativeClipboard()?.getText()||null}catch{return null}}async function readClipboardFilePaths(){let paths=await getNativeClipboard()?.getFilePaths?.();return paths?.length?paths:null}async function copyToClipboard(text){let p=platform2(),env=process.env,copied=!1;if(p!=="linux")try{let clipboard=getNativeClipboard();clipboard?.setText&&(await clipboard.setText(text),copied=!0)}catch{}if(!copied){let commands=[];p==="darwin"?commands.push(["pbcopy",[]]):p==="win32"?commands.push(["clip",[]]):(env.TERMUX_VERSION&&commands.push(["termux-clipboard-set",[]]),env.WAYLAND_DISPLAY&&commands.push(["wl-copy",[]]),env.DISPLAY&&commands.push(["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]));for(let[command,args]of commands)if(await runClipboardCommand(command,args,{input:text,timeoutMs:5e3})!==void 0){copied=!0;break}}let osc52Emitted=!1;!copied&&p==="linux"&&isWSL(env)&&(env.WT_SESSION&&(osc52Emitted=emitOsc52(text)),copied=osc52Emitted||await copyViaWindowsClipboard(text));let headless=p==="linux"&&!env.DISPLAY&&!env.WAYLAND_DISPLAY&&!env.TERMUX_VERSION,oversized=!1;if(!osc52Emitted&&(isRemoteSession(env)||!copied&&headless)&&(emitOsc52(text)?copied=!0:oversized=!0),!copied){if(oversized)throw new Error("Clipboard unavailable: text exceeds the OSC 52 size limit");if(env.TERMUX_VERSION)throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");if(p==="linux"){if(env.WAYLAND_DISPLAY)throw new Error("Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland access");if(env.DISPLAY)throw new Error("Clipboard unavailable: install `xclip` or `xsel`, or check X11 access")}throw new Error("Clipboard unavailable")}}import{join as join26,resolve as resolve12}from"node:path";function toToolExposure(exposure){return exposure==="codemode"?"deferred":exposure}var OUTPUT_PREVIEW_LINES=5;function saveToTempFile(data,extension){return writeOutputFile("draht-mcp",extension,data)}function textOf2(content){return content.filter(block=>block.type==="text").map(block=>block.text).join(`
|
|
981
981
|
`)}var CONTENT_BLOCK_SCHEMA={type:"object",properties:{type:{enum:["text","image","audio","resource_link","resource"]},text:{type:"string"},data:{type:"string"},mimeType:{type:"string"}},required:["type"],additionalProperties:!0},SCHEMA_DATA_KEYWORDS=new Set(["const","enum","default","examples"]),SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function relocateSchema(schema,pointer){if(Array.isArray(schema))return schema.map(item=>relocateSchema(item,pointer));if(typeof schema!="object"||schema===null)return schema;let relocated={};for(let[key,value]of Object.entries(schema))key==="$ref"&&typeof value=="string"&&(value==="#"||value.startsWith("#/"))?relocated[key]=`${pointer}${value.slice(1)}`:SCHEMA_DATA_KEYWORDS.has(key)?relocated[key]=value:SCHEMA_MAP_KEYWORDS.has(key)&&typeof value=="object"&&value!==null&&!Array.isArray(value)?relocated[key]=Object.fromEntries(Object.entries(value).map(([name,subschema])=>[name,relocateSchema(subschema,pointer)])):relocated[key]=relocateSchema(value,pointer);return relocated}function createMcpResultSchema(structuredContentSchema){return{type:"object",properties:{content:{type:"array",items:CONTENT_BLOCK_SCHEMA},structuredContent:structuredContentSchema?relocateSchema(structuredContentSchema,"#/properties/structuredContent"):{},isError:{type:"boolean"}},required:["content"],additionalProperties:!0}}function extensionOf(uri){let path20=URL.canParse(uri)?new URL(uri).pathname:uri;return/\.[A-Za-z0-9]{1,8}$/.exec(path20)?.[0]??".bin"}function isTextMimeType(mimeType){if(!mimeType)return!1;let type=mimeType.split(";",1)[0].trim().toLowerCase();return type.startsWith("text/")||type==="application/json"||type.endsWith("+json")||type.endsWith("+xml")}async function blockToContent(server,block,options){if(block.type==="resource_link"){let details=[block.mimeType,block.size===void 0?void 0:formatSize(block.size)].filter(Boolean),read=options.readableResources?`. Read it with ${READ_MCP_RESOURCE_TOOL} (server "${server}")`:"",description=block.description?`: ${block.description}`:"";return[{type:"text",text:`[Resource ${block.uri} "${block.title??block.name}"${details.length>0?` (${details.join(", ")})`:""}${description}${read}]`}]}if(block.type==="resource"&&"blob"in block.resource&&!block.resource.mimeType?.startsWith("image/")){let{uri,mimeType,blob}=block.resource,data=Buffer.from(blob,"base64");if(isTextMimeType(mimeType))return[{type:"text",text:data.toString("utf8")}];let kind=`${mimeType??"unknown type"}, ${formatSize(data.length)}`;try{let path20=await(options.saveOutput??saveToTempFile)(data,extensionOf(uri));return[{type:"text",text:`[Binary resource ${uri} (${kind}) saved to ${path20}]`}]}catch(error){let reason=error instanceof Error?error.message:String(error);return[{type:"text",text:`[Binary resource ${uri} (${kind}) could not be saved: ${reason}]`}]}}return toLlmContent({content:[block]})}async function toModelContent(server,blocks,options={}){return(await Promise.all(blocks.map(block=>blockToContent(server,block,options)))).flat()}async function convertMcpResult(server,tool,result,options={}){let converted=result.content.length>0?await toModelContent(server,result.content,options):toLlmContent(result);result.isError&&textOf2(converted)===""&&converted.push({type:"text",text:`MCP tool ${server}/${tool} returned an error`});let{content,fullOutputPath}=await limitMcpContent(converted,options.saveOutput??saveToTempFile),{_meta:_ignored,...scriptResult}=result;return{content,details:{server,tool,...fullOutputPath?{fullOutputPath}:{}},structuredContent:scriptResult,...result.isError?{isError:!0}:{}}}var ANNOTATION_HINTS=["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"];function toToolAnnotations(tool){let annotations={};for(let hint of ANNOTATION_HINTS){let value=tool.annotations?.[hint];typeof value=="boolean"&&(annotations[hint]=value)}return Object.keys(annotations).length>0?annotations:void 0}function createMcpToolDefinition(options){let{server,tool}=options,title=tool.title??tool.annotations?.title,annotations=toToolAnnotations(tool),label=`${server}/${tool.name}`;return{name:options.name,label,description:tool.description?.trim()||title||`MCP tool ${tool.name} from server ${server}`,parameters:normalizeMcpInputSchema(tool.inputSchema),outputSchema:createMcpResultSchema(tool.outputSchema),exposure:toToolExposure(options.exposure),namespace:options.namespace,...annotations?{annotations,annotationsScope:options.annotationsScope}:{},...createMcpToolRenderers(label),async execute(_toolCallId,params,signal,onUpdate){let result=await(await options.getClient()).callTool(tool.name,params??{},{signal,timeoutMs:options.timeoutMs,onProgress:progress=>{let total=progress.total===void 0?"":`/${progress.total}`,text=progress.message??`Progress ${progress.progress}${total}`;onUpdate?.({content:[{type:"text",text}],details:{server,tool:tool.name}})}});return convertMcpResult(server,tool.name,result,{readableResources:options.readableResources?.()})}}}function createMcpToolRenderers(label){return{renderCall(args,theme2,context){let component=context.lastComponent??new Text("",0,0);return component.setText(formatToolCallWithArgs(label,args,theme2,context.expanded)),component},renderResult(result,options,theme2,context){let component=context.lastComponent??new Container;component.clear();let output=getTextOutput(result,context.showImages).trim();if(!output)return component;let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
|
|
982
982
|
`).map(line=>theme2.fg(color,line)).join(`
|
|
983
|
-
`);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>`${theme2.fg("muted",`... (${hidden} more lines,`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme2.fg("muted",`Full output: ${fullOutputPath}`),0,0))}return component}}}function isMcpAppResource(item){return(item.uri??item.uriTemplate??"").startsWith("ui://")||/;\s*profile\s*=\s*"?mcp-app"?/i.test(item.mimeType??"")}function listed(server,item){let{_meta,icons:_icons,...rest}=item;return{server,...rest}}var stringProperty=description=>({type:"string",description}),SERVER_FILTER=stringProperty("MCP server name. Omit to list every server with resources."),CURSOR=stringProperty("Opaque cursor from a previous call with the same server; omit for the first page."),LIST_PARAMETERS={type:"object",properties:{server:SERVER_FILTER,cursor:CURSOR},additionalProperties:!1},READ_PARAMETERS={type:"object",properties:{server:stringProperty("MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources."),uri:stringProperty("Resource URI to read. Must be one of the URIs returned by list_mcp_resources.")},required:["server","uri"],additionalProperties:!1},optionalString={type:"string"},LISTING_ERRORS={type:"array",description:"Servers that could not be listed",items:{type:"object",properties:{server:{type:"string"},error:{type:"string"}},required:["server","error"]}},LIST_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resources:{type:"array",items:{type:"object",properties:{server:{type:"string"},uri:{type:"string"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString,size:{type:"number"}},required:["server","uri","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resources"]},LIST_TEMPLATES_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resourceTemplates:{type:"array",items:{type:"object",properties:{server:{type:"string"},uriTemplate:{type:"string",description:"RFC 6570 URI template"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString},required:["server","uriTemplate","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resourceTemplates"]},READ_OUTPUT_SCHEMA={type:"object",properties:{server:{type:"string"},uri:{type:"string"},contents:{type:"array",items:{anyOf:[{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,text:{type:"string"}},required:["uri","text"]},{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,blob:{type:"string",description:"base64"}},required:["uri","blob"]}]}}},required:["server","uri","contents"]};function stringArgument(params,key){let value=params?.[key];if(value!=null){if(typeof value!="string")throw new Error(`${key} must be a string`);return value.trim()||void 0}}function errorMessage(error){return error instanceof Error?error.message:String(error)}async function jsonResult(tool,server,payload){let{content,fullOutputPath}=await limitMcpContent([{type:"text",text:JSON.stringify(payload)}],saveToTempFile);return{content,details:{server:server??"",tool,...fullOutputPath?{fullOutputPath}:{}},structuredContent:payload}}function createMcpResourceToolDefinitions(options){let readOnly={readOnlyHint:!0},findServer=name=>{let servers=options.servers(),server=servers.find(candidate=>candidate.name===name);if(server)return server;let available=servers.map(candidate=>candidate.name).join(", ");throw new Error(`MCP server "${name}" has no resources${available?`. Servers with resources: ${available}`:""}`)},list=async(params,signal,key,page,all)=>{let serverName=stringArgument(params,"server"),cursor=stringArgument(params,"cursor"),visible=item=>!isMcpAppResource(item);if(serverName){let server=findServer(serverName),result=await page(server,cursor,{signal,timeoutMs:server.timeoutMs});return{server:server.name,[key]:result.items.filter(visible).map(item=>listed(server.name,item)),...result.nextCursor===void 0?{}:{nextCursor:result.nextCursor}}}if(cursor)throw new Error("cursor can only be used when a server is specified");let servers=[...options.servers()].sort((a,b)=>a.name.localeCompare(b.name)),results=await Promise.allSettled(servers.map(server=>all(server,{signal,timeoutMs:server.timeoutMs}))),items=[],errors=[];return results.forEach((result,index)=>{let server=servers[index].name;result.status==="fulfilled"?items.push(...result.value.filter(visible).map(item=>listed(server,item))):errors.push({server,error:errorMessage(result.reason)})}),{[key]:items,...errors.length>0?{errors}:{}}},listResources={name:LIST_MCP_RESOURCES_TOOL,label:LIST_MCP_RESOURCES_TOOL,description:"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resources",async(server,cursor,requestOptions)=>{let result=await server.resourcesPage(cursor,requestOptions);return{items:result.resources,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResources(requestOptions));return jsonResult(LIST_MCP_RESOURCES_TOOL,stringArgument(params,"server"),payload)}},listTemplates={name:LIST_MCP_RESOURCE_TEMPLATES_TOOL,label:LIST_MCP_RESOURCE_TEMPLATES_TOOL,description:"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_TEMPLATES_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resourceTemplates",async(server,cursor,requestOptions)=>{let result=await server.resourceTemplatesPage(cursor,requestOptions);return{items:result.resourceTemplates,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResourceTemplates(requestOptions));return jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL,stringArgument(params,"server"),payload)}},readResource={name:READ_MCP_RESOURCE_TOOL,label:READ_MCP_RESOURCE_TOOL,description:"Read a specific resource from an MCP server given the server name and resource URI.",parameters:READ_PARAMETERS,outputSchema:READ_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let serverName=stringArgument(params,"server"),uri=stringArgument(params,"uri");if(!serverName)throw new Error("server must be provided");if(!uri)throw new Error("uri must be provided");let server=findServer(serverName),result=await server.readResource(uri,{signal,timeoutMs:server.timeoutMs}),blocks=result.contents.flatMap(contents2=>[...result.contents.length>1?[{type:"text",text:`${contents2.uri}:`}]:[],{type:"resource",resource:contents2}]),converted=await toModelContent(server.name,blocks),{content,fullOutputPath}=await limitMcpContent(converted.length>0?converted:[{type:"text",text:`Resource ${uri} is empty.`}],saveToTempFile),contents=result.contents.map(({_meta:_ignored,...rest})=>rest);return{content,details:{server:server.name,tool:READ_MCP_RESOURCE_TOOL,...fullOutputPath?{fullOutputPath}:{}},structuredContent:{server:server.name,uri,contents}}}};return[listResources,listTemplates,readResource]}var loadMcpRuntime=()=>import("./runtime-L23MZBKL.js");var AuthUrlComponent=class extends Container{url;tui;hint;constructor(tui,url){super(),this.tui=tui,this.url=url,this.addChild(new Text(theme.fg("accent",hyperlink(url,url)),1,0)),this.hint=new Text("",1,0),this.addChild(this.hint),this.setHint(keyHint("app.message.copy","to copy"))}setHint(suffix){let clickHint=process.platform==="darwin"?"Cmd+click to open":"Ctrl+click to open";this.hint.setText(`${theme.fg("dim",hyperlink(clickHint,this.url))} ${theme.fg("dim","\u2022")} ${suffix}`),this.tui.requestRender()}async copy(){try{await copyToClipboard(this.url),this.setHint(theme.fg("success","Copied URL to clipboard"))}catch(error){this.setHint(theme.fg("error",error instanceof Error?error.message:String(error)))}}};function frame(theme2,title,body,footer){let container=new Container;container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container.addChild(new Text(theme2.fg("accent",theme2.bold(title)),1,0));for(let child of body)container.addChild(child);return footer&&(container.addChild(new Spacer(1)),container.addChild(new Text(theme2.fg("dim",footer),1,0))),container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container}var MAX_VISIBLE_ITEMS=12,McpManagerView=class{tui;theme;keybindings;content;inputHandler;inputTarget;_focused=!1;constructor(tui,theme2,keybindings){this.tui=tui,this.theme=theme2,this.keybindings=keybindings,this.content=frame(theme2,"MCP servers",[new Text(theme2.fg("muted","Loading\u2026"),1,1)])}get focused(){return this._focused}set focused(value){this._focused=value,this.inputTarget&&(this.inputTarget.focused=value)}get capturesViewportInput(){return this.inputHandler?.capturesViewportInput===!0}setContent(content,inputHandler,inputTarget){this.inputTarget&&(this.inputTarget.focused=!1),this.content=content,this.inputHandler=inputHandler,this.inputTarget=inputTarget,this.inputTarget&&(this.inputTarget.focused=this._focused),this.tui.requestRender()}menu(build2,subscribe){return new Promise(resolve20=>{let unsubscribe,settled=!1,finish=value=>{settled||(settled=!0,unsubscribe?.(),resolve20(value))},selected,render2=()=>{let menu=build2(),wanted=selected??menu.selected,body=[];menu.details&&body.push(new Text(this.theme.fg("muted",menu.details),1,0)),menu.error&&body.push(new Text(this.theme.fg("error",menu.error),1,0)),body.push(new Spacer(1));let footer=`${keyHint("tui.select.confirm",menu.confirmLabel)} \u2022 ${keyHint("tui.select.cancel",menu.cancelLabel)}`;if(menu.items.length===0){body.push(new Text(this.theme.fg("muted",menu.empty??"Nothing to show."),1,0)),this.setContent(frame(this.theme,menu.title,body,keyHint("tui.select.cancel",menu.cancelLabel)),{handleInput:data=>{this.keybindings.matches(data,"tui.select.cancel")&&finish(void 0)}});return}let list=new SelectList(menu.items,Math.min(menu.items.length,MAX_VISIBLE_ITEMS),getSelectListTheme()),index=menu.items.findIndex(item=>item.value===wanted);index!==-1&&list.setSelectedIndex(index),selected=list.getSelectedItem()?.value,list.onSelectionChange=item=>{selected=item.value},list.onSelect=item=>finish(item.value),list.onCancel=()=>finish(void 0),body.push(list),this.setContent(frame(this.theme,menu.title,body,footer),list)};render2(),unsubscribe=subscribe?.(()=>{settled||render2()})})}status(title,message,onCancel){let body=[new Spacer(1),new Text(this.theme.fg("muted",message),1,0)];if(!onCancel){this.setContent(frame(this.theme,title,body));return}this.setContent(frame(this.theme,title,body,keyHint("tui.select.cancel","cancel")),{handleInput:data=>{this.keybindings.matches(data,"tui.select.cancel")&&onCancel()}})}redirectUrl(title,authorizationUrl,signal){return new Promise(resolve20=>{let settled=!1,finish=value=>{settled||(settled=!0,signal.removeEventListener("abort",onAbort),resolve20(value))},onAbort=()=>finish(void 0);if(signal.aborted){finish(void 0);return}signal.addEventListener("abort",onAbort,{once:!0});let input2=new Input,link=new AuthUrlComponent(this.tui,authorizationUrl),body=[new Spacer(1),new Text(this.theme.fg("muted","Approve access in your browser. If it did not open, visit:"),1,0),link,new Spacer(1),new Text(this.theme.fg("muted","If the browser runs on another machine, paste the URL it was redirected to:"),1,0),input2];this.setContent(frame(this.theme,title,body,`${keyHint("tui.select.confirm","submit")} \u2022 ${keyHint("tui.select.cancel","cancel")}`),{handleInput:data=>{if(this.keybindings.matches(data,"tui.select.confirm")){let value=input2.getValue().trim();value&&finish(value);return}if(this.keybindings.matches(data,"tui.select.cancel")){finish(void 0);return}if(this.keybindings.matches(data,"app.message.copy")){link.copy();return}input2.handleInput(data)}},input2)})}handleInput(data){this.inputHandler?.handleInput?.(data),this.tui.requestRender()}render(width){return this.content.render(width).map(line=>visibleWidth(line)>width?truncateToWidth(line,width,""):line)}invalidate(){this.content.invalidate()}};async function showMcpManager(ctx,manage){await ctx.ui.custom((tui,theme2,keybindings,done)=>{let view=new McpManagerView(tui,theme2,keybindings);return manage(view).then(()=>done(),error=>{ctx.ui.notify(error instanceof Error?error.message:String(error),"error"),done()}),view})}var DEFAULT_STARTUP_WAIT_MS=1e4,RESOURCE_TOOL_NAMES=new Set([LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,READ_MCP_RESOURCE_TOOL]),EXPOSURE_DESCRIPTIONS={codemode:"called from codemode scripts, which find them with searchTools()",deferred:"not declared until tool_search loads them, then called directly; no codemode needed",direct:"declared to the model like built-in tools"};function errorMessage2(error){return error instanceof Error?error.message:String(error)}function firstLine4(text){return text.split(`
|
|
984
|
-
`,1)[0]??""}function isEnabled(server){return server.entry.config.enabled!==!1}function exposureOf(entry){return entry.config.exposure??"codemode"}function annotationsScopeOf(entry){return entry.scope==="global"?"user":entry.scope==="extension"?entry.extensionScope??"project":"project"}function configuredExposures(entry){return new Set([exposureOf(entry),...Object.values(entry.config.toolExposure??{})])}function hasDirectTools(entry){return configuredExposures(entry).has("direct")}function hasIndirectTools(entry){let exposures=configuredExposures(entry);return exposures.has("codemode")||exposures.has("deferred")}var MCP_SERVERS_SECTION="mcp_servers",MAX_SERVER_DESCRIPTION_CHARS=250,MAX_SERVERS_SECTION_CHARS=4096;function serversSectionIntro(reaches){let intro="MCP servers whose tools are not declared to you.";return reaches.has("codemode")&&(intro+=" Call the tools of `codemode` servers from codemode scripts."),reaches.has("tool_search")&&(intro+=" Load the tools of `tool_search` servers with `tool_search`."),intro}function truncate2(text,max){return text.length<=max?text:max<=1?"":`${sliceHead(text,max-1).trimEnd()}\u2026`}function
|
|
985
|
-
|
|
986
|
-
`).length,kept=listed2.length;for(;kept>0&&size(kept)>MAX_SERVERS_SECTION_CHARS;)kept--;let perServer=kept===0?0:Math.min(MAX_SERVER_DESCRIPTION_CHARS,Math.floor((MAX_SERVERS_SECTION_CHARS-size(kept))/kept)-2),lines=listed2.slice(0,kept).map((server,index)=>{let summary=perServer>0?truncate2(serverSummary(server),perServer):"";return summary?`${heads[index]}: ${summary}`:heads[index]});return[intro,...lines,...omitted(listed2.length-kept)].join(`
|
|
983
|
+
`);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>`${theme2.fg("muted",`... (${hidden} more lines,`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme2.fg("muted",`Full output: ${fullOutputPath}`),0,0))}return component}}}function isMcpAppResource(item){return(item.uri??item.uriTemplate??"").startsWith("ui://")||/;\s*profile\s*=\s*"?mcp-app"?/i.test(item.mimeType??"")}function listed(server,item){let{_meta,icons:_icons,...rest}=item;return{server,...rest}}var stringProperty=description=>({type:"string",description}),SERVER_FILTER=stringProperty("MCP server name. Omit to list every server with resources."),CURSOR=stringProperty("Opaque cursor from a previous call with the same server; omit for the first page."),LIST_PARAMETERS={type:"object",properties:{server:SERVER_FILTER,cursor:CURSOR},additionalProperties:!1},READ_PARAMETERS={type:"object",properties:{server:stringProperty("MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources."),uri:stringProperty("Resource URI to read. Must be one of the URIs returned by list_mcp_resources.")},required:["server","uri"],additionalProperties:!1},optionalString={type:"string"},LISTING_ERRORS={type:"array",description:"Servers that could not be listed",items:{type:"object",properties:{server:{type:"string"},error:{type:"string"}},required:["server","error"]}},LIST_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resources:{type:"array",items:{type:"object",properties:{server:{type:"string"},uri:{type:"string"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString,size:{type:"number"}},required:["server","uri","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resources"]},LIST_TEMPLATES_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resourceTemplates:{type:"array",items:{type:"object",properties:{server:{type:"string"},uriTemplate:{type:"string",description:"RFC 6570 URI template"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString},required:["server","uriTemplate","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resourceTemplates"]},READ_OUTPUT_SCHEMA={type:"object",properties:{server:{type:"string"},uri:{type:"string"},contents:{type:"array",items:{anyOf:[{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,text:{type:"string"}},required:["uri","text"]},{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,blob:{type:"string",description:"base64"}},required:["uri","blob"]}]}}},required:["server","uri","contents"]};function stringArgument(params,key){let value=params?.[key];if(value!=null){if(typeof value!="string")throw new Error(`${key} must be a string`);return value.trim()||void 0}}function errorMessage(error){return error instanceof Error?error.message:String(error)}async function jsonResult(tool,server,payload){let{content,fullOutputPath}=await limitMcpContent([{type:"text",text:JSON.stringify(payload)}],saveToTempFile);return{content,details:{server:server??"",tool,...fullOutputPath?{fullOutputPath}:{}},structuredContent:payload}}function createMcpResourceToolDefinitions(options){let readOnly={readOnlyHint:!0},findServer=name=>{let servers=options.servers(),server=servers.find(candidate=>candidate.name===name);if(server)return server;let available=servers.map(candidate=>candidate.name).join(", ");throw new Error(`MCP server "${name}" has no resources${available?`. Servers with resources: ${available}`:""}`)},list=async(params,signal,key,page,all)=>{let serverName=stringArgument(params,"server"),cursor=stringArgument(params,"cursor"),visible=item=>!isMcpAppResource(item);if(serverName){let server=findServer(serverName),result=await page(server,cursor,{signal,timeoutMs:server.timeoutMs});return{server:server.name,[key]:result.items.filter(visible).map(item=>listed(server.name,item)),...result.nextCursor===void 0?{}:{nextCursor:result.nextCursor}}}if(cursor)throw new Error("cursor can only be used when a server is specified");let servers=[...options.servers()].sort((a,b)=>a.name.localeCompare(b.name)),results=await Promise.allSettled(servers.map(server=>all(server,{signal,timeoutMs:server.timeoutMs}))),items=[],errors=[];return results.forEach((result,index)=>{let server=servers[index].name;result.status==="fulfilled"?items.push(...result.value.filter(visible).map(item=>listed(server,item))):errors.push({server,error:errorMessage(result.reason)})}),{[key]:items,...errors.length>0?{errors}:{}}},listResources={name:LIST_MCP_RESOURCES_TOOL,label:LIST_MCP_RESOURCES_TOOL,description:"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resources",async(server,cursor,requestOptions)=>{let result=await server.resourcesPage(cursor,requestOptions);return{items:result.resources,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResources(requestOptions));return jsonResult(LIST_MCP_RESOURCES_TOOL,stringArgument(params,"server"),payload)}},listTemplates={name:LIST_MCP_RESOURCE_TEMPLATES_TOOL,label:LIST_MCP_RESOURCE_TEMPLATES_TOOL,description:"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_TEMPLATES_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resourceTemplates",async(server,cursor,requestOptions)=>{let result=await server.resourceTemplatesPage(cursor,requestOptions);return{items:result.resourceTemplates,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResourceTemplates(requestOptions));return jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL,stringArgument(params,"server"),payload)}},readResource={name:READ_MCP_RESOURCE_TOOL,label:READ_MCP_RESOURCE_TOOL,description:"Read a specific resource from an MCP server given the server name and resource URI.",parameters:READ_PARAMETERS,outputSchema:READ_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let serverName=stringArgument(params,"server"),uri=stringArgument(params,"uri");if(!serverName)throw new Error("server must be provided");if(!uri)throw new Error("uri must be provided");let server=findServer(serverName),result=await server.readResource(uri,{signal,timeoutMs:server.timeoutMs}),blocks=result.contents.flatMap(contents2=>[...result.contents.length>1?[{type:"text",text:`${contents2.uri}:`}]:[],{type:"resource",resource:contents2}]),converted=await toModelContent(server.name,blocks),{content,fullOutputPath}=await limitMcpContent(converted.length>0?converted:[{type:"text",text:`Resource ${uri} is empty.`}],saveToTempFile),contents=result.contents.map(({_meta:_ignored,...rest})=>rest);return{content,details:{server:server.name,tool:READ_MCP_RESOURCE_TOOL,...fullOutputPath?{fullOutputPath}:{}},structuredContent:{server:server.name,uri,contents}}}};return[listResources,listTemplates,readResource]}var loadMcpRuntime=()=>import("./runtime-73OLLYOI.js");var AuthUrlComponent=class extends Container{url;tui;hint;constructor(tui,url){super(),this.tui=tui,this.url=url,this.addChild(new Text(theme.fg("accent",hyperlink(url,url)),1,0)),this.hint=new Text("",1,0),this.addChild(this.hint),this.setHint(keyHint("app.message.copy","to copy"))}setHint(suffix){let clickHint=process.platform==="darwin"?"Cmd+click to open":"Ctrl+click to open";this.hint.setText(`${theme.fg("dim",hyperlink(clickHint,this.url))} ${theme.fg("dim","\u2022")} ${suffix}`),this.tui.requestRender()}async copy(){try{await copyToClipboard(this.url),this.setHint(theme.fg("success","Copied URL to clipboard"))}catch(error){this.setHint(theme.fg("error",error instanceof Error?error.message:String(error)))}}};function frame(theme2,title,body,footer){let container=new Container;container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container.addChild(new Text(theme2.fg("accent",theme2.bold(title)),1,0));for(let child of body)container.addChild(child);return footer&&(container.addChild(new Spacer(1)),container.addChild(new Text(theme2.fg("dim",footer),1,0))),container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container}var MAX_VISIBLE_ITEMS=12,McpManagerView=class{tui;theme;keybindings;content;inputHandler;inputTarget;_focused=!1;constructor(tui,theme2,keybindings){this.tui=tui,this.theme=theme2,this.keybindings=keybindings,this.content=frame(theme2,"MCP servers",[new Text(theme2.fg("muted","Loading\u2026"),1,1)])}get focused(){return this._focused}set focused(value){this._focused=value,this.inputTarget&&(this.inputTarget.focused=value)}get capturesViewportInput(){return this.inputHandler?.capturesViewportInput===!0}setContent(content,inputHandler,inputTarget){this.inputTarget&&(this.inputTarget.focused=!1),this.content=content,this.inputHandler=inputHandler,this.inputTarget=inputTarget,this.inputTarget&&(this.inputTarget.focused=this._focused),this.tui.requestRender()}menu(build2,subscribe){return new Promise(resolve20=>{let unsubscribe,settled=!1,finish=value=>{settled||(settled=!0,unsubscribe?.(),resolve20(value))},selected,render2=()=>{let menu=build2(),wanted=selected??menu.selected,body=[];menu.details&&body.push(new Text(this.theme.fg("muted",menu.details),1,0)),menu.error&&body.push(new Text(this.theme.fg("error",menu.error),1,0)),body.push(new Spacer(1));let footer=`${keyHint("tui.select.confirm",menu.confirmLabel)} \u2022 ${keyHint("tui.select.cancel",menu.cancelLabel)}`;if(menu.items.length===0){body.push(new Text(this.theme.fg("muted",menu.empty??"Nothing to show."),1,0)),this.setContent(frame(this.theme,menu.title,body,keyHint("tui.select.cancel",menu.cancelLabel)),{handleInput:data=>{this.keybindings.matches(data,"tui.select.cancel")&&finish(void 0)}});return}let list=new SelectList(menu.items,Math.min(menu.items.length,MAX_VISIBLE_ITEMS),getSelectListTheme()),index=menu.items.findIndex(item=>item.value===wanted);index!==-1&&list.setSelectedIndex(index),selected=list.getSelectedItem()?.value,list.onSelectionChange=item=>{selected=item.value},list.onSelect=item=>finish(item.value),list.onCancel=()=>finish(void 0),body.push(list),this.setContent(frame(this.theme,menu.title,body,footer),list)};render2(),unsubscribe=subscribe?.(()=>{settled||render2()})})}status(title,message,onCancel){let body=[new Spacer(1),new Text(this.theme.fg("muted",message),1,0)];if(!onCancel){this.setContent(frame(this.theme,title,body));return}this.setContent(frame(this.theme,title,body,keyHint("tui.select.cancel","cancel")),{handleInput:data=>{this.keybindings.matches(data,"tui.select.cancel")&&onCancel()}})}redirectUrl(title,authorizationUrl,signal){return new Promise(resolve20=>{let settled=!1,finish=value=>{settled||(settled=!0,signal.removeEventListener("abort",onAbort),resolve20(value))},onAbort=()=>finish(void 0);if(signal.aborted){finish(void 0);return}signal.addEventListener("abort",onAbort,{once:!0});let input2=new Input,link=new AuthUrlComponent(this.tui,authorizationUrl),body=[new Spacer(1),new Text(this.theme.fg("muted","Approve access in your browser. If it did not open, visit:"),1,0),link,new Spacer(1),new Text(this.theme.fg("muted","If the browser runs on another machine, paste the URL it was redirected to:"),1,0),input2];this.setContent(frame(this.theme,title,body,`${keyHint("tui.select.confirm","submit")} \u2022 ${keyHint("tui.select.cancel","cancel")}`),{handleInput:data=>{if(this.keybindings.matches(data,"tui.select.confirm")){let value=input2.getValue().trim();value&&finish(value);return}if(this.keybindings.matches(data,"tui.select.cancel")){finish(void 0);return}if(this.keybindings.matches(data,"app.message.copy")){link.copy();return}input2.handleInput(data)}},input2)})}handleInput(data){this.inputHandler?.handleInput?.(data),this.tui.requestRender()}render(width){return this.content.render(width).map(line=>visibleWidth(line)>width?truncateToWidth(line,width,""):line)}invalidate(){this.content.invalidate()}};async function showMcpManager(ctx,manage){await ctx.ui.custom((tui,theme2,keybindings,done)=>{let view=new McpManagerView(tui,theme2,keybindings);return manage(view).then(()=>done(),error=>{ctx.ui.notify(error instanceof Error?error.message:String(error),"error"),done()}),view})}var DEFAULT_STARTUP_WAIT_MS=1e4,RESOURCE_TOOL_NAMES=new Set([LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,READ_MCP_RESOURCE_TOOL]),EXPOSURE_DESCRIPTIONS={codemode:"called from codemode scripts, which find them with searchTools()",deferred:"not declared until tool_search loads them, then called directly; no codemode needed",direct:"declared to the model like built-in tools"};function errorMessage2(error){return error instanceof Error?error.message:String(error)}function firstLine4(text){return text.split(`
|
|
984
|
+
`,1)[0]??""}function isEnabled(server){return server.entry.config.enabled!==!1}function exposureOf(entry){return entry.config.exposure??"codemode"}function annotationsScopeOf(entry){return entry.scope==="global"?"user":entry.scope==="extension"?entry.extensionScope??"project":"project"}function configuredExposures(entry){return new Set([exposureOf(entry),...Object.values(entry.config.toolExposure??{})])}function hasDirectTools(entry){return configuredExposures(entry).has("direct")}function hasIndirectTools(entry){let exposures=configuredExposures(entry);return exposures.has("codemode")||exposures.has("deferred")}var MCP_SERVERS_SECTION="mcp_servers",MAX_SERVER_DESCRIPTION_CHARS=250,MAX_SERVERS_SECTION_CHARS=4096;function serversSectionIntro(reaches){let intro="MCP servers whose tools are not declared to you.";return reaches.has("codemode")&&(intro+=" Call the tools of `codemode` servers from codemode scripts."),reaches.has("tool_search")&&(intro+=" Load the tools of `tool_search` servers with `tool_search`."),intro}function truncate2(text,max){return text.length<=max?text:max<=1?"":`${sliceHead(text,max-1).trimEnd()}\u2026`}function renderServersSection(servers){let listed2=servers.filter(server=>isEnabled(server)&&hasIndirectTools(server.entry)).sort((a,b)=>a.entry.name.localeCompare(b.entry.name));if(listed2.length===0)return;let reaches=listed2.map(server=>configuredExposures(server.entry).has("codemode")?"codemode":"tool_search"),intro=serversSectionIntro(new Set(reaches)),heads=listed2.map((server,index)=>`- ${mcpNamespace(server.entry.name)} (${reaches[index]})`),omitted=count=>count>0?[`- \u2026 ${count} more server${count===1?"":"s"}; find their tools with searchTools()`]:[],size=kept2=>[intro,...heads.slice(0,kept2),...omitted(listed2.length-kept2)].join(`
|
|
985
|
+
`).length,kept=listed2.length;for(;kept>0&&size(kept)>MAX_SERVERS_SECTION_CHARS;)kept--;let perServer=kept===0?0:Math.min(MAX_SERVER_DESCRIPTION_CHARS,Math.floor((MAX_SERVERS_SECTION_CHARS-size(kept))/kept)-2),lines=listed2.slice(0,kept).map((server,index)=>{let summary=perServer>0?truncate2(mcpServerSummary(server.entry.config.description,server.connection?.instructions),perServer):"";return summary?`${heads[index]}: ${summary}`:heads[index]});return[intro,...lines,...omitted(listed2.length-kept)].join(`
|
|
987
986
|
`)}function reachesServer(reach,server){if(reach==="all")return!0;let namespace=mcpNamespace(server);return reach.some(word=>word.includes(namespace))}function describeState(server,withError=!0){if(!isEnabled(server))return"disabled";let connection=server.connection;if(!connection)return"starting";switch(connection.state){case"needs-auth":return"needs sign-in";case"failed":return withError?`failed: ${firstLine4(connection.error??"unknown error")}`:"failed";case"connected":{let{tools,hasResources}=connection;return`connected \xB7 ${tools.length} tool${tools.length===1?"":"s"}${hasResources?" \xB7 resources":""}`}case"connecting":return"connecting\u2026";default:return connection.state}}function attentionRank(server){if(!isEnabled(server))return 5;switch(server.connection?.state){case"needs-auth":return 0;case"failed":return 1;case"disconnected":return 2;case"connected":return 4;default:return 3}}function describeTransport(entry){let{config}=entry;return"url"in config?config.url:[config.command,...config.args??[]].join(" ")}var MCP_USAGE="Usage: /mcp, /mcp login [server], /mcp logout [server], /mcp reconnect [server]";function createMcpExtension(options={}){return pi=>{let servers=[],configuredEntries=[],configErrors=[],projectConfig,overridden=[],autoEnableCodemode=!0,warnedUnreachable=!1,pending,waitedForStartup=!1,startupWaitMs=options.startupWaitMs??DEFAULT_STARTUP_WAIT_MS,sessionCwd=process.cwd(),credentials=options.credentials,modelRegistry,serverLog,openUrl=options.openUrl??openBrowser,updateConfig=options.updateConfig??((entry,patch)=>updateMcpServerConfig(entry.override??entry.source,entry.name,patch,{override:entry.override!==void 0})),session=new AbortController;session.abort();let backgroundActions=new Set,track=work=>{let task=work.then(()=>{},()=>{});return backgroundActions.add(task),task.finally(()=>backgroundActions.delete(task)),work},listeners=new Set,emitChange=()=>{for(let listener of listeners)listener()},subscribe=listener=>(listeners.add(listener),()=>{listeners.delete(listener)}),connections=()=>servers.flatMap(server=>server.connection?[server.connection]:[]),findServer=name=>servers.find(server=>server.entry.name===name),registeredServers=()=>{let registered=[],overriddenNames=[];for(let{name,config,extensionPath,extensionScope}of pi.getMcpServers()){let configured=configuredEntries.find(entry=>mcpNamespace(entry.name)===mcpNamespace(name));if(configured){overriddenNames.push(`"${name}" registered by ${extensionPath} is overridden by "${configured.name}" in ${configured.source}`);continue}registered.push({entry:{name,config,source:extensionPath,scope:"extension",extensionScope},registeredConfig:JSON.stringify(config)})}return{servers:registered,overridden:overriddenNames}},getCredentials=runtime=>(credentials??=new runtime.McpOAuthCredentialStore,credentials),getServerLog=runtime=>(serverLog??=new runtime.McpServerLog(options.logPath??join26(getAgentDir(),"mcp.log")),serverLog),toolOwners=new Map,serverTools=new Map,definitions=new Map;pi.registerToolRenderer((toolName,next)=>{let match2=/^mcp__(.+?)__(.+)$/.exec(toolName);return next()??(match2?createMcpToolRenderers(`${match2[1]}/${match2[2]}`):void 0)});let registerTools=connection=>{let server=connection.entry.name,entry=findServer(server)?.entry??connection.entry,description=entry.config.description?.trim(),namespace={name:mcpNamespace(server),aliases:[server],...description?{description}:{},...connection.instructions?{instructions:connection.instructions}:{}},previous=serverTools.get(server)??new Set,current=new Set,plain=[...new Set(connection.tools.map(tool=>tool.name))].map(tool=>createMcpToolName(server,tool)),assignName=(tool,owner)=>{let name=createMcpToolName(server,tool,candidate=>{let existing=toolOwners.get(candidate);return existing!==void 0&&existing!==owner||current.has(candidate)||plain.indexOf(candidate)!==plain.lastIndexOf(candidate)});return toolOwners.set(name,owner),current.add(name),name};for(let tool of connection.tools){let definition=createMcpToolDefinition({server,tool,name:assignName(tool.name,`${server}\0${tool.name}`),exposure:getMcpToolExposure(entry.config,tool.name),namespace,annotationsScope:annotationsScopeOf(entry),timeoutMs:connection.timeoutMs,getClient:async()=>{let current2=findServer(server);if(!current2||!isEnabled(current2))throw new Error(`MCP server "${server}" is disabled.`);let client=current2.connection;if(!client)throw new Error(`MCP server "${server}" is still starting.`);if(getMcpToolExposure(current2.entry.config,tool.name)==="hidden"||client.state==="connected"&&!client.tools.some(offered=>offered.name===tool.name))throw new Error(`MCP tool "${server}/${tool.name}" is no longer available.`);return client},readableResources:()=>resourceServers().some(current2=>current2.name===server)});definitions.set(definition.name,definition),pi.registerTool(definition)}serverTools.set(server,current);for(let name of previous){let definition=definitions.get(name);!current.has(name)&&definition&&pi.registerTool({...definition,exposure:"hidden"})}syncResourceTools()},hideTools=server=>{for(let name of serverTools.get(server)??[]){let definition=definitions.get(name);definition&&pi.registerTool({...definition,exposure:"hidden"})}serverTools.set(server,new Set),syncResourceTools()},serversWithResources=()=>servers.filter(server=>server.connection?.hasResources&&isEnabled(server)&&exposureOf(server.entry)!=="hidden"),resourceServers=()=>serversWithResources().flatMap(server=>server.connection?[server.connection]:[]),resourceToolsExposure,resourceToolsScope,syncResourceTools=()=>{let reached=serversWithResources(),exposures=new Set(reached.map(server=>exposureOf(server.entry))),next=["direct","codemode","deferred"].find(candidate=>exposures.has(candidate))??"hidden",scopes=new Set(reached.map(server=>annotationsScopeOf(server.entry))),scope=["project","user","temporary"].find(candidate=>scopes.has(candidate))??"user";if(next===resourceToolsExposure&&scope===resourceToolsScope||resourceToolsExposure===void 0&&next==="hidden")return;let wasDirect=resourceToolsExposure==="direct"&&next!=="direct";resourceToolsExposure=next,resourceToolsScope=scope;let resourceDefinitions=createMcpResourceToolDefinitions({exposure:next,servers:resourceServers});for(let definition of resourceDefinitions)pi.registerTool({...definition,annotationsScope:scope});if(wasDirect){let names=new Set(resourceDefinitions.map(definition=>definition.name));pi.setActiveTools(pi.getActiveTools().filter(name=>!names.has(name)))}},ensureDiscoveryActive=ctx=>{let exposures=new Set;for(let server of servers)if(isEnabled(server))for(let exposure of configuredExposures(server.entry))exposures.add(exposure);let needsCodemode=exposures.has("codemode"),needsToolSearch=exposures.has("deferred");if(!needsCodemode&&!needsToolSearch)return;let tools=pi.getAllTools(),hasReachingTool=name=>tools.some(tool=>tool.name===name&&tool.reachesTools),hasCodemode=hasReachingTool(CODEMODE_TOOL_NAME),hasToolSearch=hasReachingTool(TOOL_SEARCH_TOOL_NAME),active=pi.getActiveTools(),activate=[];needsCodemode&&hasCodemode&&autoEnableCodemode&&!active.includes(CODEMODE_TOOL_NAME)&&activate.push(CODEMODE_TOOL_NAME),needsToolSearch&&hasToolSearch&&!active.includes(TOOL_SEARCH_TOOL_NAME)&&activate.push(TOOL_SEARCH_TOOL_NAME),activate.length>0&&pi.setActiveTools([...active,...activate]);let reachable=[...active,...activate];if(hasCodemode&&reachable.includes(CODEMODE_TOOL_NAME)||hasToolSearch&&reachable.includes(TOOL_SEARCH_TOOL_NAME)||warnedUnreachable)return;warnedUnreachable=!0;let reason=needsCodemode&&hasCodemode&&!autoEnableCodemode?" (autoEnableCodemode is false)":"";ctx.ui.notify(`MCP tools are only reachable from the codemode or tool_search tool, but neither is active${reason}; they cannot be called.`,"warning")},tokensAtSignIn=new Map,storedTokens=connection=>{let url=connection.oauthUrl;return url&&credentials?JSON.stringify(credentials.tokens(connection.name,url)??null):"null"},onConnectionChange=connection=>{connection.state!=="needs-auth"?tokensAtSignIn.delete(connection):tokensAtSignIn.has(connection)||tokensAtSignIn.set(connection,storedTokens(connection)),emitChange()},reconnectSignedIn=async ctx=>{let signedIn=[...tokensAtSignIn].filter(([connection,tokens])=>storedTokens(connection)!==tokens);if(signedIn.length!==0){for(let[connection]of signedIn)tokensAtSignIn.delete(connection);await Promise.allSettled(signedIn.map(([connection])=>connection.reconnect())),ensureDiscoveryActive(ctx)}},createConnection=async(server,isCurrent)=>{let runtime=await loadMcpRuntime();if(!isCurrent())return;let connection=new runtime.McpServerConnection({entry:server.entry,cwd:sessionCwd,createTransport:options.createTransport??runtime.createDefaultTransport,credentials:getCredentials(runtime),providerToken:async provider=>modelRegistry?.getApiKeyForProvider(provider),log:getServerLog(runtime),onTools:connection2=>{isCurrent()&®isterTools(connection2)},onChange:connection2=>{isCurrent()?onConnectionChange(connection2):tokensAtSignIn.delete(connection2)}});return server.connection=connection,emitChange(),connection},startConnection=(server,after)=>{let{signal}=session,attempt=Symbol();server.attempt=attempt;let isCurrent=()=>!signal.aborted&&server.attempt===attempt&&isEnabled(server)&&servers.includes(server),ready=(async()=>{if(await after,!isCurrent())return;let connection=await createConnection(server,isCurrent);!connection||!isCurrent()||await connection.getClient().catch(()=>{})})();return server.ready=ready.catch(()=>{}),ready},waitForServers=async(waiting,signal)=>{for(;;){let ready=waiting.flatMap(server=>isEnabled(server)&&servers.includes(server)&&server.ready?[{server,ready:server.ready}]:[]);if(ready.length===0||signal?.aborted)return;let onAbort;if(await Promise.race([Promise.all(ready.map(attempt=>attempt.ready)),new Promise(resolve20=>{onAbort=()=>resolve20(),signal?.addEventListener("abort",onAbort,{once:!0})})]),onAbort&&signal?.removeEventListener("abort",onAbort),signal?.aborted||ready.every(attempt=>!isEnabled(attempt.server)||!servers.includes(attempt.server)||attempt.ready===attempt.server.ready))return}},reportProblems=(ctx,only)=>{let lines=only?[]:configErrors.map(error=>`config: ${error}`);for(let server of only??servers){let state2=server.connection?.state;(state2==="needs-auth"||state2==="failed")&&lines.push(`${server.entry.name}: ${describeState(server)}`)}lines.length!==0&&ctx.ui.notify(`MCP servers need attention:
|
|
988
987
|
${lines.map(line=>` ${line}`).join(`
|
|
989
988
|
`)}
|
|
@@ -1287,7 +1286,7 @@ This allows ${APP_NAME} to load ${CONFIG_DIR_NAME} settings and resources, insta
|
|
|
1287
1286
|
`).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
1288
1287
|
`);if(data)try{let event=JSON.parse(data);event&&typeof event.model=="string"&&typeof event.event=="string"&&onEvent(event)}catch{}boundary=buffer.indexOf(`
|
|
1289
1288
|
|
|
1290
|
-
`)}}}async loadAndWait(model,onProgress,signal){let watcher=new AbortController,unlink2=linkSignal(signal,watcher),eventLoaded=!1,eventError;this.watch(event=>{if(event.model!==model||event.event!=="model_status"&&event.event!=="status_change")return;let data=event.data;data?.status==="loaded"&&(eventLoaded=!0),data?.status==="unloaded"&&(eventError="Model failed to load");let progress=parseLoadProgress(event.data);progress&&onProgress(progress)},watcher.signal).catch(()=>{});try{for(await this.load(model,signal),onProgress({message:"Loading model"});;){if(signal?.aborted)throw signal.reason??new Error("Cancelled");let entry=(await this.list({signal})).find(candidate=>candidate.id===model);if(entry?.status.value==="loaded")return entry;if(eventLoaded&&!entry)return{id:model,status:{value:"loaded"}};if(entry?.status.failed||eventError)throw new Error(entry?.status.exit_code===void 0?eventError??"Model failed to load":`Model exited with code ${entry.status.exit_code}`);await sleep2(250,signal)}}finally{unlink2(),watcher.abort()}}async downloadAndWait(model,onProgress,signal){let watcher=new AbortController,unlink2=linkSignal(signal,watcher),finished=!1,failure2,sawDownloading=!1,polls=0;this.watch(event=>{if(event.model===model&&(event.event==="download_finished"&&(finished=!0),event.event==="download_failed"&&(failure2=errorMessage4(event.data,"Download failed")),event.event==="download_progress")){sawDownloading=!0;let progress=parseDownloadProgress(event.data);progress&&onProgress(progress)}},watcher.signal).catch(()=>{});try{for(await this.download(model,signal),onProgress({message:"Downloading model"});;){if(signal?.aborted)throw signal.reason??new Error("Cancelled");if(failure2)throw new Error(failure2);let models=await this.list({signal});polls++;let entry=models.find(candidate=>candidate.id===model);if(entry?.status.value==="downloading"){sawDownloading=!0;let progress=parseDownloadProgress(entry.status.progress);progress&&onProgress(progress)}else if(finished||entry&&(sawDownloading||polls>=2))return this.list({reload:!0,signal});await sleep2(500,signal)}}finally{unlink2(),watcher.abort()}}};import{readFile as readFile5}from"node:fs/promises";import{homedir as homedir3}from"node:os";import{join as join34}from"node:path";var DEFAULT_HUGGING_FACE_URL="https://huggingface.co",QUANTIZATION_PATTERN=/(?:^|[-_.])((?:UD-)?(?:IQ\d(?:_[A-Z0-9]+)+|Q\d(?:_[A-Z0-9]+)+|BF16|F16|F32|MXFP\d(?:_[A-Z0-9]+)*))$/iu,SHARD_SUFFIX_PATTERN=/-\d{5}-of-\d{5}$/u;function payloadError(payload,fallback){if(typeof payload!="object"||payload===null)return fallback;let error=payload.error;return typeof error=="string"&&error?error:fallback}function parseRateLimitDelay(value){let match2=value?.match(/(?:^|;)t=(\d+)/u);return match2?Number(match2[1]):void 0}async function readToken(path20){try{return(await readFile5(path20,"utf8")).trim()||void 0}catch{return}}async function findHuggingFaceToken(env=process.env){let fromEnvironment=env.HF_TOKEN?.trim();if(fromEnvironment)return fromEnvironment;let paths=[env.HF_TOKEN_PATH,env.HF_HOME?join34(env.HF_HOME,"token"):void 0,env.XDG_CACHE_HOME?join34(env.XDG_CACHE_HOME,"huggingface","token"):void 0,join34(homedir3(),".cache","huggingface","token")].filter(path20=>!!path20);for(let path20 of new Set(paths)){let token=await readToken(path20);if(token)return token}}var HuggingFaceClient=class{token;baseUrl;constructor(token,baseUrl=DEFAULT_HUGGING_FACE_URL){this.token=token,this.baseUrl=baseUrl.replace(/\/+$/u,"")}async request(path20,signal){let headers=new Headers;this.token&&headers.set("Authorization",`Bearer ${this.token}`);let timeout=AbortSignal.timeout(15e3),response=await fetch(`${this.baseUrl}${path20}`,{headers,signal:signal?AbortSignal.any([signal,timeout]):timeout}),payload;try{payload=await response.json()}catch{payload=void 0}if(!response.ok){let fallback=`Hugging Face returned HTTP ${response.status}`;if(response.status===429){let delay=Number(response.headers.get("retry-after"))||parseRateLimitDelay(response.headers.get("ratelimit"));throw new Error(delay?`Hugging Face rate limit reached; retry in ${delay}s`:"Hugging Face rate limit reached")}throw new Error(payloadError(payload,fallback))}return payload}async search(query,signal){let params=new URLSearchParams({search:query,filter:"gguf",sort:"downloads",direction:"-1",limit:"20"}),payload=await this.request(`/api/models?${params}`,signal);if(!Array.isArray(payload))throw new Error("Hugging Face returned invalid search results");return payload.flatMap(value=>{if(typeof value!="object"||value===null||typeof value.id!="string")return[];let model=value;return[{id:model.id,downloads:typeof model.downloads=="number"?model.downloads:0}]})}async details(id,signal){let encodedId=id.split("/").map(encodeURIComponent).join("/"),payload=await this.request(`/api/models/${encodedId}?blobs=true`,signal);if(typeof payload!="object"||payload===null)throw new Error("Hugging Face returned invalid model details");let model=payload,sizes=new Map;if(Array.isArray(model.siblings))for(let value of model.siblings){if(typeof value!="object"||value===null)continue;let file=value;if(typeof file.rfilename!="string"||!file.rfilename.toLowerCase().endsWith(".gguf"))continue;let filename=file.rfilename.split("/").at(-1);if(filename.toLowerCase().startsWith("mmproj"))continue;let quantization=filename.slice(0,-5).replace(SHARD_SUFFIX_PATTERN,"").match(QUANTIZATION_PATTERN)?.[1]?.toUpperCase();if(!quantization)continue;let current=sizes.get(quantization)??{total:0,complete:!0};typeof file.size=="number"?current.total+=file.size:current.complete=!1,sizes.set(quantization,current)}let quantizations=[...sizes].map(([name,size])=>({name,size:size.complete?size.total:void 0})).sort((left,right)=>left.name==="Q4_K_M"?-1:right.name==="Q4_K_M"?1:(left.size??Number.MAX_SAFE_INTEGER)-(right.size??Number.MAX_SAFE_INTEGER)||left.name.localeCompare(right.name));return{id:typeof model.id=="string"?model.id:id,gated:model.gated==="auto"||model.gated==="manual"?model.gated:!1,quantizations}}};var llamaCppClassifyApi=()=>({classify:async(model,context,options)=>(await import("./llama-cpp-classify-7DEQ4ZUF.js")).classify(model,context,options)});var LLAMA_PROVIDER_ID="llama.cpp",DEFAULT_LLAMA_SERVER_URL="http://127.0.0.1:9931";function credentialServerUrl(credential){let value=credential?.env?.LLAMA_BASE_URL;return typeof value=="string"&&value.trim()?normalizeLlamaServerUrl(value):void 0}async function resolveServerUrl(ctx,credential){let configured=credentialServerUrl(credential)??(await ctx.env("LLAMA_BASE_URL"))?.trim();return configured?normalizeLlamaServerUrl(configured):void 0}function modelIsSelectable(model,routerAutoload){return model.status.value==="loaded"||model.status.value==="sleeping"?!0:routerAutoload&&model.status.value==="unloaded"&&!model.status.failed&&model.source==="preset"}async function routerAutoloadEnabled(client,catalog,signal){if(!catalog.some(model=>model.status.value==="unloaded"&&model.source==="preset"))return!1;try{return(await client.props({signal})).models_autoload===!0}catch{return!1}}function configuredContextWindow(model){let args=model.status.args??[];for(let index=0;index<args.length-1;index++){let flag=args[index];if(flag!=="--ctx-size"&&flag!=="-c"&&flag!=="-ctx")continue;let contextWindow=Number(args[index+1]);if(Number.isSafeInteger(contextWindow)&&contextWindow>0)return contextWindow}}function contextWindowOf(model,cachedContextWindow){let runtimeContextWindow=model.meta?.n_ctx;if(runtimeContextWindow&&runtimeContextWindow>0)return runtimeContextWindow;let configuredContext=configuredContextWindow(model);if(configuredContext)return configuredContext;if(cachedContextWindow&&cachedContextWindow>0)return cachedContextWindow;let trainingContextWindow=model.meta?.n_ctx_train;return trainingContextWindow&&trainingContextWindow>0?trainingContextWindow:128e3}function isDecisionModel(model){return model.architecture?.output_modalities?.includes("decisions")===!0}function isChatModel(model){return!isDecisionModel(model)||model.architecture?.output_modalities?.includes("text")===!0}function toPiClassifierModel(model,serverUrl,cachedContextWindow){let decision=isDecisionModel(model);return{type:"classifier",id:model.id,name:model.id,api:decision?"typesafe-system-one":"llama-cpp-classify",provider:LLAMA_PROVIDER_ID,baseUrl:decision?llamaInferenceUrl(serverUrl):serverUrl,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:contextWindowOf(model,cachedContextWindow)}}function isLlamaClassifierModel(model){return isModelType(model,"classifier")&&(model.api==="llama-cpp-classify"||model.api==="typesafe-system-one")}function toPiModel(model,serverUrl,props,cachedContextWindow){let contextWindow=contextWindowOf(model,cachedContextWindow),reasoning=props?.chat_template?.includes("enable_thinking")===!0;return{id:model.id,name:model.id,api:"openai-completions",provider:LLAMA_PROVIDER_ID,baseUrl:llamaInferenceUrl(serverUrl),reasoning,...reasoning&&{thinkingLevelMap:{off:"off",minimal:null,low:null,medium:"medium",high:null,xhigh:null}},input:model.architecture?.input_modalities?.includes("image")?["text","image"]:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow,maxTokens:contextWindow,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0,supportsStrictMode:!1,maxTokensField:"max_tokens",...reasoning&&{thinkingFormat:"qwen-chat-template"}}}}function createLlamaProvider(){let models=[],classifiers=[],fallbackClassifier=llamaCppClassifyApi(),decisionClassifier=typesafeSystemOneApi(),setCatalog=(catalog,serverUrl,options={})=>{let selectable=catalog.filter(model=>modelIsSelectable(model,options.routerAutoload===!0));models=selectable.filter(isChatModel).map(model=>toPiModel(model,serverUrl)),classifiers=selectable.map(model=>toPiClassifierModel(model,serverUrl))};return{provider:{id:LLAMA_PROVIDER_ID,name:"llama.cpp",baseUrl:llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),auth:{apiKey:{name:"llama.cpp server",login:async interaction=>{let enteredUrl=await interaction.prompt({type:"text",message:"llama.cpp server URL",placeholder:process.env.LLAMA_BASE_URL??DEFAULT_LLAMA_SERVER_URL}),serverUrl=normalizeLlamaServerUrl(enteredUrl.trim()||process.env.LLAMA_BASE_URL||DEFAULT_LLAMA_SERVER_URL),apiKey=(await interaction.prompt({type:"secret",message:"API key (optional)"})).trim();return await new LlamaClient(serverUrl,apiKey||void 0).list({signal:interaction.signal}),{type:"api_key",key:apiKey||void 0,env:{LLAMA_BASE_URL:serverUrl}}},check:async({ctx,credential})=>await resolveServerUrl(ctx,credential)?{type:"api_key",source:credential?"stored credential":"LLAMA_BASE_URL"}:void 0,resolve:async({ctx,credential})=>{let serverUrl=await resolveServerUrl(ctx,credential);return serverUrl?{auth:{apiKey:credential?.key??await ctx.env("LLAMA_API_KEY")??"local",baseUrl:llamaInferenceUrl(serverUrl)},env:{...credential?.env,LLAMA_BASE_URL:serverUrl},source:credential?"stored credential":"LLAMA_BASE_URL"}:void 0}}},getModels:()=>models,getAllModels:()=>[...models,...classifiers],refreshModels:async context=>{let cachedContextWindows=new Map;if(context.stored){let stored=context.stored.models.filter(model=>model.provider===LLAMA_PROVIDER_ID),restored=stored.filter(model=>isModelType(model,"chat")&&model.api==="openai-completions"),restoredClassifiers=stored.filter(isLlamaClassifierModel);for(let model of[...restored,...restoredClassifiers])cachedContextWindows.set(model.id,model.contextWindow);if(!await context.publish({update:()=>{models=restored,classifiers=restoredClassifiers}}))return}if(!context.allowNetwork||context.signal.aborted||context.credential?.type!=="api_key")return;let serverUrl=credentialServerUrl(context.credential);if(!serverUrl)return;let client=new LlamaClient(serverUrl,context.credential.key),catalog=await client.list({signal:context.signal});if(context.signal.aborted)return;let routerAutoload=await routerAutoloadEnabled(client,catalog,context.signal);if(context.signal.aborted)return;let selectable=catalog.filter(model=>modelIsSelectable(model,routerAutoload)),refreshed=await Promise.all(selectable.filter(isChatModel).map(async model=>{let cachedContextWindow=cachedContextWindows.get(model.id);if(model.status.value!=="loaded")return toPiModel(model,serverUrl,void 0,cachedContextWindow);let props=await client.props({model:model.id,signal:context.signal});return toPiModel(model,serverUrl,props,cachedContextWindow)})),refreshedClassifiers=selectable.map(model=>toPiClassifierModel(model,serverUrl,cachedContextWindows.get(model.id)));context.signal.aborted||await context.publish({persist:{models:[...refreshed,...refreshedClassifiers],checkedAt:Date.now()},update:()=>{models=refreshed,classifiers=refreshedClassifiers}})},stream:(model,context,options)=>stream(model,context,options),streamSimple:(model,context,options)=>streamSimple(model,context,options),classify:(model,context,options)=>(model.api==="typesafe-system-one"?decisionClassifier:fallbackClassifier).classify(model,context,options)},setCatalog}}var DOWNLOAD_VALUE="\0download",SEARCH_MAX_VISIBLE=10;function contextLabel(model){let context=model.meta?.n_ctx??model.meta?.n_ctx_train;if(context)return context>=1e3?`${Math.round(context/1e3)}k`:String(context);let args=model.status.args??[];for(let index=0;index<args.length-1;index++){if(args[index]!=="--ctx-size"&&args[index]!=="-c"&&args[index]!=="-ctx")continue;let value=Number(args[index+1]);if(Number.isFinite(value)&&value>0)return value>=1e3?`${Math.round(value/1e3)}k`:String(value)}}function modelDescription(model){let details=[],loaded=model.status.value==="loaded"||model.status.value==="sleeping";loaded?details.push("loaded"):model.status.value!=="unloaded"&&details.push(model.status.value);let context=loaded?contextLabel(model):void 0;return context&&details.push(`${context} context`),details.join(" \xB7 ")}function selectTheme(theme2){return{selectedPrefix:text=>theme2.fg("accent",text),selectedText:text=>theme2.fg("accent",text),description:text=>theme2.fg("muted",text),scrollInfo:text=>theme2.fg("dim",text),noMatch:text=>theme2.fg("warning",text)}}function frame2(theme2,title,body,footer){let container=new Container;container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container.addChild(new Text(theme2.fg("accent",theme2.bold(title)),1,0));for(let child of body)container.addChild(child);return footer&&(container.addChild(new Spacer(1)),container.addChild(new Text(theme2.fg("dim",footer),1,0))),container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container}function compactCount(value){return value>=1e6?`${(value/1e6).toFixed(value>=1e7?0:1)}M`:value>=1e3?`${(value/1e3).toFixed(value>=1e5?0:1)}k`:String(value)}var HuggingFaceSearch=class extends Container{capturesViewportInput=!0;tui;theme;keybindings;search;cache;onSelectModel;input=new Input;resultsContainer=new Container;results=[];filteredResults=[];selectedIndex=0;selectionTouched=!1;query="";status="Type at least 2 characters";debounce;request;closed=!1;_focused=!1;constructor(tui,theme2,keybindings,search,cache2,onSelectModel){super(),this.tui=tui,this.theme=theme2,this.keybindings=keybindings,this.search=search,this.cache=cache2,this.onSelectModel=onSelectModel,this.addChild(new Text(theme2.fg("dim","Model name or owner/repository[:quant]"),1,0)),this.addChild(this.input),this.addChild(new Spacer(1)),this.addChild(this.resultsContainer),this.updateResults()}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}updateResults(){this.resultsContainer.clear();let start=Math.max(0,Math.min(this.selectedIndex-Math.floor(SEARCH_MAX_VISIBLE/2),this.filteredResults.length-SEARCH_MAX_VISIBLE)),end=Math.min(start+SEARCH_MAX_VISIBLE,this.filteredResults.length);for(let index=start;index<end;index++){let model=this.filteredResults[index];if(!model)continue;let prefix=index===this.selectedIndex?"\u2192 ":" ",details=`${compactCount(model.downloads)} downloads`;this.resultsContainer.addChild(new Text(index===this.selectedIndex?this.theme.fg("accent",`${prefix}${model.id} ${details}`):`${prefix}${model.id}${this.theme.fg("muted",` ${details}`)}`,0,0))}(start>0||end<this.filteredResults.length)&&this.resultsContainer.addChild(new Text(this.theme.fg("dim",` (${this.selectedIndex+1}/${this.filteredResults.length})`),0,0)),this.filteredResults.length===0?this.resultsContainer.addChild(new Text(this.theme.fg("dim",` ${this.status}`),0,0)):this.status==="Searching Hugging Face\u2026"&&this.resultsContainer.addChild(new Text(this.theme.fg("dim",` ${this.status}`),0,0)),this.tui.requestRender()}filterResults(preferredId){if(this.query){let matches2=new Set(fuzzyFilter(this.results,this.query,model=>model.id).map(model=>model.id));this.filteredResults=this.results.filter(model=>matches2.has(model.id))}else this.filteredResults=this.results;let preferredIndex=preferredId?this.filteredResults.findIndex(model=>model.id===preferredId):-1;preferredIndex>=0?this.selectedIndex=preferredIndex:this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredResults.length-1)),this.updateResults()}scheduleSearch(){if(this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.request=void 0,this.query.length<2){this.status="Type at least 2 characters",this.filterResults();return}let cached=this.cache.get(this.query.toLowerCase());if(cached){this.results=cached,this.status=cached.length===0?"No GGUF models found":"",this.filterResults();return}this.status="Searching Hugging Face\u2026",this.filterResults(),this.debounce=setTimeout(()=>{this.runSearch(this.query)},500)}async runSearch(query){let request=new AbortController;this.request=request;try{let results=await this.search(query,request.signal);if(this.cache.set(query.toLowerCase(),results),this.closed||request.signal.aborted||this.query!==query)return;let selectedId=this.selectionTouched?this.filteredResults[this.selectedIndex]?.id:void 0;this.results=results,this.selectedIndex=0,this.status=results.length===0?"No GGUF models found":"",this.filterResults(selectedId)}catch(error){if(this.closed||request.signal.aborted||this.query!==query)return;this.results=[],this.status=error instanceof Error?error.message:String(error),this.filterResults()}finally{this.request===request&&(this.request=void 0)}}close(model){this.closed||(this.closed=!0,this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.onSelectModel(model))}handleInput(data){if(this.keybindings.matches(data,"tui.select.up")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===0?this.filteredResults.length-1:this.selectedIndex-1,this.selectionTouched=!0,this.updateResults());return}if(this.keybindings.matches(data,"tui.select.down")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===this.filteredResults.length-1?0:this.selectedIndex+1,this.selectionTouched=!0,this.updateResults());return}let pageIndex=getSelectPageIndex(this.keybindings,data,this.selectedIndex,this.filteredResults.length,SEARCH_MAX_VISIBLE);if(pageIndex!==void 0){this.filteredResults.length>0&&(this.selectedIndex=pageIndex,this.selectionTouched=!0,this.updateResults());return}if(this.keybindings.matches(data,"tui.select.confirm")){let selected=(/^[^/\s]+\/[^:\s]+(?::[^\s:]+)?$/u.test(this.query)?this.query:void 0)??this.filteredResults[this.selectedIndex]?.id;selected&&this.close(selected);return}if(this.keybindings.matches(data,"tui.select.cancel")){this.close(void 0);return}this.input.handleInput(data);let query=this.input.getValue().trim();query!==this.query&&(this.query=query,this.selectionTouched=!1,this.scheduleSearch())}},LlamaView=class{tui;theme;keybindings;searchCache=new Map;content;inputHandler;inputTarget;progressPromise;progressResolver;showingProgress=!1;_focused=!1;constructor(tui,theme2,keybindings){this.tui=tui,this.theme=theme2,this.keybindings=keybindings,this.content=frame2(theme2,"llama.cpp models",[new Text(theme2.fg("muted","Loading\u2026"),1,1)])}get focused(){return this._focused}set focused(value){this._focused=value,this.inputTarget&&(this.inputTarget.focused=value)}get capturesViewportInput(){return this.inputHandler?.capturesViewportInput===!0}setContent(content,inputHandler,inputTarget){this.inputTarget&&(this.inputTarget.focused=!1),this.progressPromise=void 0,this.progressResolver=void 0,this.showingProgress=!1,this.content=content,this.inputHandler=inputHandler,this.inputTarget=inputTarget,this.inputTarget&&(this.inputTarget.focused=this._focused),this.tui.requestRender()}showModels(serverUrl,models){let sorted=[...models].sort((left,right)=>+(right.status.value==="loaded")-+(left.status.value==="loaded")||left.id.localeCompare(right.id)),byId=new Map(sorted.map(model=>[model.id,model])),items=[...sorted.map(model=>({value:model.id,label:model.id,description:modelDescription(model)})),{value:DOWNLOAD_VALUE,label:"Download model\u2026",description:"Hugging Face owner/repository[:quant]"}];return new Promise(resolve20=>{let list=new SelectList(items,Math.min(items.length,12),selectTheme(this.theme),{minPrimaryColumnWidth:36,maxPrimaryColumnWidth:56});list.onSelect=item=>{if(item.value===DOWNLOAD_VALUE)resolve20({type:"download"});else{let model=byId.get(item.value);model&&resolve20({type:"model",model})}},list.onCancel=()=>resolve20({type:"close"}),this.setContent(frame2(this.theme,"llama.cpp models",[new Text(this.theme.fg("dim",serverUrl),1,0),new Spacer(1),list],`${keyHint("tui.select.confirm","load/unload/download")} \u2022 ${keyHint("tui.select.cancel","close")}`),list)})}select(title,options){return new Promise(resolve20=>{let list=new SelectList(options.map(option=>({value:option,label:option})),Math.min(options.length,12),selectTheme(this.theme));list.onSelect=item=>resolve20(item.value),list.onCancel=()=>resolve20(void 0),this.setContent(frame2(this.theme,title,[new Spacer(1),list],`${keyHint("tui.select.confirm","select")} \u2022 ${keyHint("tui.select.cancel","cancel")}`),list)})}async confirm(title,message){return await this.select(`${title}
|
|
1289
|
+
`)}}}async loadAndWait(model,onProgress,signal){let watcher=new AbortController,unlink2=linkSignal(signal,watcher),eventLoaded=!1,eventError;this.watch(event=>{if(event.model!==model||event.event!=="model_status"&&event.event!=="status_change")return;let data=event.data;data?.status==="loaded"&&(eventLoaded=!0),data?.status==="unloaded"&&(eventError="Model failed to load");let progress=parseLoadProgress(event.data);progress&&onProgress(progress)},watcher.signal).catch(()=>{});try{for(await this.load(model,signal),onProgress({message:"Loading model"});;){if(signal?.aborted)throw signal.reason??new Error("Cancelled");let entry=(await this.list({signal})).find(candidate=>candidate.id===model);if(entry?.status.value==="loaded")return entry;if(eventLoaded&&!entry)return{id:model,status:{value:"loaded"}};if(entry?.status.failed||eventError)throw new Error(entry?.status.exit_code===void 0?eventError??"Model failed to load":`Model exited with code ${entry.status.exit_code}`);await sleep2(250,signal)}}finally{unlink2(),watcher.abort()}}async downloadAndWait(model,onProgress,signal){let watcher=new AbortController,unlink2=linkSignal(signal,watcher),finished=!1,failure2,sawDownloading=!1,polls=0;this.watch(event=>{if(event.model===model&&(event.event==="download_finished"&&(finished=!0),event.event==="download_failed"&&(failure2=errorMessage4(event.data,"Download failed")),event.event==="download_progress")){sawDownloading=!0;let progress=parseDownloadProgress(event.data);progress&&onProgress(progress)}},watcher.signal).catch(()=>{});try{for(await this.download(model,signal),onProgress({message:"Downloading model"});;){if(signal?.aborted)throw signal.reason??new Error("Cancelled");if(failure2)throw new Error(failure2);let models=await this.list({signal});polls++;let entry=models.find(candidate=>candidate.id===model);if(entry?.status.value==="downloading"){sawDownloading=!0;let progress=parseDownloadProgress(entry.status.progress);progress&&onProgress(progress)}else if(finished||entry&&(sawDownloading||polls>=2))return this.list({reload:!0,signal});await sleep2(500,signal)}}finally{unlink2(),watcher.abort()}}};import{readFile as readFile5}from"node:fs/promises";import{homedir as homedir3}from"node:os";import{join as join34}from"node:path";var DEFAULT_HUGGING_FACE_URL="https://huggingface.co",QUANTIZATION_PATTERN=/(?:^|[-_.])((?:UD-)?(?:IQ\d(?:_[A-Z0-9]+)+|Q\d(?:_[A-Z0-9]+)+|BF16|F16|F32|MXFP\d(?:_[A-Z0-9]+)*))$/iu,SHARD_SUFFIX_PATTERN=/-\d{5}-of-\d{5}$/u;function payloadError(payload,fallback){if(typeof payload!="object"||payload===null)return fallback;let error=payload.error;return typeof error=="string"&&error?error:fallback}function parseRateLimitDelay(value){let match2=value?.match(/(?:^|;)t=(\d+)/u);return match2?Number(match2[1]):void 0}async function readToken(path20){try{return(await readFile5(path20,"utf8")).trim()||void 0}catch{return}}async function findHuggingFaceToken(env=process.env){let fromEnvironment=env.HF_TOKEN?.trim();if(fromEnvironment)return fromEnvironment;let paths=[env.HF_TOKEN_PATH,env.HF_HOME?join34(env.HF_HOME,"token"):void 0,env.XDG_CACHE_HOME?join34(env.XDG_CACHE_HOME,"huggingface","token"):void 0,join34(homedir3(),".cache","huggingface","token")].filter(path20=>!!path20);for(let path20 of new Set(paths)){let token=await readToken(path20);if(token)return token}}var HuggingFaceClient=class{token;baseUrl;constructor(token,baseUrl=DEFAULT_HUGGING_FACE_URL){this.token=token,this.baseUrl=baseUrl.replace(/\/+$/u,"")}async request(path20,signal){let headers=new Headers;this.token&&headers.set("Authorization",`Bearer ${this.token}`);let timeout=AbortSignal.timeout(15e3),response=await fetch(`${this.baseUrl}${path20}`,{headers,signal:signal?AbortSignal.any([signal,timeout]):timeout}),payload;try{payload=await response.json()}catch{payload=void 0}if(!response.ok){let fallback=`Hugging Face returned HTTP ${response.status}`;if(response.status===429){let delay=Number(response.headers.get("retry-after"))||parseRateLimitDelay(response.headers.get("ratelimit"));throw new Error(delay?`Hugging Face rate limit reached; retry in ${delay}s`:"Hugging Face rate limit reached")}throw new Error(payloadError(payload,fallback))}return payload}async search(query,signal){let params=new URLSearchParams({search:query,filter:"gguf",sort:"downloads",direction:"-1",limit:"20"}),payload=await this.request(`/api/models?${params}`,signal);if(!Array.isArray(payload))throw new Error("Hugging Face returned invalid search results");return payload.flatMap(value=>{if(typeof value!="object"||value===null||typeof value.id!="string")return[];let model=value;return[{id:model.id,downloads:typeof model.downloads=="number"?model.downloads:0}]})}async details(id,signal){let encodedId=id.split("/").map(encodeURIComponent).join("/"),payload=await this.request(`/api/models/${encodedId}?blobs=true`,signal);if(typeof payload!="object"||payload===null)throw new Error("Hugging Face returned invalid model details");let model=payload,sizes=new Map;if(Array.isArray(model.siblings))for(let value of model.siblings){if(typeof value!="object"||value===null)continue;let file=value;if(typeof file.rfilename!="string"||!file.rfilename.toLowerCase().endsWith(".gguf"))continue;let filename=file.rfilename.split("/").at(-1);if(filename.toLowerCase().startsWith("mmproj"))continue;let quantization=filename.slice(0,-5).replace(SHARD_SUFFIX_PATTERN,"").match(QUANTIZATION_PATTERN)?.[1]?.toUpperCase();if(!quantization)continue;let current=sizes.get(quantization)??{total:0,complete:!0};typeof file.size=="number"?current.total+=file.size:current.complete=!1,sizes.set(quantization,current)}let quantizations=[...sizes].map(([name,size])=>({name,size:size.complete?size.total:void 0})).sort((left,right)=>left.name==="Q4_K_M"?-1:right.name==="Q4_K_M"?1:(left.size??Number.MAX_SAFE_INTEGER)-(right.size??Number.MAX_SAFE_INTEGER)||left.name.localeCompare(right.name));return{id:typeof model.id=="string"?model.id:id,gated:model.gated==="auto"||model.gated==="manual"?model.gated:!1,quantizations}}};var llamaCppClassifyApi=()=>({classify:async(model,context,options)=>(await import("./llama-cpp-classify-6LLMLBUC.js")).classify(model,context,options)});var LLAMA_PROVIDER_ID="llama.cpp",DEFAULT_LLAMA_SERVER_URL="http://127.0.0.1:9931";function credentialServerUrl(credential){let value=credential?.env?.LLAMA_BASE_URL;return typeof value=="string"&&value.trim()?normalizeLlamaServerUrl(value):void 0}async function resolveServerUrl(ctx,credential){let configured=credentialServerUrl(credential)??(await ctx.env("LLAMA_BASE_URL"))?.trim();return configured?normalizeLlamaServerUrl(configured):void 0}function modelIsSelectable(model,routerAutoload){return model.status.value==="loaded"||model.status.value==="sleeping"?!0:routerAutoload&&model.status.value==="unloaded"&&!model.status.failed&&model.source==="preset"}async function routerAutoloadEnabled(client,catalog,signal){if(!catalog.some(model=>model.status.value==="unloaded"&&model.source==="preset"))return!1;try{return(await client.props({signal})).models_autoload===!0}catch{return!1}}function configuredContextWindow(model){let args=model.status.args??[];for(let index=0;index<args.length-1;index++){let flag=args[index];if(flag!=="--ctx-size"&&flag!=="-c"&&flag!=="-ctx")continue;let contextWindow=Number(args[index+1]);if(Number.isSafeInteger(contextWindow)&&contextWindow>0)return contextWindow}}function contextWindowOf(model,cachedContextWindow){let runtimeContextWindow=model.meta?.n_ctx;if(runtimeContextWindow&&runtimeContextWindow>0)return runtimeContextWindow;let configuredContext=configuredContextWindow(model);if(configuredContext)return configuredContext;if(cachedContextWindow&&cachedContextWindow>0)return cachedContextWindow;let trainingContextWindow=model.meta?.n_ctx_train;return trainingContextWindow&&trainingContextWindow>0?trainingContextWindow:128e3}function isDecisionModel(model){return model.architecture?.output_modalities?.includes("decisions")===!0}function isChatModel(model){return!isDecisionModel(model)||model.architecture?.output_modalities?.includes("text")===!0}function toPiClassifierModel(model,serverUrl,cachedContextWindow){let decision=isDecisionModel(model);return{type:"classifier",id:model.id,name:model.id,api:decision?"typesafe-system-one":"llama-cpp-classify",provider:LLAMA_PROVIDER_ID,baseUrl:decision?llamaInferenceUrl(serverUrl):serverUrl,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:contextWindowOf(model,cachedContextWindow)}}function isLlamaClassifierModel(model){return isModelType(model,"classifier")&&(model.api==="llama-cpp-classify"||model.api==="typesafe-system-one")}function toPiModel(model,serverUrl,props,cachedContextWindow){let contextWindow=contextWindowOf(model,cachedContextWindow),reasoning=props?.chat_template?.includes("enable_thinking")===!0;return{id:model.id,name:model.id,api:"openai-completions",provider:LLAMA_PROVIDER_ID,baseUrl:llamaInferenceUrl(serverUrl),reasoning,...reasoning&&{thinkingLevelMap:{off:"off",minimal:null,low:null,medium:"medium",high:null,xhigh:null}},input:model.architecture?.input_modalities?.includes("image")?["text","image"]:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow,maxTokens:contextWindow,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0,supportsStrictMode:!1,maxTokensField:"max_tokens",...reasoning&&{thinkingFormat:"qwen-chat-template"}}}}function createLlamaProvider(){let models=[],classifiers=[],fallbackClassifier=llamaCppClassifyApi(),decisionClassifier=typesafeSystemOneApi(),setCatalog=(catalog,serverUrl,options={})=>{let selectable=catalog.filter(model=>modelIsSelectable(model,options.routerAutoload===!0));models=selectable.filter(isChatModel).map(model=>toPiModel(model,serverUrl)),classifiers=selectable.map(model=>toPiClassifierModel(model,serverUrl))};return{provider:{id:LLAMA_PROVIDER_ID,name:"llama.cpp",baseUrl:llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),auth:{apiKey:{name:"llama.cpp server",login:async interaction=>{let enteredUrl=await interaction.prompt({type:"text",message:"llama.cpp server URL",placeholder:process.env.LLAMA_BASE_URL??DEFAULT_LLAMA_SERVER_URL}),serverUrl=normalizeLlamaServerUrl(enteredUrl.trim()||process.env.LLAMA_BASE_URL||DEFAULT_LLAMA_SERVER_URL),apiKey=(await interaction.prompt({type:"secret",message:"API key (optional)"})).trim();return await new LlamaClient(serverUrl,apiKey||void 0).list({signal:interaction.signal}),{type:"api_key",key:apiKey||void 0,env:{LLAMA_BASE_URL:serverUrl}}},check:async({ctx,credential})=>await resolveServerUrl(ctx,credential)?{type:"api_key",source:credential?"stored credential":"LLAMA_BASE_URL"}:void 0,resolve:async({ctx,credential})=>{let serverUrl=await resolveServerUrl(ctx,credential);return serverUrl?{auth:{apiKey:credential?.key??await ctx.env("LLAMA_API_KEY")??"local",baseUrl:llamaInferenceUrl(serverUrl)},env:{...credential?.env,LLAMA_BASE_URL:serverUrl},source:credential?"stored credential":"LLAMA_BASE_URL"}:void 0}}},getModels:()=>models,getAllModels:()=>[...models,...classifiers],refreshModels:async context=>{let cachedContextWindows=new Map;if(context.stored){let stored=context.stored.models.filter(model=>model.provider===LLAMA_PROVIDER_ID),restored=stored.filter(model=>isModelType(model,"chat")&&model.api==="openai-completions"),restoredClassifiers=stored.filter(isLlamaClassifierModel);for(let model of[...restored,...restoredClassifiers])cachedContextWindows.set(model.id,model.contextWindow);if(!await context.publish({update:()=>{models=restored,classifiers=restoredClassifiers}}))return}if(!context.allowNetwork||context.signal.aborted||context.credential?.type!=="api_key")return;let serverUrl=credentialServerUrl(context.credential);if(!serverUrl)return;let client=new LlamaClient(serverUrl,context.credential.key),catalog=await client.list({signal:context.signal});if(context.signal.aborted)return;let routerAutoload=await routerAutoloadEnabled(client,catalog,context.signal);if(context.signal.aborted)return;let selectable=catalog.filter(model=>modelIsSelectable(model,routerAutoload)),refreshed=await Promise.all(selectable.filter(isChatModel).map(async model=>{let cachedContextWindow=cachedContextWindows.get(model.id);if(model.status.value!=="loaded")return toPiModel(model,serverUrl,void 0,cachedContextWindow);let props=await client.props({model:model.id,signal:context.signal});return toPiModel(model,serverUrl,props,cachedContextWindow)})),refreshedClassifiers=selectable.map(model=>toPiClassifierModel(model,serverUrl,cachedContextWindows.get(model.id)));context.signal.aborted||await context.publish({persist:{models:[...refreshed,...refreshedClassifiers],checkedAt:Date.now()},update:()=>{models=refreshed,classifiers=refreshedClassifiers}})},stream:(model,context,options)=>stream(model,context,options),streamSimple:(model,context,options)=>streamSimple(model,context,options),classify:(model,context,options)=>(model.api==="typesafe-system-one"?decisionClassifier:fallbackClassifier).classify(model,context,options)},setCatalog}}var DOWNLOAD_VALUE="\0download",SEARCH_MAX_VISIBLE=10;function contextLabel(model){let context=model.meta?.n_ctx??model.meta?.n_ctx_train;if(context)return context>=1e3?`${Math.round(context/1e3)}k`:String(context);let args=model.status.args??[];for(let index=0;index<args.length-1;index++){if(args[index]!=="--ctx-size"&&args[index]!=="-c"&&args[index]!=="-ctx")continue;let value=Number(args[index+1]);if(Number.isFinite(value)&&value>0)return value>=1e3?`${Math.round(value/1e3)}k`:String(value)}}function modelDescription(model){let details=[],loaded=model.status.value==="loaded"||model.status.value==="sleeping";loaded?details.push("loaded"):model.status.value!=="unloaded"&&details.push(model.status.value);let context=loaded?contextLabel(model):void 0;return context&&details.push(`${context} context`),details.join(" \xB7 ")}function selectTheme(theme2){return{selectedPrefix:text=>theme2.fg("accent",text),selectedText:text=>theme2.fg("accent",text),description:text=>theme2.fg("muted",text),scrollInfo:text=>theme2.fg("dim",text),noMatch:text=>theme2.fg("warning",text)}}function frame2(theme2,title,body,footer){let container=new Container;container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container.addChild(new Text(theme2.fg("accent",theme2.bold(title)),1,0));for(let child of body)container.addChild(child);return footer&&(container.addChild(new Spacer(1)),container.addChild(new Text(theme2.fg("dim",footer),1,0))),container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container}function compactCount(value){return value>=1e6?`${(value/1e6).toFixed(value>=1e7?0:1)}M`:value>=1e3?`${(value/1e3).toFixed(value>=1e5?0:1)}k`:String(value)}var HuggingFaceSearch=class extends Container{capturesViewportInput=!0;tui;theme;keybindings;search;cache;onSelectModel;input=new Input;resultsContainer=new Container;results=[];filteredResults=[];selectedIndex=0;selectionTouched=!1;query="";status="Type at least 2 characters";debounce;request;closed=!1;_focused=!1;constructor(tui,theme2,keybindings,search,cache2,onSelectModel){super(),this.tui=tui,this.theme=theme2,this.keybindings=keybindings,this.search=search,this.cache=cache2,this.onSelectModel=onSelectModel,this.addChild(new Text(theme2.fg("dim","Model name or owner/repository[:quant]"),1,0)),this.addChild(this.input),this.addChild(new Spacer(1)),this.addChild(this.resultsContainer),this.updateResults()}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}updateResults(){this.resultsContainer.clear();let start=Math.max(0,Math.min(this.selectedIndex-Math.floor(SEARCH_MAX_VISIBLE/2),this.filteredResults.length-SEARCH_MAX_VISIBLE)),end=Math.min(start+SEARCH_MAX_VISIBLE,this.filteredResults.length);for(let index=start;index<end;index++){let model=this.filteredResults[index];if(!model)continue;let prefix=index===this.selectedIndex?"\u2192 ":" ",details=`${compactCount(model.downloads)} downloads`;this.resultsContainer.addChild(new Text(index===this.selectedIndex?this.theme.fg("accent",`${prefix}${model.id} ${details}`):`${prefix}${model.id}${this.theme.fg("muted",` ${details}`)}`,0,0))}(start>0||end<this.filteredResults.length)&&this.resultsContainer.addChild(new Text(this.theme.fg("dim",` (${this.selectedIndex+1}/${this.filteredResults.length})`),0,0)),this.filteredResults.length===0?this.resultsContainer.addChild(new Text(this.theme.fg("dim",` ${this.status}`),0,0)):this.status==="Searching Hugging Face\u2026"&&this.resultsContainer.addChild(new Text(this.theme.fg("dim",` ${this.status}`),0,0)),this.tui.requestRender()}filterResults(preferredId){if(this.query){let matches2=new Set(fuzzyFilter(this.results,this.query,model=>model.id).map(model=>model.id));this.filteredResults=this.results.filter(model=>matches2.has(model.id))}else this.filteredResults=this.results;let preferredIndex=preferredId?this.filteredResults.findIndex(model=>model.id===preferredId):-1;preferredIndex>=0?this.selectedIndex=preferredIndex:this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredResults.length-1)),this.updateResults()}scheduleSearch(){if(this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.request=void 0,this.query.length<2){this.status="Type at least 2 characters",this.filterResults();return}let cached=this.cache.get(this.query.toLowerCase());if(cached){this.results=cached,this.status=cached.length===0?"No GGUF models found":"",this.filterResults();return}this.status="Searching Hugging Face\u2026",this.filterResults(),this.debounce=setTimeout(()=>{this.runSearch(this.query)},500)}async runSearch(query){let request=new AbortController;this.request=request;try{let results=await this.search(query,request.signal);if(this.cache.set(query.toLowerCase(),results),this.closed||request.signal.aborted||this.query!==query)return;let selectedId=this.selectionTouched?this.filteredResults[this.selectedIndex]?.id:void 0;this.results=results,this.selectedIndex=0,this.status=results.length===0?"No GGUF models found":"",this.filterResults(selectedId)}catch(error){if(this.closed||request.signal.aborted||this.query!==query)return;this.results=[],this.status=error instanceof Error?error.message:String(error),this.filterResults()}finally{this.request===request&&(this.request=void 0)}}close(model){this.closed||(this.closed=!0,this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.onSelectModel(model))}handleInput(data){if(this.keybindings.matches(data,"tui.select.up")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===0?this.filteredResults.length-1:this.selectedIndex-1,this.selectionTouched=!0,this.updateResults());return}if(this.keybindings.matches(data,"tui.select.down")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===this.filteredResults.length-1?0:this.selectedIndex+1,this.selectionTouched=!0,this.updateResults());return}let pageIndex=getSelectPageIndex(this.keybindings,data,this.selectedIndex,this.filteredResults.length,SEARCH_MAX_VISIBLE);if(pageIndex!==void 0){this.filteredResults.length>0&&(this.selectedIndex=pageIndex,this.selectionTouched=!0,this.updateResults());return}if(this.keybindings.matches(data,"tui.select.confirm")){let selected=(/^[^/\s]+\/[^:\s]+(?::[^\s:]+)?$/u.test(this.query)?this.query:void 0)??this.filteredResults[this.selectedIndex]?.id;selected&&this.close(selected);return}if(this.keybindings.matches(data,"tui.select.cancel")){this.close(void 0);return}this.input.handleInput(data);let query=this.input.getValue().trim();query!==this.query&&(this.query=query,this.selectionTouched=!1,this.scheduleSearch())}},LlamaView=class{tui;theme;keybindings;searchCache=new Map;content;inputHandler;inputTarget;progressPromise;progressResolver;showingProgress=!1;_focused=!1;constructor(tui,theme2,keybindings){this.tui=tui,this.theme=theme2,this.keybindings=keybindings,this.content=frame2(theme2,"llama.cpp models",[new Text(theme2.fg("muted","Loading\u2026"),1,1)])}get focused(){return this._focused}set focused(value){this._focused=value,this.inputTarget&&(this.inputTarget.focused=value)}get capturesViewportInput(){return this.inputHandler?.capturesViewportInput===!0}setContent(content,inputHandler,inputTarget){this.inputTarget&&(this.inputTarget.focused=!1),this.progressPromise=void 0,this.progressResolver=void 0,this.showingProgress=!1,this.content=content,this.inputHandler=inputHandler,this.inputTarget=inputTarget,this.inputTarget&&(this.inputTarget.focused=this._focused),this.tui.requestRender()}showModels(serverUrl,models){let sorted=[...models].sort((left,right)=>+(right.status.value==="loaded")-+(left.status.value==="loaded")||left.id.localeCompare(right.id)),byId=new Map(sorted.map(model=>[model.id,model])),items=[...sorted.map(model=>({value:model.id,label:model.id,description:modelDescription(model)})),{value:DOWNLOAD_VALUE,label:"Download model\u2026",description:"Hugging Face owner/repository[:quant]"}];return new Promise(resolve20=>{let list=new SelectList(items,Math.min(items.length,12),selectTheme(this.theme),{minPrimaryColumnWidth:36,maxPrimaryColumnWidth:56});list.onSelect=item=>{if(item.value===DOWNLOAD_VALUE)resolve20({type:"download"});else{let model=byId.get(item.value);model&&resolve20({type:"model",model})}},list.onCancel=()=>resolve20({type:"close"}),this.setContent(frame2(this.theme,"llama.cpp models",[new Text(this.theme.fg("dim",serverUrl),1,0),new Spacer(1),list],`${keyHint("tui.select.confirm","load/unload/download")} \u2022 ${keyHint("tui.select.cancel","close")}`),list)})}select(title,options){return new Promise(resolve20=>{let list=new SelectList(options.map(option=>({value:option,label:option})),Math.min(options.length,12),selectTheme(this.theme));list.onSelect=item=>resolve20(item.value),list.onCancel=()=>resolve20(void 0),this.setContent(frame2(this.theme,title,[new Spacer(1),list],`${keyHint("tui.select.confirm","select")} \u2022 ${keyHint("tui.select.cancel","cancel")}`),list)})}async confirm(title,message){return await this.select(`${title}
|
|
1291
1290
|
${message}`,["Yes","No"])==="Yes"}async connectionError(serverUrl,message){return await this.select(`llama.cpp unavailable
|
|
1292
1291
|
${serverUrl}
|
|
1293
1292
|
|
|
@@ -1299,7 +1298,7 @@ https://huggingface.co/${details.id}
|
|
|
1299
1298
|
|
|
1300
1299
|
The llama.cpp server needs HF_TOKEN with access.`,["Continue","Back"])!=="Continue")return}let quantization=parsed.quantization;if(!quantization&&details.quantizations.length>0){let options=details.quantizations.map(entry=>{let detail=[entry.size===void 0?void 0:formatBytes(entry.size),entry.name==="Q4_K_M"?"recommended":void 0].filter(value=>!!value).join(" \xB7 ");return detail?`${entry.name} \xB7 ${detail}`:entry.name}),choice=await ui.select(`Select quantization
|
|
1301
1300
|
${details.id}`,options);if(!choice||(quantization=details.quantizations[options.indexOf(choice)]?.name,!quantization))return}let model=quantization?`${details.id}:${quantization}`:details.id,result=await runWithProgress(ui,{title:"Downloading model",model,initialMessage:"Starting\u2026",cancelTitle:"Stop download?",cancelMessage:model,run:(signal,update)=>client.downloadAndWait(model,update,signal),cancel:()=>client.unload(model)});result.cancelled||(await syncCatalog(ctx,client,result.value),ctx.ui.notify(`Downloaded ${model}`))};pi.registerCommand("llama",{description:"Manage llama.cpp router models",handler:async(_args,ctx)=>{if(ctx.mode!=="tui"){ctx.ui.notify("/llama is available in interactive mode","warning");return}let client=await configuredClient(ctx);client&&await showLlamaUi(ctx,async ui=>{let readCatalog=async()=>{for(;;)try{return await syncCatalog(ctx,client)}catch(error){if(await ui.connectionError(client.serverUrl,connectionErrorMessage(error))==="close")return}},catalog=await readCatalog();if(catalog)for(;;){let action=await ui.showModels(client.serverUrl,catalog);if(action.type==="close")return;let actionError;try{action.type==="download"?await downloadModel(ctx,ui,client):modelIsLoaded(action.model)?await unloadModel(ctx,ui,client,action.model):action.model.status.value==="unloaded"?await loadModel(ctx,ui,client,catalog,action.model):ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`,"warning")}catch(error){actionError=error}let refreshed=await readCatalog();if(!refreshed)return;catalog=refreshed,actionError&&!isConnectionError(actionError)&&ctx.ui.notify(actionError instanceof Error?actionError.message:String(actionError),"error")}})}})}import{writeFileSync as writeFileSync12}from"node:fs";var STUB_PROVIDER_ID="draht-stub",STUB_MODEL_ID="stub-1",STUB_REPLY_PREFIX="stub: ",STUB_PROVIDER_ENV="DRAHT_STUB_PROVIDER",STUB_PROVIDER_TOKENS_PER_SECOND_ENV="DRAHT_STUB_PROVIDER_TOKENS_PER_SECOND",STUB_PROVIDER_TOOL_CALLS_ENV="DRAHT_STUB_TOOL_CALLS",STUB_PROVIDER_RECORD_CONTEXT_ENV="DRAHT_STUB_RECORD_CONTEXT";function isStubProviderEnabled(env=process.env){let value=env[STUB_PROVIDER_ENV];return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}function stubTokensPerSecond(env){let raw=env[STUB_PROVIDER_TOKENS_PER_SECOND_ENV];if(!raw)return;let parsed=Number(raw);return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function lastUserText(messages){for(let index=messages.length-1;index>=0;index--){let message=messages[index];if(message.role==="user")return typeof message.content=="string"?message.content:Array.isArray(message.content)?message.content.map(block=>block.type==="text"?block.text??"":"[image]").join(`
|
|
1302
|
-
`):""}return""}function stubReplyFor(prompt){return`${STUB_REPLY_PREFIX}${prompt}`}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseTurnScript(raw){if(!isPlainObject(raw)||raw.text!==void 0&&typeof raw.text!="string")return;let toolCalls=raw.toolCalls??[];if(!Array.isArray(toolCalls))return;let parsed=[];for(let entry of toolCalls){if(!isPlainObject(entry)||typeof entry.id!="string"||typeof entry.name!="string")return;let arguments_=entry.arguments??{};if(!isPlainObject(arguments_))return;parsed.push({id:entry.id,name:entry.name,arguments:arguments_})}return{toolCalls:parsed,text:raw.text}}function parseStubToolCallScripts(env=process.env){let raw=env[STUB_PROVIDER_TOOL_CALLS_ENV];if(raw===void 0||raw.trim()==="")return;let decoded;try{decoded=JSON.parse(raw)}catch(error){console.error(`${STUB_PROVIDER_TOOL_CALLS_ENV}: ignoring malformed JSON (${error instanceof Error?error.message:String(error)})`);return}if(!Array.isArray(decoded)){console.error(`${STUB_PROVIDER_TOOL_CALLS_ENV}: ignoring value, expected an array of turn scripts`);return}let scripts=[];for(let entry of decoded){let script=parseTurnScript(entry);if(!script){console.error(`${STUB_PROVIDER_TOOL_CALLS_ENV}: ignoring value, expected an array of turn scripts`);return}scripts.push(script)}return scripts}function createStubProvider(env=process.env){let handle=fauxProvider({provider:STUB_PROVIDER_ID,api:"faux-stub",models:[{id:STUB_MODEL_ID,name:"Draht Stub",cost:{input:0,output:0,cacheRead:0,cacheWrite:0}}],tokensPerSecond:stubTokensPerSecond(env),tokenSize:{min:1,max:1}}),scripts=parseStubToolCallScripts(env),turn=0,recordContextPath=env[STUB_PROVIDER_RECORD_CONTEXT_ENV],recorded=!1,respond=context=>{if(handle.appendResponses([respond]),recordContextPath&&!recorded){recorded=!0;try{writeFileSync12(recordContextPath,getCurrentSystemPrompt(context.messages),"utf-8")}catch{}}let script=scripts?.[turn++];if(!script||script.toolCalls.length===0)return fauxAssistantMessage(script?.text??stubReplyFor(lastUserText(context.messages)));let content=[];script.text!==void 0&&content.push(fauxText(script.text));for(let call of script.toolCalls)content.push(fauxToolCall(call.name,call.arguments,{id:call.id}));return fauxAssistantMessage(content,{stopReason:"toolUse"})};return handle.setResponses([respond]),handle.provider}function stubProviderExtension(pi){isStubProviderEnabled()&&pi.registerProvider(createStubProvider())}var builtInExtensions=[{name:"llama.cpp",factory:llamaExtension,builtin:!0},{name:"stub-provider",factory:stubProviderExtension,hidden:!0},{name:"codemode",factory:codemode_default,replaceable:!0,builtin:!0},{name:"tool-search",factory:tool_search_default,replaceable:!0,builtin:!0},{name:"mcp",factory:mcp_default,replaceable:!0,builtin:!0}];var loadMcpCommand=()=>import("./cli-
|
|
1301
|
+
`):""}return""}function stubReplyFor(prompt){return`${STUB_REPLY_PREFIX}${prompt}`}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseTurnScript(raw){if(!isPlainObject(raw)||raw.text!==void 0&&typeof raw.text!="string")return;let toolCalls=raw.toolCalls??[];if(!Array.isArray(toolCalls))return;let parsed=[];for(let entry of toolCalls){if(!isPlainObject(entry)||typeof entry.id!="string"||typeof entry.name!="string")return;let arguments_=entry.arguments??{};if(!isPlainObject(arguments_))return;parsed.push({id:entry.id,name:entry.name,arguments:arguments_})}return{toolCalls:parsed,text:raw.text}}function parseStubToolCallScripts(env=process.env){let raw=env[STUB_PROVIDER_TOOL_CALLS_ENV];if(raw===void 0||raw.trim()==="")return;let decoded;try{decoded=JSON.parse(raw)}catch(error){console.error(`${STUB_PROVIDER_TOOL_CALLS_ENV}: ignoring malformed JSON (${error instanceof Error?error.message:String(error)})`);return}if(!Array.isArray(decoded)){console.error(`${STUB_PROVIDER_TOOL_CALLS_ENV}: ignoring value, expected an array of turn scripts`);return}let scripts=[];for(let entry of decoded){let script=parseTurnScript(entry);if(!script){console.error(`${STUB_PROVIDER_TOOL_CALLS_ENV}: ignoring value, expected an array of turn scripts`);return}scripts.push(script)}return scripts}function createStubProvider(env=process.env){let handle=fauxProvider({provider:STUB_PROVIDER_ID,api:"faux-stub",models:[{id:STUB_MODEL_ID,name:"Draht Stub",cost:{input:0,output:0,cacheRead:0,cacheWrite:0}}],tokensPerSecond:stubTokensPerSecond(env),tokenSize:{min:1,max:1}}),scripts=parseStubToolCallScripts(env),turn=0,recordContextPath=env[STUB_PROVIDER_RECORD_CONTEXT_ENV],recorded=!1,respond=context=>{if(handle.appendResponses([respond]),recordContextPath&&!recorded){recorded=!0;try{writeFileSync12(recordContextPath,getCurrentSystemPrompt(context.messages),"utf-8")}catch{}}let script=scripts?.[turn++];if(!script||script.toolCalls.length===0)return fauxAssistantMessage(script?.text??stubReplyFor(lastUserText(context.messages)));let content=[];script.text!==void 0&&content.push(fauxText(script.text));for(let call of script.toolCalls)content.push(fauxToolCall(call.name,call.arguments,{id:call.id}));return fauxAssistantMessage(content,{stopReason:"toolUse"})};return handle.setResponses([respond]),handle.provider}function stubProviderExtension(pi){isStubProviderEnabled()&&pi.registerProvider(createStubProvider())}var builtInExtensions=[{name:"llama.cpp",factory:llamaExtension,builtin:!0},{name:"stub-provider",factory:stubProviderExtension,hidden:!0},{name:"codemode",factory:codemode_default,replaceable:!0,builtin:!0},{name:"tool-search",factory:tool_search_default,replaceable:!0,builtin:!0},{name:"mcp",factory:mcp_default,replaceable:!0,builtin:!0}];var loadMcpCommand=()=>import("./cli-L6U4GJHK.js");import{existsSync as existsSync23,mkdirSync as mkdirSync11,readdirSync as readdirSync12,readFileSync as readFileSync23,renameSync as renameSync3,rmSync as rmSync12,writeFileSync as writeFileSync13}from"fs";import{dirname as dirname17,join as join35}from"path";var MIGRATION_GUIDE_URL="https://github.com/draht-dev/draht/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration",EXTENSIONS_DOC_URL="https://github.com/draht-dev/draht/blob/main/packages/coding-agent/docs/extensions.md";function migrateAuthToAuthJson(){let agentDir=getAgentDir(),authPath=join35(agentDir,"auth.json"),oauthPath=join35(agentDir,"oauth.json"),settingsPath=join35(agentDir,"settings.json");if(existsSync23(authPath))return[];let migrated={},providers=[];if(existsSync23(oauthPath))try{let oauth=JSON.parse(stripBom(readFileSync23(oauthPath,"utf-8")));for(let[provider,cred]of Object.entries(oauth))migrated[provider]={type:"oauth",...cred},providers.push(provider);renameSync3(oauthPath,`${oauthPath}.migrated`)}catch{}if(existsSync23(settingsPath))try{let content=readFileSync23(settingsPath,"utf-8"),settings=JSON.parse(stripBom(content));if(settings.apiKeys&&typeof settings.apiKeys=="object"){for(let[provider,key]of Object.entries(settings.apiKeys))!migrated[provider]&&typeof key=="string"&&(migrated[provider]={type:"api_key",key},providers.push(provider));delete settings.apiKeys,writeFileSync13(settingsPath,JSON.stringify(settings,null,2))}}catch{}return Object.keys(migrated).length>0&&(mkdirSync11(dirname17(authPath),{recursive:!0}),writeFileSync13(authPath,JSON.stringify(migrated,null,2),{mode:384})),providers}function migrateSessionsFromAgentRoot(){let agentDir=getAgentDir(),files;try{files=readdirSync12(agentDir).filter(f=>f.endsWith(".jsonl")).map(f=>join35(agentDir,f))}catch{return}if(files.length!==0)for(let file of files)try{let firstLine6=readFileSync23(file,"utf8").split(`
|
|
1303
1302
|
`)[0];if(!firstLine6?.trim())continue;let header=JSON.parse(firstLine6);if(header.type!=="session"||!header.cwd)continue;let safePath=`--${header.cwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`,correctDir=join35(agentDir,"sessions",safePath);existsSync23(correctDir)||mkdirSync11(correctDir,{recursive:!0});let fileName=file.split("/").pop()||file.split("\\").pop(),newPath=join35(correctDir,fileName);if(existsSync23(newPath))continue;renameSync3(file,newPath)}catch{}}function migrateCommandsToPrompts(baseDir,label){let commandsDir=join35(baseDir,"commands"),promptsDir=join35(baseDir,"prompts");if(existsSync23(commandsDir)&&!existsSync23(promptsDir))try{return renameSync3(commandsDir,promptsDir),console.log(source_default.green(`Migrated ${label} commands/ \u2192 prompts/`)),!0}catch(err){console.log(source_default.yellow(`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error?err.message:err}`))}return!1}function migrateKeybindingsConfigFile(){let configPath=join35(getAgentDir(),"keybindings.json");if(existsSync23(configPath))try{let parsed=JSON.parse(stripBom(readFileSync23(configPath,"utf-8")));if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return;let{config,migrated}=migrateKeybindingsConfig(parsed);if(!migrated)return;writeFileSync13(configPath,`${JSON.stringify(config,null,2)}
|
|
1304
1303
|
`,"utf-8")}catch{}}function migrateToolsToBin(){let agentDir=getAgentDir(),toolsDir=join35(agentDir,"tools"),binDir=getBinDir();if(!existsSync23(toolsDir))return;let binaries=["fd","rg","fd.exe","rg.exe"],movedAny=!1;for(let bin of binaries){let oldPath=join35(toolsDir,bin),newPath=join35(binDir,bin);if(existsSync23(oldPath))if(existsSync23(binDir)||mkdirSync11(binDir,{recursive:!0}),existsSync23(newPath))try{rmSync12?.(oldPath,{force:!0})}catch{}else try{renameSync3(oldPath,newPath),movedAny=!0}catch{}}movedAny&&console.log(source_default.green("Migrated managed binaries tools/ \u2192 bin/"))}function checkDeprecatedExtensionDirs(baseDir,label){let hooksDir=join35(baseDir,"hooks"),toolsDir=join35(baseDir,"tools"),warnings=[];if(existsSync23(hooksDir)&&warnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`),existsSync23(toolsDir))try{readdirSync12(toolsDir).filter(e=>{let lower=e.toLowerCase();return lower!=="fd"&&lower!=="rg"&&lower!=="fd.exe"&&lower!=="rg.exe"&&!e.startsWith(".")}).length>0&&warnings.push(`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`)}catch{}return warnings}function migrateExtensionSystem(cwd){let agentDir=getAgentDir(),projectDir=join35(cwd,CONFIG_DIR_NAME);return migrateCommandsToPrompts(agentDir,"Global"),migrateCommandsToPrompts(projectDir,"Project"),[...checkDeprecatedExtensionDirs(agentDir,"Global"),...checkDeprecatedExtensionDirs(projectDir,"Project")]}async function showDeprecationWarnings(warnings){if(warnings.length!==0){for(let warning of warnings)console.log(source_default.yellow(`Warning: ${warning}`));console.log(source_default.yellow(`
|
|
1305
1304
|
Move your extensions to the extensions/ directory.`)),console.log(source_default.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`)),console.log(source_default.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`)),console.log(source_default.dim(`
|