dal-code 1.0.54 → 1.0.55
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 +10 -0
- package/NOTICE +11 -0
- package/dist/bundle/chunks/{anthropic-messages-UHE6F2IE.js → anthropic-messages-LJWWEQIU.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-EK4W2MKL.js → azure-openai-responses-GK4VH6GM.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-K4B5ABCQ.js → chunk-2XX4WZT6.js} +1 -1
- package/dist/bundle/chunks/{chunk-CSZTBJOE.js → chunk-3ANBT7AT.js} +1 -1
- package/dist/bundle/chunks/{chunk-SCYK4XNE.js → chunk-44EXLOHK.js} +1 -1
- package/dist/bundle/chunks/{chunk-3ZHZINH3.js → chunk-5TGFM4KW.js} +2 -2
- package/dist/bundle/chunks/{chunk-RKLUP6JT.js → chunk-6U37J6E7.js} +343 -343
- package/dist/bundle/chunks/{chunk-EH7SFF47.js → chunk-AL3DFAIM.js} +2 -2
- package/dist/bundle/chunks/{chunk-356BFRU3.js → chunk-D3HKK2ZD.js} +1 -1
- package/dist/bundle/chunks/{chunk-IDZ3QKHZ.js → chunk-DBT5OS5V.js} +1 -1
- package/dist/bundle/chunks/{chunk-VIS5PYQO.js → chunk-DWMC4U2M.js} +1 -1
- package/dist/bundle/chunks/{chunk-K7VBBYTT.js → chunk-F5SIUTR7.js} +1 -1
- package/dist/bundle/chunks/{chunk-O7G23ELK.js → chunk-GX37DI5S.js} +1 -1
- package/dist/bundle/chunks/{chunk-FE533CCR.js → chunk-KSF7BFGS.js} +1 -1
- package/dist/bundle/chunks/{chunk-L3RBW36Y.js → chunk-NMU45EFT.js} +1 -1
- package/dist/bundle/chunks/{chunk-2C7JTP5O.js → chunk-PRBATF6B.js} +1 -1
- package/dist/bundle/chunks/{chunk-4DMD6C65.js → chunk-SCSGNIU5.js} +1 -1
- package/dist/bundle/chunks/{chunk-33MCYYJ3.js → chunk-SMPERFJU.js} +1 -1
- package/dist/bundle/chunks/{chunk-XRF4A4KI.js → chunk-SNBVCTMQ.js} +2 -2
- package/dist/bundle/chunks/{chunk-R7FBN5UP.js → chunk-YDOF6JVP.js} +2 -2
- package/dist/bundle/chunks/{chunk-B5GJW7C2.js → chunk-ZYP3V3TD.js} +1 -1
- package/dist/bundle/chunks/{cli-XOLEGZVC.js → cli-VKNCK5P5.js} +1 -1
- package/dist/bundle/chunks/{cli-YJV3WN2N.js → cli-Z44UHMMU.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KNGB64NR.js → cloudflare-workers-ai-system-one-G4E4L26A.js} +1 -1
- package/dist/bundle/chunks/{easter-egg-3d-5TFBCTIS.js → easter-egg-3d-W2F3ROZ6.js} +1 -1
- package/dist/bundle/chunks/{execute-6PNQ63VS.js → execute-3FWM3EMV.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-YJN7TGWU.js → google-generative-ai-HVFDKPI3.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-3BVJFMMZ.js → google-vertex-6E4HATAC.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-JVUWNG3E.js → llama-cpp-classify-3HAEJDKO.js} +1 -1
- package/dist/bundle/chunks/{mcp-PC3Y3FBI.js → mcp-SGBPG7LV.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-O6YIQAS5.js → mistral-conversations-6UC2WYUC.js} +1 -1
- package/dist/bundle/chunks/{office-AXLGVCMO.js → office-2F4B572E.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-YQ5NNPTG.js → openai-codex-responses-WPSZR4EE.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-R4I3PKBD.js → openai-completions-2RGIFVKJ.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-IUHMKKHZ.js → openai-decisions-BLZVYNRQ.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-E2PHOQF4.js → openai-responses-N65DO7MB.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-NCMLTKZW.js → openrouter-images-LQ4VP5P7.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-GLTSGLSO.js → pi-messages-VYTRLMVB.js} +1 -1
- package/dist/bundle/chunks/{review-KXWT7T3V.js → review-MKITXKSI.js} +1 -1
- package/dist/bundle/chunks/{router-26PXJ7YH.js → router-RL7OYANY.js} +1 -1
- package/dist/bundle/chunks/{runtime-LJBCO7CX.js → runtime-KB5ZUQB6.js} +1 -1
- package/dist/bundle/chunks/{sdk-6GP346VB.js → sdk-C5BAFGNR.js} +1 -1
- package/dist/bundle/chunks/sync-AQUDRXHM.js +7 -0
- package/dist/bundle/chunks/{typesafe-system-one-GQFHU7SQ.js → typesafe-system-one-6ZFGVJMV.js} +1 -1
- package/dist/bundle/chunks/{usage-MY7HTXQB.js → usage-CK3QZLTW.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-BEBLHRXC.js → virtual-modules-GRXCAWTO.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/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/types.d.ts +9 -5
- package/dist/core/tools/bash.js +1 -1
- package/dist/core/tools/edit.js +2 -3
- package/dist/core/tools/renderers/bash.js +1 -1
- package/dist/core/tools/renderers/edit.js +2 -2
- package/dist/modes/interactive/components/assistant-message.d.ts +3 -0
- package/dist/modes/interactive/components/assistant-message.js +2 -2
- package/dist/modes/interactive/components/diff.d.ts +22 -0
- package/dist/modes/interactive/components/diff.js +4 -3
- package/dist/modes/interactive/components/keybinding-hints.js +1 -1
- package/dist/modes/interactive/components/panel-line.js +1 -0
- package/dist/modes/interactive/components/status-indicator.d.ts +23 -1
- package/dist/modes/interactive/components/status-indicator.js +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +2 -2
- package/dist/modes/interactive/components/tool-execution.js +5 -5
- package/dist/modes/interactive/interactive-mode.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.js +18 -18
- package/dist/modes/interactive/theme/dark.json +4 -0
- package/dist/modes/interactive/theme/light.json +4 -0
- package/dist/modes/interactive/theme/system-theme.js +1 -1
- package/dist/modes/interactive/theme/theme-tokens.d.ts +10 -0
- package/dist/modes/interactive/theme/theme-tokens.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +2 -6
- package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-learn/src/engine.js +2 -2
- package/dist/node_modules/@dalcode/dal-learn/src/index.js +14 -14
- package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +4 -4
- package/dist/node_modules/@dalcode/dal-learn/src/safety.js +2 -2
- package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
- package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/bundle/chunks/sync-ONQZCAYG.js +0 -7
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ye=Object.defineProperty;var e=(o,t)=>ye(o,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const _i=Le(import.meta.url);import{ADAPTATION_FILE as Fe,AgentSession as Ie,AgentSessionRuntime as Oe,AssistantMessageComponent as Ne,BackgroundProcessManager as we,BashExecutionComponent as ve,BorderedLoader as Me,BranchSummaryMessageComponent as He,CURRENT_SESSION_VERSION as xe,CompactionSummaryMessageComponent as be,CustomEditor as Be,CustomMessageComponent as Ue,DEFAULT_COMPACTION_SETTINGS as je,DefaultPackageManager as Ke,DefaultResourceLoader as We,DynamicBorder as Ge,ENGINE_MARKET_CACHE_FILE as $e,ExtensionEditorComponent as Ve,ExtensionFatalError as ze,ExtensionInputComponent as Je,ExtensionRunner as Xe,ExtensionSelectorComponent as Ye,FooterComponent as qe,HOST_CAPABILITIES_ENV as Qe,HOST_TOKEN_ENV as Ze,HOST_TOKEN_HEADER as et,HOST_URL_ENV as tt,HostCallError as ot,HostCapabilities as rt,InteractiveMode as nt,LoginDialogComponent as it,MARKET_SECTIONS as st,MAX_BACKGROUND_PROCESSES as at,ModelRegistry as lt,ModelSelectorComponent as ut,OAuthSelectorComponent as ct,PROTECTED_WRITE_NAMES as dt,REQUIRED_EXTENSION_FAILED as mt,RequiredExtensionError as pt,RpcClient as Et,RpcCommandError as St,SANDBOX_ENV as gt,SessionManager as ht,SessionSelectorComponent as ft,SettingsManager as Tt,SettingsSelectorComponent as Ct,ShellSandbox as kt,SkillInvocationMessageComponent as _t,ThinkingSelectorComponent as At,ToolExecutionComponent as Dt,TreeSelectorComponent as Rt,UserMessageComponent as Pt,UserMessageSelectorComponent as yt,adaptPackage as Lt,adaptationState as Ft,agentLogPath as It,appendAgentLog as Ot,applyCommunityEnv as Nt,buildContextEntries as wt,buildProjectMap as vt,buildRuleSet as Mt,buildSessionContext as Ht,buildSessionProjection as xt,calculateContextTokens as bt,chromeBottom as te,chromeTop as oe,collectEntriesForBranchSummary as Bt,communityEnv as Ut,compact as jt,convertToLlm as Kt,convertToPng as Wt,copyToClipboard as Gt,createAgentSession as $t,createAgentSessionFromServices as Vt,createAgentSessionRuntime as zt,createAgentSessionServices as Jt,createBashTool as Xt,createBashToolDefinition as Yt,createCodemodeExtension as qt,createCodingTools as Qt,createEditTool as Zt,createEditToolDefinition as eo,createEventBus as to,createExtensionRuntime as oo,createFindTool as ro,createFindToolDefinition as no,createGrepTool as io,createGrepToolDefinition as so,createLocalBashOperations as ao,createLocalPowerShellOperations as lo,createLsTool as uo,createLsToolDefinition as co,createMcpExtension as mo,createPowerShellTool as po,createPowerShellToolDefinition as Eo,createProcessToolDefinition as So,createReadOnlyTools as go,createReadTool as ho,createReadToolDefinition as fo,createSyntheticSourceInfo as To,createToolSearchExtension as Co,createWriteTool as ko,createWriteToolDefinition as _o,defineTool as Ao,describeProjectFacts as Do,detectProjectFacts as Ro,detectSandboxAvailability as Po,detectSupportedImageMimeTypeFromFile as yo,discoverAndLoadExtensions as Lo,ensurePackageAdapted as Fo,estimateTokens as Io,evaluateToolPolicy as Oo,expandTempDirVariable as No,fetchSignedMarket as wo,findCutPoint as vo,findTurnStartIndex as Mo,formatDimensionNote as Ho,formatProjectMapPrompt as xo,formatSkillsForPrompt as bo,generateBranchSummary as Bo,generateDiffString as Uo,generateSummary as jo,generateSummaryWithUsage as Ko,generateUnifiedPatch as Wo,getHostCapabilities as Go,getLastAssistantUsage as $o,getLatestCompactionEntry as Vo,getProcessShellSandbox as zo,getToolDenial as Jo,isAdaptablePackage as Xo,isBashToolResult as Yo,isEditToolResult as qo,isFatalExtensionError as Qo,isFindToolResult as Zo,isGrepToolResult as er,isHostExtensionPath as tr,isLsToolResult as or,isPowerShellToolResult as rr,isReadOnlyBashCommand as nr,isReadToolResult as ir,isToolCallEventType as sr,isWriteToolResult as ar,loadMcpRuntime as lr,loadProjectContextFiles as ur,loadSkills as cr,loadSkillsFromDir as dr,main as mr,markHostExtensionPaths as pr,marketCacheDir as Er,matchPermissionRules as Sr,migrateSessionEntries as gr,normalizeForFuzzyMatch as hr,parseArgs as fr,parseFrontmatter as Tr,parseHostCapabilities as Cr,parsePermissionRule as kr,parseSessionEntries as _r,parseSkillBlock as Ar,prepareBranchEntries as Dr,projectPackageManager as Rr,readAccessDenial as Pr,readAdaptation as yr,readSignedSection as Lr,registerPermissionAskHandler as Fr,registerSandboxEscalationHandler as Ir,registerShellExecutionGuard as Or,renderDiff as Nr,resizeImage as wr,resolveCliModel as vr,resolveMarketEndpoint as Mr,resolveModelScopeWithDiagnostics as Hr,resolveSandboxPolicy as xr,resolveToCwd as br,runPrintMode as Br,runRpcMode as Ur,scanHardcodedPiPaths as jr,serializeConversation as Kr,sessionEntryToContextMessages as Wr,shellExecutionRefusal as Gr,shouldCompact as $r,simpleCommands as Vr,stripFrontmatter as zr,systemTempDirs as Jr,tryEnsurePackageAdapted as Xr,unwrapCommand as Yr,verifyAdaptation as qr,verifySignedSection as Qr,withFileMutationQueue as Zr,wrapRegisteredTool as en,wrapRegisteredTools as tn}from"./chunk-RKLUP6JT.js";import{CredentialSynchronizationError as on,DALCODE_PROJECT_DIR_NAME as rn,DEFAULT_HOOK_TIMEOUT_SECONDS as nn,ModelRuntime as sn,PROJECT_HOOKS_FILE_ENV as an,ProjectTrustStore as ln,TRUST_REQUIRING_PROJECT_HOOK_FILES as un,VIRTUAL_MODEL_STATE_ENTRY as cn,dalHookSourceFiles as dn,deriveHookName as mn,hasTrustRequiringProjectResources as pn,loadDalHooks as re,openBrowser as En,projectFileDeclaresHooks as Sn,projectHooksFileFromEnv as ne}from"./chunk-R7FBN5UP.js";import{formatReadLineRange as gn,truncateToVisualLines as hn}from"./chunk-3ZHZINH3.js";import{readStoredCredential as fn}from"./chunk-356BFRU3.js";import{DEFAULT_MAX_BYTES as Tn,DEFAULT_MAX_LINES as Cn,DEFAULT_SHELL_ENV_EXCLUDES as kn,applyShellEnvironmentPolicy as _n,formatSize as An,getPowerShellConfig as Dn,getShellConfig as Rn,getShellEnv as Pn,isDalCodeCredentialName as yn,truncateHead as Ln,truncateLine as Fn,truncateTail as In,withoutDalCodeCredentials as ie}from"./chunk-SE42OS3U.js";import{ArminComponent as On}from"./chunk-K7VBBYTT.js";import{Container as se,SelectList as ae,Theme as Nn,getAvailableThemes as wn,getLanguageFromPath as vn,getMarkdownTheme as Mn,getSelectListTheme as N,getSettingsListTheme as Hn,highlightCode as xn,initTheme as bn,keyHint as Bn,keyText as Un,rawKeyHint as jn}from"./chunk-EH7SFF47.js";import{CONFIG_DIR_NAME as Kn,SHARED_SKILL_CONFIG_DIRS as Wn,VERSION as Gn,getAgentDir as le,getDocsPath as $n,getExamplesPath as Vn,getPackageDir as zn,getReadmePath as Jn}from"./chunk-R47JBGS3.js";import{t as S}from"./chunk-XRF4A4KI.js";import{__export as Xn}from"./chunk-JXWJOIH4.js";var ue={};Xn(ue,{ADAPTATION_FILE:e(()=>Fe,"ADAPTATION_FILE"),AgentSession:e(()=>Ie,"AgentSession"),AgentSessionRuntime:e(()=>Oe,"AgentSessionRuntime"),ArminComponent:e(()=>On,"ArminComponent"),AssistantMessageComponent:e(()=>Ne,"AssistantMessageComponent"),BackgroundProcessManager:e(()=>we,"BackgroundProcessManager"),BashExecutionComponent:e(()=>ve,"BashExecutionComponent"),BorderedLoader:e(()=>Me,"BorderedLoader"),BranchSummaryMessageComponent:e(()=>He,"BranchSummaryMessageComponent"),CONFIG_DIR_NAME:e(()=>Kn,"CONFIG_DIR_NAME"),CURRENT_SESSION_VERSION:e(()=>xe,"CURRENT_SESSION_VERSION"),CompactionSummaryMessageComponent:e(()=>be,"CompactionSummaryMessageComponent"),CredentialSynchronizationError:e(()=>on,"CredentialSynchronizationError"),CustomEditor:e(()=>Be,"CustomEditor"),CustomMessageComponent:e(()=>Ue,"CustomMessageComponent"),DALCODE_PROJECT_DIR_NAME:e(()=>rn,"DALCODE_PROJECT_DIR_NAME"),DAL_HOOK_ENTRY_TYPE:e(()=>B,"DAL_HOOK_ENTRY_TYPE"),DAL_HOOK_NOTIFICATION_CHANNEL:e(()=>ee,"DAL_HOOK_NOTIFICATION_CHANNEL"),DEFAULT_COMPACTION_SETTINGS:e(()=>je,"DEFAULT_COMPACTION_SETTINGS"),DEFAULT_HOOK_TIMEOUT_SECONDS:e(()=>nn,"DEFAULT_HOOK_TIMEOUT_SECONDS"),DEFAULT_MAX_BYTES:e(()=>Tn,"DEFAULT_MAX_BYTES"),DEFAULT_MAX_LINES:e(()=>Cn,"DEFAULT_MAX_LINES"),DEFAULT_SHELL_ENV_EXCLUDES:e(()=>kn,"DEFAULT_SHELL_ENV_EXCLUDES"),DefaultPackageManager:e(()=>Ke,"DefaultPackageManager"),DefaultResourceLoader:e(()=>We,"DefaultResourceLoader"),DynamicBorder:e(()=>Ge,"DynamicBorder"),ENGINE_MARKET_CACHE_FILE:e(()=>$e,"ENGINE_MARKET_CACHE_FILE"),ExtensionEditorComponent:e(()=>Ve,"ExtensionEditorComponent"),ExtensionFatalError:e(()=>ze,"ExtensionFatalError"),ExtensionInputComponent:e(()=>Je,"ExtensionInputComponent"),ExtensionRunner:e(()=>Xe,"ExtensionRunner"),ExtensionSelectorComponent:e(()=>Ye,"ExtensionSelectorComponent"),FooterComponent:e(()=>qe,"FooterComponent"),HOST_CAPABILITIES_ENV:e(()=>Qe,"HOST_CAPABILITIES_ENV"),HOST_TOKEN_ENV:e(()=>Ze,"HOST_TOKEN_ENV"),HOST_TOKEN_HEADER:e(()=>et,"HOST_TOKEN_HEADER"),HOST_URL_ENV:e(()=>tt,"HOST_URL_ENV"),HostCallError:e(()=>ot,"HostCallError"),HostCapabilities:e(()=>rt,"HostCapabilities"),InteractiveMode:e(()=>nt,"InteractiveMode"),LoginDialogComponent:e(()=>it,"LoginDialogComponent"),MARKET_SECTIONS:e(()=>st,"MARKET_SECTIONS"),MAX_BACKGROUND_PROCESSES:e(()=>at,"MAX_BACKGROUND_PROCESSES"),ModelRegistry:e(()=>lt,"ModelRegistry"),ModelRuntime:e(()=>sn,"ModelRuntime"),ModelSelectorComponent:e(()=>ut,"ModelSelectorComponent"),OAuthSelectorComponent:e(()=>ct,"OAuthSelectorComponent"),PROJECT_HOOKS_FILE_ENV:e(()=>an,"PROJECT_HOOKS_FILE_ENV"),PROTECTED_WRITE_NAMES:e(()=>dt,"PROTECTED_WRITE_NAMES"),ProjectTrustStore:e(()=>ln,"ProjectTrustStore"),REQUIRED_EXTENSION_FAILED:e(()=>mt,"REQUIRED_EXTENSION_FAILED"),RequiredExtensionError:e(()=>pt,"RequiredExtensionError"),RpcClient:e(()=>Et,"RpcClient"),RpcCommandError:e(()=>St,"RpcCommandError"),SANDBOX_ENV:e(()=>gt,"SANDBOX_ENV"),SHARED_SKILL_CONFIG_DIRS:e(()=>Wn,"SHARED_SKILL_CONFIG_DIRS"),STALE_AFTER_MS:e(()=>H,"STALE_AFTER_MS"),SessionManager:e(()=>ht,"SessionManager"),SessionSelectorComponent:e(()=>ft,"SessionSelectorComponent"),SettingsManager:e(()=>Tt,"SettingsManager"),SettingsSelectorComponent:e(()=>Ct,"SettingsSelectorComponent"),ShellSandbox:e(()=>kt,"ShellSandbox"),ShowImagesSelectorComponent:e(()=>Re,"ShowImagesSelectorComponent"),SkillInvocationMessageComponent:e(()=>_t,"SkillInvocationMessageComponent"),TRUST_REQUIRING_PROJECT_HOOK_FILES:e(()=>un,"TRUST_REQUIRING_PROJECT_HOOK_FILES"),Theme:e(()=>Nn,"Theme"),ThemeSelectorComponent:e(()=>Pe,"ThemeSelectorComponent"),ThinkingSelectorComponent:e(()=>At,"ThinkingSelectorComponent"),ToolExecutionComponent:e(()=>Dt,"ToolExecutionComponent"),TreeSelectorComponent:e(()=>Rt,"TreeSelectorComponent"),UserMessageComponent:e(()=>Pt,"UserMessageComponent"),UserMessageSelectorComponent:e(()=>yt,"UserMessageSelectorComponent"),VERSION:e(()=>Gn,"VERSION"),VIRTUAL_MODEL_STATE_ENTRY:e(()=>cn,"VIRTUAL_MODEL_STATE_ENTRY"),WORKSPACE_LOCK_DIR_NAME:e(()=>v,"WORKSPACE_LOCK_DIR_NAME"),WORKSPACE_LOCK_FILE:e(()=>L,"WORKSPACE_LOCK_FILE"),adaptPackage:e(()=>Lt,"adaptPackage"),adaptationState:e(()=>Ft,"adaptationState"),agentLogPath:e(()=>It,"agentLogPath"),appendAgentLog:e(()=>Ot,"appendAgentLog"),applyCommunityEnv:e(()=>Nt,"applyCommunityEnv"),applyShellEnvironmentPolicy:e(()=>_n,"applyShellEnvironmentPolicy"),buildContextEntries:e(()=>wt,"buildContextEntries"),buildDalHookInput:e(()=>V,"buildDalHookInput"),buildProjectMap:e(()=>vt,"buildProjectMap"),buildRuleSet:e(()=>Mt,"buildRuleSet"),buildSessionContext:e(()=>Ht,"buildSessionContext"),buildSessionProjection:e(()=>xt,"buildSessionProjection"),calculateContextTokens:e(()=>bt,"calculateContextTokens"),claimWorkspace:e(()=>pe,"claimWorkspace"),collectEntriesForBranchSummary:e(()=>Bt,"collectEntriesForBranchSummary"),communityEnv:e(()=>Ut,"communityEnv"),compact:e(()=>jt,"compact"),convertToLlm:e(()=>Kt,"convertToLlm"),convertToPng:e(()=>Wt,"convertToPng"),copyToClipboard:e(()=>Gt,"copyToClipboard"),createAgentSession:e(()=>$t,"createAgentSession"),createAgentSessionFromServices:e(()=>Vt,"createAgentSessionFromServices"),createAgentSessionRuntime:e(()=>zt,"createAgentSessionRuntime"),createAgentSessionServices:e(()=>Jt,"createAgentSessionServices"),createBashTool:e(()=>Xt,"createBashTool"),createBashToolDefinition:e(()=>Yt,"createBashToolDefinition"),createCodemodeExtension:e(()=>qt,"createCodemodeExtension"),createCodingTools:e(()=>Qt,"createCodingTools"),createEditTool:e(()=>Zt,"createEditTool"),createEditToolDefinition:e(()=>eo,"createEditToolDefinition"),createEventBus:e(()=>to,"createEventBus"),createExtensionRuntime:e(()=>oo,"createExtensionRuntime"),createFindTool:e(()=>ro,"createFindTool"),createFindToolDefinition:e(()=>no,"createFindToolDefinition"),createGrepTool:e(()=>io,"createGrepTool"),createGrepToolDefinition:e(()=>so,"createGrepToolDefinition"),createLocalBashOperations:e(()=>ao,"createLocalBashOperations"),createLocalPowerShellOperations:e(()=>lo,"createLocalPowerShellOperations"),createLsTool:e(()=>uo,"createLsTool"),createLsToolDefinition:e(()=>co,"createLsToolDefinition"),createMcpExtension:e(()=>mo,"createMcpExtension"),createPowerShellTool:e(()=>po,"createPowerShellTool"),createPowerShellToolDefinition:e(()=>Eo,"createPowerShellToolDefinition"),createProcessToolDefinition:e(()=>So,"createProcessToolDefinition"),createReadOnlyTools:e(()=>go,"createReadOnlyTools"),createReadTool:e(()=>ho,"createReadTool"),createReadToolDefinition:e(()=>fo,"createReadToolDefinition"),createSyntheticSourceInfo:e(()=>To,"createSyntheticSourceInfo"),createToolSearchExtension:e(()=>Co,"createToolSearchExtension"),createWriteTool:e(()=>ko,"createWriteTool"),createWriteToolDefinition:e(()=>_o,"createWriteToolDefinition"),dalHookActivity:e(()=>g,"dalHookActivity"),dalHookSourceFiles:e(()=>dn,"dalHookSourceFiles"),dalHooksExtension:e(()=>De,"dalHooksExtension"),decideDalHooks:e(()=>$,"decideDalHooks"),defaultWorkspaceLockDir:e(()=>M,"defaultWorkspaceLockDir"),defineTool:e(()=>Ao,"defineTool"),deriveHookName:e(()=>mn,"deriveHookName"),describeProjectFacts:e(()=>Do,"describeProjectFacts"),detectProjectFacts:e(()=>Ro,"detectProjectFacts"),detectSandboxAvailability:e(()=>Po,"detectSandboxAvailability"),detectSupportedImageMimeTypeFromFile:e(()=>yo,"detectSupportedImageMimeTypeFromFile"),discoverAndLoadExtensions:e(()=>Lo,"discoverAndLoadExtensions"),engineToolInput:e(()=>j,"engineToolInput"),ensurePackageAdapted:e(()=>Fo,"ensurePackageAdapted"),estimateTokens:e(()=>Io,"estimateTokens"),evaluateToolPolicy:e(()=>Oo,"evaluateToolPolicy"),expandTempDirVariable:e(()=>No,"expandTempDirVariable"),fetchSignedMarket:e(()=>wo,"fetchSignedMarket"),findCutPoint:e(()=>vo,"findCutPoint"),findTurnStartIndex:e(()=>Mo,"findTurnStartIndex"),formatDalHookActivity:e(()=>U,"formatDalHookActivity"),formatDimensionNote:e(()=>Ho,"formatDimensionNote"),formatProjectMapPrompt:e(()=>xo,"formatProjectMapPrompt"),formatReadLineRange:e(()=>gn,"formatReadLineRange"),formatSize:e(()=>An,"formatSize"),formatSkillsForPrompt:e(()=>bo,"formatSkillsForPrompt"),generateBranchSummary:e(()=>Bo,"generateBranchSummary"),generateDiffString:e(()=>Uo,"generateDiffString"),generateSummary:e(()=>jo,"generateSummary"),generateSummaryWithUsage:e(()=>Ko,"generateSummaryWithUsage"),generateUnifiedPatch:e(()=>Wo,"generateUnifiedPatch"),getAgentDir:e(()=>le,"getAgentDir"),getDocsPath:e(()=>$n,"getDocsPath"),getExamplesPath:e(()=>Vn,"getExamplesPath"),getHostCapabilities:e(()=>Go,"getHostCapabilities"),getLanguageFromPath:e(()=>vn,"getLanguageFromPath"),getLastAssistantUsage:e(()=>$o,"getLastAssistantUsage"),getLatestCompactionEntry:e(()=>Vo,"getLatestCompactionEntry"),getMarkdownTheme:e(()=>Mn,"getMarkdownTheme"),getPackageDir:e(()=>zn,"getPackageDir"),getPowerShellConfig:e(()=>Dn,"getPowerShellConfig"),getProcessShellSandbox:e(()=>zo,"getProcessShellSandbox"),getReadmePath:e(()=>Jn,"getReadmePath"),getSelectListTheme:e(()=>N,"getSelectListTheme"),getSettingsListTheme:e(()=>Hn,"getSettingsListTheme"),getShellConfig:e(()=>Rn,"getShellConfig"),getShellEnv:e(()=>Pn,"getShellEnv"),getToolDenial:e(()=>Jo,"getToolDenial"),gitDirOf:e(()=>x,"gitDirOf"),hasTrustRequiringProjectResources:e(()=>pn,"hasTrustRequiringProjectResources"),highlightCode:e(()=>xn,"highlightCode"),hookToolInput:e(()=>I,"hookToolInput"),hookToolName:e(()=>R,"hookToolName"),initTheme:e(()=>bn,"initTheme"),isAdaptablePackage:e(()=>Xo,"isAdaptablePackage"),isBashToolResult:e(()=>Yo,"isBashToolResult"),isDalCodeCredentialName:e(()=>yn,"isDalCodeCredentialName"),isDalHookActivity:e(()=>ge,"isDalHookActivity"),isEditToolResult:e(()=>qo,"isEditToolResult"),isFatalExtensionError:e(()=>Qo,"isFatalExtensionError"),isFindToolResult:e(()=>Zo,"isFindToolResult"),isGrepToolResult:e(()=>er,"isGrepToolResult"),isHostExtensionPath:e(()=>tr,"isHostExtensionPath"),isLsToolResult:e(()=>or,"isLsToolResult"),isPowerShellToolResult:e(()=>rr,"isPowerShellToolResult"),isReadOnlyBashCommand:e(()=>nr,"isReadOnlyBashCommand"),isReadToolResult:e(()=>ir,"isReadToolResult"),isToolCallEventType:e(()=>sr,"isToolCallEventType"),isWriteToolResult:e(()=>ar,"isWriteToolResult"),keyHint:e(()=>Bn,"keyHint"),keyText:e(()=>Un,"keyText"),loadDalHooks:e(()=>re,"loadDalHooks"),loadMcpRuntime:e(()=>lr,"loadMcpRuntime"),loadProjectContextFiles:e(()=>ur,"loadProjectContextFiles"),loadSkills:e(()=>cr,"loadSkills"),loadSkillsFromDir:e(()=>dr,"loadSkillsFromDir"),main:e(()=>mr,"main"),markHostExtensionPaths:e(()=>pr,"markHostExtensionPaths"),marketCacheDir:e(()=>Er,"marketCacheDir"),matchPermissionRules:e(()=>Sr,"matchPermissionRules"),migrateSessionEntries:e(()=>gr,"migrateSessionEntries"),normalizeForFuzzyMatch:e(()=>hr,"normalizeForFuzzyMatch"),openBrowser:e(()=>En,"openBrowser"),parseArgs:e(()=>fr,"parseArgs"),parseFrontmatter:e(()=>Tr,"parseFrontmatter"),parseHostCapabilities:e(()=>Cr,"parseHostCapabilities"),parsePermissionRule:e(()=>kr,"parsePermissionRule"),parseSessionEntries:e(()=>_r,"parseSessionEntries"),parseSkillBlock:e(()=>Ar,"parseSkillBlock"),prepareBranchEntries:e(()=>Dr,"prepareBranchEntries"),projectFileDeclaresHooks:e(()=>Sn,"projectFileDeclaresHooks"),projectHooksFileFromEnv:e(()=>ne,"projectHooksFileFromEnv"),projectPackageManager:e(()=>Rr,"projectPackageManager"),rawKeyHint:e(()=>jn,"rawKeyHint"),readAccessDenial:e(()=>Pr,"readAccessDenial"),readAdaptation:e(()=>yr,"readAdaptation"),readSignedSection:e(()=>Lr,"readSignedSection"),readStoredCredential:e(()=>fn,"readStoredCredential"),readWorkspaceLock:e(()=>de,"readWorkspaceLock"),registerPermissionAskHandler:e(()=>Fr,"registerPermissionAskHandler"),registerSandboxEscalationHandler:e(()=>Ir,"registerSandboxEscalationHandler"),registerShellExecutionGuard:e(()=>Or,"registerShellExecutionGuard"),releaseWorkspace:e(()=>Ee,"releaseWorkspace"),renderDiff:e(()=>Nr,"renderDiff"),reportDalHookProblems:e(()=>z,"reportDalHookProblems"),resizeImage:e(()=>wr,"resizeImage"),resolveCliModel:e(()=>vr,"resolveCliModel"),resolveMarketEndpoint:e(()=>Mr,"resolveMarketEndpoint"),resolveModelScopeWithDiagnostics:e(()=>Hr,"resolveModelScopeWithDiagnostics"),resolveSandboxPolicy:e(()=>xr,"resolveSandboxPolicy"),resolveToCwd:e(()=>br,"resolveToCwd"),runDalCommandHook:e(()=>W,"runDalCommandHook"),runDalHookEvent:e(()=>T,"runDalHookEvent"),runDalHooks:e(()=>G,"runDalHooks"),runNotificationHooks:e(()=>Z,"runNotificationHooks"),runPostToolUseHooks:e(()=>X,"runPostToolUseHooks"),runPreToolUseHooks:e(()=>J,"runPreToolUseHooks"),runPrintMode:e(()=>Br,"runPrintMode"),runRpcMode:e(()=>Ur,"runRpcMode"),runSessionStartHooks:e(()=>Y,"runSessionStartHooks"),runStopHooks:e(()=>Q,"runStopHooks"),runUserPromptSubmitHooks:e(()=>q,"runUserPromptSubmitHooks"),scanHardcodedPiPaths:e(()=>jr,"scanHardcodedPiPaths"),selectDalHooks:e(()=>K,"selectDalHooks"),serializeConversation:e(()=>Kr,"serializeConversation"),sessionEntryToContextMessages:e(()=>Wr,"sessionEntryToContextMessages"),shellCommandDirectory:e(()=>Se,"shellCommandDirectory"),shellExecutionRefusal:e(()=>Gr,"shellExecutionRefusal"),shouldCompact:e(()=>$r,"shouldCompact"),simpleCommands:e(()=>Vr,"simpleCommands"),stripFrontmatter:e(()=>zr,"stripFrontmatter"),systemTempDirs:e(()=>Jr,"systemTempDirs"),toolMatchNames:e(()=>O,"toolMatchNames"),truncateHead:e(()=>Ln,"truncateHead"),truncateLine:e(()=>Fn,"truncateLine"),truncateTail:e(()=>In,"truncateTail"),truncateToVisualLines:e(()=>hn,"truncateToVisualLines"),tryEnsurePackageAdapted:e(()=>Xr,"tryEnsurePackageAdapted"),unwrapCommand:e(()=>Yr,"unwrapCommand"),verifyAdaptation:e(()=>qr,"verifyAdaptation"),verifySignedSection:e(()=>Qr,"verifySignedSection"),withFileMutationQueue:e(()=>Zr,"withFileMutationQueue"),withoutDalCodeCredentials:e(()=>ie,"withoutDalCodeCredentials"),workspaceLockIsLive:e(()=>F,"workspaceLockIsLive"),workspaceLockPath:e(()=>A,"workspaceLockPath"),workspaceOwnerSessionId:e(()=>b,"workspaceOwnerSessionId"),wrapRegisteredTool:e(()=>en,"wrapRegisteredTool"),wrapRegisteredTools:e(()=>tn,"wrapRegisteredTools")});import{execFileSync as Yn}from"node:child_process";import{createHash as qn}from"node:crypto";import{mkdirSync as Qn,readFileSync as Zn,realpathSync as ei,renameSync as ti,rmSync as oi,writeFileSync as ri}from"node:fs";import{hostname as P}from"node:os";import{basename as w,isAbsolute as ni,join as y,resolve as k}from"node:path";var v="workspace-locks",L="dal-workspace.lock";function M(){return y(le(),v)}e(M,"defaultWorkspaceLockDir");function A(o,t=M()){let r=k(o);try{r=ei.native(r)}catch{}let n=qn("sha256").update(r).digest("hex").slice(0,16),a=w(r)===".git"?w(k(r,"..")):w(r);return y(t,`${a.replace(/[^\w.-]/g,"_").slice(0,40)||"repo"}-${n}.lock`)}e(A,"workspaceLockPath");var H=7200*1e3,ii=60*1e3,si="DALCODE_PARENT_SESSION_ID",ce=new Map;function x(o){let t=k(o),r=ce.get(t);if(r!==void 0)return r??void 0;let n=null;try{let a=Yn("git",["rev-parse","--git-dir","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(`
|
|
1
|
+
var ye=Object.defineProperty;var e=(o,t)=>ye(o,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const _i=Le(import.meta.url);import{ADAPTATION_FILE as Fe,AgentSession as Ie,AgentSessionRuntime as Oe,AssistantMessageComponent as Ne,BackgroundProcessManager as we,BashExecutionComponent as ve,BorderedLoader as Me,BranchSummaryMessageComponent as He,CURRENT_SESSION_VERSION as xe,CompactionSummaryMessageComponent as be,CustomEditor as Be,CustomMessageComponent as Ue,DEFAULT_COMPACTION_SETTINGS as je,DefaultPackageManager as Ke,DefaultResourceLoader as We,DynamicBorder as Ge,ENGINE_MARKET_CACHE_FILE as $e,ExtensionEditorComponent as Ve,ExtensionFatalError as ze,ExtensionInputComponent as Je,ExtensionRunner as Xe,ExtensionSelectorComponent as Ye,FooterComponent as qe,HOST_CAPABILITIES_ENV as Qe,HOST_TOKEN_ENV as Ze,HOST_TOKEN_HEADER as et,HOST_URL_ENV as tt,HostCallError as ot,HostCapabilities as rt,InteractiveMode as nt,LoginDialogComponent as it,MARKET_SECTIONS as st,MAX_BACKGROUND_PROCESSES as at,ModelRegistry as lt,ModelSelectorComponent as ut,OAuthSelectorComponent as ct,PROTECTED_WRITE_NAMES as dt,REQUIRED_EXTENSION_FAILED as mt,RequiredExtensionError as pt,RpcClient as Et,RpcCommandError as St,SANDBOX_ENV as gt,SessionManager as ht,SessionSelectorComponent as ft,SettingsManager as Tt,SettingsSelectorComponent as Ct,ShellSandbox as kt,SkillInvocationMessageComponent as _t,ThinkingSelectorComponent as At,ToolExecutionComponent as Dt,TreeSelectorComponent as Rt,UserMessageComponent as Pt,UserMessageSelectorComponent as yt,adaptPackage as Lt,adaptationState as Ft,agentLogPath as It,appendAgentLog as Ot,applyCommunityEnv as Nt,buildContextEntries as wt,buildProjectMap as vt,buildRuleSet as Mt,buildSessionContext as Ht,buildSessionProjection as xt,calculateContextTokens as bt,chromeBottom as te,chromeTop as oe,collectEntriesForBranchSummary as Bt,communityEnv as Ut,compact as jt,convertToLlm as Kt,convertToPng as Wt,copyToClipboard as Gt,createAgentSession as $t,createAgentSessionFromServices as Vt,createAgentSessionRuntime as zt,createAgentSessionServices as Jt,createBashTool as Xt,createBashToolDefinition as Yt,createCodemodeExtension as qt,createCodingTools as Qt,createEditTool as Zt,createEditToolDefinition as eo,createEventBus as to,createExtensionRuntime as oo,createFindTool as ro,createFindToolDefinition as no,createGrepTool as io,createGrepToolDefinition as so,createLocalBashOperations as ao,createLocalPowerShellOperations as lo,createLsTool as uo,createLsToolDefinition as co,createMcpExtension as mo,createPowerShellTool as po,createPowerShellToolDefinition as Eo,createProcessToolDefinition as So,createReadOnlyTools as go,createReadTool as ho,createReadToolDefinition as fo,createSyntheticSourceInfo as To,createToolSearchExtension as Co,createWriteTool as ko,createWriteToolDefinition as _o,defineTool as Ao,describeProjectFacts as Do,detectProjectFacts as Ro,detectSandboxAvailability as Po,detectSupportedImageMimeTypeFromFile as yo,discoverAndLoadExtensions as Lo,ensurePackageAdapted as Fo,estimateTokens as Io,evaluateToolPolicy as Oo,expandTempDirVariable as No,fetchSignedMarket as wo,findCutPoint as vo,findTurnStartIndex as Mo,formatDimensionNote as Ho,formatProjectMapPrompt as xo,formatSkillsForPrompt as bo,generateBranchSummary as Bo,generateDiffString as Uo,generateSummary as jo,generateSummaryWithUsage as Ko,generateUnifiedPatch as Wo,getHostCapabilities as Go,getLastAssistantUsage as $o,getLatestCompactionEntry as Vo,getProcessShellSandbox as zo,getToolDenial as Jo,isAdaptablePackage as Xo,isBashToolResult as Yo,isEditToolResult as qo,isFatalExtensionError as Qo,isFindToolResult as Zo,isGrepToolResult as er,isHostExtensionPath as tr,isLsToolResult as or,isPowerShellToolResult as rr,isReadOnlyBashCommand as nr,isReadToolResult as ir,isToolCallEventType as sr,isWriteToolResult as ar,loadMcpRuntime as lr,loadProjectContextFiles as ur,loadSkills as cr,loadSkillsFromDir as dr,main as mr,markHostExtensionPaths as pr,marketCacheDir as Er,matchPermissionRules as Sr,migrateSessionEntries as gr,normalizeForFuzzyMatch as hr,parseArgs as fr,parseFrontmatter as Tr,parseHostCapabilities as Cr,parsePermissionRule as kr,parseSessionEntries as _r,parseSkillBlock as Ar,prepareBranchEntries as Dr,projectPackageManager as Rr,readAccessDenial as Pr,readAdaptation as yr,readSignedSection as Lr,registerPermissionAskHandler as Fr,registerSandboxEscalationHandler as Ir,registerShellExecutionGuard as Or,renderDiff as Nr,resizeImage as wr,resolveCliModel as vr,resolveMarketEndpoint as Mr,resolveModelScopeWithDiagnostics as Hr,resolveSandboxPolicy as xr,resolveToCwd as br,runPrintMode as Br,runRpcMode as Ur,scanHardcodedPiPaths as jr,serializeConversation as Kr,sessionEntryToContextMessages as Wr,shellExecutionRefusal as Gr,shouldCompact as $r,simpleCommands as Vr,stripFrontmatter as zr,systemTempDirs as Jr,tryEnsurePackageAdapted as Xr,unwrapCommand as Yr,verifyAdaptation as qr,verifySignedSection as Qr,withFileMutationQueue as Zr,wrapRegisteredTool as en,wrapRegisteredTools as tn}from"./chunk-6U37J6E7.js";import{CredentialSynchronizationError as on,DALCODE_PROJECT_DIR_NAME as rn,DEFAULT_HOOK_TIMEOUT_SECONDS as nn,ModelRuntime as sn,PROJECT_HOOKS_FILE_ENV as an,ProjectTrustStore as ln,TRUST_REQUIRING_PROJECT_HOOK_FILES as un,VIRTUAL_MODEL_STATE_ENTRY as cn,dalHookSourceFiles as dn,deriveHookName as mn,hasTrustRequiringProjectResources as pn,loadDalHooks as re,openBrowser as En,projectFileDeclaresHooks as Sn,projectHooksFileFromEnv as ne}from"./chunk-YDOF6JVP.js";import{formatReadLineRange as gn,truncateToVisualLines as hn}from"./chunk-5TGFM4KW.js";import{readStoredCredential as fn}from"./chunk-D3HKK2ZD.js";import{DEFAULT_MAX_BYTES as Tn,DEFAULT_MAX_LINES as Cn,DEFAULT_SHELL_ENV_EXCLUDES as kn,applyShellEnvironmentPolicy as _n,formatSize as An,getPowerShellConfig as Dn,getShellConfig as Rn,getShellEnv as Pn,isDalCodeCredentialName as yn,truncateHead as Ln,truncateLine as Fn,truncateTail as In,withoutDalCodeCredentials as ie}from"./chunk-SE42OS3U.js";import{ArminComponent as On}from"./chunk-F5SIUTR7.js";import{Container as se,SelectList as ae,Theme as Nn,getAvailableThemes as wn,getLanguageFromPath as vn,getMarkdownTheme as Mn,getSelectListTheme as N,getSettingsListTheme as Hn,highlightCode as xn,initTheme as bn,keyHint as Bn,keyText as Un,rawKeyHint as jn}from"./chunk-AL3DFAIM.js";import{CONFIG_DIR_NAME as Kn,SHARED_SKILL_CONFIG_DIRS as Wn,VERSION as Gn,getAgentDir as le,getDocsPath as $n,getExamplesPath as Vn,getPackageDir as zn,getReadmePath as Jn}from"./chunk-R47JBGS3.js";import{t as S}from"./chunk-SNBVCTMQ.js";import{__export as Xn}from"./chunk-JXWJOIH4.js";var ue={};Xn(ue,{ADAPTATION_FILE:e(()=>Fe,"ADAPTATION_FILE"),AgentSession:e(()=>Ie,"AgentSession"),AgentSessionRuntime:e(()=>Oe,"AgentSessionRuntime"),ArminComponent:e(()=>On,"ArminComponent"),AssistantMessageComponent:e(()=>Ne,"AssistantMessageComponent"),BackgroundProcessManager:e(()=>we,"BackgroundProcessManager"),BashExecutionComponent:e(()=>ve,"BashExecutionComponent"),BorderedLoader:e(()=>Me,"BorderedLoader"),BranchSummaryMessageComponent:e(()=>He,"BranchSummaryMessageComponent"),CONFIG_DIR_NAME:e(()=>Kn,"CONFIG_DIR_NAME"),CURRENT_SESSION_VERSION:e(()=>xe,"CURRENT_SESSION_VERSION"),CompactionSummaryMessageComponent:e(()=>be,"CompactionSummaryMessageComponent"),CredentialSynchronizationError:e(()=>on,"CredentialSynchronizationError"),CustomEditor:e(()=>Be,"CustomEditor"),CustomMessageComponent:e(()=>Ue,"CustomMessageComponent"),DALCODE_PROJECT_DIR_NAME:e(()=>rn,"DALCODE_PROJECT_DIR_NAME"),DAL_HOOK_ENTRY_TYPE:e(()=>B,"DAL_HOOK_ENTRY_TYPE"),DAL_HOOK_NOTIFICATION_CHANNEL:e(()=>ee,"DAL_HOOK_NOTIFICATION_CHANNEL"),DEFAULT_COMPACTION_SETTINGS:e(()=>je,"DEFAULT_COMPACTION_SETTINGS"),DEFAULT_HOOK_TIMEOUT_SECONDS:e(()=>nn,"DEFAULT_HOOK_TIMEOUT_SECONDS"),DEFAULT_MAX_BYTES:e(()=>Tn,"DEFAULT_MAX_BYTES"),DEFAULT_MAX_LINES:e(()=>Cn,"DEFAULT_MAX_LINES"),DEFAULT_SHELL_ENV_EXCLUDES:e(()=>kn,"DEFAULT_SHELL_ENV_EXCLUDES"),DefaultPackageManager:e(()=>Ke,"DefaultPackageManager"),DefaultResourceLoader:e(()=>We,"DefaultResourceLoader"),DynamicBorder:e(()=>Ge,"DynamicBorder"),ENGINE_MARKET_CACHE_FILE:e(()=>$e,"ENGINE_MARKET_CACHE_FILE"),ExtensionEditorComponent:e(()=>Ve,"ExtensionEditorComponent"),ExtensionFatalError:e(()=>ze,"ExtensionFatalError"),ExtensionInputComponent:e(()=>Je,"ExtensionInputComponent"),ExtensionRunner:e(()=>Xe,"ExtensionRunner"),ExtensionSelectorComponent:e(()=>Ye,"ExtensionSelectorComponent"),FooterComponent:e(()=>qe,"FooterComponent"),HOST_CAPABILITIES_ENV:e(()=>Qe,"HOST_CAPABILITIES_ENV"),HOST_TOKEN_ENV:e(()=>Ze,"HOST_TOKEN_ENV"),HOST_TOKEN_HEADER:e(()=>et,"HOST_TOKEN_HEADER"),HOST_URL_ENV:e(()=>tt,"HOST_URL_ENV"),HostCallError:e(()=>ot,"HostCallError"),HostCapabilities:e(()=>rt,"HostCapabilities"),InteractiveMode:e(()=>nt,"InteractiveMode"),LoginDialogComponent:e(()=>it,"LoginDialogComponent"),MARKET_SECTIONS:e(()=>st,"MARKET_SECTIONS"),MAX_BACKGROUND_PROCESSES:e(()=>at,"MAX_BACKGROUND_PROCESSES"),ModelRegistry:e(()=>lt,"ModelRegistry"),ModelRuntime:e(()=>sn,"ModelRuntime"),ModelSelectorComponent:e(()=>ut,"ModelSelectorComponent"),OAuthSelectorComponent:e(()=>ct,"OAuthSelectorComponent"),PROJECT_HOOKS_FILE_ENV:e(()=>an,"PROJECT_HOOKS_FILE_ENV"),PROTECTED_WRITE_NAMES:e(()=>dt,"PROTECTED_WRITE_NAMES"),ProjectTrustStore:e(()=>ln,"ProjectTrustStore"),REQUIRED_EXTENSION_FAILED:e(()=>mt,"REQUIRED_EXTENSION_FAILED"),RequiredExtensionError:e(()=>pt,"RequiredExtensionError"),RpcClient:e(()=>Et,"RpcClient"),RpcCommandError:e(()=>St,"RpcCommandError"),SANDBOX_ENV:e(()=>gt,"SANDBOX_ENV"),SHARED_SKILL_CONFIG_DIRS:e(()=>Wn,"SHARED_SKILL_CONFIG_DIRS"),STALE_AFTER_MS:e(()=>H,"STALE_AFTER_MS"),SessionManager:e(()=>ht,"SessionManager"),SessionSelectorComponent:e(()=>ft,"SessionSelectorComponent"),SettingsManager:e(()=>Tt,"SettingsManager"),SettingsSelectorComponent:e(()=>Ct,"SettingsSelectorComponent"),ShellSandbox:e(()=>kt,"ShellSandbox"),ShowImagesSelectorComponent:e(()=>Re,"ShowImagesSelectorComponent"),SkillInvocationMessageComponent:e(()=>_t,"SkillInvocationMessageComponent"),TRUST_REQUIRING_PROJECT_HOOK_FILES:e(()=>un,"TRUST_REQUIRING_PROJECT_HOOK_FILES"),Theme:e(()=>Nn,"Theme"),ThemeSelectorComponent:e(()=>Pe,"ThemeSelectorComponent"),ThinkingSelectorComponent:e(()=>At,"ThinkingSelectorComponent"),ToolExecutionComponent:e(()=>Dt,"ToolExecutionComponent"),TreeSelectorComponent:e(()=>Rt,"TreeSelectorComponent"),UserMessageComponent:e(()=>Pt,"UserMessageComponent"),UserMessageSelectorComponent:e(()=>yt,"UserMessageSelectorComponent"),VERSION:e(()=>Gn,"VERSION"),VIRTUAL_MODEL_STATE_ENTRY:e(()=>cn,"VIRTUAL_MODEL_STATE_ENTRY"),WORKSPACE_LOCK_DIR_NAME:e(()=>v,"WORKSPACE_LOCK_DIR_NAME"),WORKSPACE_LOCK_FILE:e(()=>L,"WORKSPACE_LOCK_FILE"),adaptPackage:e(()=>Lt,"adaptPackage"),adaptationState:e(()=>Ft,"adaptationState"),agentLogPath:e(()=>It,"agentLogPath"),appendAgentLog:e(()=>Ot,"appendAgentLog"),applyCommunityEnv:e(()=>Nt,"applyCommunityEnv"),applyShellEnvironmentPolicy:e(()=>_n,"applyShellEnvironmentPolicy"),buildContextEntries:e(()=>wt,"buildContextEntries"),buildDalHookInput:e(()=>V,"buildDalHookInput"),buildProjectMap:e(()=>vt,"buildProjectMap"),buildRuleSet:e(()=>Mt,"buildRuleSet"),buildSessionContext:e(()=>Ht,"buildSessionContext"),buildSessionProjection:e(()=>xt,"buildSessionProjection"),calculateContextTokens:e(()=>bt,"calculateContextTokens"),claimWorkspace:e(()=>pe,"claimWorkspace"),collectEntriesForBranchSummary:e(()=>Bt,"collectEntriesForBranchSummary"),communityEnv:e(()=>Ut,"communityEnv"),compact:e(()=>jt,"compact"),convertToLlm:e(()=>Kt,"convertToLlm"),convertToPng:e(()=>Wt,"convertToPng"),copyToClipboard:e(()=>Gt,"copyToClipboard"),createAgentSession:e(()=>$t,"createAgentSession"),createAgentSessionFromServices:e(()=>Vt,"createAgentSessionFromServices"),createAgentSessionRuntime:e(()=>zt,"createAgentSessionRuntime"),createAgentSessionServices:e(()=>Jt,"createAgentSessionServices"),createBashTool:e(()=>Xt,"createBashTool"),createBashToolDefinition:e(()=>Yt,"createBashToolDefinition"),createCodemodeExtension:e(()=>qt,"createCodemodeExtension"),createCodingTools:e(()=>Qt,"createCodingTools"),createEditTool:e(()=>Zt,"createEditTool"),createEditToolDefinition:e(()=>eo,"createEditToolDefinition"),createEventBus:e(()=>to,"createEventBus"),createExtensionRuntime:e(()=>oo,"createExtensionRuntime"),createFindTool:e(()=>ro,"createFindTool"),createFindToolDefinition:e(()=>no,"createFindToolDefinition"),createGrepTool:e(()=>io,"createGrepTool"),createGrepToolDefinition:e(()=>so,"createGrepToolDefinition"),createLocalBashOperations:e(()=>ao,"createLocalBashOperations"),createLocalPowerShellOperations:e(()=>lo,"createLocalPowerShellOperations"),createLsTool:e(()=>uo,"createLsTool"),createLsToolDefinition:e(()=>co,"createLsToolDefinition"),createMcpExtension:e(()=>mo,"createMcpExtension"),createPowerShellTool:e(()=>po,"createPowerShellTool"),createPowerShellToolDefinition:e(()=>Eo,"createPowerShellToolDefinition"),createProcessToolDefinition:e(()=>So,"createProcessToolDefinition"),createReadOnlyTools:e(()=>go,"createReadOnlyTools"),createReadTool:e(()=>ho,"createReadTool"),createReadToolDefinition:e(()=>fo,"createReadToolDefinition"),createSyntheticSourceInfo:e(()=>To,"createSyntheticSourceInfo"),createToolSearchExtension:e(()=>Co,"createToolSearchExtension"),createWriteTool:e(()=>ko,"createWriteTool"),createWriteToolDefinition:e(()=>_o,"createWriteToolDefinition"),dalHookActivity:e(()=>g,"dalHookActivity"),dalHookSourceFiles:e(()=>dn,"dalHookSourceFiles"),dalHooksExtension:e(()=>De,"dalHooksExtension"),decideDalHooks:e(()=>$,"decideDalHooks"),defaultWorkspaceLockDir:e(()=>M,"defaultWorkspaceLockDir"),defineTool:e(()=>Ao,"defineTool"),deriveHookName:e(()=>mn,"deriveHookName"),describeProjectFacts:e(()=>Do,"describeProjectFacts"),detectProjectFacts:e(()=>Ro,"detectProjectFacts"),detectSandboxAvailability:e(()=>Po,"detectSandboxAvailability"),detectSupportedImageMimeTypeFromFile:e(()=>yo,"detectSupportedImageMimeTypeFromFile"),discoverAndLoadExtensions:e(()=>Lo,"discoverAndLoadExtensions"),engineToolInput:e(()=>j,"engineToolInput"),ensurePackageAdapted:e(()=>Fo,"ensurePackageAdapted"),estimateTokens:e(()=>Io,"estimateTokens"),evaluateToolPolicy:e(()=>Oo,"evaluateToolPolicy"),expandTempDirVariable:e(()=>No,"expandTempDirVariable"),fetchSignedMarket:e(()=>wo,"fetchSignedMarket"),findCutPoint:e(()=>vo,"findCutPoint"),findTurnStartIndex:e(()=>Mo,"findTurnStartIndex"),formatDalHookActivity:e(()=>U,"formatDalHookActivity"),formatDimensionNote:e(()=>Ho,"formatDimensionNote"),formatProjectMapPrompt:e(()=>xo,"formatProjectMapPrompt"),formatReadLineRange:e(()=>gn,"formatReadLineRange"),formatSize:e(()=>An,"formatSize"),formatSkillsForPrompt:e(()=>bo,"formatSkillsForPrompt"),generateBranchSummary:e(()=>Bo,"generateBranchSummary"),generateDiffString:e(()=>Uo,"generateDiffString"),generateSummary:e(()=>jo,"generateSummary"),generateSummaryWithUsage:e(()=>Ko,"generateSummaryWithUsage"),generateUnifiedPatch:e(()=>Wo,"generateUnifiedPatch"),getAgentDir:e(()=>le,"getAgentDir"),getDocsPath:e(()=>$n,"getDocsPath"),getExamplesPath:e(()=>Vn,"getExamplesPath"),getHostCapabilities:e(()=>Go,"getHostCapabilities"),getLanguageFromPath:e(()=>vn,"getLanguageFromPath"),getLastAssistantUsage:e(()=>$o,"getLastAssistantUsage"),getLatestCompactionEntry:e(()=>Vo,"getLatestCompactionEntry"),getMarkdownTheme:e(()=>Mn,"getMarkdownTheme"),getPackageDir:e(()=>zn,"getPackageDir"),getPowerShellConfig:e(()=>Dn,"getPowerShellConfig"),getProcessShellSandbox:e(()=>zo,"getProcessShellSandbox"),getReadmePath:e(()=>Jn,"getReadmePath"),getSelectListTheme:e(()=>N,"getSelectListTheme"),getSettingsListTheme:e(()=>Hn,"getSettingsListTheme"),getShellConfig:e(()=>Rn,"getShellConfig"),getShellEnv:e(()=>Pn,"getShellEnv"),getToolDenial:e(()=>Jo,"getToolDenial"),gitDirOf:e(()=>x,"gitDirOf"),hasTrustRequiringProjectResources:e(()=>pn,"hasTrustRequiringProjectResources"),highlightCode:e(()=>xn,"highlightCode"),hookToolInput:e(()=>I,"hookToolInput"),hookToolName:e(()=>R,"hookToolName"),initTheme:e(()=>bn,"initTheme"),isAdaptablePackage:e(()=>Xo,"isAdaptablePackage"),isBashToolResult:e(()=>Yo,"isBashToolResult"),isDalCodeCredentialName:e(()=>yn,"isDalCodeCredentialName"),isDalHookActivity:e(()=>ge,"isDalHookActivity"),isEditToolResult:e(()=>qo,"isEditToolResult"),isFatalExtensionError:e(()=>Qo,"isFatalExtensionError"),isFindToolResult:e(()=>Zo,"isFindToolResult"),isGrepToolResult:e(()=>er,"isGrepToolResult"),isHostExtensionPath:e(()=>tr,"isHostExtensionPath"),isLsToolResult:e(()=>or,"isLsToolResult"),isPowerShellToolResult:e(()=>rr,"isPowerShellToolResult"),isReadOnlyBashCommand:e(()=>nr,"isReadOnlyBashCommand"),isReadToolResult:e(()=>ir,"isReadToolResult"),isToolCallEventType:e(()=>sr,"isToolCallEventType"),isWriteToolResult:e(()=>ar,"isWriteToolResult"),keyHint:e(()=>Bn,"keyHint"),keyText:e(()=>Un,"keyText"),loadDalHooks:e(()=>re,"loadDalHooks"),loadMcpRuntime:e(()=>lr,"loadMcpRuntime"),loadProjectContextFiles:e(()=>ur,"loadProjectContextFiles"),loadSkills:e(()=>cr,"loadSkills"),loadSkillsFromDir:e(()=>dr,"loadSkillsFromDir"),main:e(()=>mr,"main"),markHostExtensionPaths:e(()=>pr,"markHostExtensionPaths"),marketCacheDir:e(()=>Er,"marketCacheDir"),matchPermissionRules:e(()=>Sr,"matchPermissionRules"),migrateSessionEntries:e(()=>gr,"migrateSessionEntries"),normalizeForFuzzyMatch:e(()=>hr,"normalizeForFuzzyMatch"),openBrowser:e(()=>En,"openBrowser"),parseArgs:e(()=>fr,"parseArgs"),parseFrontmatter:e(()=>Tr,"parseFrontmatter"),parseHostCapabilities:e(()=>Cr,"parseHostCapabilities"),parsePermissionRule:e(()=>kr,"parsePermissionRule"),parseSessionEntries:e(()=>_r,"parseSessionEntries"),parseSkillBlock:e(()=>Ar,"parseSkillBlock"),prepareBranchEntries:e(()=>Dr,"prepareBranchEntries"),projectFileDeclaresHooks:e(()=>Sn,"projectFileDeclaresHooks"),projectHooksFileFromEnv:e(()=>ne,"projectHooksFileFromEnv"),projectPackageManager:e(()=>Rr,"projectPackageManager"),rawKeyHint:e(()=>jn,"rawKeyHint"),readAccessDenial:e(()=>Pr,"readAccessDenial"),readAdaptation:e(()=>yr,"readAdaptation"),readSignedSection:e(()=>Lr,"readSignedSection"),readStoredCredential:e(()=>fn,"readStoredCredential"),readWorkspaceLock:e(()=>de,"readWorkspaceLock"),registerPermissionAskHandler:e(()=>Fr,"registerPermissionAskHandler"),registerSandboxEscalationHandler:e(()=>Ir,"registerSandboxEscalationHandler"),registerShellExecutionGuard:e(()=>Or,"registerShellExecutionGuard"),releaseWorkspace:e(()=>Ee,"releaseWorkspace"),renderDiff:e(()=>Nr,"renderDiff"),reportDalHookProblems:e(()=>z,"reportDalHookProblems"),resizeImage:e(()=>wr,"resizeImage"),resolveCliModel:e(()=>vr,"resolveCliModel"),resolveMarketEndpoint:e(()=>Mr,"resolveMarketEndpoint"),resolveModelScopeWithDiagnostics:e(()=>Hr,"resolveModelScopeWithDiagnostics"),resolveSandboxPolicy:e(()=>xr,"resolveSandboxPolicy"),resolveToCwd:e(()=>br,"resolveToCwd"),runDalCommandHook:e(()=>W,"runDalCommandHook"),runDalHookEvent:e(()=>T,"runDalHookEvent"),runDalHooks:e(()=>G,"runDalHooks"),runNotificationHooks:e(()=>Z,"runNotificationHooks"),runPostToolUseHooks:e(()=>X,"runPostToolUseHooks"),runPreToolUseHooks:e(()=>J,"runPreToolUseHooks"),runPrintMode:e(()=>Br,"runPrintMode"),runRpcMode:e(()=>Ur,"runRpcMode"),runSessionStartHooks:e(()=>Y,"runSessionStartHooks"),runStopHooks:e(()=>Q,"runStopHooks"),runUserPromptSubmitHooks:e(()=>q,"runUserPromptSubmitHooks"),scanHardcodedPiPaths:e(()=>jr,"scanHardcodedPiPaths"),selectDalHooks:e(()=>K,"selectDalHooks"),serializeConversation:e(()=>Kr,"serializeConversation"),sessionEntryToContextMessages:e(()=>Wr,"sessionEntryToContextMessages"),shellCommandDirectory:e(()=>Se,"shellCommandDirectory"),shellExecutionRefusal:e(()=>Gr,"shellExecutionRefusal"),shouldCompact:e(()=>$r,"shouldCompact"),simpleCommands:e(()=>Vr,"simpleCommands"),stripFrontmatter:e(()=>zr,"stripFrontmatter"),systemTempDirs:e(()=>Jr,"systemTempDirs"),toolMatchNames:e(()=>O,"toolMatchNames"),truncateHead:e(()=>Ln,"truncateHead"),truncateLine:e(()=>Fn,"truncateLine"),truncateTail:e(()=>In,"truncateTail"),truncateToVisualLines:e(()=>hn,"truncateToVisualLines"),tryEnsurePackageAdapted:e(()=>Xr,"tryEnsurePackageAdapted"),unwrapCommand:e(()=>Yr,"unwrapCommand"),verifyAdaptation:e(()=>qr,"verifyAdaptation"),verifySignedSection:e(()=>Qr,"verifySignedSection"),withFileMutationQueue:e(()=>Zr,"withFileMutationQueue"),withoutDalCodeCredentials:e(()=>ie,"withoutDalCodeCredentials"),workspaceLockIsLive:e(()=>F,"workspaceLockIsLive"),workspaceLockPath:e(()=>A,"workspaceLockPath"),workspaceOwnerSessionId:e(()=>b,"workspaceOwnerSessionId"),wrapRegisteredTool:e(()=>en,"wrapRegisteredTool"),wrapRegisteredTools:e(()=>tn,"wrapRegisteredTools")});import{execFileSync as Yn}from"node:child_process";import{createHash as qn}from"node:crypto";import{mkdirSync as Qn,readFileSync as Zn,realpathSync as ei,renameSync as ti,rmSync as oi,writeFileSync as ri}from"node:fs";import{hostname as P}from"node:os";import{basename as w,isAbsolute as ni,join as y,resolve as k}from"node:path";var v="workspace-locks",L="dal-workspace.lock";function M(){return y(le(),v)}e(M,"defaultWorkspaceLockDir");function A(o,t=M()){let r=k(o);try{r=ei.native(r)}catch{}let n=qn("sha256").update(r).digest("hex").slice(0,16),a=w(r)===".git"?w(k(r,"..")):w(r);return y(t,`${a.replace(/[^\w.-]/g,"_").slice(0,40)||"repo"}-${n}.lock`)}e(A,"workspaceLockPath");var H=7200*1e3,ii=60*1e3,si="DALCODE_PARENT_SESSION_ID",ce=new Map;function x(o){let t=k(o),r=ce.get(t);if(r!==void 0)return r??void 0;let n=null;try{let a=Yn("git",["rev-parse","--git-dir","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(`
|
|
2
2
|
`),l=a[0]?.trim();l&&(n={gitDir:ni(l)?l:k(t,l),worktree:a[1]?.trim()})}catch{n=null}return ce.set(t,n),n??void 0}e(x,"gitDirOf");function b(o,t=process.env){return t[si]||o}e(b,"workspaceOwnerSessionId");function D(o){try{let t=JSON.parse(Zn(o,"utf8"));return typeof t.pid!="number"||typeof t.sessionId!="string"||typeof t.host!="string"?void 0:{pid:t.pid,host:t.host,sessionId:t.sessionId,startedAt:typeof t.startedAt=="string"?t.startedAt:new Date(0).toISOString(),refreshedAt:typeof t.refreshedAt=="string"?t.refreshedAt:new Date(0).toISOString(),...typeof t.worktree=="string"?{worktree:t.worktree}:{}}}catch{return}}e(D,"readLockFile");function de(o,t){return D(A(o,t))??D(y(o,L))}e(de,"readWorkspaceLock");function ai(o){try{return process.kill(o,0),!0}catch(t){return t.code==="EPERM"}}e(ai,"processAlive");function F(o,t=Date.now()){let r=Date.parse(o.refreshedAt);return!Number.isFinite(r)||t-r>H?!1:o.host===P()?ai(o.pid):!0}e(F,"workspaceLockIsLive");function me(o,t){Qn(k(o,".."),{recursive:!0});let r=`${o}.${process.pid}.tmp`;ri(r,`${JSON.stringify(t,null,2)}
|
|
3
3
|
`),ti(r,o)}e(me,"writeLock");function pe(o,t,r={}){let n=x(o);if(!n)return;let a=r.now??Date.now(),l=b(t,r.env),d=A(n.gitDir,r.lockDir),c=D(d),u={gitDir:n.gitDir,...n.worktree?{worktree:n.worktree}:{}},i=D(y(n.gitDir,L));for(let s of[c,i])if(s&&s.sessionId!==l&&F(s,a)&&!r.force)return{...u,heldBy:s};if(c?.sessionId===l&&F(c,a)){if(!(c.pid===process.pid&&c.host===P())||a-Date.parse(c.refreshedAt)<ii)return u;try{me(d,{...c,refreshedAt:new Date(a).toISOString()})}catch{}return u}try{me(d,{pid:process.pid,host:P(),sessionId:l,startedAt:new Date(a).toISOString(),refreshedAt:new Date(a).toISOString(),...n.worktree?{worktree:n.worktree}:{}})}catch{return}return u}e(pe,"claimWorkspace");function Ee(o,t){let r=A(o,t),n=D(r);if(!(!n||n.pid!==process.pid||n.host!==P()))try{oi(r,{force:!0})}catch{}}e(Ee,"releaseWorkspace");function Se(o,t){let r=t;for(let a of o.split(/&&|;|\n/)){let l=/^\s*cd\s+("([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(a);if(!l)break;let d=(l[2]??l[3]??l[4]??"").replace(/^~(?=\/|$)/,process.env.HOME??"~");r=k(r,d)}let n=/\bgit\s+-C\s+("([^"]+)"|'([^']+)'|(\S+))/.exec(o);return n&&(r=k(r,n[2]??n[3]??n[4]??".")),r}e(Se,"shellCommandDirectory");var B="dal-hook";function h(o,t){return o.replace(/\{(\w+)\}/g,(r,n)=>String(t[n]??""))}e(h,"fill");function li(o,t=300){let r=(o??"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}e(li,"oneLine");function U(o){let t={name:o.hookName??"",tool:o.toolName??"",event:o.event,detail:li(o.detail),path:o.path??"",seconds:o.timeoutSeconds??""};switch(o.kind){case"blocked":return o.toolName?h(S("\u94A9\u5B50 {name} \u62E6\u622A\u4E86 {tool}\uFF1A{detail}"),t):h(S("\u94A9\u5B50 {name} \u62E6\u622A\u4E86\u8FD9\u6761\u6D88\u606F\uFF1A{detail}"),t);case"modified":return h(S("\u94A9\u5B50 {name} \u4FEE\u6539\u4E86 {tool} \u7684\u8F93\u5165"),t);case"context":return h(S("\u94A9\u5B50 {name} \u4E3A {event} \u8865\u5145\u4E86\u4E0A\u4E0B\u6587"),t);case"message":return h(S("\u94A9\u5B50 {name}\uFF1A{detail}"),t);case"stop-ignored":return h(S("\u94A9\u5B50 {name} \u8981\u6C42\u7EE7\u7EED\u5DE5\u4F5C\uFF0C\u4F46 Stop \u94A9\u5B50\u4E0D\u80FD\u8BA9\u56DE\u5408\u7EED\u8DD1\uFF0C\u5DF2\u5FFD\u7565\uFF1A{detail}"),t);case"failed":return h(S("\u94A9\u5B50 {name}\uFF08{event}\uFF09\u8FD0\u884C\u5931\u8D25\uFF0C\u5DF2\u7EE7\u7EED\uFF1A{detail}"),t);case"timeout":return h(S("\u94A9\u5B50 {name}\uFF08{event}\uFF09\u8D85\u8FC7 {seconds} \u79D2\u672A\u7ED3\u675F\uFF0C\u5DF2\u7EC8\u6B62\u5E76\u7EE7\u7EED"),t);case"config":return h(S("\u94A9\u5B50\u914D\u7F6E\u6709\u8BEF\uFF08{path}\uFF09\uFF1A{detail}"),t)}}e(U,"formatDalHookActivity");var ui=new Set(["stop-ignored","failed","timeout","config"]);function g(o){return{...o,text:U(o),level:ui.has(o.kind)?"warning":"info"}}e(g,"dalHookActivity");function ge(o){if(typeof o!="object"||o===null)return!1;let t=o;return typeof t.kind=="string"&&typeof t.event=="string"&&typeof t.text=="string"}e(ge,"isDalHookActivity");import{spawn as he}from"node:child_process";var fe=64*1024,ci={bash:"Bash",powershell:"PowerShell",read:"Read",write:"Write",edit:"Edit",grep:"Grep",find:"Glob",ls:"LS",task:"Task"},Te=new Set(["read","write","edit"]);function R(o){return ci[o]??o}e(R,"hookToolName");function I(o,t){return Te.has(o)&&typeof t.path=="string"&&t.file_path===void 0?{...t,file_path:t.path}:{...t}}e(I,"hookToolInput");function j(o,t){if(!Te.has(o)||!("file_path"in t))return{...t};let{file_path:r,...n}=t;return typeof r=="string"?{...n,path:r}:n}e(j,"engineToolInput");function di(o,t){if(/^[A-Za-z0-9_|-]+$/.test(o)){let n=o.split("|").filter(Boolean);return t.some(a=>n.includes(a))}let r;try{r=new RegExp(`^(?:${o})$`)}catch{return!1}return t.some(n=>r.test(n))}e(di,"matcherAccepts");function K(o,t,r){return o.filter(n=>n.event!==t?!1:n.matcher===void 0||r===void 0?!0:di(n.matcher,r))}e(K,"selectDalHooks");function O(o){return[o,R(o)]}e(O,"toolMatchNames");function Ce(o){if(o!==void 0)try{process.platform==="win32"?he("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore"}):process.kill(-o,"SIGKILL")}catch{}}e(Ce,"killTree");function mi(o){let t=o.trim();if(t.startsWith("{"))try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}catch{return}}e(mi,"parseJsonObject");function W(o,t,r){let n=Date.now();return new Promise(a=>{let l="",d="",c=!1,u=!1,i=he(o.command,{cwd:r.cwd,shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"],env:{...ie(process.env),...r.env,DAL_PROJECT_DIR:r.cwd,CLAUDE_PROJECT_DIR:r.cwd}}),s=e(m=>{c||(c=!0,clearTimeout(p),r.signal?.removeEventListener("abort",E),a({hook:o,stdout:l,stderr:d,durationMs:Date.now()-n,...m}))},"finish"),p=setTimeout(()=>{u=!0,Ce(i.pid)},o.timeoutSeconds*1e3),E=e(()=>Ce(i.pid),"onAbort");r.signal?.addEventListener("abort",E,{once:!0}),i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",m=>{l.length<fe&&(l+=m)}),i.stderr.on("data",m=>{d.length<fe&&(d+=m)}),i.stdin.on("error",()=>{}),i.stdin.end(JSON.stringify(t)),i.on("error",m=>{s({status:"failed",exitCode:null,error:m.message})}),i.on("close",m=>{if(u){s({status:"timeout",exitCode:m,error:`timed out after ${o.timeoutSeconds}s`});return}if(r.signal?.aborted){s({status:"failed",exitCode:m,error:"cancelled"});return}if(m===2){s({status:"blocked",exitCode:m});return}if(m!==0){s({status:"failed",exitCode:m,error:`exited with code ${m}`});return}let C=mi(l);s({status:"success",exitCode:0,...C?{output:C}:{}})})})}e(W,"runDalCommandHook");function G(o,t,r){return Promise.all(o.map(n=>W(n,t,r)))}e(G,"runDalHooks");function _(o,t){let r=o?.[t];return typeof r=="string"&&r.trim()!==""?r:void 0}e(_,"stringField");var pi=new Set(["SessionStart","UserPromptSubmit"]);function $(o,t){let r,n,a,l=[],d=[],c=[];for(let u of t){if(u.status==="failed"||u.status==="timeout"){c.push(u);continue}if(u.status==="blocked"){r??={hook:u.hook,reason:u.stderr.trim()||`hook ${u.hook.name} blocked (exit 2)`};continue}let i=u.output;if(!i){pi.has(o)&&u.stdout.trim()!==""&&l.push({hook:u.hook,text:u.stdout.trim()});continue}let s=typeof i.hookSpecificOutput=="object"&&i.hookSpecificOutput!==null?i.hookSpecificOutput:void 0,p=_(s,"permissionDecisionReason")??_(i,"reason");i.continue===!1&&(n??={hook:u.hook,reason:_(i,"stopReason")??p??u.hook.name}),(_(s,"permissionDecision")==="deny"||i.decision==="block")&&(r??={hook:u.hook,reason:p??`hook ${u.hook.name} blocked`});let E=s?.updatedInput;typeof E=="object"&&E!==null&&!Array.isArray(E)&&(a={hook:u.hook,input:E});let m=_(s,"additionalContext");m&&l.push({hook:u.hook,text:m});let C=_(i,"systemMessage");C&&d.push({hook:u.hook,text:C})}return{...r?{blocked:r}:{},...n?{stop:n}:{},...a?{updatedInput:a}:{},additionalContext:l,systemMessages:d,failures:c}}e($,"decideDalHooks");function V(o,t,r={}){return{session_id:t.sessionId,transcript_path:t.transcriptPath??"",cwd:t.cwd,...t.permissionMode?{permission_mode:t.permissionMode}:{},...t.agentId?{agent_id:t.agentId}:{},...t.agentType?{agent_type:t.agentType}:{},hook_event_name:o,...r}}e(V,"buildDalHookInput");function f(o){return{hookName:o.name,scope:o.scope}}e(f,"scopeOf");function Ei(o,t,r){for(let n of t.failures)r(g({kind:n.status==="timeout"?"timeout":"failed",event:o,...f(n.hook),detail:Si(n),timeoutSeconds:n.hook.timeoutSeconds}));for(let n of t.systemMessages)r(g({kind:"message",event:o,...f(n.hook),detail:n.text}))}e(Ei,"reportCommon");function Si(o){let t=o.stderr.trim();return t?`${o.error??""} ${t}`.trim():o.error??""}e(Si,"failureDetail");function z(o,t){for(let r of o.problems)t(g({kind:"config",event:r.event??"",path:r.path,detail:r.message}))}e(z,"reportDalHookProblems");async function T(o,t,r,n){let a=K(o.config.hooks,t,n);if(a.length===0)return;let l=await G(a,V(t,o.base,r),{cwd:o.base.cwd,...o.signal?{signal:o.signal}:{}}),d=$(t,l);return Ei(t,d,o.report),d}e(T,"runDalHookEvent");async function J(o,t){let r=await T(o,"PreToolUse",{tool_name:R(t.toolName),tool_input:I(t.toolName,t.input),tool_use_id:t.toolCallId},O(t.toolName));if(!r)return{};let n=r.stop??r.blocked;return n?(o.report(g({kind:"blocked",event:"PreToolUse",...f(n.hook),toolName:t.toolName,detail:n.reason})),{blockReason:`[hook ${n.hook.name}] ${n.reason}`,...r.stop?{stop:!0}:{}}):r.updatedInput?(o.report(g({kind:"modified",event:"PreToolUse",...f(r.updatedInput.hook),toolName:t.toolName})),{input:j(t.toolName,r.updatedInput.input)}):{}}e(J,"runPreToolUseHooks");async function X(o,t){let r=t.isError?"PostToolUseFailure":"PostToolUse",n=await T(o,r,{tool_name:R(t.toolName),tool_input:I(t.toolName,t.input),tool_use_id:t.toolCallId,...t.isError?{error:t.output}:{tool_response:{content:t.output,...t.details!==void 0?{details:t.details}:{}}}},O(t.toolName));if(!n)return{};let a=[],l=n.stop??n.blocked;l&&(o.report(g({kind:"blocked",event:r,...f(l.hook),toolName:t.toolName,detail:l.reason})),a.push(`[hook ${l.hook.name}] ${l.reason}`));for(let d of n.additionalContext)o.report(g({kind:"context",event:r,...f(d.hook),toolName:t.toolName})),a.push(`[hook ${d.hook.name}] ${d.text}`);return a.length>0?{appendText:a.join(`
|
|
4
4
|
`)}:{}}e(X,"runPostToolUseHooks");async function Y(o,t){let r=await T(o,"SessionStart",{source:t},[t]);return ke("SessionStart",r,o.report)}e(Y,"runSessionStartHooks");function ke(o,t,r){if(!(!t||t.additionalContext.length===0)){for(let n of t.additionalContext)r(g({kind:"context",event:o,...f(n.hook)}));return t.additionalContext.map(n=>n.text).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Ha=Object.defineProperty;var p=(e,t)=>Ha(e,"name",{value:t,configurable:!0});import{createRequire as Va}from"node:module";const Fy=Va(import.meta.url);import{require_safe_buffer as Bt}from"./chunk-567OJLS7.js";import{getJsonSchemaToolParameters as $a,resolveJsonSchemaStrictSampling as tn,transformMessages as Ja}from"./chunk-FE533CCR.js";import{sanitizeSurrogates as St}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest as Wa}from"./chunk-ML5DIOWR.js";import{clampThinkingLevel as Xa,collapseSystemMessages as Ka,withoutInitialSystemMessage as Ya}from"./chunk-K4B5ABCQ.js";import{__commonJS as z,__require as te,__toESM as ze}from"./chunk-JXWJOIH4.js";var za=z({"node_modules/retry/lib/retry_operation.js"(e,t){function r(n,i){typeof i=="boolean"&&(i={forever:i}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=i||{},this._maxRetryTime=i&&i.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}p(r,"RetryOperation"),t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var i=new Date().getTime();if(n&&i-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},o),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(n,i){this._fn=n,i&&(i.timeout&&(this._operationTimeout=i.timeout),i.cb&&(this._operationTimeoutCb=i.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},r.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)},r.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},i=null,o=0,a=0;a<this._errors.length;a++){var c=this._errors[a],u=c.message,d=(n[u]||0)+1;n[u]=d,d>=o&&(i=c,o=d)}return i}}}),Qa=z({"node_modules/retry/lib/retry.js"(e){var t=za();e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in r)n[i]=r[i];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],a=0;a<n.retries;a++)o.push(this.createTimeout(a,n));return r&&r.forever&&!o.length&&o.push(this.createTimeout(a,n)),o.sort(function(c,u){return c-u}),o},e.createTimeout=function(r,n){var i=n.randomize?Math.random()+1:1,o=Math.round(i*Math.max(n.minTimeout,1)*Math.pow(n.factor,r));return o=Math.min(o,n.maxTimeout),o},e.wrap=function(r,n,i){if(n instanceof Array&&(i=n,n=null),!i){i=[];for(var o in r)typeof r[o]=="function"&&i.push(o)}for(var a=0;a<i.length;a++){var c=i[a],u=r[c];r[c]=function(d){var h=e.operation(n),m=Array.prototype.slice.call(arguments,1),g=m.pop();m.push(function(_){h.retry(_)||(_&&(arguments[0]=h.mainError()),g.apply(this,arguments))}),h.attempt(function(){d.apply(r,m)})}.bind(r,u),r[c].options=n}}}}),Za=z({"node_modules/retry/index.js"(e,t){t.exports=Qa()}}),ja=z({"node_modules/p-retry/index.js"(e,t){"use strict";var r=Za(),n=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],i=class extends Error{static{p(this,"AbortError")}constructor(u){super(),u instanceof Error?(this.originalError=u,{message:u}=u):(this.originalError=new Error(u),this.originalError.stack=this.stack),this.name="AbortError",this.message=u}},o=p((u,d,h)=>{let m=h.retries-(d-1);return u.attemptNumber=d,u.retriesLeft=m,u},"decorateErrorWithCounts"),a=p(u=>n.includes(u),"isNetworkError"),c=p((u,d)=>new Promise((h,m)=>{d={onFailedAttempt:p(()=>{},"onFailedAttempt"),retries:10,...d};let g=r.operation(d);g.attempt(async _=>{try{h(await u(_))}catch(f){if(!(f instanceof Error)){m(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof i)g.stop(),m(f.originalError);else if(f instanceof TypeError&&!a(f.message))g.stop(),m(f);else{o(f,_,d);try{await d.onFailedAttempt(f)}catch(y){m(y);return}g.retry(f)||m(g.mainError())}}})}),"pRetry2");t.exports=c,t.exports.default=c,t.exports.AbortError=i}}),rn=z({"node_modules/extend/index.js"(e,t){"use strict";var r=Object.prototype.hasOwnProperty,n=Object.prototype.toString,i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=p(function(h){return typeof Array.isArray=="function"?Array.isArray(h):n.call(h)==="[object Array]"},"isArray"),c=p(function(h){if(!h||n.call(h)!=="[object Object]")return!1;var m=r.call(h,"constructor"),g=h.constructor&&h.constructor.prototype&&r.call(h.constructor.prototype,"isPrototypeOf");if(h.constructor&&!m&&!g)return!1;var _;for(_ in h);return typeof _>"u"||r.call(h,_)},"isPlainObject2"),u=p(function(h,m){i&&m.name==="__proto__"?i(h,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):h[m.name]=m.newValue},"setProperty"),d=p(function(h,m){if(m==="__proto__")if(r.call(h,m)){if(o)return o(h,m).value}else return;return h[m]},"getProperty");t.exports=p(function h(){var m,g,_,f,y,E,C=arguments[0],S=1,A=arguments.length,v=!1;for(typeof C=="boolean"&&(v=C,C=arguments[1]||{},S=2),(C==null||typeof C!="object"&&typeof C!="function")&&(C={});S<A;++S)if(m=arguments[S],m!=null)for(g in m)_=d(C,g),f=d(m,g),C!==f&&(v&&f&&(c(f)||(y=a(f)))?(y?(y=!1,E=_&&a(_)?_:[]):E=_&&c(_)?_:{},u(C,{name:g,newValue:h(v,E,f)})):typeof f<"u"&&u(C,{name:g,newValue:f}));return C},"extend")}}),el=z({"node_modules/gaxios/package.json"(e,t){t.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}}),tl=z({"node_modules/gaxios/build/cjs/src/util.cjs"(e,t){"use strict";var r=el();t.exports={pkg:r}}}),nn=z({"node_modules/gaxios/build/cjs/src/common.js"(e){"use strict";var t=e&&e.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=c;var r=t(rn()),n=t(tl()),i=n.default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${i.name}-gaxios-error`);var o=class wa extends Error{static{p(this,"_GaxiosError")}config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=i.version;static[Symbol.hasInstance](d){return d&&typeof d=="object"&&e.GAXIOS_ERROR_SYMBOL in d&&d[e.GAXIOS_ERROR_SYMBOL]===i.version?!0:Function.prototype[Symbol.hasInstance].call(wa,d)}constructor(d,h,m,g){if(super(d,{cause:g}),this.config=h,this.response=m,this.error=g instanceof Error?g:void 0,this.config=(0,r.default)(!0,{},h),this.response&&(this.response.config=(0,r.default)(!0,{},this.response.config)),this.response){try{this.response.data=a(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}g instanceof DOMException?this.code=g.name:g&&typeof g=="object"&&"code"in g&&(typeof g.code=="string"||typeof g.code=="number")&&(this.code=g.code)}static extractAPIErrorFromResponse(d,h="The request failed"){let m=h;if(typeof d.data=="string"&&(m=d.data),d.data&&typeof d.data=="object"&&"error"in d.data&&d.data.error&&!d.ok){if(typeof d.data.error=="string")return{message:d.data.error,code:d.status,status:d.statusText};if(typeof d.data.error=="object"){m="message"in d.data.error&&typeof d.data.error.message=="string"?d.data.error.message:m;let g="status"in d.data.error&&typeof d.data.error.status=="string"?d.data.error.status:d.statusText,_="code"in d.data.error&&typeof d.data.error.code=="number"?d.data.error.code:d.status;if("errors"in d.data.error&&Array.isArray(d.data.error.errors)){let f=[];for(let y of d.data.error.errors)typeof y=="object"&&"message"in y&&typeof y.message=="string"&&f.push(y.message);return Object.assign({message:f.join(`
|
|
1
|
+
var Ha=Object.defineProperty;var p=(e,t)=>Ha(e,"name",{value:t,configurable:!0});import{createRequire as Va}from"node:module";const Fy=Va(import.meta.url);import{require_safe_buffer as Bt}from"./chunk-567OJLS7.js";import{getJsonSchemaToolParameters as $a,resolveJsonSchemaStrictSampling as tn,transformMessages as Ja}from"./chunk-KSF7BFGS.js";import{sanitizeSurrogates as St}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest as Wa}from"./chunk-ML5DIOWR.js";import{clampThinkingLevel as Xa,collapseSystemMessages as Ka,withoutInitialSystemMessage as Ya}from"./chunk-2XX4WZT6.js";import{__commonJS as z,__require as te,__toESM as ze}from"./chunk-JXWJOIH4.js";var za=z({"node_modules/retry/lib/retry_operation.js"(e,t){function r(n,i){typeof i=="boolean"&&(i={forever:i}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=i||{},this._maxRetryTime=i&&i.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}p(r,"RetryOperation"),t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var i=new Date().getTime();if(n&&i-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},o),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(n,i){this._fn=n,i&&(i.timeout&&(this._operationTimeout=i.timeout),i.cb&&(this._operationTimeoutCb=i.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},r.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)},r.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},i=null,o=0,a=0;a<this._errors.length;a++){var c=this._errors[a],u=c.message,d=(n[u]||0)+1;n[u]=d,d>=o&&(i=c,o=d)}return i}}}),Qa=z({"node_modules/retry/lib/retry.js"(e){var t=za();e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in r)n[i]=r[i];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],a=0;a<n.retries;a++)o.push(this.createTimeout(a,n));return r&&r.forever&&!o.length&&o.push(this.createTimeout(a,n)),o.sort(function(c,u){return c-u}),o},e.createTimeout=function(r,n){var i=n.randomize?Math.random()+1:1,o=Math.round(i*Math.max(n.minTimeout,1)*Math.pow(n.factor,r));return o=Math.min(o,n.maxTimeout),o},e.wrap=function(r,n,i){if(n instanceof Array&&(i=n,n=null),!i){i=[];for(var o in r)typeof r[o]=="function"&&i.push(o)}for(var a=0;a<i.length;a++){var c=i[a],u=r[c];r[c]=function(d){var h=e.operation(n),m=Array.prototype.slice.call(arguments,1),g=m.pop();m.push(function(_){h.retry(_)||(_&&(arguments[0]=h.mainError()),g.apply(this,arguments))}),h.attempt(function(){d.apply(r,m)})}.bind(r,u),r[c].options=n}}}}),Za=z({"node_modules/retry/index.js"(e,t){t.exports=Qa()}}),ja=z({"node_modules/p-retry/index.js"(e,t){"use strict";var r=Za(),n=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],i=class extends Error{static{p(this,"AbortError")}constructor(u){super(),u instanceof Error?(this.originalError=u,{message:u}=u):(this.originalError=new Error(u),this.originalError.stack=this.stack),this.name="AbortError",this.message=u}},o=p((u,d,h)=>{let m=h.retries-(d-1);return u.attemptNumber=d,u.retriesLeft=m,u},"decorateErrorWithCounts"),a=p(u=>n.includes(u),"isNetworkError"),c=p((u,d)=>new Promise((h,m)=>{d={onFailedAttempt:p(()=>{},"onFailedAttempt"),retries:10,...d};let g=r.operation(d);g.attempt(async _=>{try{h(await u(_))}catch(f){if(!(f instanceof Error)){m(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof i)g.stop(),m(f.originalError);else if(f instanceof TypeError&&!a(f.message))g.stop(),m(f);else{o(f,_,d);try{await d.onFailedAttempt(f)}catch(y){m(y);return}g.retry(f)||m(g.mainError())}}})}),"pRetry2");t.exports=c,t.exports.default=c,t.exports.AbortError=i}}),rn=z({"node_modules/extend/index.js"(e,t){"use strict";var r=Object.prototype.hasOwnProperty,n=Object.prototype.toString,i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=p(function(h){return typeof Array.isArray=="function"?Array.isArray(h):n.call(h)==="[object Array]"},"isArray"),c=p(function(h){if(!h||n.call(h)!=="[object Object]")return!1;var m=r.call(h,"constructor"),g=h.constructor&&h.constructor.prototype&&r.call(h.constructor.prototype,"isPrototypeOf");if(h.constructor&&!m&&!g)return!1;var _;for(_ in h);return typeof _>"u"||r.call(h,_)},"isPlainObject2"),u=p(function(h,m){i&&m.name==="__proto__"?i(h,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):h[m.name]=m.newValue},"setProperty"),d=p(function(h,m){if(m==="__proto__")if(r.call(h,m)){if(o)return o(h,m).value}else return;return h[m]},"getProperty");t.exports=p(function h(){var m,g,_,f,y,E,C=arguments[0],S=1,A=arguments.length,v=!1;for(typeof C=="boolean"&&(v=C,C=arguments[1]||{},S=2),(C==null||typeof C!="object"&&typeof C!="function")&&(C={});S<A;++S)if(m=arguments[S],m!=null)for(g in m)_=d(C,g),f=d(m,g),C!==f&&(v&&f&&(c(f)||(y=a(f)))?(y?(y=!1,E=_&&a(_)?_:[]):E=_&&c(_)?_:{},u(C,{name:g,newValue:h(v,E,f)})):typeof f<"u"&&u(C,{name:g,newValue:f}));return C},"extend")}}),el=z({"node_modules/gaxios/package.json"(e,t){t.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}}),tl=z({"node_modules/gaxios/build/cjs/src/util.cjs"(e,t){"use strict";var r=el();t.exports={pkg:r}}}),nn=z({"node_modules/gaxios/build/cjs/src/common.js"(e){"use strict";var t=e&&e.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=c;var r=t(rn()),n=t(tl()),i=n.default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${i.name}-gaxios-error`);var o=class wa extends Error{static{p(this,"_GaxiosError")}config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=i.version;static[Symbol.hasInstance](d){return d&&typeof d=="object"&&e.GAXIOS_ERROR_SYMBOL in d&&d[e.GAXIOS_ERROR_SYMBOL]===i.version?!0:Function.prototype[Symbol.hasInstance].call(wa,d)}constructor(d,h,m,g){if(super(d,{cause:g}),this.config=h,this.response=m,this.error=g instanceof Error?g:void 0,this.config=(0,r.default)(!0,{},h),this.response&&(this.response.config=(0,r.default)(!0,{},this.response.config)),this.response){try{this.response.data=a(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}g instanceof DOMException?this.code=g.name:g&&typeof g=="object"&&"code"in g&&(typeof g.code=="string"||typeof g.code=="number")&&(this.code=g.code)}static extractAPIErrorFromResponse(d,h="The request failed"){let m=h;if(typeof d.data=="string"&&(m=d.data),d.data&&typeof d.data=="object"&&"error"in d.data&&d.data.error&&!d.ok){if(typeof d.data.error=="string")return{message:d.data.error,code:d.status,status:d.statusText};if(typeof d.data.error=="object"){m="message"in d.data.error&&typeof d.data.error.message=="string"?d.data.error.message:m;let g="status"in d.data.error&&typeof d.data.error.status=="string"?d.data.error.status:d.statusText,_="code"in d.data.error&&typeof d.data.error.code=="number"?d.data.error.code:d.status;if("errors"in d.data.error&&Array.isArray(d.data.error.errors)){let f=[];for(let y of d.data.error.errors)typeof y=="object"&&"message"in y&&typeof y.message=="string"&&f.push(y.message);return Object.assign({message:f.join(`
|
|
2
2
|
`)||m,code:_,status:g},d.data.error)}return Object.assign({message:m,code:_,status:g},d.data.error)}}return{message:m,code:d.status,status:d.statusText}}};e.GaxiosError=o;function a(u,d){switch(u){case"stream":return d;case"json":return JSON.parse(JSON.stringify(d));case"arraybuffer":return JSON.parse(Buffer.from(d).toString("utf8"));case"blob":return JSON.parse(d.text());default:return d}}p(a,"translateData");function c(u){let d="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function h(_){_&&_.forEach((f,y)=>{(/^authentication$/i.test(y)||/^authorization$/i.test(y)||/secret/i.test(y))&&_.set(y,d)})}p(h,"redactHeaders");function m(_,f){if(typeof _=="object"&&_!==null&&typeof _[f]=="string"){let y=_[f];(/grant_type=/i.test(y)||/assertion=/i.test(y)||/secret/i.test(y))&&(_[f]=d)}}p(m,"redactString");function g(_){!_||typeof _!="object"||(_ instanceof FormData||_ instanceof URLSearchParams||"forEach"in _&&"set"in _?_.forEach((f,y)=>{(["grant_type","assertion"].includes(y)||/secret/.test(y))&&_.set(y,d)}):("grant_type"in _&&(_.grant_type=d),"assertion"in _&&(_.assertion=d),"client_secret"in _&&(_.client_secret=d)))}return p(g,"redactObject"),u.config&&(h(u.config.headers),m(u.config,"data"),g(u.config.data),m(u.config,"body"),g(u.config.body),u.config.url.searchParams.has("token")&&u.config.url.searchParams.set("token",d),u.config.url.searchParams.has("client_secret")&&u.config.url.searchParams.set("client_secret",d)),u.response&&(c({config:u.response.config}),h(u.response.headers),u.response.bodyUsed&&(m(u.response,"data"),g(u.response.data))),u}p(c,"defaultErrorRedactor")}}),rl=z({"node_modules/gaxios/build/cjs/src/retry.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getRetryConfig=t;async function t(o){let a=n(o);if(!o||!o.config||!a&&!o.config.retry)return{shouldRetry:!1};a=a||{},a.currentRetryAttempt=a.currentRetryAttempt||0,a.retry=a.retry===void 0||a.retry===null?3:a.retry,a.httpMethodsToRetry=a.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],a.noResponseRetries=a.noResponseRetries===void 0||a.noResponseRetries===null?2:a.noResponseRetries,a.retryDelayMultiplier=a.retryDelayMultiplier?a.retryDelayMultiplier:2,a.timeOfFirstRequest=a.timeOfFirstRequest?a.timeOfFirstRequest:Date.now(),a.totalTimeout=a.totalTimeout?a.totalTimeout:Number.MAX_SAFE_INTEGER,a.maxRetryDelay=a.maxRetryDelay?a.maxRetryDelay:Number.MAX_SAFE_INTEGER;let c=[[100,199],[408,408],[429,429],[500,599]];if(a.statusCodesToRetry=a.statusCodesToRetry||c,o.config.retryConfig=a,!await(a.shouldRetry||r)(o))return{shouldRetry:!1,config:o.config};let u=i(a);o.config.retryConfig.currentRetryAttempt+=1;let d=a.retryBackoff?a.retryBackoff(o,u):new Promise(h=>{setTimeout(h,u)});return a.onRetryAttempt&&await a.onRetryAttempt(o),await d,{shouldRetry:!0,config:o.config}}p(t,"getRetryConfig");function r(o){let a=n(o);if(o.config.signal?.aborted&&o.code!=="TimeoutError"||o.code==="AbortError"||!a||a.retry===0||!o.response&&(a.currentRetryAttempt||0)>=a.noResponseRetries||!a.httpMethodsToRetry||!a.httpMethodsToRetry.includes(o.config.method?.toUpperCase()||"GET"))return!1;if(o.response&&o.response.status){let c=!1;for(let[u,d]of a.statusCodesToRetry){let h=o.response.status;if(h>=u&&h<=d){c=!0;break}}if(!c)return!1}return a.currentRetryAttempt=a.currentRetryAttempt||0,!(a.currentRetryAttempt>=a.retry)}p(r,"shouldRetryRequest");function n(o){if(o&&o.config&&o.config.retryConfig)return o.config.retryConfig}p(n,"getConfig");function i(o){let a=(o.currentRetryAttempt?0:o.retryDelay??100)+(Math.pow(o.retryDelayMultiplier,o.currentRetryAttempt)-1)/2*1e3,c=o.totalTimeout-(Date.now()-o.timeOfFirstRequest);return Math.min(a,c,o.maxRetryDelay)}p(i,"getNextRetryDelay")}}),on=z({"node_modules/gaxios/build/cjs/src/interceptor.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosInterceptorManager=void 0;var t=class extends Set{static{p(this,"GaxiosInterceptorManager")}};e.GaxiosInterceptorManager=t}}),nl=z({"node_modules/gaxios/build/cjs/src/gaxios.js"(e){"use strict";var t=e&&e.__importDefault||function(g){return g&&g.__esModule?g:{default:g}},r;Object.defineProperty(e,"__esModule",{value:!0}),e.Gaxios=void 0;var n=t(rn()),i=te("https"),o=nn(),a=rl(),c=te("stream"),u=on(),d=p(async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),"randomUUID"),h=204,m=class{static{p(this,"Gaxios")}agentCache=new Map;defaults;interceptors;constructor(g){this.defaults=g||{},this.interceptors={request:new u.GaxiosInterceptorManager,response:new u.GaxiosInterceptorManager}}fetch(...g){let _=g[0],f=g[1],y,E=new Headers;return typeof _=="string"?y=new URL(_):_ instanceof URL?y=_:_&&_.url&&(y=new URL(_.url)),_&&typeof _=="object"&&"headers"in _&&r.mergeHeaders(E,_.headers),f&&r.mergeHeaders(E,new Headers(f.headers)),typeof _=="object"&&!(_ instanceof URL)?this.request({...f,..._,headers:E,url:y}):this.request({...f,headers:E,url:y})}async request(g={}){let _=await this.#n(g);return _=await this.#t(_),this.#r(this._request(_))}async _defaultAdapter(g){let _=g.fetchImplementation||this.defaults.fetchImplementation||await r.#l(),f={...g};delete f.data;let y=await _(g.url,f),E=await this.getResponseData(g,y);return Object.getOwnPropertyDescriptor(y,"data")?.configurable||Object.defineProperties(y,{data:{configurable:!0,writable:!0,enumerable:!0,value:E}}),Object.assign(y,{config:g,data:E})}async _request(g){try{let _;if(g.adapter?_=await g.adapter(g,this._defaultAdapter.bind(this)):_=await this._defaultAdapter(g),!g.validateStatus(_.status)){if(g.responseType==="stream"){let y=[];for await(let E of _.data)y.push(E);_.data=y.toString()}let f=o.GaxiosError.extractAPIErrorFromResponse(_,`Request failed with status code ${_.status}`);throw new o.GaxiosError(f?.message,g,_,f)}return _}catch(_){let f;_ instanceof o.GaxiosError?f=_:_ instanceof Error?f=new o.GaxiosError(_.message,g,void 0,_):f=new o.GaxiosError("Unexpected Gaxios Error",g,void 0,_);let{shouldRetry:y,config:E}=await(0,a.getRetryConfig)(f);if(y&&E)return f.config.retryConfig.currentRetryAttempt=E.retryConfig.currentRetryAttempt,g.retryConfig=f.config?.retryConfig,this.#i(g),this._request(g);throw g.errorRedactor&&g.errorRedactor(f),f}}async getResponseData(g,_){if(_.status===h)return"";if(g.maxContentLength&&_.headers.has("content-length")&&g.maxContentLength<Number.parseInt(_.headers?.get("content-length")||""))throw new o.GaxiosError("Response's `Content-Length` is over the limit.",g,Object.assign(_,{config:g}));switch(g.responseType){case"stream":return _.body;case"json":{let f=await _.text();try{return JSON.parse(f)}catch{return f}}case"arraybuffer":return _.arrayBuffer();case"blob":return _.blob();case"text":return _.text();default:return this.getResponseDataFromContentType(_)}}#e(g,_=[]){let f=new URL(g),y=[..._],E=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let C of E)y.push(C.trim());for(let C of y)if(C instanceof RegExp){if(C.test(f.toString()))return!1}else if(C instanceof URL){if(C.origin===f.origin)return!1}else if(C.startsWith("*.")||C.startsWith(".")){let S=C.replace(/^\*\./,".");if(f.hostname.endsWith(S))return!1}else if(C===f.origin||C===f.hostname||C===f.href)return!1;return!0}async#t(g){let _=Promise.resolve(g);for(let f of this.interceptors.request.values())f&&(_=_.then(f.resolved,f.rejected));return _}async#r(g){let _=Promise.resolve(g);for(let f of this.interceptors.response.values())f&&(_=_.then(f.resolved,f.rejected));return _}async#n(g){let _=new Headers(this.defaults.headers);r.mergeHeaders(_,g.headers);let f=(0,n.default)(!0,{},this.defaults,g);if(!f.url)throw new Error("URL is required.");if(f.baseURL&&(f.url=new URL(f.url,f.baseURL)),f.url=new URL(f.url),f.params)if(f.paramsSerializer){let C=f.paramsSerializer(f.params);C.startsWith("?")&&(C=C.slice(1));let S=f.url.toString().includes("?")?"&":"?";f.url=f.url+S+C}else{let C=f.url instanceof URL?f.url:new URL(f.url);for(let[S,A]of new URLSearchParams(f.params))C.searchParams.append(S,A);f.url=C}typeof g.maxContentLength=="number"&&(f.size=g.maxContentLength),typeof g.maxRedirects=="number"&&(f.follow=g.maxRedirects);let y=typeof f.data=="string"||f.data instanceof ArrayBuffer||f.data instanceof Blob||globalThis.File&&f.data instanceof File||f.data instanceof FormData||f.data instanceof c.Readable||f.data instanceof ReadableStream||f.data instanceof String||f.data instanceof URLSearchParams||ArrayBuffer.isView(f.data)||["Blob","File","FormData"].includes(f.data?.constructor?.name||"");if(f.multipart?.length){let C=await d();_.set("content-type",`multipart/related; boundary=${C}`),f.body=c.Readable.from(this.getMultipartRequest(f.multipart,C))}else y?f.body=f.data:typeof f.data=="object"?_.get("Content-Type")==="application/x-www-form-urlencoded"?f.body=f.paramsSerializer?f.paramsSerializer(f.data):new URLSearchParams(f.data):(_.has("content-type")||_.set("content-type","application/json"),f.body=JSON.stringify(f.data)):f.data&&(f.body=f.data);f.validateStatus=f.validateStatus||this.validateStatus,f.responseType=f.responseType||"unknown",!_.has("accept")&&f.responseType==="json"&&_.set("accept","application/json");let E=f.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!f.agent)if(E&&this.#e(f.url,f.noProxy)){let C=await r.#a();this.agentCache.has(E)?f.agent=this.agentCache.get(E):(f.agent=new C(E,{cert:f.cert,key:f.key}),this.agentCache.set(E,f.agent))}else f.cert&&f.key&&(this.agentCache.has(f.key)?f.agent=this.agentCache.get(f.key):(f.agent=new i.Agent({cert:f.cert,key:f.key}),this.agentCache.set(f.key,f.agent)));return typeof f.errorRedactor!="function"&&f.errorRedactor!==!1&&(f.errorRedactor=o.defaultErrorRedactor),f.body&&!("duplex"in f)&&(f.duplex="half"),this.#i(f),Object.assign(f,{headers:_,url:f.url instanceof URL?f.url:new URL(f.url)})}#i(g){if(g.timeout){let _=AbortSignal.timeout(g.timeout);g.signal&&!g.signal.aborted?g.signal=AbortSignal.any([g.signal,_]):g.signal=_}}validateStatus(g){return g>=200&&g<300}async getResponseDataFromContentType(g){let _=g.headers.get("Content-Type");if(_===null)return g.text();if(_=_.toLowerCase(),_.includes("application/json")){let f=await g.text();try{f=JSON.parse(f)}catch{}return f}else return _.match(/^text\//)?g.text():g.blob()}async*getMultipartRequest(g,_){let f=`--${_}--`;for(let y of g){let E=y.headers.get("Content-Type")||"application/octet-stream";yield`--${_}\r
|
|
3
3
|
Content-Type: ${E}\r
|
|
4
4
|
\r
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-356BFRU3.js";import{sliceTail as Y}from"./chunk-SE42OS3U.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-R47JBGS3.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
|
|
1
|
+
var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-D3HKK2ZD.js";import{sliceTail as Y}from"./chunk-SE42OS3U.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-R47JBGS3.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
|
|
2
2
|
|
|
3
3
|
${e.details}`:e.message}s(bt,"plainText");var _e=class ze{static{s(this,"_OAuthCallbackServer")}redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(t,r,i,n,a){this.server=t,this.redirectUrl=r,this.paths=i,this.timeoutMs=n,this.renderPage=a}static async listen(t={}){let r=t.host??"127.0.0.1",i=t.redirectHost??r,n=t.path??"/callback",a,o=Ct((l,h)=>a?.handle(l.url??"/",h));await new Promise((l,h)=>{o.once("error",h),o.listen(t.port??0,r,()=>{o.off("error",h),l()})});let c=o.address();if(!c||typeof c=="string")throw new Error("OAuth callback server did not bind to TCP");return a=new ze(o,`http://${i.includes(":")?`[${i}]`:i}:${c.port}${n}`,[n,...t.extraPaths??[]],t.timeoutMs??5*6e4,t.renderPage),a}waitForCallback(t,r){if(this.pending.has(t))throw new Error("OAuth state is already pending");return new Promise((i,n)=>{let a=setTimeout(()=>{this.pending.delete(t),n(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(t,{resolve:i,reject:n,timer:a,path:r})})}async close(){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(new Error("OAuth callback server closed"));this.pending.clear();let t=new Promise((r,i)=>{this.server.close(n=>n?i(n):r())});this.server.closeAllConnections(),await t}reply(t,r,i){this.renderPage?(t.writeHead(r,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),t.end(this.renderPage(i))):t.writeHead(r,{"content-type":"text/plain; charset=utf-8"}).end(bt(i))}handle(t,r){let i=new URL(t,this.redirectUrl);if(!this.paths.includes(i.pathname)){this.reply(r,404,{ok:!1,message:"Not found"});return}let n=i.searchParams.get("state"),a=n?this.pending.get(n):void 0;if(!n||!a){this.reply(r,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(a.timer),this.pending.delete(n),a.path!==void 0&&i.pathname!==a.path){a.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(r,400,{ok:!1,message:"Unexpected redirect URI"});return}let o=i.searchParams.get("error");if(o){let h=i.searchParams.get("error_description")??o;a.reject(new Error(h)),this.reply(r,200,{ok:!1,message:"Authorization failed. You may close this window.",details:h});return}let c=i.searchParams.get("code");if(!c){a.reject(new Error("OAuth callback did not include an authorization code")),this.reply(r,400,{ok:!1,message:"Missing authorization code"});return}let l=i.searchParams.get("iss");a.resolve({code:c,state:n,...l?{iss:l}:{}}),this.reply(r,200,{ok:!0})}},g=class extends Error{static{s(this,"McpSignInCancelledError")}constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};async function Tt(e){if(e.signal?.aborted)throw new g;let t=e.challenge?.error==="insufficient_scope";return!t&&await zt(e)==="AUTHORIZED"?{kind:"authorized"}:D(e.signal,()=>It(e,t))}s(Tt,"startMcpSignIn");async function zt(e){let{store:t,settings:r,challenge:i,redirectUrl:n,signal:a}=e,o=t.withRefreshLock(async()=>{if(a?.aborted)return"REDIRECT";let c=await t.load();return!c?.tokens?.refresh_token||r.clientRegistration==="cimd"&&c.clientInformation&&!r.clientId?"REDIRECT":me(e,c,{challenge:i,redirectUrl:n})});try{return await Pt(a,o)}catch(c){if(c instanceof oe)return"REDIRECT";throw c}}s(zt,"refreshBeforeSignIn");function Pt(e,t){return e?new Promise((r,i)=>{let n=s(()=>i(new g),"abort");e.addEventListener("abort",n,{once:!0}),t.then(r,i).finally(()=>e.removeEventListener("abort",n))}):t}s(Pt,"untilAborted");async function It(e,t){let{store:r,settings:i,redirectUrl:n,challenge:a}=e,o=await r.load();o&&await r.save(Ot(o,e));let c,l=P(e,n,f=>{c=f}),h=Lt(i.scope,t?Et(o?.tokens?.scope,a?.scope):a?.scope);if(await $(l,{...ve(e),scope:h,skipRefresh:!0}),!c)throw new Error("OAuth flow did not produce an authorization URL");let d=c.searchParams.get("scope");return{kind:"redirect",authorizationUrl:c.href,redirectUrl:c.searchParams.get("redirect_uri")??n,state:await l.state(),...d?{scope:d}:{}}}s(It,"startBrowserStep");function Ot(e,t){let{settings:r,redirectUrl:i}=t,n={...e};return delete n.oauthState,r.clientId||(e.clientInformation?r.clientRegistration!=="cimd"&&O(e.clientInformation).includes(i):I(r,t.clientMetadataDocuments,i))||(delete n.clientInformation,delete n.tokens,delete n.tokensExpireAt),n}s(Ot,"stateForSignIn");function Lt(...e){let t=[...new Set(e.flatMap(r=>r?.split(/\s+/).filter(Boolean)??[]))];return t.length>0?t.join(" "):void 0}s(Lt,"mergeScopes");async function xt(e){await D(e.signal,async()=>{let{authorization:t,response:r}=e;if(r.state!==t.state)throw new Error("The authorization response belongs to a different sign-in");if((await e.store.load())?.oauthState!==t.state)throw new Error("Another sign-in to this MCP server started since; sign in again");await $(P(e,e.redirectUrl),{...ve(e),scope:t.scope,authorizationRedirectUrl:t.redirectUrl,authorizationCode:r.code,iss:r.iss})})}s(xt,"completeMcpSignIn");function ve(e){return{serverUrl:e.serverUrl,fetch:te(),signal:e.signal,resourceMetadataUrl:e.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl}}s(ve,"flowOptions");async function D(e,t){if(e?.aborted)throw new g;try{return await t()}catch(r){throw e?.aborted?new g:r}}s(D,"cancellable");async function $t(e){let{settings:t}=e,r=ne(t),i=O((await e.store.load())?.clientInformation)[0],n=r.port??(i&&Number(new URL(i).port)||void 0),a=I(t,e.clientMetadataDocuments,r.url),o={host:r.host,redirectHost:r.redirectHost,path:r.path,extraPaths:a?[X(r.path,e.serverUrl)]:[],renderPage:e.renderPage},c;try{c=await _e.listen({...o,port:n??0})}catch(l){if(r.port!==void 0||n===void 0)throw l;c=await _e.listen(o)}return{callback:c,redirectUrl:r.fixedRedirectUrl??c.redirectUrl}}s($t,"listenForLoopbackSignIn");async function Dt(e){let{authorization:t}=e,r=new AbortController,i=e.signal?AbortSignal.any([r.signal,e.signal]):r.signal,n=e.callback.waitForCallback(t.state,new URL(t.redirectUrl).pathname),a=e.promptForRedirectUrl?e.promptForRedirectUrl(i).then(o=>{if(!o?.trim())throw new g;return Ht(o,t)}):new Promise((o,c)=>{i.addEventListener("abort",()=>c(new g),{once:!0})});try{return await D(e.signal,()=>Promise.race([n,a]))}finally{r.abort(),n.catch(()=>{}),a.catch(()=>{})}}s(Dt,"waitForLoopbackSignIn");function Ht(e,t){let r;try{r=new URL(e.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}let i=new URL(t.redirectUrl);if(r.origin!==i.origin||r.pathname!==i.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let n=r.searchParams.get("error");if(n)throw new Error(r.searchParams.get("error_description")??n);let a=r.searchParams.get("state");if(a!==t.state)throw new Error("The redirect URL belongs to a different sign-in");let o=r.searchParams.get("code");if(!o)throw new Error("The redirect URL does not contain an authorization code");let c=r.searchParams.get("iss");return{code:o,state:a,...c?{iss:c}:{}}}s(Ht,"responseFromRedirectUrl");import{createHash as Nt}from"node:crypto";import{mkdirSync as Ft}from"node:fs";import{join as ye}from"node:path";var Vt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function A(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}s(A,"escapeHtml");function Ue(e){let t=A(e.title),r=A(e.heading),i=A(e.message),n=e.details?A(e.details):void 0;return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var i=(t,e)=>c(t,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";const h=y(import.meta.url);import{ownedSlice as p}from"./chunk-
|
|
1
|
+
var c=Object.defineProperty;var i=(t,e)=>c(t,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";const h=y(import.meta.url);import{ownedSlice as p}from"./chunk-44EXLOHK.js";var g=4e3;function m(t){if(!(t instanceof Error))return{message:a(t),messageCarriesBody:!1};let e=t,n=b(e),s=$(e),o=s===void 0||t.message.includes(s),u=n===void 0&&s===void 0?r(t):t.message;return{status:n,body:s,message:u,messageCarriesBody:o}}i(m,"normalizeProviderError");var l=5;function r(t){let e,n=t.cause;for(let u=0;u<l&&n instanceof Error;u++)e=n,n=n.cause;if(!e)return t.message;let s=(e.message||e.name).trim(),o=e.code;return(typeof o=="string"||typeof o=="number")&&!s.includes(String(o))&&(s=s?`${s} (${o})`:String(o)),!s||t.message.includes(s)?t.message:t.message?`${t.message}: ${s}`:s}i(r,"withCauseDetail");function b(t){if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;if(typeof t.$metadata?.httpStatusCode=="number")return t.$metadata.httpStatusCode;if(typeof t.$response?.statusCode=="number")return t.$response.statusCode}i(b,"extractStatus");function $(t){let e=S(t);if(e===void 0)return;let n=e.trim();if(n.length!==0)return f(n,g)}i($,"extractBody");function S(t){if(typeof t.body=="string")return t.body;if(d(t.error))return a(t.error);let e=t.$response?.body;if(typeof e=="string")return e;if(!C(e)&&d(e))return a(e)}i(S,"pickBodyText");function C(t){return typeof t=="object"&&t!==null&&"pipe"in t&&typeof t.pipe=="function"}i(C,"isReadableStreamLike");function d(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e!==Object.prototype&&e!==null?!1:Object.keys(t).length>0}i(d,"isPlainNonEmptyObject");function E(t,e){return t.messageCarriesBody||t.status===void 0||t.body===void 0?e!==void 0&&t.status!==void 0?`${e} (${t.status}): ${t.message}`:t.message:e!==void 0?`${e} (${t.status}): ${t.body}`:`${t.status}: ${t.body}`}i(E,"formatProviderError");function f(t,e){return t.length<=e?t:`${p(t,0,e)}... [truncated ${t.length-e} chars]`}i(f,"truncateErrorText");function a(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}i(a,"safeJsonStringify");export{E as formatProviderError,m as normalizeProviderError,f as truncateErrorText,r as withCauseDetail};
|