@code-yeongyu/senpi 2026.11.2-1 → 2026.11.2-2
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 +19 -0
- package/dist/bundle/chunks/{chunk-AMCDEC5A.js → chunk-B2LRAXQU.js} +2 -2
- package/dist/bundle/chunks/{chunk-D22YF34L.js → chunk-CQ3G57HE.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZUVGFXCS.js → chunk-FVYWSBX3.js} +3 -3
- package/dist/bundle/chunks/{chunk-665UPAKG.js → chunk-H3BTMIH5.js} +6 -6
- package/dist/bundle/chunks/{chunk-KEJWNCLN.js → chunk-HUSQY3ID.js} +1 -1
- package/dist/bundle/chunks/{chunk-IBV4OVXQ.js → chunk-N6OHYIJR.js} +1 -1
- package/dist/bundle/chunks/{chunk-XZR4J6HM.js → chunk-PP52OWBB.js} +1 -1
- package/dist/bundle/chunks/{chunk-XVQISKHL.js → chunk-QV2IEA3B.js} +4 -4
- package/dist/bundle/chunks/{chunk-2V6BR24J.js → chunk-VEWJSPOZ.js} +1 -1
- package/dist/bundle/chunks/{cli-main-REFQSP6S.js → cli-main-6ZI4QO2Z.js} +1 -1
- package/dist/bundle/chunks/{host-command-Y3ZT6YLD.js → host-command-O3ALG2O3.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-VW73K4WA.js → host-lifecycle-SGTVODHB.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +5 -5
- package/dist/bundle/chunks/{host-session-command-YDEUZBTX.js → host-session-command-4WRR5JSB.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-UZXPNJ4V.js → interactive-mode-TF7R35GK.js} +1 -1
- package/dist/bundle/chunks/{main-O5G75MYS.js → main-XLUYSOXP.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-AZKJYA2X.js → multi-session-host-CADYC2BS.js} +4 -3
- package/dist/bundle/chunks/{package-manager-cli-2YDUGJNR.js → package-manager-cli-I62KMIWK.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-KZD5HZNI.js → rpc-mode-T5GVMUBQ.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-7LSJAINZ.js → schedule-command-YXGRN5CM.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-BG2KQ6MJ.js → session-control-endpoint-PREVS5UO.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +63 -62
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +5 -5
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/session-recovery-identity.d.ts +12 -1
- package/dist/modes/rpc/compact-call-fold.d.ts +3 -1
- package/dist/modes/rpc/compact-call-fold.js +17 -6
- package/dist/modes/rpc/compact-call-identity.d.ts +13 -0
- package/dist/modes/rpc/compact-call-identity.js +30 -0
- package/dist/modes/rpc/compact-call-model.d.ts +14 -0
- package/dist/modes/rpc/compact-call-model.js +4 -0
- package/dist/modes/rpc/compact-call-table.d.ts +9 -0
- package/dist/modes/rpc/compact-call-table.js +20 -0
- package/dist/modes/rpc/compact-catalog-settled.d.ts +5 -0
- package/dist/modes/rpc/compact-catalog-settled.js +9 -2
- package/dist/modes/rpc/compact-lane-current.d.ts +2 -0
- package/dist/modes/rpc/compact-lane-current.js +4 -0
- package/dist/modes/rpc/compact-message-identity.d.ts +74 -0
- package/dist/modes/rpc/compact-message-identity.js +101 -0
- package/dist/modes/rpc/compact-session-calls.d.ts +5 -4
- package/dist/modes/rpc/compact-session-calls.js +13 -8
- package/dist/modes/rpc/compact-session-state.d.ts +2 -0
- package/dist/modes/rpc/compact-session-state.js +4 -0
- package/dist/modes/rpc/compact-settled-messages.d.ts +12 -4
- package/dist/modes/rpc/compact-settled-messages.js +18 -10
- package/dist/modes/rpc/connection-handler.js +1 -1
- package/dist/modes/rpc/connection-question-bridge.d.ts +2 -1
- package/dist/modes/rpc/connection-question-bridge.js +3 -1
- package/dist/modes/rpc/host-lifecycle-proxy.d.ts +9 -0
- package/dist/modes/rpc/host-lifecycle-proxy.js +29 -7
- package/dist/modes/rpc/rpc-question-types.d.ts +2 -0
- package/dist/modes/rpc/session-acceptance-compact.d.ts +17 -7
- package/dist/modes/rpc/session-acceptance-compact.js +20 -8
- package/dist/modes/rpc/session-acceptance-lane.d.ts +5 -0
- package/dist/modes/rpc/session-acceptance-lane.js +12 -11
- package/dist/modes/rpc/session-event-writer-destinations.d.ts +2 -1
- package/dist/modes/rpc/session-event-writer-destinations.js +24 -9
- package/dist/utils/version-check.js +9 -3
- package/docs/engine-socket/fixtures/admission-routes/i-live-identity.json +716 -0
- package/docs/engine-socket/fixtures/admission-routes/index.json +3 -1
- package/docs/engine-socket/fixtures/admission-routes/j-live-call-identity.json +1020 -0
- package/docs/rpc.md +66 -0
- package/package.json +6 -6
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{DEFERRED_RETRY_MS,InvalidSidecarStoreError,UnsupportedSidecarStoreVersionError,breakStaleLock,cancelScheduledJob,createScheduledJob,createSidecarStore,encodedSessionId,ensureDir,errorCode,holdSessionFile,isWatchRunnerAvailable,listScheduledJobs,liveSessionHolders,ownRunnerIdentity,publishExclusive,publishReplace,readLeaseText,readProcessStartMs,reclaimInspected,reclaimLockState,removeRunnerLease,runDueJobs,scheduleDir,serializeByKey,sidecarFilePath,unlinkIfPresent,withSessionMoveLock,writeRunnerLease}from"./chunk-2BTB7AWD.js";import{containStaleExtensionError}from"./chunk-KEJWNCLN.js";import{ClientAdmissions,ClientMessageIdConflict,ConnectionQuestionBridge,ConnectionRoles,DEFAULT_COMPACTION_SETTINGS,DEFAULT_EXTENSION_SESSION_PROFILE,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,ExecuteToolError,ExtensionTransportOwner,IDLE_COMPACTION_INSTRUCTIONS,McpPresenterAuthority,ModelSwitchAuthError,ModelUsabilityBudgetError,PROMPT_CACHE_PREWARM_ENTRY_TYPE,RESOLUTION_TIMED_OUT,RUNTIME_EXTENSION_PATH,SERVER_SEARCH_FALLBACK,SESSION_CONTROL_DELIVERY_TYPE,SUMMARIZATION_INPUT_BUDGET_RATIO,SessionExtensionUiRequests,SessionRecoveryIdentity,SummarizationOverflowExhaustedError,ToolBarrier,WakeScheduler,acquireFileMutationLock,addUsageToTotals,admitContextToolResults,advertisedCompactCapabilities,all_exports,allowOverflowRetry,answerGetEntries,answeredUiRequestId,attachMcpGrantPresentation,attachRestorationDirective,availableModelsData,baseThresholdRatioForWindow,boundSummarizationInput,buildRpcSessionState,builtinProviders,calculateContextTokens,captureAgentCheckpoint,carryRecovery,clampThinkingSelection,classifyReasoningCapability,clearMcpGrantPresentations,clientFacingIdentity,clientInputContext,collectEntriesForBranchSummary,combineUsage,compact,compat_exports,completeSimple,computeEffectiveKeepRecentTokens,computeEffectiveThreshold,consumePendingPayload,countDiffChanges,createBlockingRemoteCompactionEvent,createFsWatchEventSource,createRemoteCompactionDeadline,createRestorationDirectiveState,createRestorationTrackerState,createUnifiedPatch,createUsageTotals,cursorProvider,defineTool,degradeQuestion,diffLines,diffWords,disableServerSearch,endCompactionFeedback,estimateContextTokens,estimatePendingPromptTokens,estimateProjectedContextTokens,estimateTokens,estimateTotalTokens,extension_default,extractPatchedPaths,findCutPoint,findTurnStartIndex,formatThinkingClampWarning,generateBranchSummary,generateImages,generateSummary,generateSummaryWithUsage,getApplyPatchWireMode,getBuiltinModelDataGeneratedAt,getCursorContextLimit,getImageModel,getLastAssistantUsage,getMcpGrantPresentation,getModels,getPromptCachePrewarmUsage,getPromptContextWindow,getProviders,getSnapshot,getSupportedThinkingLevels as getSupportedThinkingLevels2,getThinkingClampNotice,getUsageCostBreakdown,hasServerSearchFailed,injectTokenBudgetReminder,installCursorContextLimitPersistence,installImagesProviderScopeAccessor,interruptRunningTurn,isAbortedAssistantMessage,isAtHardLimit,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isMissingPathError,isMonitorableMessageEvent,isPowerShellToolResult,isReadToolResult,isServerSearchDisabled,isServerSearchFallback,isSessionControlDeliveryDetails,isToolCallEventType,isWriteToolResult,linkAbortSignal,markServerSearchFallback,markTransientMessage,normalizeApplyPatchArguments,normalizeToolExposure,openAiRemoteCompactionTimeoutMs,parsePatch,persistCheckpoint,prepareBranchEntries,prepareCompaction,preparePendingPayload,projectModelUsabilityBudget,pruneOldMessagesToBudget,recentCheckpoint,recoveryCarrier,refusedExtensionUiResponse,registerBundledOAuthFlowLoaders,rememberServerSearchFailure,renderToolDiff,reportRemoteCompactionTimeout,requiresDeterministicCompactionFallback,resetApiProviders,resetServerSearchFailures,resolveBeforeAgentStartMessage,resolveCompactionGeometry,resolveCursorContextWindow,resolveEffectiveReserveTokens,resolveIdleWarmAction,resolvePatchPath,resolveThresholdContextTokens,roleConnection,rpcCommandPayloadError,rpcCommandShapeError,rpcMessageLengthError,runAbort,runGetEffectStatus,runQueuedInputChange,runSetModel,runSetThinkingLevel,runWithRemoteTimeout,selectMcpGrant,serializeConversation,sessionControlSenderOf,sessionDeclaration,sessionDialogRequests,sessionQuestionBridges,sessionRetryFallbackError,sessionUiAnswerLedger,settleExtensionUiResponse,shouldCompact,shouldDeferGraceBand,shouldRunIdleCompaction,shouldStartSpeculativeCompaction,shouldTriggerCompaction,shouldWarmAtIdle,shrinkSummarizationInputForOverflowRetry,stream,streamSimple,subscribeSessionRecords,supportsMax,supportsXhigh,toolBarrierSpecError,trackToolCall,watchInbox,withAdditionalTokens,withFileMutationQueue,withResolutionDeadline,withoutServerSearch}from"./chunk-AMCDEC5A.js";import{MissingSessionCwdError,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UNKNOWN_COMMAND_CONFIRM_HINT,UnknownCommandError,assertSessionCwdExists,commandShapedName,findUnknownCommand,formatMissingSessionCwdPrompt,getMissingSessionCwdIssue,isTransportGoneError}from"./chunk-5TG7AOLR.js";import{RPC_ERROR_EVAL_CELLS_UNAVAILABLE,RPC_ERROR_EVAL_CELL_NOT_FOUND,RPC_ERROR_INVALID_ARGUMENT,RPC_ERROR_INVALID_EVAL_CELL_REQUEST,RPC_ERROR_MEDIA_NOT_FOUND,RPC_ERROR_MODEL_NOT_FOUND,RPC_ERROR_NO_MODEL_SELECTED,RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED,RPC_ERROR_PROVIDER_CREDENTIALS_MISSING,RPC_ERROR_UNKNOWN_COMMAND,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY,clientMessageIdentity,readClientMessageIdentity}from"./chunk-VRKA3LIT.js";import{allocateMonitorId,defaultEvents,parseRpcTarget}from"./chunk-C5G5PONA.js";import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,writeHelpFlagsCache}from"./chunk-OG2JODU6.js";import{BlockedSkillLinkError,CONTINUE_FROM_LEAF_CUSTOM_TYPE,CONTINUE_FROM_LEAF_DIRECTIVE,CircuitProbes,ContinueFromLeafError,DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS,DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS,DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS,DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS,DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS,DEFAULT_STREAM_START_TIMEOUT_MS,DEFAULT_TOOL_NAMES,DefaultPackageManager,ENGINE_TURN_LIMIT_ENTRY_TYPE,ENGINE_TURN_LIMIT_EVENT,ENGINE_TURN_START_ENTRY_TYPE,FABLE55_LAUNCH,FileSettingsStorage,InteractiveThemeController,MANUAL_CONTINUE_CUSTOM_TYPE,MANUAL_CONTINUE_DIRECTIVE,SKILL_FRONTMATTER_PREFIX_BYTES,SessionSelectorComponent,SettingsManager,TERMINAL_MOUSE_MODES,acquireFallbackCircuits,addIgnoreRules,areExperimentalFeaturesEnabled,authorizeSkillPath,buildSkillAllowedSet,createFallbackCircuitAccess,engineTurnHistory,engineTurnLimitNotice,engineTurnStop,getSettingsPath,insideSkillRoot,isFable55ModelId,isHealthExhaustionFailure,isManualContinueSubmission,isTerminalMouseMode,isUserDirectedTurn,minimatch,monotonicNow,parseGitUrl,parseSettingsJson,readPiManifest,readSkillFileChecked,readSkillFileCheckedSync,readSkillMarkdownSource,resetsEngineTurnHistory,shouldRunFirstTimeSetup,shouldSkipSkillWalkDirectoryName,showFirstTimeSetup,showStartupInput,showStartupSelector,skillProjectRoot,stopResumeDirective,trackTurnAdmission,wasSelfWrite}from"./chunk-HECKLNOO.js";import{HTTP_IDLE_TIMEOUT_CHOICES,applyHttpProxySettings,configureHttpDispatcher,formatHttpIdleTimeoutMs,require_undici}from"./chunk-FEQDJBDL.js";import{CURRENT_SESSION_VERSION,EventLoopSlicer,GOAL_CONTINUATION_MESSAGE_TYPE,REPOSITORY_IDENTITY_ENTRY_TYPE,SESSION_CONTEXT_ENTRY_ID,SESSION_MOVED_IN,SESSION_RELEASED,SessionManager,TRANSPORT_IMAGE_BUDGET_BYTES,VIRTUAL_MODEL_STATE_ENTRY,assertValidSessionId,buildContextEntries,buildSessionContext,buildSessionProjection,compactUpdatesEnabled,compareRepositoryIdentities,convertToLlm,convertToLlmForTransport,createCompactionSummaryMessage,createCustomMessage,createVirtualModel,elidedImageIds,environmentContextMessageIfChanged,findLatestResponse,findMostRecentSession,getBranchSelection,getDefaultSessionDir,getLatestCompactionEntry,getSessionContextEntryId,getVirtualModelState,hasUnsafeRetainedContent,imageContentId,inheritSessionContextEntryId,isSafeBoundedValue,isVirtualModel,listSessionsFromDir,loadEntriesFromFileAsync,migrateSessionEntries,parseEntryLine,parseRepositoryIdentity,parseSessionEntries,readFileLines,readRepositoryIdentity,rejectedImageSources,reserveSessionWrite,resolveEnvironmentContext,sameRepositoryIdentity,sessionCwdMatcher,sessionEntryToContextMessages,sessionFileNameId,unregisterSessionWriter,withVirtualModels}from"./chunk-ARNSNIED.js";import{currentPathPlatform,knownMove,knownPrefixKeys,logGuardEvent,looksMoved,movedPathReason,movedPathWalk,prefixKey,readJsonFileAsync,resolveMovedPath}from"./chunk-L5OFGHDA.js";import{ProjectTrustStore,bundledBuiltinExtensions,getBundledResourceRoots,getProjectTrustOptions,getSavedProjectTrust,hasTrustRequiringProjectResources,imagegenSkillPath}from"./chunk-UURGXV5B.js";import{ASK_USER_ASKED_EVENT,ASK_USER_QUESTION_ENTRY,ASK_USER_SETTLED_EVENT,ASK_USER_SETTLEMENT_ENTRY,AskUserCountdown,AskUserQuestionComponent,AskUserSchemaError,AssistantMessageComponent,CLAUDE_PARAMS,CODEX_PARAMS,CustomEditor,DEFAULT_ASK_USER_TIMEOUT_MS,ExtensionEditorComponent,UserMessageComponent,askUserAnswerDisplayText,copyToClipboard,createBoundedRenderSignature,createChatViewport,createInteractiveTui,createInteractiveTuiReference,editFileInExternalEditor,editInExternalEditor,emitAskUserClosed,emitAskUserNotification,failureAlreadyDescribed,formatCountdownLabel,formatDuration,formatGatedCancellation,formatModelAnswer,formatProviderNativeBody,formatProviderNativeSummary,formatResultDetails,formatResultText,formatUserMessage,getAskUserAnswerHeaders,headNoticeShownElsewhere,openBrowser,parseAskUserAnswerFrame,prepareInteractiveStderrCapture,readClipboardFilePaths,readClipboardText,resolveUserWordReferences,restoreInteractiveStderr,runClipboardCommand,showsPartialAnswers,stripAnsi,takeOverInteractiveStderr,toCanonical}from"./chunk-NEOL3GWO.js";import{DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,DEFAULT_SUMMARIZATION_MAX_DURATION_MS,StreamDurationBudgetError,StreamIdleTimeoutError,SummarizationTotalBudgetError,consumeStreamWithIdleTimeout,createSummarizationDeadline,summarizationMaxDurationMs,summarizationTotalBudgetMs}from"./chunk-Y4MPEIY5.js";import{CountdownTimer,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SecretInputUnavailableError,armSecretInputDeadline,flushRawStdout,formatKeyText,isSecretInputValue,keyDisplayText,keyHint,keyText,rawKeyHint,resolveSecretInputTimeout,restoreStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-ZJSGYBBD.js";import{AccountUsageLimitError,FS_WATCH_RETRY_DELAY_MS,SYSTEM_THEME_NAME,Theme,canonicalWatchPath,closeWatcher,describeUsageLimitEntry,describeUsageLimitMessage,findReservedKeywordRuns,findReservedKeywordSpans,getAvailableThemes,getAvailableThemesWithPaths,getEditorTheme,getLanguageFromPath,getMarkdownTheme,getReservedKeywordHighlight,getResolvedThemeColors,getSelectListTheme,getSettingsListTheme,getThemeByName,getThemeExportColors,highlightCode,initTheme,isBillingErrorMessage,loadThemeFromPath,onThemeChange,parseAutoThemeSetting,probeDirectoryOpenable,setRegisteredThemes,sharedMarkdownTheme,stopThemeWatcher,theme,usageLimitCause,usageLimitScope,watchWithErrorHandler}from"./chunk-FOMJ73UU.js";import{toolResultUserWords}from"./chunk-VICVLJNU.js";import{TIP_DEFINITIONS}from"./chunk-PIAY636U.js";import{KEYBINDINGS,KeybindingsManager,QUESTION_ANSWER_FALLBACK_KEY,QUESTION_ANSWER_PRIMARY_KEY,isWSL,migrateKeybindingsConfig}from"./chunk-LGO25HPL.js";import{require_applicator,require_codegen,require_compile,require_core,require_core2,require_dependencies,require_discriminator,require_format,require_metadata,require_names,require_ref,require_ref_error,require_util,require_validate,require_validation,require_validation_error}from"./chunk-Y3TMJV3J.js";import{AuthError,ConnectError,LOG_SINK_RETRY_MS,OAuthFlowError,SessionExpiredError,TimeoutError,ToolExecError,collectMrtrForm,createMcpLogger,createMcpRequestOrigin,delay,fingerprintSecret,isEphemeralIdentity,isInvalidGrant,isMcpNeedsAuthError,isMcpSessionExpiredError,isModernMcpClient,isRetriableMcpError,isTransientTokenError,keyedIdentity,legacyMcpFormEligible,legacyMcpFormsAdvertised,loadMcpSdkAuth,loadMcpSdkStdioTransport,loadMcpSdkTypes,mcpRequestOptions,reapProcessTree,redactMcpLogText,registerMcpClientAlias,reportMcpAsyncError,rotateLogIfNeeded,safeDelay,safeEventBusOn,safeInterval,safeTimer,wrapAsync}from"./chunk-ETCYVVVO.js";import{McpMrtrError,getMcpMrtrPresentation,inheritMcpMrtrPresentation,markMcpFormPresented,queuedForm,registerMcpMrtrPresentation}from"./chunk-7ICGN62G.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,WakeSourceTracker,classifyEndpointLiveness,endpointProbeTimeoutMs,ensureHost,handoffHost,isSessionBusySnapshot,loadHostLaunchSpec,normalizeWaitItems,parseHostLaunchSpec,projectWaitItems,readAllHostStatus,readHostStatus,readWaitItems,runHostCommand,runHostRequest,waitItemSignature,wakeSourceItems}from"./chunk-IBV4OVXQ.js";import{AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DEFAULT_CUSTOM_EXTENSION_LABEL,ENTRIES_TAIL_CAPABILITY,EVAL_CELLS_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,INTERACTIVE_USER_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,PROVIDER_ACCOUNT_TEST_CAPABILITY,QUESTION_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,REQUIRED_HOST_CAPABILITIES,RESUME_SESSION_CAPABILITY,RETRY_FALLBACK_COMMAND_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_RELOCATION_CAPABILITY,TASK_PARENT_CAPABILITY,TOOL_BARRIER_CAPABILITY,buildCustomUnsupportedRequest,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseClientCapabilities,parseHostProtocolInfo,probeHost,protocolIdentity,stopHost}from"./chunk-VOSHKGXG.js";import{listHostEndpoints}from"./chunk-WEOFT5KT.js";import{BUILTIN_PATH_PREFIX,createSourceInfo,createSyntheticSourceInfo,getSyntheticPathSource,isSyntheticPath}from"./chunk-QMRJYMNH.js";import{recordProcessLifetime,resolveCliMainPathAsync,runtimeExecArgv}from"./chunk-ZUVGFXCS.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunk-FNBEICAA.js";import{createRgEngine,ensureTool}from"./chunk-SGS76663.js";import{GrepEngineError}from"./chunk-H4QOEVS5.js";import{AllAccountsBlockedError,CLAUDE_CLI_SHARED_LINKS,SENTINEL_OAUTH_FIELDS,accountDirFor,assertValidAccountName,assertValidAccountName2,buildClaudeCliEnvironment,claudeCliSharedRoot,clearExpiredBlocks,credentialPoolRepository,defaultExecutableDeps,emptyCredential,ensureAccountDir,envSlotToken,getCredentialAccounts,hasRequestOauthToken,isBlockedFor,isEnvSlot,isListedStoredSlot,listAccounts,logoutClaudeCli,mergeRequestAuthEnvironment,newAccountDirId,pinAccount,pinCredentialAccount,readClaudeCliAuthStatus,removeAccountDir,removeCredentialAccount,renameCredentialAccount,resolveClaudeCodeExecutable,resolveClaudeCodeRun,selectAccount,spawnClaudeCli,stopClaudeCli,stripManagedAuthEnvironment,summarizeCredentialAccounts}from"./chunk-3CKVTGWG.js";import{ConfigValueSchema,NonemptyConfigValueSchema,assertConfigReferenceAuthority,getConfigValueEnvVarNames,isCommandConfigValue,isCommittedRotationOutput,isConfigReference,isConfigValueConfigured,rememberConfigReferenceOrigin,resolveConfigReference,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,sleep,warnMissingConfigEnvironment,warnOpaqueConfigEnvironment}from"./chunk-PE3PNVKT.js";import{ACCOUNT_POOL_REFUSAL_NOTE,CredentialFailoverError,MAX_SLOT_BLOCK_MS,applyAccountOrder,emitProviderAccountFailover,emitProviderAccountsChanged,isSlotBlocked,rendezvousOrder,slotKind,slotsOfOwnKind,subscribeProviderAccountEvents,unusedSlotKinds,withoutOrderedAccount}from"./chunk-5UVTDRIP.js";import{usageLimitResetMs}from"./chunk-ZNPH5BWS.js";import{activeModelBlockUntil,describeModelBlocks,mergeModelBlocks,modelBlockKey,pruneModelBlocks,rateLimitModelFamily,withModelBlock}from"./chunk-6VWIMHMH.js";import{discoverEnvSlots}from"./chunk-RQDLTDNO.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{lockWithLossHandling}from"./chunk-F7GBSQRV.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{TOOL_RUNTIME_UNSUPPORTED_HOST,ToolRuntimeUnsupportedHostError,isHostOwnedToolRuntimeCapability,isValidThinkingLevel,normalizeSessionName,parseArgs,printHelp,resolveSessionRuntime,resolveToolRuntime,toolRuntimeCapabilities,toolRuntimeHostRefusal}from"./chunk-PZSDJIXD.js";import{source_default}from"./chunk-26UBFF6N.js";import{readOwnFootprint,readProcessFootprint}from"./chunk-MTQQ2VQH.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-H52J72VA.js";import{parseOpenAIImageOutputOptions,parseOpenAIImageSize}from"./chunk-HB35RBP4.js";import{CredentialStoreBusyError,FILE_STORAGE_LOCK_OPTIONS,FILE_STORAGE_LOCK_RETRY_BUDGET_MS,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,FILE_STORAGE_SYNC_LOCK_BUDGET_MS,isLockError}from"./chunk-7X72IACK.js";import{appendUncaughtCrashLog,appendUnhandledRejectionLog}from"./chunk-YWD54RHU.js";import{deriveOpenAIPromptCacheKey}from"./chunk-C5XX36EB.js";import{resolveRootObjectSchema}from"./chunk-IYL5E4QQ.js";import{hasRefusedForcedToolChoice}from"./chunk-OEFCY46F.js";import{extract429RetryAfterMs,parseRetryAfterMsMarker}from"./chunk-RQFD6LG2.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DescendantsLedger,HostCallAdmission,JOB_WIDGET_AGGS,JOB_WIDGET_TONES,LaunchLog,MODULE_JOB_KIND,PayloadRefReader,PayloadRefWriter,TERMINAL_CHILD_JOB_KINDS,TEST_CONTROL_DIR_ENV,TOOL_CHILD_GENERATION_ENV,TOOL_CHILD_MODULE_ROOTS_ENV,TOOL_CHILD_PROTOCOL_VERSION,TerminalManager,TerminalNotifier,WindowsJob,WindowsJobError,closeJobWidgetSession,createBashInputTool,createBashOutputTool,createBashResizeTool,createKillBashTool,createPtyBashTool,cutPlain,defaultGroupProbes,describeExit,ensureMonitorStateDir,errorResult,formatJobWidgetLine,formatSize,generationLedgerPath,getJobWidgetState,getTerminalNotificationDelivery,isModelOnlyText,jobWidgetHostResolver,jobWidgetLineStyle,loadKernel32Job,modelOnlyText,onJobWidgetSessionChange,openJobWidgetSession,packPayload,parkJobWidgetSession,proofIsOrdered,readTestControls,recordGenerationChild,registerJobWidgetSource,removeMonitorStateDir,renderMonitorCall,resendJobWidgetState,resolveForegroundWindowSeconds,resolveTerminalId,sanitizeTerminalOutput,secretOutputObfuscator,setJobWidgetAuthorResolver,spawnCommandSession,sweepGroups,sweepStaleGenerations,terminalChildJob,terminalStateDir,textResult,truncateHead,truncateLine,truncateTail,truncateText,truncateToVisualLines,unpackPayload,withTerminalContext}from"./chunk-RPAEB2Z5.js";import{Box,CancellableLoader,CombinedAutocompleteProvider,Container,Image,Input,Key,Loader,Markdown,MouseRegion,Q,SelectList,SettingsList,Spacer,Text,TruncatedText,TuiAltScreen,TuiMainScreen,claimFrameRow,currentRenderRevision,decodeKittyPrintable,detectCapabilities,dispatchMouseEvent,dist_exports as dist_exports2,expandPasteMarkers,frameMode,frameScrollbackRows,fuzzyFilter,fuzzyMatch,getCapabilities,getGraphemeSegmenter,getImageDimensions,getKeybindings,getNativeClipboard,getTerminalColorMode,hyperlink,imageFallback,isKeyRelease,isViewportTUI,joinLineArrays,mainScreenHistoryLines,matchesKey,nextRenderRevision,outerKittyGraphicsMode,renderAtFrameRow,sanitizeTerminalLabel,setCapabilityOverrides,setKeybindings,sliceByColumn,stripTerminalSequences,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-D2ROBVZ4.js";import{Agent,EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,ProviderRetryWatchdogAbortError,STREAMED_DELTA_TYPES,buildProviderContext,createDefaultReadSummary,createInternalAgentChannel,dist_exports,getPowerShellConfig,getShellConfig,getShellEnv,killProcessTree,killTrackedDetachedChildren,noteDetachedChildExited,prepareAgentToolCall,prepareReadFolder,pruneTrackedDetachedChildren,reasonedBeforeFirstDelta,resolveToolNameAlias,runToolCall,sanitizeBinaryOutput,selectedReadFolder,setDefaultStreamFn,trackDetachedChildPid,untrackDetachedChildPid,withBundledBunCommands}from"./chunk-CLZLV65G.js";import{require_ignore}from"./chunk-YU4AYH4C.js";import{redactSecrets,redactSensitiveOutput,redactSensitiveTokenValues}from"./chunk-LNAZ7XEU.js";import{redactResolvedReferenceData,redactResolvedReferenceValues}from"./chunk-DLAY7CIU.js";import{Compile,StringEnum,compile_exports,composeShellCommand,cursorOverflowCompactionSettings,dropFailedAssistantTurns,getApiProvider,getCursorVariantAlias,getProtocol,getToolCallFormat,installProviderScopeAccessor,isClassifierRefusal,isContextOverflow,isCursorPayloadResourceExhausted,isCursorQuotaResourceExhausted,isCursorZeroTokenResourceExhausted,isRecoverableLength,measureCursorModelInputSerializedBytes,normalizeCursorCatalog,omitUndefinedArgs,parseCursorVariantId,parseEndpointReasoningEfforts,piLimit,piLsPath,piReadArgs,piTimeout,registerToolArgumentValidator,renderCursorCliModelString,require_dist,shouldRetryOverflowWithoutCompact,transformContext,validateToolArguments,warmPromptCache,wrapStreamWithModelRecovery,wrapStreamWithToolCallMiddleware}from"./chunk-KKVVSE6C.js";import{supportsAllowedToolChoice}from"./chunk-COH5F7QV.js";import{hasCredentialHeaders,isCredentialHeaderName}from"./chunk-RFB5CBW7.js";import{extractChatGptSubscriptionAccountId,getWireIdentity,setWireIdentity}from"./chunk-Y7QPP7BG.js";import{convertResponsesMessages,getContextProvenance,isOpenAIResponsesPromptCacheModel}from"./chunk-4WWORAQH.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC,findEnvKeys,getEnvApiKey,sanitizeAnthropicToolPairs}from"./chunk-TG4E7Z7W.js";import{getAnthropicCompat,isAnthropicApiBaseUrl,resolvePromptCacheLifetime,resolvePromptCacheTtlSeconds}from"./chunk-32R442XT.js";import{cleanupSessionResources,processSingleton}from"./chunk-WHPDEDCC.js";import{sanitizeProviderDiagnostic}from"./chunk-7UC4W2T2.js";import{estimateTextTokens}from"./chunk-WBTKUCRH.js";import{parseJsonWithRepair,parseStreamingJson}from"./chunk-3W47LTXQ.js";import{ConfigReferenceError,LEGACY_PROVIDER_IDS,ModelsError,PROVIDER_NOT_CONFIGURED_PREFIX,TURN_RETRY_SUPPRESSION_PREFIX,accountLabel,appendLoginSlot,assertChatModel,assertClassifierModel,assertImageModel,calculateCost,clampThinkingLevel,classifierErrorResult,collapseSystemMessages,contentText,costCardAt,createModels,describeProviderFailureForUser,findSlot,getCurrentSystemMessage,getCurrentSystemPrompt,getCurrentTools,getInitialSystemMessage,getModelType,getSupportedThinkingLevels,imageErrorResult,isModelType,isOAuthRefreshUnavailableError,isProviderStreamStallError,isProviderTimeoutError,isRetryableAssistantError,isRetryableErrorMessage,lazyStream,legacyProviderIdRejection,listSlots,modelsAreEqual,normalizeContext,normalizeProviderId,projectSlot,providerNotConfiguredMessage,readByProviderId,removeSlot,repairManagedSentinelSlots,retryAssistantCall,retryTransientCall,stripProviderRequestIds,stripTurnRetrySuppressionPrefix,supportsConfigurationUpdate,upsertSlot,upstreamProviderIdFor}from"./chunk-3BJFH3CZ.js";import{SeedFrontierError,carryAssistantCapture,createAssistantMessageDiagnostic,createAssistantMessageEventStream,getAssistantCapture,seedNextOffset}from"./chunk-5CSZPC55.js";import{MIN_BUN_VERSION,RUNTIME_ENV_VAR,bunVersionSatisfies,checkForNewPiVersion,findBunBinary,getPiUserAgent,getReleaseChangelogUrl,processBunRuntimeOptions}from"./chunk-XZR4J6HM.js";import{INSPECTOR_VM_IMPORT_WARNING,consumeEarlyInspectorVmImportRecoveries,dispatchConfigCommand,dispatchHostCommand,dispatchPackageCommand,dispatchScheduleCommand,exitAfterOutput,hasInheritedInspectorOption,isRecoverableInspectorVmImportError,printThenExit}from"./chunk-D22YF34L.js";import{require_semver}from"./chunk-ZOFZRJSL.js";import{markModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{fetchWithRetry}from"./chunk-2SOVDETB.js";import{StaleExtensionContextError,TOOL_CHILD_LIMITS,TOOL_CHILD_ROLE_ENV,isStaleExtensionContextError,openChannelListener}from"./chunk-UKSFF47T.js";import{APP_COMMAND,APP_NAME,APP_TITLE,BRAND,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,DISPLAY_VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,FLAT_LAYOUT_SENTINEL,PACKAGE_NAME,VERSION,brandEnvNames,canonicalizePath,detectInstallMethod,envValue,expandTildePath,findNodePackageDir,formatPathRelativeToCwdOrAbsolute,getAgentDir,getAuthPath,getBinDir,getBundledInteractiveAssetPath,getChangelogPath,getCwdRelativePath,getDebugLogPath,getDocsPath,getExamplesPath,getExportTemplateDir,getFileContentRevision,getFileRevision,getInstallPackageDir,getModelsPath,getPackageDir,getReadmePath,getSessionsDir,getShareViewerBase,isBunBinary,isBunRuntime,isBundledNode,isLocalPath,isShareDisabledByEnvironment,normalizePath,realpathWithoutOpen,realpathWithoutOpenStrict,resolveAgentDir,resolveInstallPath,resolvePath,splitBom,stripBom,waitForChildProcess}from"./chunk-ISZ4EWIS.js";import{Check,build_exports,typebox_exports,value_exports,value_exports2}from"./chunk-MIENF2YK.js";import{TOOL_CHILD_LEDGER_ENV,TOOL_CHILD_REENTRY_ENV,TOOL_CHILD_REFS_ROOT_ENV}from"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs,processBootAtMs,sameBoot}from"./chunk-QN2BHP3M.js";import{DEFAULT_COLS,DEFAULT_MAX_SESSIONS,DEFAULT_MONITOR_RUNAWAY_LINES_PER_MINUTE,DEFAULT_MONITOR_RUNAWAY_MINUTES,DEFAULT_MONITOR_WAKES_PER_HOUR,DEFAULT_ROWS,DEFAULT_SCROLLBACK,DURABLE_MONITOR_EXPIRY_MS,FIRE_BUDGET_WINDOW_MS,MONITOR_ENV_DOWNTIME_MS,MONITOR_ENV_ID,MONITOR_ENV_RESTORED,MONITOR_ENV_STATE_DIR,MONITOR_OVERFLOW_FILE_MAX_BYTES,RESTORE_GRACE_MS,RUNAWAY_PAUSE_SUMMARY_PREFIX,SecretOutputRedactor,TERMINAL_BASH_TOOL,TERMINAL_COMPANION_TOOLS,TERMINAL_MONITOR_TOOL,runawayPauseSummary}from"./chunk-AOTHPTMU.js";import{PROCESS_START_TOLERANCE_MS,sameProcessStartMs}from"./chunk-O5RYI3IW.js";import{__commonJS,__export,__toESM}from"./chunk-IKOFCODM.js";var require_dynamicAnchor=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.dynamicAnchor=void 0;var codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),ref_1=require_ref(),def={keyword:"$dynamicAnchor",schemaType:"string",code:cxt=>dynamicAnchor(cxt,cxt.schema)};function dynamicAnchor(cxt,anchor){let{gen,it}=cxt;it.schemaEnv.root.dynamicAnchors[anchor]=!0;let v=(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`,validate=it.errSchemaPath==="#"?it.validateName:_getValidate(cxt);gen.if((0,codegen_1._)`!${v}`,()=>gen.assign(v,validate))}exports.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){let{schemaEnv,schema,self}=cxt.it,{root,baseId,localRefs,meta}=schemaEnv.root,{schemaId}=self.opts,sch=new compile_1.SchemaEnv({schema,schemaId,root,baseId,localRefs,meta});return compile_1.compileSchema.call(self,sch),(0,ref_1.getValidate)(cxt,sch)}exports.default=def}});var require_dynamicRef=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.dynamicRef=void 0;var codegen_1=require_codegen(),names_1=require_names(),ref_1=require_ref(),def={keyword:"$dynamicRef",schemaType:"string",code:cxt=>dynamicRef(cxt,cxt.schema)};function dynamicRef(cxt,ref){let{gen,keyword,it}=cxt;if(ref[0]!=="#")throw new Error(`"${keyword}" only supports hash fragment reference`);let anchor=ref.slice(1);if(it.allErrors)_dynamicRef();else{let valid2=gen.let("valid",!1);_dynamicRef(valid2),cxt.ok(valid2)}function _dynamicRef(valid2){if(it.schemaEnv.root.dynamicAnchors[anchor]){let v=gen.let("_v",(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`);gen.if(v,_callRef(v,valid2),_callRef(it.validateName,valid2))}else _callRef(it.validateName,valid2)()}function _callRef(validate,valid2){return valid2?()=>gen.block(()=>{(0,ref_1.callRef)(cxt,validate),gen.let(valid2,!0)}):()=>(0,ref_1.callRef)(cxt,validate)}}exports.dynamicRef=dynamicRef;exports.default=def}});var require_recursiveAnchor=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dynamicAnchor_1=require_dynamicAnchor(),util_1=require_util(),def={keyword:"$recursiveAnchor",schemaType:"boolean",code(cxt){cxt.schema?(0,dynamicAnchor_1.dynamicAnchor)(cxt,""):(0,util_1.checkStrictMode)(cxt.it,"$recursiveAnchor: false is ignored")}};exports.default=def}});var require_recursiveRef=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dynamicRef_1=require_dynamicRef(),def={keyword:"$recursiveRef",schemaType:"string",code:cxt=>(0,dynamicRef_1.dynamicRef)(cxt,cxt.schema)};exports.default=def}});var require_dynamic=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dynamicAnchor_1=require_dynamicAnchor(),dynamicRef_1=require_dynamicRef(),recursiveAnchor_1=require_recursiveAnchor(),recursiveRef_1=require_recursiveRef(),dynamic=[dynamicAnchor_1.default,dynamicRef_1.default,recursiveAnchor_1.default,recursiveRef_1.default];exports.default=dynamic}});var require_dependentRequired=__commonJS({"node_modules/ajv/dist/vocabularies/validation/dependentRequired.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dependencies_1=require_dependencies(),def={keyword:"dependentRequired",type:"object",schemaType:"object",error:dependencies_1.error,code:cxt=>(0,dependencies_1.validatePropertyDeps)(cxt)};exports.default=def}});var require_dependentSchemas=__commonJS({"node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dependencies_1=require_dependencies(),def={keyword:"dependentSchemas",type:"object",schemaType:"object",code:cxt=>(0,dependencies_1.validateSchemaDeps)(cxt)};exports.default=def}});var require_limitContains=__commonJS({"node_modules/ajv/dist/vocabularies/validation/limitContains.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var util_1=require_util(),def={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword,parentSchema,it}){parentSchema.contains===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "contains" is ignored`)}};exports.default=def}});var require_next=__commonJS({"node_modules/ajv/dist/vocabularies/next.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dependentRequired_1=require_dependentRequired(),dependentSchemas_1=require_dependentSchemas(),limitContains_1=require_limitContains(),next=[dependentRequired_1.default,dependentSchemas_1.default,limitContains_1.default];exports.default=next}});var require_unevaluatedProperties=__commonJS({"node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),error2={message:"must NOT have unevaluated properties",params:({params})=>(0,codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`},def={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:error2,code(cxt){let{gen,schema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,props}=it;props instanceof codegen_1.Name?gen.if((0,codegen_1._)`${props} !== true`,()=>gen.forIn("key",data,key=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key)))):props!==!0&&gen.forIn("key",data,key=>props===void 0?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key))),it.props=!0,cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema===!1){cxt.setParams({unevaluatedProperty:key}),cxt.error(),allErrors||gen.break();return}if(!(0,util_1.alwaysValidSchema)(it,schema)){let valid2=gen.name("valid");cxt.subschema({keyword:"unevaluatedProperties",dataProp:key,dataPropType:util_1.Type.Str},valid2),allErrors||gen.if((0,codegen_1.not)(valid2),()=>gen.break())}}function unevaluatedDynamic(evaluatedProps,key){return(0,codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){let ps=[];for(let p in evaluatedProps)evaluatedProps[p]===!0&&ps.push((0,codegen_1._)`${key} !== ${p}`);return(0,codegen_1.and)(...ps)}}};exports.default=def}});var require_unevaluatedItems=__commonJS({"node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),error2={message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},def={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:error2,code(cxt){let{gen,schema,data,it}=cxt,items=it.items||0;if(items===!0)return;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema===!1)cxt.setParams({len:items}),cxt.fail((0,codegen_1._)`${len} > ${items}`);else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid2=gen.var("valid",(0,codegen_1._)`${len} <= ${items}`);gen.if((0,codegen_1.not)(valid2),()=>validateItems(valid2,items)),cxt.ok(valid2)}it.items=!0;function validateItems(valid2,from){gen.forRange("i",from,len,i=>{cxt.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:util_1.Type.Num},valid2),it.allErrors||gen.if((0,codegen_1.not)(valid2),()=>gen.break())})}}};exports.default=def}});var require_unevaluated=__commonJS({"node_modules/ajv/dist/vocabularies/unevaluated/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var unevaluatedProperties_1=require_unevaluatedProperties(),unevaluatedItems_1=require_unevaluatedItems(),unevaluated=[unevaluatedProperties_1.default,unevaluatedItems_1.default];exports.default=unevaluated}});var require_draft2020=__commonJS({"node_modules/ajv/dist/vocabularies/draft2020.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var core_1=require_core2(),validation_1=require_validation(),applicator_1=require_applicator(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated(),format_1=require_format(),metadata_1=require_metadata(),draft2020Vocabularies=[dynamic_1.default,core_1.default,validation_1.default,(0,applicator_1.default)(!0),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary,next_1.default,unevaluated_1.default];exports.default=draft2020Vocabularies}});var require_schema=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/schema.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}}});var require_applicator2=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}}});var require_unevaluated2=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}}});var require_content=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}}});var require_core3=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}}});var require_format_annotation=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}}});var require_meta_data=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}});var require_validation2=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}});var require_json_schema_2020_12=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var metaSchema=require_schema(),applicator=require_applicator2(),unevaluated=require_unevaluated2(),content=require_content(),core=require_core3(),format=require_format_annotation(),metadata=require_meta_data(),validation=require_validation2(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2020($data){return[metaSchema,applicator,unevaluated,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2020}});var require__=__commonJS({"node_modules/ajv/dist/2020.js"(exports,module){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2020=void 0;var core_1=require_core(),draft2020_1=require_draft2020(),discriminator_1=require_discriminator(),json_schema_2020_12_1=require_json_schema_2020_12(),META_SCHEMA_ID="https://json-schema.org/draft/2020-12/schema",Ajv20202=class extends core_1.default{constructor(opts2={}){super({...opts2,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),draft2020_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta}=this.opts;meta&&(json_schema_2020_12_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv2020=Ajv20202;module.exports=exports=Ajv20202;module.exports.Ajv2020=Ajv20202;Object.defineProperty(exports,"__esModule",{value:!0});exports.default=Ajv20202;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})}});var require_constants=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/constants.js"(exports,module){"use strict";var WIN_NO_SLASH="[^\\\\/]",ONE_CHAR="(?=.)",QMARK="[^/]",END_ANCHOR="(?:\\/|$)",START_ANCHOR="(?:^|\\/)",DOTS_SLASH=`\\.{1,2}${END_ANCHOR}`,NO_DOT="(?!\\.)",NO_DOTS=`(?!${START_ANCHOR}${DOTS_SLASH})`,NO_DOT_SLASH=`(?!\\.{0,1}${END_ANCHOR})`,NO_DOTS_SLASH=`(?!${DOTS_SLASH})`,QMARK_NO_DOT="[^.\\/]",STAR=`${QMARK}*?`,SEP="/",POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR,QMARK,END_ANCHOR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK_NO_DOT,STAR,START_ANCHOR,SEP},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:WIN_NO_SLASH,STAR:`${WIN_NO_SLASH}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win325){return win325===!0?WINDOWS_CHARS:POSIX_CHARS}}}});var require_utils=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/utils.js"(exports){"use strict";var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=val=>val!==null&&typeof val=="object"&&!Array.isArray(val);exports.hasRegexChars=str3=>REGEX_SPECIAL_CHARS.test(str3);exports.isRegexChar=str3=>str3.length===1&&exports.hasRegexChars(str3);exports.escapeRegex=str3=>str3.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=str3=>str3.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform4=navigator.platform.toLowerCase();return platform4==="win32"||platform4==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};exports.removeBackslashes=str3=>str3.replace(REGEX_REMOVE_BACKSLASH,match=>match==="\\"?"":match);exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);return idx===-1?input:input[idx-1]==="\\"?exports.escapeLast(input,char,idx-1):`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state3={})=>{let output=input;return output.startsWith("./")&&(output=output.slice(2),state3.prefix="./"),output};exports.wrapOutput=(input,state3={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;return state3.negated===!0&&(output=`(?:^(?!${output}).*$)`),output};exports.basename=(path16,{windows}={})=>{let segs=path16.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];return last===""?segs[segs.length-2]:last}}});var require_scan=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/scan.js"(exports,module){"use strict";var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=code=>code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH,depth=token=>{token.isPrefix!==!0&&(token.depth=token.isGlobstar?1/0:1)},scan2=(input,options)=>{let opts2=options||{},length=input.length-1,scanToEnd=opts2.parts===!0||opts2.tokens===!0||opts2.scanToEnd===!0,slashes=[],tokens=[],parts=[],str3=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str3.charCodeAt(index+1),advance=()=>(prev=code,str3.charCodeAt(++index));for(;index<length;){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE&&(braceEscaped=!0);continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){for(braces++;eos()!==!0&&(code=advance());){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE&&(braces--,braces===0)){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts2.noext!==!0&&(code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start&&(negatedExtglob=!0),scanToEnd===!0){let parens=0;for(;eos()!==!0&&(code=advance());){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_PARENTHESES){parens++;continue}if(code===CHAR_RIGHT_PARENTHESES&&--parens===0){finished=!0;break}}continue}break}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK&&(isGlobstar=token.isGlobstar=!0),isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){for(;eos()!==!0&&(next=advance());){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts2.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts2.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){let parens=1;for(;eos()!==!0&&(code=advance());){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_PARENTHESES){parens++;continue}if(code===CHAR_RIGHT_PARENTHESES&&--parens===0){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}opts2.noext===!0&&(isExtglob=!1,isGlob=!1);let base=str3,prefix="",glob="";start>0&&(prefix=str3.slice(0,start),str3=str3.slice(start),lastIndex-=start),base&&isGlob===!0&&lastIndex>0?(base=str3.slice(0,lastIndex),glob=str3.slice(lastIndex)):isGlob===!0?(base="",glob=str3):base=str3,base&&base!==""&&base!=="/"&&base!==str3&&isPathSeparator(base.charCodeAt(base.length-1))&&(base=base.slice(0,-1)),opts2.unescape===!0&&(glob&&(glob=utils.removeBackslashes(glob)),base&&backslashes===!0&&(base=utils.removeBackslashes(base)));let state3={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts2.tokens===!0&&(state3.maxDepth=0,isPathSeparator(code)||tokens.push(token),state3.tokens=tokens),opts2.parts===!0||opts2.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n2=prevIndex!==void 0?prevIndex+1:start,i=slashes[idx],value2=input.slice(n2,i);opts2.tokens&&(idx===0&&start!==0?(tokens[idx].isPrefix=!0,tokens[idx].value=prefix):tokens[idx].value=value2,depth(tokens[idx]),state3.maxDepth+=tokens[idx].depth),i>=start&&(parts.push(value2),prevIndex=i)}let n=prevIndex!==void 0?prevIndex+1:start,value=input.slice(n);parts.push(value),opts2.tokens&&prevIndex&&prevIndex+1<input.length&&(tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state3.maxDepth+=tokens[tokens.length-1].depth),state3.slashes=slashes,state3.parts=parts}return state3};module.exports=scan2}});var require_parse=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/parse.js"(exports,module){"use strict";var constants11=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants11,expandRange=(args,options)=>{if(typeof options.expandRange=="function")return options.expandRange(...args,options);args.sort();let value=`[${args.join("-")}]`;try{new RegExp(value)}catch{return args.map(v=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type2,char)=>`Missing ${type2}: "${char}" - use "\\\\${char}" to match literal characters`,splitTopLevel=input=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=branch=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=branch=>{let value=branch.trim(),changed=!0;for(;changed===!0;)changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value)&&(value=value.slice(2,-1),changed=!0);if(isPlainBranch(value))return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=branches=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))&&(a===b||a.startsWith(b)||b.startsWith(a)))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote!==1){if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(!(bracket>0)){if(ch==="("){paren++;continue}if(ch===")"&&(paren--,paren===0))return requireEnd===!0&&i!==pattern.length-1?void 0:{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},buildCharClassStar=chars=>`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map(ch=>utils.escapeRegex(ch)).join("")}]`}*`,getStarExtglobSequenceChars=pattern=>{let index=0,chars=[];for(;index<pattern.length;){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map(branch2=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(!(chars.length<1))return chars},repeatedExtglobRecursion=pattern=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);for(;match;)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion=="number"?options.maxExtglobRecursion:constants11.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map(branch=>branch.trim());if(branches.length>1&&(branches.some(branch=>branch==="")||branches.some(branch=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches)))return{risky:!0};let safeChars=[],sawStarSequence=!1,combinable=!0;for(let branch of branches){let chars=getStarExtglobSequenceChars(branch);if(chars){sawStarSequence=!0,safeChars.push(...chars);continue}let literal=normalizeSimpleBranch(branch);if(literal&&literal.length===1){safeChars.push(literal);continue}if(combinable=!1,repeatedExtglobRecursion(branch)>max)return{risky:!0}}return sawStarSequence?combinable?{risky:!0,safeOutput:buildCharClassStar([...new Set(safeChars)])}:{risky:!0}:{risky:!1}},parse8=(input,options)=>{if(typeof input!="string")throw new TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts2={...options},max=typeof opts2.maxLength=="number"?Math.min(MAX_LENGTH,opts2.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts2.prepend||""},tokens=[bos],capture=opts2.capture?"":"?:",PLATFORM_CHARS=constants11.globChars(opts2.windows),EXTGLOB_CHARS=constants11.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=opts3=>`(${capture}(?:(?!${START_ANCHOR}${opts3.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`,nodot=opts2.dot?"":NO_DOT,qmarkNoDot=opts2.dot?QMARK:QMARK_NO_DOT,star=opts2.bash===!0?globstar(opts2):STAR;opts2.capture&&(star=`(${star})`),typeof opts2.noext=="boolean"&&(opts2.noextglob=opts2.noext);let state3={input,index:-1,start:0,dot:opts2.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state3),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state3.index===len-1,peek=state3.peek=(n=1)=>input[state3.index+n],advance=state3.advance=()=>input[++state3.index]||"",remaining=()=>input.slice(state3.index+1),consume=(value2="",num2=0)=>{state3.consumed+=value2,state3.index+=num2},append=token=>{state3.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count2=1;for(;peek()==="!"&&(peek(2)!=="("||peek(3)==="?");)advance(),state3.start++,count2++;return count2%2===0?!1:(state3.negated=!0,state3.start++,!0)},increment=type2=>{state3[type2]++,stack.push(type2)},decrement=type2=>{state3[type2]--,stack.pop()},push=tok=>{if(prev.type==="globstar"){let isBrace=state3.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob&&(state3.output=state3.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state3.output+=prev.output)}if(extglobs.length&&tok.type!=="paren"&&(extglobs[extglobs.length-1].inner+=tok.value),(tok.value||tok.output)&&append(tok),prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type2,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state3.parens,token.output=state3.output,token.startIndex=state3.index,token.tokensIndex=tokens.length;let output=(opts2.capture?"(":"")+token.open;increment("parens"),push({type:type2,value:value2,output:state3.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=token=>{let literal=input.slice(token.startIndex,state3.index+1),body=input.slice(token.startIndex+2,state3.index),analysis=analyzeRepeatedExtglob(body,opts2);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts2.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open12=tokens[token.tokensIndex];open12.type="text",open12.value=literal,open12.output=safeOutput||utils.escapeRegex(literal);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state3.output=token.output+open12.output,state3.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts2.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/")&&(extglobStar=globstar(opts2)),(extglobStar!==star||eos()||/^\)+$/.test(remaining()))&&(output=token.close=`)$))${extglobStar}`),token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse8(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}token.prev.type==="bos"&&(state3.negatedExtglob=!0)}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts2.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc,chars,first,rest,index)=>first==="\\"?(backslashes=!0,m):first==="?"?esc?esc+first+(rest?QMARK.repeat(rest.length):""):index===0?qmarkNoDot+(rest?QMARK.repeat(rest.length):""):QMARK.repeat(chars.length):first==="."?DOT_LITERAL.repeat(chars.length):first==="*"?esc?esc+first+(rest?star:""):star:esc?m:`\\${m}`);return backslashes===!0&&(opts2.unescape===!0?output=output.replace(/\\/g,""):output=output.replace(/\\+/g,m=>m.length%2===0?"\\\\":m?"\\":"")),output===input&&opts2.contains===!0?(state3.output=input,state3):(state3.output=utils.wrapOutput(output,state3,options),state3)}for(;!eos();){if(value=advance(),value==="\0")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts2.bash!==!0||next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2&&(slashes=match[0].length,state3.index+=slashes,slashes%2!==0&&(value+="\\")),opts2.unescape===!0?value=advance():value+=advance(),state3.brackets===0){push({type:"text",value});continue}}if(state3.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts2.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")&&(prev.posix=!0,inner.includes(":"))){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix4=POSIX_REGEX_SOURCE[rest2];if(posix4){prev.value=pre+posix4,state3.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1&&(bos.output=ONE_CHAR);continue}}}(value==="["&&peek()!==":"||value==="-"&&peek()==="]")&&(value=`\\${value}`),value==="]"&&(prev.value==="["||prev.value==="[^")&&(value=`\\${value}`),opts2.posix===!0&&value==="!"&&prev.value==="["&&(value="^"),prev.value+=value,append({value});continue}if(state3.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){state3.quotes=state3.quotes===1?0:1,opts2.keepQuotes===!0&&push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state3.parens===0&&opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state3.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state3.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts2.nobracket===!0||!remaining().includes("]")){if(opts2.nobracket!==!0&&opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts2.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state3.brackets===0){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/")&&(value=`/${value}`),prev.value+=value,append({value}),opts2.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state3.output=state3.output.slice(0,-prev.value.length),opts2.literalBrackets===!0){state3.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state3.output+=prev.value;continue}if(value==="{"&&opts2.nobrace!==!0){increment("braces");let open12={type:"brace",value,output:"(",outputIndex:state3.output.length,tokensIndex:state3.tokens.length};braces.push(open12),push(open12);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts2.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0&&(tokens.pop(),arr[i].type!=="brace");i--)arr[i].type!=="dots"&&range.unshift(arr[i].value);output=expandRange(range,opts2),state3.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state3.output.slice(0,brace.outputIndex),toks=state3.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state3.output=out;for(let t of toks)state3.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){extglobs.length>0&&extglobs[extglobs.length-1].conditions++,push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];brace&&stack[stack.length-1]==="braces"&&(brace.comma=!0,output="|"),push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state3.index===state3.start+1){state3.start=state3.index+1,state3.consumed="",state3.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state3.braces>0&&prev.type==="dot"){prev.value==="."&&(prev.output=DOT_LITERAL);let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state3.braces+state3.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts2.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))&&(output=`\\${value}`),push({type:"text",value,output});continue}if(opts2.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts2.noextglob!==!0&&peek()==="("&&(peek(2)!=="?"||!/[!=<:]/.test(peek(3)))){extglobOpen("negate",value);continue}if(opts2.nonegate!==!0&&state3.index===0){negate();continue}}if(value==="+"){if(opts2.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts2.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state3.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts2.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){(value==="$"||value==="^")&&(value=`\\${value}`);let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());match&&(value+=match[0],state3.index+=match[0].length),push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state3.backtrack=!0,state3.globstar=!0,consume(value);continue}let rest=remaining();if(opts2.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts2.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts2.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state3.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}for(;rest.slice(0,3)==="/**";){let after2=input[state3.index+4];if(after2&&after2!=="/")break;rest=rest.slice(3),consume("/**",3)}let isEnd=eos()||state3.parens>0&&rest===")".repeat(state3.parens)&&!extglobs.some(extglob=>extglob.type==="negate");if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts2),state3.output=prev.output,state3.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&isEnd){state3.output=state3.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts2)+(opts2.strictSlashes?")":"|$)"),prev.value+=value,state3.globstar=!0,state3.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state3.output=state3.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts2)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state3.output+=prior.output+prev.output,state3.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts2)}${SLASH_LITERAL})`,state3.output=prev.output,state3.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state3.output=state3.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts2),prev.value+=value,state3.output+=prev.output,state3.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts2.bash===!0){token.output=".*?",(prev.type==="bos"||prev.type==="slash")&&(token.output=nodot+token.output),push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts2.regex===!0){token.output=value,push(token);continue}(state3.index===state3.start||prev.type==="slash"||prev.type==="dot")&&(prev.type==="dot"?(state3.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH):opts2.dot===!0?(state3.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH):(state3.output+=nodot,prev.output+=nodot),peek()!=="*"&&(state3.output+=ONE_CHAR,prev.output+=ONE_CHAR)),push(token)}for(;state3.brackets>0;){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing","]"));state3.output=utils.escapeLast(state3.output,"["),decrement("brackets")}for(;state3.parens>0;){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing",")"));state3.output=utils.escapeLast(state3.output,"("),decrement("parens")}for(;state3.braces>0;){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing","}"));state3.output=utils.escapeLast(state3.output,"{"),decrement("braces")}if(opts2.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket")&&push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`}),state3.backtrack===!0){state3.output="";for(let token of state3.tokens)state3.output+=token.output!=null?token.output:token.value,token.suffix&&(state3.output+=token.suffix)}return state3};parse8.fastpaths=(input,options)=>{let opts2={...options},max=typeof opts2.maxLength=="number"?Math.min(MAX_LENGTH,opts2.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants11.globChars(opts2.windows),nodot=opts2.dot?NO_DOTS:NO_DOT,slashDot=opts2.dot?NO_DOTS_SLASH:NO_DOT,capture=opts2.capture?"":"?:",state3={negated:!1,prefix:""},star=opts2.bash===!0?".*?":STAR;opts2.capture&&(star=`(${star})`);let globstar=opts3=>opts3.noglobstar===!0?star:`(${capture}(?:(?!${START_ANCHOR}${opts3.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`,create2=str3=>{switch(str3){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts2);case"**/*":return`(?:${nodot}${globstar(opts2)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts2)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts2)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str3);if(!match)return;let source3=create2(match[1]);return source3?source3+DOT_LITERAL+match[2]:void 0}}},output=utils.removePrefix(input,state3),source2=create2(output);return source2&&opts2.strictSlashes!==!0&&(source2+=`${SLASH_LITERAL}?`),source2};module.exports=parse8}});var require_picomatch=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/picomatch.js"(exports,module){"use strict";var scan2=require_scan(),parse8=require_parse(),utils=require_utils(),constants11=require_constants(),isObject4=val=>val&&typeof val=="object"&&!Array.isArray(val),picomatch4=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map(input=>picomatch4(input,options,returnState));return str3=>{for(let isMatch of fns){let state4=isMatch(str3);if(state4)return state4}return!1}}let isState2=isObject4(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!="string"&&!isState2)throw new TypeError("Expected pattern to be a non-empty string");let opts2=options||{},posix4=opts2.windows,regex=isState2?picomatch4.compileRe(glob,options):picomatch4.makeRe(glob,options,!1,!0),state3=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts2.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch4(opts2.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch4.test(input,regex,options,{glob,posix:posix4}),result3={glob,state:state3,regex,posix:posix4,input,output,match,isMatch};return typeof opts2.onResult=="function"&&opts2.onResult(result3),isMatch===!1?(result3.isMatch=!1,returnObject?result3:!1):isIgnored(input)?(typeof opts2.onIgnore=="function"&&opts2.onIgnore(result3),result3.isMatch=!1,returnObject?result3:!1):(typeof opts2.onMatch=="function"&&opts2.onMatch(result3),returnObject?result3:!0)};return returnState&&(matcher.state=state3),matcher};picomatch4.test=(input,regex,options,{glob,posix:posix4}={})=>{if(typeof input!="string")throw new TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts2=options||{},format=opts2.format||(posix4?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;return match===!1&&(output=format?format(input):input,match=output===glob),(match===!1||opts2.capture===!0)&&(opts2.matchBase===!0||opts2.basename===!0?match=picomatch4.matchBase(input,regex,options,posix4):match=regex.exec(output)),{isMatch:!!match,match,output}};picomatch4.matchBase=(input,glob,options,posix4=options&&options.windows)=>(glob instanceof RegExp?glob:picomatch4.makeRe(glob,options)).test(utils.basename(input,{windows:posix4}));picomatch4.isMatch=(str3,patterns,options)=>picomatch4(patterns,options)(str3);picomatch4.parse=(pattern,options)=>Array.isArray(pattern)?pattern.map(p=>picomatch4.parse(p,options)):parse8(pattern,{...options,fastpaths:!1});picomatch4.scan=(input,options)=>scan2(input,options);picomatch4.compileRe=(state3,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state3.output;let opts2=options||{},prepend=opts2.contains?"":"^",append=opts2.contains?"":"$",source2=`${prepend}(?:${state3.output})${append}`;state3&&state3.negated===!0&&(source2=`^(?!${source2}).*$`);let regex=picomatch4.toRegex(source2,options);return returnState===!0&&(regex.state=state3),regex};picomatch4.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!="string")throw new TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};return options.fastpaths!==!1&&(input[0]==="."||input[0]==="*")&&(parsed.output=parse8.fastpaths(input,options)),parsed.output||(parsed=parse8(input,options)),picomatch4.compileRe(parsed,options,returnOutput,returnState)};picomatch4.toRegex=(source2,options)=>{try{let opts2=options||{};return new RegExp(source2,opts2.flags||(opts2.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch4.constants=constants11;module.exports=picomatch4}});var require_picomatch2=__commonJS({"packages/coding-agent/node_modules/picomatch/index.js"(exports,module){"use strict";var pico=require_picomatch(),utils=require_utils();function picomatch4(glob,options,returnState=!1){return options&&(options.windows===null||options.windows===void 0)&&(options={...options,windows:utils.isWindows()}),pico(glob,options,returnState)}Object.assign(picomatch4,pico);module.exports=picomatch4}});function toJsonAssistantMessageEvent(event){if(event.type==="toolcall_start"){let toolCall=event.partial.content[event.contentIndex];if(toolCall?.type!=="toolCall")throw new Error(`toolcall_start content at index ${event.contentIndex} is not a tool call`);let{partial:_partial2,...deltaEvent2}=event;return{...deltaEvent2,id:toolCall.id,toolName:toolCall.name}}if(!("partial"in event))return event;let{partial:_partial,...deltaEvent}=event;return deltaEvent}function toSeededAssistantEvent(event,capture){if(event.type==="start")return capture.message&&{type:"start",seed:{message:capture.message}};if(event.type==="done")return{type:"done",reason:event.reason,message:event.message};if(event.type==="error")return{type:"error",reason:event.reason,error:event.error};let contentIndex=capture.contentIndex??event.contentIndex;if(event.type==="text_delta"||event.type==="thinking_delta"||event.type==="toolcall_delta"){let{offset,parsedThrough:parsedThrough2}=capture;return offset===void 0?void 0:event.type!=="toolcall_delta"?{type:event.type,contentIndex,delta:event.delta,offset}:parsedThrough2===void 0?void 0:{type:event.type,contentIndex,delta:event.delta,offset,parsedThrough:parsedThrough2}}let{block,coveredCodeUnits}=capture;if(event.type==="toolcall_end")return block?.type==="toolCall"?{type:event.type,contentIndex,toolCall:block}:void 0;if(event.type==="text_end")return block?.type==="text"?{type:event.type,contentIndex,content:event.content,block}:void 0;if(event.type==="thinking_end")return block?.type==="thinking"?{type:event.type,contentIndex,content:event.content,block}:void 0;if(coveredCodeUnits===void 0)return;let seedLength=block?.type==="text"?block.text.length:block?.type==="thinking"?block.thinking.length:capture.rawArgumentPrefix?.length??0,nextOffset=seedNextOffset(capture.nextOffset,seedLength);if(event.type==="text_start")return block?.type==="text"?{type:event.type,contentIndex,seed:{block,coveredCodeUnits,nextOffset}}:void 0;if(event.type==="thinking_start")return block?.type==="thinking"?{type:event.type,contentIndex,seed:{block,coveredCodeUnits,nextOffset}}:void 0;let{rawArgumentPrefix,parsedThrough}=capture;if(!(block?.type!=="toolCall"||rawArgumentPrefix===void 0||parsedThrough===void 0))return{type:event.type,contentIndex,id:block.id,toolName:block.name,seed:{block,rawArgumentPrefix,parsedThrough,coveredCodeUnits,nextOffset}}}function toSeededJsonEvent(event){if((event.type==="message_start"||event.type==="message_end")&&event.message.role==="assistant"){let message=getAssistantCapture(event)?.message;return message?{...event,message}:event.type==="message_end"?event:void 0}if(event.type!=="message_update")return event;let capture=getAssistantCapture(event),assistantMessageEvent=capture&&toSeededAssistantEvent(event.assistantMessageEvent,capture);if(!capture||!assistantMessageEvent)return;let{message:_message,assistantMessageEvent:_event,...outer}=event,changed=capture.metadata!==void 0&&Object.keys(capture.metadata).length>0;return{...outer,usage:capture.usage,...changed?{messageMetadata:capture.metadata}:{},assistantMessageEvent}}function toJsonEvent(event,options){if(options)return toSeededJsonEvent(event);if(event.type!=="message_update")return event;if(event.message.role!=="assistant")throw new Error("message_update message is not an assistant message");return{type:"message_update",usage:event.message.usage,assistantMessageEvent:toJsonAssistantMessageEvent(event.assistantMessageEvent),...event.resolvedToolName===void 0?{}:{resolvedToolName:event.resolvedToolName}}}import{realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{homedir as homedir2}from"node:os";import{isAbsolute,join as join2,resolve as resolve2,win32}from"node:path";import{existsSync,realpathSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join,resolve}from"node:path";var PROJECT_MARKERS=[".git","pnpm-workspace.yaml","package.json","pyproject.toml","Cargo.toml","go.mod",".venv"],PROJECT_RULE_SUBDIRS=[[".pi","rules"],[".omo","rules"],[".claude","rules"],[".cursor","rules"],[".github","instructions"]],PROJECT_SINGLE_FILES=[".github/copilot-instructions.md","AGENTS.md","CLAUDE.md","CONTEXT.md"],USER_HOME_RULE_SUBDIRS=[".pi/rules",".omo/rules",".opencode/rules",".claude/rules"],USER_HOME_SINGLE_FILES=[".config/opencode/AGENTS.md",".claude/CLAUDE.md"],RULE_FILE_EXTENSIONS=[".md",".mdc"],SOURCE_PRIORITY=new Map([[".pi/rules",0],[".omo/rules",1],[".claude/rules",2],[".cursor/rules",3],[".github/instructions",4],[".github/copilot-instructions.md",5],["AGENTS.md",6],["CLAUDE.md",7],["CONTEXT.md",8],["~/.pi/rules",100],["~/.omo/rules",101],["~/.opencode/rules",102],["~/.claude/rules",103],["~/.config/opencode/AGENTS.md",104],["~/.claude/CLAUDE.md",105]]),GLOBAL_DISTANCE=9999,DEFAULT_MAX_RULE_CHARS=12e3,DEFAULT_MAX_RESULT_CHARS=4e4,TRUNCATION_NOTICE=`
|
|
2
|
+
import{DEFERRED_RETRY_MS,InvalidSidecarStoreError,UnsupportedSidecarStoreVersionError,breakStaleLock,cancelScheduledJob,createScheduledJob,createSidecarStore,encodedSessionId,ensureDir,errorCode,holdSessionFile,isWatchRunnerAvailable,listScheduledJobs,liveSessionHolders,ownRunnerIdentity,publishExclusive,publishReplace,readLeaseText,readProcessStartMs,reclaimInspected,reclaimLockState,removeRunnerLease,runDueJobs,scheduleDir,serializeByKey,sidecarFilePath,unlinkIfPresent,withSessionMoveLock,writeRunnerLease}from"./chunk-2BTB7AWD.js";import{containStaleExtensionError}from"./chunk-HUSQY3ID.js";import{ClientAdmissions,ClientMessageIdConflict,ConnectionQuestionBridge,ConnectionRoles,DEFAULT_COMPACTION_SETTINGS,DEFAULT_EXTENSION_SESSION_PROFILE,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,ExecuteToolError,ExtensionTransportOwner,IDLE_COMPACTION_INSTRUCTIONS,McpPresenterAuthority,ModelSwitchAuthError,ModelUsabilityBudgetError,PROMPT_CACHE_PREWARM_ENTRY_TYPE,RESOLUTION_TIMED_OUT,RUNTIME_EXTENSION_PATH,SERVER_SEARCH_FALLBACK,SESSION_CONTROL_DELIVERY_TYPE,SUMMARIZATION_INPUT_BUDGET_RATIO,SessionExtensionUiRequests,SessionRecoveryIdentity,SummarizationOverflowExhaustedError,ToolBarrier,WakeScheduler,acquireFileMutationLock,addUsageToTotals,admitContextToolResults,advertisedCompactCapabilities,all_exports,allowOverflowRetry,answerGetEntries,answeredUiRequestId,attachMcpGrantPresentation,attachRestorationDirective,availableModelsData,baseThresholdRatioForWindow,boundSummarizationInput,buildRpcSessionState,builtinProviders,calculateContextTokens,captureAgentCheckpoint,carryRecovery,clampThinkingSelection,classifyReasoningCapability,clearMcpGrantPresentations,clientFacingIdentity,clientInputContext,collectEntriesForBranchSummary,combineUsage,compact,compat_exports,completeSimple,computeEffectiveKeepRecentTokens,computeEffectiveThreshold,consumePendingPayload,countDiffChanges,createBlockingRemoteCompactionEvent,createFsWatchEventSource,createRemoteCompactionDeadline,createRestorationDirectiveState,createRestorationTrackerState,createUnifiedPatch,createUsageTotals,cursorProvider,defineTool,degradeQuestion,diffLines,diffWords,disableServerSearch,endCompactionFeedback,estimateContextTokens,estimatePendingPromptTokens,estimateProjectedContextTokens,estimateTokens,estimateTotalTokens,extension_default,extractPatchedPaths,findCutPoint,findTurnStartIndex,formatThinkingClampWarning,generateBranchSummary,generateImages,generateSummary,generateSummaryWithUsage,getApplyPatchWireMode,getBuiltinModelDataGeneratedAt,getCursorContextLimit,getImageModel,getLastAssistantUsage,getMcpGrantPresentation,getModels,getPromptCachePrewarmUsage,getPromptContextWindow,getProviders,getSnapshot,getSupportedThinkingLevels as getSupportedThinkingLevels2,getThinkingClampNotice,getUsageCostBreakdown,hasServerSearchFailed,injectTokenBudgetReminder,installCursorContextLimitPersistence,installImagesProviderScopeAccessor,interruptRunningTurn,isAbortedAssistantMessage,isAtHardLimit,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isMissingPathError,isMonitorableMessageEvent,isPowerShellToolResult,isReadToolResult,isServerSearchDisabled,isServerSearchFallback,isSessionControlDeliveryDetails,isToolCallEventType,isWriteToolResult,linkAbortSignal,markServerSearchFallback,markTransientMessage,normalizeApplyPatchArguments,normalizeToolExposure,openAiRemoteCompactionTimeoutMs,parsePatch,persistCheckpoint,prepareBranchEntries,prepareCompaction,preparePendingPayload,projectModelUsabilityBudget,pruneOldMessagesToBudget,recentCheckpoint,recoveryCarrier,refusedExtensionUiResponse,registerBundledOAuthFlowLoaders,rememberServerSearchFailure,renderToolDiff,reportRemoteCompactionTimeout,requiresDeterministicCompactionFallback,resetApiProviders,resetServerSearchFailures,resolveBeforeAgentStartMessage,resolveCompactionGeometry,resolveCursorContextWindow,resolveEffectiveReserveTokens,resolveIdleWarmAction,resolvePatchPath,resolveThresholdContextTokens,roleConnection,rpcCommandPayloadError,rpcCommandShapeError,rpcMessageLengthError,runAbort,runGetEffectStatus,runQueuedInputChange,runSetModel,runSetThinkingLevel,runWithRemoteTimeout,selectMcpGrant,serializeConversation,sessionControlSenderOf,sessionDeclaration,sessionDialogRequests,sessionQuestionBridges,sessionRetryFallbackError,sessionUiAnswerLedger,settleExtensionUiResponse,shouldCompact,shouldDeferGraceBand,shouldRunIdleCompaction,shouldStartSpeculativeCompaction,shouldTriggerCompaction,shouldWarmAtIdle,shrinkSummarizationInputForOverflowRetry,stream,streamSimple,subscribeSessionRecords,supportsMax,supportsXhigh,toolBarrierSpecError,trackToolCall,watchInbox,withAdditionalTokens,withFileMutationQueue,withResolutionDeadline,withoutServerSearch}from"./chunk-B2LRAXQU.js";import{MissingSessionCwdError,RpcClient,RpcClientOpenInFlightError,RpcTransportGoneError,UNKNOWN_COMMAND_CONFIRM_HINT,UnknownCommandError,assertSessionCwdExists,commandShapedName,findUnknownCommand,formatMissingSessionCwdPrompt,getMissingSessionCwdIssue,isTransportGoneError}from"./chunk-5TG7AOLR.js";import{RPC_ERROR_EVAL_CELLS_UNAVAILABLE,RPC_ERROR_EVAL_CELL_NOT_FOUND,RPC_ERROR_INVALID_ARGUMENT,RPC_ERROR_INVALID_EVAL_CELL_REQUEST,RPC_ERROR_MEDIA_NOT_FOUND,RPC_ERROR_MODEL_NOT_FOUND,RPC_ERROR_NO_MODEL_SELECTED,RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED,RPC_ERROR_PROVIDER_CREDENTIALS_MISSING,RPC_ERROR_UNKNOWN_COMMAND,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY,clientMessageIdentity,readClientMessageIdentity}from"./chunk-VRKA3LIT.js";import{allocateMonitorId,defaultEvents,parseRpcTarget}from"./chunk-C5G5PONA.js";import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,writeHelpFlagsCache}from"./chunk-OG2JODU6.js";import{BlockedSkillLinkError,CONTINUE_FROM_LEAF_CUSTOM_TYPE,CONTINUE_FROM_LEAF_DIRECTIVE,CircuitProbes,ContinueFromLeafError,DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS,DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS,DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS,DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS,DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS,DEFAULT_STREAM_START_TIMEOUT_MS,DEFAULT_TOOL_NAMES,DefaultPackageManager,ENGINE_TURN_LIMIT_ENTRY_TYPE,ENGINE_TURN_LIMIT_EVENT,ENGINE_TURN_START_ENTRY_TYPE,FABLE55_LAUNCH,FileSettingsStorage,InteractiveThemeController,MANUAL_CONTINUE_CUSTOM_TYPE,MANUAL_CONTINUE_DIRECTIVE,SKILL_FRONTMATTER_PREFIX_BYTES,SessionSelectorComponent,SettingsManager,TERMINAL_MOUSE_MODES,acquireFallbackCircuits,addIgnoreRules,areExperimentalFeaturesEnabled,authorizeSkillPath,buildSkillAllowedSet,createFallbackCircuitAccess,engineTurnHistory,engineTurnLimitNotice,engineTurnStop,getSettingsPath,insideSkillRoot,isFable55ModelId,isHealthExhaustionFailure,isManualContinueSubmission,isTerminalMouseMode,isUserDirectedTurn,minimatch,monotonicNow,parseGitUrl,parseSettingsJson,readPiManifest,readSkillFileChecked,readSkillFileCheckedSync,readSkillMarkdownSource,resetsEngineTurnHistory,shouldRunFirstTimeSetup,shouldSkipSkillWalkDirectoryName,showFirstTimeSetup,showStartupInput,showStartupSelector,skillProjectRoot,stopResumeDirective,trackTurnAdmission,wasSelfWrite}from"./chunk-HECKLNOO.js";import{HTTP_IDLE_TIMEOUT_CHOICES,applyHttpProxySettings,configureHttpDispatcher,formatHttpIdleTimeoutMs,require_undici}from"./chunk-FEQDJBDL.js";import{CURRENT_SESSION_VERSION,EventLoopSlicer,GOAL_CONTINUATION_MESSAGE_TYPE,REPOSITORY_IDENTITY_ENTRY_TYPE,SESSION_CONTEXT_ENTRY_ID,SESSION_MOVED_IN,SESSION_RELEASED,SessionManager,TRANSPORT_IMAGE_BUDGET_BYTES,VIRTUAL_MODEL_STATE_ENTRY,assertValidSessionId,buildContextEntries,buildSessionContext,buildSessionProjection,compactUpdatesEnabled,compareRepositoryIdentities,convertToLlm,convertToLlmForTransport,createCompactionSummaryMessage,createCustomMessage,createVirtualModel,elidedImageIds,environmentContextMessageIfChanged,findLatestResponse,findMostRecentSession,getBranchSelection,getDefaultSessionDir,getLatestCompactionEntry,getSessionContextEntryId,getVirtualModelState,hasUnsafeRetainedContent,imageContentId,inheritSessionContextEntryId,isSafeBoundedValue,isVirtualModel,listSessionsFromDir,loadEntriesFromFileAsync,migrateSessionEntries,parseEntryLine,parseRepositoryIdentity,parseSessionEntries,readFileLines,readRepositoryIdentity,rejectedImageSources,reserveSessionWrite,resolveEnvironmentContext,sameRepositoryIdentity,sessionCwdMatcher,sessionEntryToContextMessages,sessionFileNameId,unregisterSessionWriter,withVirtualModels}from"./chunk-ARNSNIED.js";import{currentPathPlatform,knownMove,knownPrefixKeys,logGuardEvent,looksMoved,movedPathReason,movedPathWalk,prefixKey,readJsonFileAsync,resolveMovedPath}from"./chunk-L5OFGHDA.js";import{ProjectTrustStore,bundledBuiltinExtensions,getBundledResourceRoots,getProjectTrustOptions,getSavedProjectTrust,hasTrustRequiringProjectResources,imagegenSkillPath}from"./chunk-UURGXV5B.js";import{ASK_USER_ASKED_EVENT,ASK_USER_QUESTION_ENTRY,ASK_USER_SETTLED_EVENT,ASK_USER_SETTLEMENT_ENTRY,AskUserCountdown,AskUserQuestionComponent,AskUserSchemaError,AssistantMessageComponent,CLAUDE_PARAMS,CODEX_PARAMS,CustomEditor,DEFAULT_ASK_USER_TIMEOUT_MS,ExtensionEditorComponent,UserMessageComponent,askUserAnswerDisplayText,copyToClipboard,createBoundedRenderSignature,createChatViewport,createInteractiveTui,createInteractiveTuiReference,editFileInExternalEditor,editInExternalEditor,emitAskUserClosed,emitAskUserNotification,failureAlreadyDescribed,formatCountdownLabel,formatDuration,formatGatedCancellation,formatModelAnswer,formatProviderNativeBody,formatProviderNativeSummary,formatResultDetails,formatResultText,formatUserMessage,getAskUserAnswerHeaders,headNoticeShownElsewhere,openBrowser,parseAskUserAnswerFrame,prepareInteractiveStderrCapture,readClipboardFilePaths,readClipboardText,resolveUserWordReferences,restoreInteractiveStderr,runClipboardCommand,showsPartialAnswers,stripAnsi,takeOverInteractiveStderr,toCanonical}from"./chunk-NEOL3GWO.js";import{DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,DEFAULT_SUMMARIZATION_MAX_DURATION_MS,StreamDurationBudgetError,StreamIdleTimeoutError,SummarizationTotalBudgetError,consumeStreamWithIdleTimeout,createSummarizationDeadline,summarizationMaxDurationMs,summarizationTotalBudgetMs}from"./chunk-Y4MPEIY5.js";import{CountdownTimer,DynamicBorder,ExtensionInputComponent,ExtensionSelectorComponent,SecretInputUnavailableError,armSecretInputDeadline,flushRawStdout,formatKeyText,isSecretInputValue,keyDisplayText,keyHint,keyText,rawKeyHint,resolveSecretInputTimeout,restoreStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-ZJSGYBBD.js";import{AccountUsageLimitError,FS_WATCH_RETRY_DELAY_MS,SYSTEM_THEME_NAME,Theme,canonicalWatchPath,closeWatcher,describeUsageLimitEntry,describeUsageLimitMessage,findReservedKeywordRuns,findReservedKeywordSpans,getAvailableThemes,getAvailableThemesWithPaths,getEditorTheme,getLanguageFromPath,getMarkdownTheme,getReservedKeywordHighlight,getResolvedThemeColors,getSelectListTheme,getSettingsListTheme,getThemeByName,getThemeExportColors,highlightCode,initTheme,isBillingErrorMessage,loadThemeFromPath,onThemeChange,parseAutoThemeSetting,probeDirectoryOpenable,setRegisteredThemes,sharedMarkdownTheme,stopThemeWatcher,theme,usageLimitCause,usageLimitScope,watchWithErrorHandler}from"./chunk-FOMJ73UU.js";import{toolResultUserWords}from"./chunk-VICVLJNU.js";import{TIP_DEFINITIONS}from"./chunk-PIAY636U.js";import{KEYBINDINGS,KeybindingsManager,QUESTION_ANSWER_FALLBACK_KEY,QUESTION_ANSWER_PRIMARY_KEY,isWSL,migrateKeybindingsConfig}from"./chunk-LGO25HPL.js";import{require_applicator,require_codegen,require_compile,require_core,require_core2,require_dependencies,require_discriminator,require_format,require_metadata,require_names,require_ref,require_ref_error,require_util,require_validate,require_validation,require_validation_error}from"./chunk-Y3TMJV3J.js";import{AuthError,ConnectError,LOG_SINK_RETRY_MS,OAuthFlowError,SessionExpiredError,TimeoutError,ToolExecError,collectMrtrForm,createMcpLogger,createMcpRequestOrigin,delay,fingerprintSecret,isEphemeralIdentity,isInvalidGrant,isMcpNeedsAuthError,isMcpSessionExpiredError,isModernMcpClient,isRetriableMcpError,isTransientTokenError,keyedIdentity,legacyMcpFormEligible,legacyMcpFormsAdvertised,loadMcpSdkAuth,loadMcpSdkStdioTransport,loadMcpSdkTypes,mcpRequestOptions,reapProcessTree,redactMcpLogText,registerMcpClientAlias,reportMcpAsyncError,rotateLogIfNeeded,safeDelay,safeEventBusOn,safeInterval,safeTimer,wrapAsync}from"./chunk-ETCYVVVO.js";import{McpMrtrError,getMcpMrtrPresentation,inheritMcpMrtrPresentation,markMcpFormPresented,queuedForm,registerMcpMrtrPresentation}from"./chunk-7ICGN62G.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_FALLBACK,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,PINNED_HOST_CLIENT_CAPABILITIES,TUI_PROBE_TIMEOUT_MS,WakeSourceTracker,classifyEndpointLiveness,endpointProbeTimeoutMs,ensureHost,handoffHost,isSessionBusySnapshot,loadHostLaunchSpec,normalizeWaitItems,parseHostLaunchSpec,projectWaitItems,readAllHostStatus,readHostStatus,readWaitItems,runHostCommand,runHostRequest,waitItemSignature,wakeSourceItems}from"./chunk-N6OHYIJR.js";import{AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DEFAULT_CUSTOM_EXTENSION_LABEL,ENTRIES_TAIL_CAPABILITY,EVAL_CELLS_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,INTERACTIVE_USER_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,PROVIDER_ACCOUNT_TEST_CAPABILITY,QUESTION_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,REQUIRED_HOST_CAPABILITIES,RESUME_SESSION_CAPABILITY,RETRY_FALLBACK_COMMAND_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_RELOCATION_CAPABILITY,TASK_PARENT_CAPABILITY,TOOL_BARRIER_CAPABILITY,buildCustomUnsupportedRequest,compareEngineOrdinal,decideHostAction,engineBuildIdentity,engineBuildIdentityFrom,gcHostEndpoints,parseClientCapabilities,parseHostProtocolInfo,probeHost,protocolIdentity,stopHost}from"./chunk-VOSHKGXG.js";import{listHostEndpoints}from"./chunk-WEOFT5KT.js";import{BUILTIN_PATH_PREFIX,createSourceInfo,createSyntheticSourceInfo,getSyntheticPathSource,isSyntheticPath}from"./chunk-QMRJYMNH.js";import{recordProcessLifetime,resolveCliMainPathAsync,runtimeExecArgv}from"./chunk-FVYWSBX3.js";import{ENDPOINT_REGISTRY_VERSION,createHostDaemonPaths,daemonDirectoryName,shardKey,shardSocketPath,shardSocketPathForKey}from"./chunk-FNBEICAA.js";import{createRgEngine,ensureTool}from"./chunk-SGS76663.js";import{GrepEngineError}from"./chunk-H4QOEVS5.js";import{AllAccountsBlockedError,CLAUDE_CLI_SHARED_LINKS,SENTINEL_OAUTH_FIELDS,accountDirFor,assertValidAccountName,assertValidAccountName2,buildClaudeCliEnvironment,claudeCliSharedRoot,clearExpiredBlocks,credentialPoolRepository,defaultExecutableDeps,emptyCredential,ensureAccountDir,envSlotToken,getCredentialAccounts,hasRequestOauthToken,isBlockedFor,isEnvSlot,isListedStoredSlot,listAccounts,logoutClaudeCli,mergeRequestAuthEnvironment,newAccountDirId,pinAccount,pinCredentialAccount,readClaudeCliAuthStatus,removeAccountDir,removeCredentialAccount,renameCredentialAccount,resolveClaudeCodeExecutable,resolveClaudeCodeRun,selectAccount,spawnClaudeCli,stopClaudeCli,stripManagedAuthEnvironment,summarizeCredentialAccounts}from"./chunk-3CKVTGWG.js";import{ConfigValueSchema,NonemptyConfigValueSchema,assertConfigReferenceAuthority,getConfigValueEnvVarNames,isCommandConfigValue,isCommittedRotationOutput,isConfigReference,isConfigValueConfigured,rememberConfigReferenceOrigin,resolveConfigReference,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,sleep,warnMissingConfigEnvironment,warnOpaqueConfigEnvironment}from"./chunk-PE3PNVKT.js";import{ACCOUNT_POOL_REFUSAL_NOTE,CredentialFailoverError,MAX_SLOT_BLOCK_MS,applyAccountOrder,emitProviderAccountFailover,emitProviderAccountsChanged,isSlotBlocked,rendezvousOrder,slotKind,slotsOfOwnKind,subscribeProviderAccountEvents,unusedSlotKinds,withoutOrderedAccount}from"./chunk-5UVTDRIP.js";import{usageLimitResetMs}from"./chunk-ZNPH5BWS.js";import{activeModelBlockUntil,describeModelBlocks,mergeModelBlocks,modelBlockKey,pruneModelBlocks,rateLimitModelFamily,withModelBlock}from"./chunk-6VWIMHMH.js";import{discoverEnvSlots}from"./chunk-RQDLTDNO.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{lockWithLossHandling}from"./chunk-F7GBSQRV.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{TOOL_RUNTIME_UNSUPPORTED_HOST,ToolRuntimeUnsupportedHostError,isHostOwnedToolRuntimeCapability,isValidThinkingLevel,normalizeSessionName,parseArgs,printHelp,resolveSessionRuntime,resolveToolRuntime,toolRuntimeCapabilities,toolRuntimeHostRefusal}from"./chunk-PZSDJIXD.js";import{source_default}from"./chunk-26UBFF6N.js";import{readOwnFootprint,readProcessFootprint}from"./chunk-MTQQ2VQH.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-H52J72VA.js";import{parseOpenAIImageOutputOptions,parseOpenAIImageSize}from"./chunk-HB35RBP4.js";import{CredentialStoreBusyError,FILE_STORAGE_LOCK_OPTIONS,FILE_STORAGE_LOCK_RETRY_BUDGET_MS,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,FILE_STORAGE_SYNC_LOCK_BUDGET_MS,isLockError}from"./chunk-7X72IACK.js";import{appendUncaughtCrashLog,appendUnhandledRejectionLog}from"./chunk-YWD54RHU.js";import{deriveOpenAIPromptCacheKey}from"./chunk-C5XX36EB.js";import{resolveRootObjectSchema}from"./chunk-IYL5E4QQ.js";import{hasRefusedForcedToolChoice}from"./chunk-OEFCY46F.js";import{extract429RetryAfterMs,parseRetryAfterMsMarker}from"./chunk-RQFD6LG2.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DescendantsLedger,HostCallAdmission,JOB_WIDGET_AGGS,JOB_WIDGET_TONES,LaunchLog,MODULE_JOB_KIND,PayloadRefReader,PayloadRefWriter,TERMINAL_CHILD_JOB_KINDS,TEST_CONTROL_DIR_ENV,TOOL_CHILD_GENERATION_ENV,TOOL_CHILD_MODULE_ROOTS_ENV,TOOL_CHILD_PROTOCOL_VERSION,TerminalManager,TerminalNotifier,WindowsJob,WindowsJobError,closeJobWidgetSession,createBashInputTool,createBashOutputTool,createBashResizeTool,createKillBashTool,createPtyBashTool,cutPlain,defaultGroupProbes,describeExit,ensureMonitorStateDir,errorResult,formatJobWidgetLine,formatSize,generationLedgerPath,getJobWidgetState,getTerminalNotificationDelivery,isModelOnlyText,jobWidgetHostResolver,jobWidgetLineStyle,loadKernel32Job,modelOnlyText,onJobWidgetSessionChange,openJobWidgetSession,packPayload,parkJobWidgetSession,proofIsOrdered,readTestControls,recordGenerationChild,registerJobWidgetSource,removeMonitorStateDir,renderMonitorCall,resendJobWidgetState,resolveForegroundWindowSeconds,resolveTerminalId,sanitizeTerminalOutput,secretOutputObfuscator,setJobWidgetAuthorResolver,spawnCommandSession,sweepGroups,sweepStaleGenerations,terminalChildJob,terminalStateDir,textResult,truncateHead,truncateLine,truncateTail,truncateText,truncateToVisualLines,unpackPayload,withTerminalContext}from"./chunk-RPAEB2Z5.js";import{Box,CancellableLoader,CombinedAutocompleteProvider,Container,Image,Input,Key,Loader,Markdown,MouseRegion,Q,SelectList,SettingsList,Spacer,Text,TruncatedText,TuiAltScreen,TuiMainScreen,claimFrameRow,currentRenderRevision,decodeKittyPrintable,detectCapabilities,dispatchMouseEvent,dist_exports as dist_exports2,expandPasteMarkers,frameMode,frameScrollbackRows,fuzzyFilter,fuzzyMatch,getCapabilities,getGraphemeSegmenter,getImageDimensions,getKeybindings,getNativeClipboard,getTerminalColorMode,hyperlink,imageFallback,isKeyRelease,isViewportTUI,joinLineArrays,mainScreenHistoryLines,matchesKey,nextRenderRevision,outerKittyGraphicsMode,renderAtFrameRow,sanitizeTerminalLabel,setCapabilityOverrides,setKeybindings,sliceByColumn,stripTerminalSequences,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-D2ROBVZ4.js";import{Agent,EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,ProviderRetryWatchdogAbortError,STREAMED_DELTA_TYPES,buildProviderContext,createDefaultReadSummary,createInternalAgentChannel,dist_exports,getPowerShellConfig,getShellConfig,getShellEnv,killProcessTree,killTrackedDetachedChildren,noteDetachedChildExited,prepareAgentToolCall,prepareReadFolder,pruneTrackedDetachedChildren,reasonedBeforeFirstDelta,resolveToolNameAlias,runToolCall,sanitizeBinaryOutput,selectedReadFolder,setDefaultStreamFn,trackDetachedChildPid,untrackDetachedChildPid,withBundledBunCommands}from"./chunk-CLZLV65G.js";import{require_ignore}from"./chunk-YU4AYH4C.js";import{redactSecrets,redactSensitiveOutput,redactSensitiveTokenValues}from"./chunk-LNAZ7XEU.js";import{redactResolvedReferenceData,redactResolvedReferenceValues}from"./chunk-DLAY7CIU.js";import{Compile,StringEnum,compile_exports,composeShellCommand,cursorOverflowCompactionSettings,dropFailedAssistantTurns,getApiProvider,getCursorVariantAlias,getProtocol,getToolCallFormat,installProviderScopeAccessor,isClassifierRefusal,isContextOverflow,isCursorPayloadResourceExhausted,isCursorQuotaResourceExhausted,isCursorZeroTokenResourceExhausted,isRecoverableLength,measureCursorModelInputSerializedBytes,normalizeCursorCatalog,omitUndefinedArgs,parseCursorVariantId,parseEndpointReasoningEfforts,piLimit,piLsPath,piReadArgs,piTimeout,registerToolArgumentValidator,renderCursorCliModelString,require_dist,shouldRetryOverflowWithoutCompact,transformContext,validateToolArguments,warmPromptCache,wrapStreamWithModelRecovery,wrapStreamWithToolCallMiddleware}from"./chunk-KKVVSE6C.js";import{supportsAllowedToolChoice}from"./chunk-COH5F7QV.js";import{hasCredentialHeaders,isCredentialHeaderName}from"./chunk-RFB5CBW7.js";import{extractChatGptSubscriptionAccountId,getWireIdentity,setWireIdentity}from"./chunk-Y7QPP7BG.js";import{convertResponsesMessages,getContextProvenance,isOpenAIResponsesPromptCacheModel}from"./chunk-4WWORAQH.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC,findEnvKeys,getEnvApiKey,sanitizeAnthropicToolPairs}from"./chunk-TG4E7Z7W.js";import{getAnthropicCompat,isAnthropicApiBaseUrl,resolvePromptCacheLifetime,resolvePromptCacheTtlSeconds}from"./chunk-32R442XT.js";import{cleanupSessionResources,processSingleton}from"./chunk-WHPDEDCC.js";import{sanitizeProviderDiagnostic}from"./chunk-7UC4W2T2.js";import{estimateTextTokens}from"./chunk-WBTKUCRH.js";import{parseJsonWithRepair,parseStreamingJson}from"./chunk-3W47LTXQ.js";import{ConfigReferenceError,LEGACY_PROVIDER_IDS,ModelsError,PROVIDER_NOT_CONFIGURED_PREFIX,TURN_RETRY_SUPPRESSION_PREFIX,accountLabel,appendLoginSlot,assertChatModel,assertClassifierModel,assertImageModel,calculateCost,clampThinkingLevel,classifierErrorResult,collapseSystemMessages,contentText,costCardAt,createModels,describeProviderFailureForUser,findSlot,getCurrentSystemMessage,getCurrentSystemPrompt,getCurrentTools,getInitialSystemMessage,getModelType,getSupportedThinkingLevels,imageErrorResult,isModelType,isOAuthRefreshUnavailableError,isProviderStreamStallError,isProviderTimeoutError,isRetryableAssistantError,isRetryableErrorMessage,lazyStream,legacyProviderIdRejection,listSlots,modelsAreEqual,normalizeContext,normalizeProviderId,projectSlot,providerNotConfiguredMessage,readByProviderId,removeSlot,repairManagedSentinelSlots,retryAssistantCall,retryTransientCall,stripProviderRequestIds,stripTurnRetrySuppressionPrefix,supportsConfigurationUpdate,upsertSlot,upstreamProviderIdFor}from"./chunk-3BJFH3CZ.js";import{SeedFrontierError,carryAssistantCapture,createAssistantMessageDiagnostic,createAssistantMessageEventStream,getAssistantCapture,seedNextOffset}from"./chunk-5CSZPC55.js";import{MIN_BUN_VERSION,RUNTIME_ENV_VAR,bunVersionSatisfies,checkForNewPiVersion,findBunBinary,getPiUserAgent,getReleaseChangelogUrl,processBunRuntimeOptions}from"./chunk-PP52OWBB.js";import{INSPECTOR_VM_IMPORT_WARNING,consumeEarlyInspectorVmImportRecoveries,dispatchConfigCommand,dispatchHostCommand,dispatchPackageCommand,dispatchScheduleCommand,exitAfterOutput,hasInheritedInspectorOption,isRecoverableInspectorVmImportError,printThenExit}from"./chunk-CQ3G57HE.js";import{require_semver}from"./chunk-ZOFZRJSL.js";import{markModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{fetchWithRetry}from"./chunk-2SOVDETB.js";import{StaleExtensionContextError,TOOL_CHILD_LIMITS,TOOL_CHILD_ROLE_ENV,isStaleExtensionContextError,openChannelListener}from"./chunk-UKSFF47T.js";import{APP_COMMAND,APP_NAME,APP_TITLE,BRAND,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,DISPLAY_VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,FLAT_LAYOUT_SENTINEL,PACKAGE_NAME,VERSION,brandEnvNames,canonicalizePath,detectInstallMethod,envValue,expandTildePath,findNodePackageDir,formatPathRelativeToCwdOrAbsolute,getAgentDir,getAuthPath,getBinDir,getBundledInteractiveAssetPath,getChangelogPath,getCwdRelativePath,getDebugLogPath,getDocsPath,getExamplesPath,getExportTemplateDir,getFileContentRevision,getFileRevision,getInstallPackageDir,getModelsPath,getPackageDir,getReadmePath,getSessionsDir,getShareViewerBase,isBunBinary,isBunRuntime,isBundledNode,isLocalPath,isShareDisabledByEnvironment,normalizePath,realpathWithoutOpen,realpathWithoutOpenStrict,resolveAgentDir,resolveInstallPath,resolvePath,splitBom,stripBom,waitForChildProcess}from"./chunk-ISZ4EWIS.js";import{Check,build_exports,typebox_exports,value_exports,value_exports2}from"./chunk-MIENF2YK.js";import{TOOL_CHILD_LEDGER_ENV,TOOL_CHILD_REENTRY_ENV,TOOL_CHILD_REFS_ROOT_ENV}from"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs,processBootAtMs,sameBoot}from"./chunk-QN2BHP3M.js";import{DEFAULT_COLS,DEFAULT_MAX_SESSIONS,DEFAULT_MONITOR_RUNAWAY_LINES_PER_MINUTE,DEFAULT_MONITOR_RUNAWAY_MINUTES,DEFAULT_MONITOR_WAKES_PER_HOUR,DEFAULT_ROWS,DEFAULT_SCROLLBACK,DURABLE_MONITOR_EXPIRY_MS,FIRE_BUDGET_WINDOW_MS,MONITOR_ENV_DOWNTIME_MS,MONITOR_ENV_ID,MONITOR_ENV_RESTORED,MONITOR_ENV_STATE_DIR,MONITOR_OVERFLOW_FILE_MAX_BYTES,RESTORE_GRACE_MS,RUNAWAY_PAUSE_SUMMARY_PREFIX,SecretOutputRedactor,TERMINAL_BASH_TOOL,TERMINAL_COMPANION_TOOLS,TERMINAL_MONITOR_TOOL,runawayPauseSummary}from"./chunk-AOTHPTMU.js";import{PROCESS_START_TOLERANCE_MS,sameProcessStartMs}from"./chunk-O5RYI3IW.js";import{__commonJS,__export,__toESM}from"./chunk-IKOFCODM.js";var require_dynamicAnchor=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.dynamicAnchor=void 0;var codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),ref_1=require_ref(),def={keyword:"$dynamicAnchor",schemaType:"string",code:cxt=>dynamicAnchor(cxt,cxt.schema)};function dynamicAnchor(cxt,anchor){let{gen,it}=cxt;it.schemaEnv.root.dynamicAnchors[anchor]=!0;let v=(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`,validate=it.errSchemaPath==="#"?it.validateName:_getValidate(cxt);gen.if((0,codegen_1._)`!${v}`,()=>gen.assign(v,validate))}exports.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){let{schemaEnv,schema,self}=cxt.it,{root,baseId,localRefs,meta}=schemaEnv.root,{schemaId}=self.opts,sch=new compile_1.SchemaEnv({schema,schemaId,root,baseId,localRefs,meta});return compile_1.compileSchema.call(self,sch),(0,ref_1.getValidate)(cxt,sch)}exports.default=def}});var require_dynamicRef=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.dynamicRef=void 0;var codegen_1=require_codegen(),names_1=require_names(),ref_1=require_ref(),def={keyword:"$dynamicRef",schemaType:"string",code:cxt=>dynamicRef(cxt,cxt.schema)};function dynamicRef(cxt,ref){let{gen,keyword,it}=cxt;if(ref[0]!=="#")throw new Error(`"${keyword}" only supports hash fragment reference`);let anchor=ref.slice(1);if(it.allErrors)_dynamicRef();else{let valid2=gen.let("valid",!1);_dynamicRef(valid2),cxt.ok(valid2)}function _dynamicRef(valid2){if(it.schemaEnv.root.dynamicAnchors[anchor]){let v=gen.let("_v",(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`);gen.if(v,_callRef(v,valid2),_callRef(it.validateName,valid2))}else _callRef(it.validateName,valid2)()}function _callRef(validate,valid2){return valid2?()=>gen.block(()=>{(0,ref_1.callRef)(cxt,validate),gen.let(valid2,!0)}):()=>(0,ref_1.callRef)(cxt,validate)}}exports.dynamicRef=dynamicRef;exports.default=def}});var require_recursiveAnchor=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dynamicAnchor_1=require_dynamicAnchor(),util_1=require_util(),def={keyword:"$recursiveAnchor",schemaType:"boolean",code(cxt){cxt.schema?(0,dynamicAnchor_1.dynamicAnchor)(cxt,""):(0,util_1.checkStrictMode)(cxt.it,"$recursiveAnchor: false is ignored")}};exports.default=def}});var require_recursiveRef=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dynamicRef_1=require_dynamicRef(),def={keyword:"$recursiveRef",schemaType:"string",code:cxt=>(0,dynamicRef_1.dynamicRef)(cxt,cxt.schema)};exports.default=def}});var require_dynamic=__commonJS({"node_modules/ajv/dist/vocabularies/dynamic/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dynamicAnchor_1=require_dynamicAnchor(),dynamicRef_1=require_dynamicRef(),recursiveAnchor_1=require_recursiveAnchor(),recursiveRef_1=require_recursiveRef(),dynamic=[dynamicAnchor_1.default,dynamicRef_1.default,recursiveAnchor_1.default,recursiveRef_1.default];exports.default=dynamic}});var require_dependentRequired=__commonJS({"node_modules/ajv/dist/vocabularies/validation/dependentRequired.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dependencies_1=require_dependencies(),def={keyword:"dependentRequired",type:"object",schemaType:"object",error:dependencies_1.error,code:cxt=>(0,dependencies_1.validatePropertyDeps)(cxt)};exports.default=def}});var require_dependentSchemas=__commonJS({"node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dependencies_1=require_dependencies(),def={keyword:"dependentSchemas",type:"object",schemaType:"object",code:cxt=>(0,dependencies_1.validateSchemaDeps)(cxt)};exports.default=def}});var require_limitContains=__commonJS({"node_modules/ajv/dist/vocabularies/validation/limitContains.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var util_1=require_util(),def={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword,parentSchema,it}){parentSchema.contains===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "contains" is ignored`)}};exports.default=def}});var require_next=__commonJS({"node_modules/ajv/dist/vocabularies/next.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dependentRequired_1=require_dependentRequired(),dependentSchemas_1=require_dependentSchemas(),limitContains_1=require_limitContains(),next=[dependentRequired_1.default,dependentSchemas_1.default,limitContains_1.default];exports.default=next}});var require_unevaluatedProperties=__commonJS({"node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),error2={message:"must NOT have unevaluated properties",params:({params})=>(0,codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`},def={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:error2,code(cxt){let{gen,schema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,props}=it;props instanceof codegen_1.Name?gen.if((0,codegen_1._)`${props} !== true`,()=>gen.forIn("key",data,key=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key)))):props!==!0&&gen.forIn("key",data,key=>props===void 0?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key))),it.props=!0,cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema===!1){cxt.setParams({unevaluatedProperty:key}),cxt.error(),allErrors||gen.break();return}if(!(0,util_1.alwaysValidSchema)(it,schema)){let valid2=gen.name("valid");cxt.subschema({keyword:"unevaluatedProperties",dataProp:key,dataPropType:util_1.Type.Str},valid2),allErrors||gen.if((0,codegen_1.not)(valid2),()=>gen.break())}}function unevaluatedDynamic(evaluatedProps,key){return(0,codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){let ps=[];for(let p in evaluatedProps)evaluatedProps[p]===!0&&ps.push((0,codegen_1._)`${key} !== ${p}`);return(0,codegen_1.and)(...ps)}}};exports.default=def}});var require_unevaluatedItems=__commonJS({"node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var codegen_1=require_codegen(),util_1=require_util(),error2={message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},def={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:error2,code(cxt){let{gen,schema,data,it}=cxt,items=it.items||0;if(items===!0)return;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema===!1)cxt.setParams({len:items}),cxt.fail((0,codegen_1._)`${len} > ${items}`);else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid2=gen.var("valid",(0,codegen_1._)`${len} <= ${items}`);gen.if((0,codegen_1.not)(valid2),()=>validateItems(valid2,items)),cxt.ok(valid2)}it.items=!0;function validateItems(valid2,from){gen.forRange("i",from,len,i=>{cxt.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:util_1.Type.Num},valid2),it.allErrors||gen.if((0,codegen_1.not)(valid2),()=>gen.break())})}}};exports.default=def}});var require_unevaluated=__commonJS({"node_modules/ajv/dist/vocabularies/unevaluated/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var unevaluatedProperties_1=require_unevaluatedProperties(),unevaluatedItems_1=require_unevaluatedItems(),unevaluated=[unevaluatedProperties_1.default,unevaluatedItems_1.default];exports.default=unevaluated}});var require_draft2020=__commonJS({"node_modules/ajv/dist/vocabularies/draft2020.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var core_1=require_core2(),validation_1=require_validation(),applicator_1=require_applicator(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated(),format_1=require_format(),metadata_1=require_metadata(),draft2020Vocabularies=[dynamic_1.default,core_1.default,validation_1.default,(0,applicator_1.default)(!0),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary,next_1.default,unevaluated_1.default];exports.default=draft2020Vocabularies}});var require_schema=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/schema.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}}});var require_applicator2=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}}});var require_unevaluated2=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}}});var require_content=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}}});var require_core3=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}}});var require_format_annotation=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}}});var require_meta_data=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}});var require_validation2=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json"(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}});var require_json_schema_2020_12=__commonJS({"node_modules/ajv/dist/refs/json-schema-2020-12/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var metaSchema=require_schema(),applicator=require_applicator2(),unevaluated=require_unevaluated2(),content=require_content(),core=require_core3(),format=require_format_annotation(),metadata=require_meta_data(),validation=require_validation2(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2020($data){return[metaSchema,applicator,unevaluated,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2020}});var require__=__commonJS({"node_modules/ajv/dist/2020.js"(exports,module){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2020=void 0;var core_1=require_core(),draft2020_1=require_draft2020(),discriminator_1=require_discriminator(),json_schema_2020_12_1=require_json_schema_2020_12(),META_SCHEMA_ID="https://json-schema.org/draft/2020-12/schema",Ajv20202=class extends core_1.default{constructor(opts2={}){super({...opts2,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),draft2020_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta}=this.opts;meta&&(json_schema_2020_12_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv2020=Ajv20202;module.exports=exports=Ajv20202;module.exports.Ajv2020=Ajv20202;Object.defineProperty(exports,"__esModule",{value:!0});exports.default=Ajv20202;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:!0,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:!0,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:!0,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})}});var require_constants=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/constants.js"(exports,module){"use strict";var WIN_NO_SLASH="[^\\\\/]",ONE_CHAR="(?=.)",QMARK="[^/]",END_ANCHOR="(?:\\/|$)",START_ANCHOR="(?:^|\\/)",DOTS_SLASH=`\\.{1,2}${END_ANCHOR}`,NO_DOT="(?!\\.)",NO_DOTS=`(?!${START_ANCHOR}${DOTS_SLASH})`,NO_DOT_SLASH=`(?!\\.{0,1}${END_ANCHOR})`,NO_DOTS_SLASH=`(?!${DOTS_SLASH})`,QMARK_NO_DOT="[^.\\/]",STAR=`${QMARK}*?`,SEP="/",POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR,QMARK,END_ANCHOR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK_NO_DOT,STAR,START_ANCHOR,SEP},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:WIN_NO_SLASH,STAR:`${WIN_NO_SLASH}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win325){return win325===!0?WINDOWS_CHARS:POSIX_CHARS}}}});var require_utils=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/utils.js"(exports){"use strict";var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=val=>val!==null&&typeof val=="object"&&!Array.isArray(val);exports.hasRegexChars=str3=>REGEX_SPECIAL_CHARS.test(str3);exports.isRegexChar=str3=>str3.length===1&&exports.hasRegexChars(str3);exports.escapeRegex=str3=>str3.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=str3=>str3.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform4=navigator.platform.toLowerCase();return platform4==="win32"||platform4==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};exports.removeBackslashes=str3=>str3.replace(REGEX_REMOVE_BACKSLASH,match=>match==="\\"?"":match);exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);return idx===-1?input:input[idx-1]==="\\"?exports.escapeLast(input,char,idx-1):`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state3={})=>{let output=input;return output.startsWith("./")&&(output=output.slice(2),state3.prefix="./"),output};exports.wrapOutput=(input,state3={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;return state3.negated===!0&&(output=`(?:^(?!${output}).*$)`),output};exports.basename=(path16,{windows}={})=>{let segs=path16.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];return last===""?segs[segs.length-2]:last}}});var require_scan=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/scan.js"(exports,module){"use strict";var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=code=>code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH,depth=token=>{token.isPrefix!==!0&&(token.depth=token.isGlobstar?1/0:1)},scan2=(input,options)=>{let opts2=options||{},length=input.length-1,scanToEnd=opts2.parts===!0||opts2.tokens===!0||opts2.scanToEnd===!0,slashes=[],tokens=[],parts=[],str3=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str3.charCodeAt(index+1),advance=()=>(prev=code,str3.charCodeAt(++index));for(;index<length;){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE&&(braceEscaped=!0);continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){for(braces++;eos()!==!0&&(code=advance());){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE&&(braces--,braces===0)){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts2.noext!==!0&&(code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start&&(negatedExtglob=!0),scanToEnd===!0){let parens=0;for(;eos()!==!0&&(code=advance());){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_PARENTHESES){parens++;continue}if(code===CHAR_RIGHT_PARENTHESES&&--parens===0){finished=!0;break}}continue}break}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK&&(isGlobstar=token.isGlobstar=!0),isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){for(;eos()!==!0&&(next=advance());){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts2.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts2.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){let parens=1;for(;eos()!==!0&&(code=advance());){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_PARENTHESES){parens++;continue}if(code===CHAR_RIGHT_PARENTHESES&&--parens===0){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}opts2.noext===!0&&(isExtglob=!1,isGlob=!1);let base=str3,prefix="",glob="";start>0&&(prefix=str3.slice(0,start),str3=str3.slice(start),lastIndex-=start),base&&isGlob===!0&&lastIndex>0?(base=str3.slice(0,lastIndex),glob=str3.slice(lastIndex)):isGlob===!0?(base="",glob=str3):base=str3,base&&base!==""&&base!=="/"&&base!==str3&&isPathSeparator(base.charCodeAt(base.length-1))&&(base=base.slice(0,-1)),opts2.unescape===!0&&(glob&&(glob=utils.removeBackslashes(glob)),base&&backslashes===!0&&(base=utils.removeBackslashes(base)));let state3={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts2.tokens===!0&&(state3.maxDepth=0,isPathSeparator(code)||tokens.push(token),state3.tokens=tokens),opts2.parts===!0||opts2.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n2=prevIndex!==void 0?prevIndex+1:start,i=slashes[idx],value2=input.slice(n2,i);opts2.tokens&&(idx===0&&start!==0?(tokens[idx].isPrefix=!0,tokens[idx].value=prefix):tokens[idx].value=value2,depth(tokens[idx]),state3.maxDepth+=tokens[idx].depth),i>=start&&(parts.push(value2),prevIndex=i)}let n=prevIndex!==void 0?prevIndex+1:start,value=input.slice(n);parts.push(value),opts2.tokens&&prevIndex&&prevIndex+1<input.length&&(tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state3.maxDepth+=tokens[tokens.length-1].depth),state3.slashes=slashes,state3.parts=parts}return state3};module.exports=scan2}});var require_parse=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/parse.js"(exports,module){"use strict";var constants11=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants11,expandRange=(args,options)=>{if(typeof options.expandRange=="function")return options.expandRange(...args,options);args.sort();let value=`[${args.join("-")}]`;try{new RegExp(value)}catch{return args.map(v=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type2,char)=>`Missing ${type2}: "${char}" - use "\\\\${char}" to match literal characters`,splitTopLevel=input=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=branch=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=branch=>{let value=branch.trim(),changed=!0;for(;changed===!0;)changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value)&&(value=value.slice(2,-1),changed=!0);if(isPlainBranch(value))return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=branches=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))&&(a===b||a.startsWith(b)||b.startsWith(a)))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote!==1){if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(!(bracket>0)){if(ch==="("){paren++;continue}if(ch===")"&&(paren--,paren===0))return requireEnd===!0&&i!==pattern.length-1?void 0:{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},buildCharClassStar=chars=>`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map(ch=>utils.escapeRegex(ch)).join("")}]`}*`,getStarExtglobSequenceChars=pattern=>{let index=0,chars=[];for(;index<pattern.length;){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map(branch2=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(!(chars.length<1))return chars},repeatedExtglobRecursion=pattern=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);for(;match;)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion=="number"?options.maxExtglobRecursion:constants11.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map(branch=>branch.trim());if(branches.length>1&&(branches.some(branch=>branch==="")||branches.some(branch=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches)))return{risky:!0};let safeChars=[],sawStarSequence=!1,combinable=!0;for(let branch of branches){let chars=getStarExtglobSequenceChars(branch);if(chars){sawStarSequence=!0,safeChars.push(...chars);continue}let literal=normalizeSimpleBranch(branch);if(literal&&literal.length===1){safeChars.push(literal);continue}if(combinable=!1,repeatedExtglobRecursion(branch)>max)return{risky:!0}}return sawStarSequence?combinable?{risky:!0,safeOutput:buildCharClassStar([...new Set(safeChars)])}:{risky:!0}:{risky:!1}},parse8=(input,options)=>{if(typeof input!="string")throw new TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts2={...options},max=typeof opts2.maxLength=="number"?Math.min(MAX_LENGTH,opts2.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts2.prepend||""},tokens=[bos],capture=opts2.capture?"":"?:",PLATFORM_CHARS=constants11.globChars(opts2.windows),EXTGLOB_CHARS=constants11.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=opts3=>`(${capture}(?:(?!${START_ANCHOR}${opts3.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`,nodot=opts2.dot?"":NO_DOT,qmarkNoDot=opts2.dot?QMARK:QMARK_NO_DOT,star=opts2.bash===!0?globstar(opts2):STAR;opts2.capture&&(star=`(${star})`),typeof opts2.noext=="boolean"&&(opts2.noextglob=opts2.noext);let state3={input,index:-1,start:0,dot:opts2.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state3),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state3.index===len-1,peek=state3.peek=(n=1)=>input[state3.index+n],advance=state3.advance=()=>input[++state3.index]||"",remaining=()=>input.slice(state3.index+1),consume=(value2="",num2=0)=>{state3.consumed+=value2,state3.index+=num2},append=token=>{state3.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count2=1;for(;peek()==="!"&&(peek(2)!=="("||peek(3)==="?");)advance(),state3.start++,count2++;return count2%2===0?!1:(state3.negated=!0,state3.start++,!0)},increment=type2=>{state3[type2]++,stack.push(type2)},decrement=type2=>{state3[type2]--,stack.pop()},push=tok=>{if(prev.type==="globstar"){let isBrace=state3.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob&&(state3.output=state3.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state3.output+=prev.output)}if(extglobs.length&&tok.type!=="paren"&&(extglobs[extglobs.length-1].inner+=tok.value),(tok.value||tok.output)&&append(tok),prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type2,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state3.parens,token.output=state3.output,token.startIndex=state3.index,token.tokensIndex=tokens.length;let output=(opts2.capture?"(":"")+token.open;increment("parens"),push({type:type2,value:value2,output:state3.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=token=>{let literal=input.slice(token.startIndex,state3.index+1),body=input.slice(token.startIndex+2,state3.index),analysis=analyzeRepeatedExtglob(body,opts2);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts2.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open12=tokens[token.tokensIndex];open12.type="text",open12.value=literal,open12.output=safeOutput||utils.escapeRegex(literal);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state3.output=token.output+open12.output,state3.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts2.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/")&&(extglobStar=globstar(opts2)),(extglobStar!==star||eos()||/^\)+$/.test(remaining()))&&(output=token.close=`)$))${extglobStar}`),token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse8(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}token.prev.type==="bos"&&(state3.negatedExtglob=!0)}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts2.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc,chars,first,rest,index)=>first==="\\"?(backslashes=!0,m):first==="?"?esc?esc+first+(rest?QMARK.repeat(rest.length):""):index===0?qmarkNoDot+(rest?QMARK.repeat(rest.length):""):QMARK.repeat(chars.length):first==="."?DOT_LITERAL.repeat(chars.length):first==="*"?esc?esc+first+(rest?star:""):star:esc?m:`\\${m}`);return backslashes===!0&&(opts2.unescape===!0?output=output.replace(/\\/g,""):output=output.replace(/\\+/g,m=>m.length%2===0?"\\\\":m?"\\":"")),output===input&&opts2.contains===!0?(state3.output=input,state3):(state3.output=utils.wrapOutput(output,state3,options),state3)}for(;!eos();){if(value=advance(),value==="\0")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts2.bash!==!0||next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2&&(slashes=match[0].length,state3.index+=slashes,slashes%2!==0&&(value+="\\")),opts2.unescape===!0?value=advance():value+=advance(),state3.brackets===0){push({type:"text",value});continue}}if(state3.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts2.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")&&(prev.posix=!0,inner.includes(":"))){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix4=POSIX_REGEX_SOURCE[rest2];if(posix4){prev.value=pre+posix4,state3.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1&&(bos.output=ONE_CHAR);continue}}}(value==="["&&peek()!==":"||value==="-"&&peek()==="]")&&(value=`\\${value}`),value==="]"&&(prev.value==="["||prev.value==="[^")&&(value=`\\${value}`),opts2.posix===!0&&value==="!"&&prev.value==="["&&(value="^"),prev.value+=value,append({value});continue}if(state3.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){state3.quotes=state3.quotes===1?0:1,opts2.keepQuotes===!0&&push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state3.parens===0&&opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state3.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state3.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts2.nobracket===!0||!remaining().includes("]")){if(opts2.nobracket!==!0&&opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts2.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state3.brackets===0){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/")&&(value=`/${value}`),prev.value+=value,append({value}),opts2.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state3.output=state3.output.slice(0,-prev.value.length),opts2.literalBrackets===!0){state3.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state3.output+=prev.value;continue}if(value==="{"&&opts2.nobrace!==!0){increment("braces");let open12={type:"brace",value,output:"(",outputIndex:state3.output.length,tokensIndex:state3.tokens.length};braces.push(open12),push(open12);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts2.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0&&(tokens.pop(),arr[i].type!=="brace");i--)arr[i].type!=="dots"&&range.unshift(arr[i].value);output=expandRange(range,opts2),state3.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state3.output.slice(0,brace.outputIndex),toks=state3.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state3.output=out;for(let t of toks)state3.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){extglobs.length>0&&extglobs[extglobs.length-1].conditions++,push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];brace&&stack[stack.length-1]==="braces"&&(brace.comma=!0,output="|"),push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state3.index===state3.start+1){state3.start=state3.index+1,state3.consumed="",state3.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state3.braces>0&&prev.type==="dot"){prev.value==="."&&(prev.output=DOT_LITERAL);let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state3.braces+state3.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts2.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))&&(output=`\\${value}`),push({type:"text",value,output});continue}if(opts2.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts2.noextglob!==!0&&peek()==="("&&(peek(2)!=="?"||!/[!=<:]/.test(peek(3)))){extglobOpen("negate",value);continue}if(opts2.nonegate!==!0&&state3.index===0){negate();continue}}if(value==="+"){if(opts2.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts2.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state3.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts2.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){(value==="$"||value==="^")&&(value=`\\${value}`);let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());match&&(value+=match[0],state3.index+=match[0].length),push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state3.backtrack=!0,state3.globstar=!0,consume(value);continue}let rest=remaining();if(opts2.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts2.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts2.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state3.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}for(;rest.slice(0,3)==="/**";){let after2=input[state3.index+4];if(after2&&after2!=="/")break;rest=rest.slice(3),consume("/**",3)}let isEnd=eos()||state3.parens>0&&rest===")".repeat(state3.parens)&&!extglobs.some(extglob=>extglob.type==="negate");if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts2),state3.output=prev.output,state3.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&isEnd){state3.output=state3.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts2)+(opts2.strictSlashes?")":"|$)"),prev.value+=value,state3.globstar=!0,state3.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state3.output=state3.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts2)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state3.output+=prior.output+prev.output,state3.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts2)}${SLASH_LITERAL})`,state3.output=prev.output,state3.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state3.output=state3.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts2),prev.value+=value,state3.output+=prev.output,state3.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts2.bash===!0){token.output=".*?",(prev.type==="bos"||prev.type==="slash")&&(token.output=nodot+token.output),push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts2.regex===!0){token.output=value,push(token);continue}(state3.index===state3.start||prev.type==="slash"||prev.type==="dot")&&(prev.type==="dot"?(state3.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH):opts2.dot===!0?(state3.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH):(state3.output+=nodot,prev.output+=nodot),peek()!=="*"&&(state3.output+=ONE_CHAR,prev.output+=ONE_CHAR)),push(token)}for(;state3.brackets>0;){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing","]"));state3.output=utils.escapeLast(state3.output,"["),decrement("brackets")}for(;state3.parens>0;){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing",")"));state3.output=utils.escapeLast(state3.output,"("),decrement("parens")}for(;state3.braces>0;){if(opts2.strictBrackets===!0)throw new SyntaxError(syntaxError("closing","}"));state3.output=utils.escapeLast(state3.output,"{"),decrement("braces")}if(opts2.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket")&&push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`}),state3.backtrack===!0){state3.output="";for(let token of state3.tokens)state3.output+=token.output!=null?token.output:token.value,token.suffix&&(state3.output+=token.suffix)}return state3};parse8.fastpaths=(input,options)=>{let opts2={...options},max=typeof opts2.maxLength=="number"?Math.min(MAX_LENGTH,opts2.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants11.globChars(opts2.windows),nodot=opts2.dot?NO_DOTS:NO_DOT,slashDot=opts2.dot?NO_DOTS_SLASH:NO_DOT,capture=opts2.capture?"":"?:",state3={negated:!1,prefix:""},star=opts2.bash===!0?".*?":STAR;opts2.capture&&(star=`(${star})`);let globstar=opts3=>opts3.noglobstar===!0?star:`(${capture}(?:(?!${START_ANCHOR}${opts3.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`,create2=str3=>{switch(str3){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts2);case"**/*":return`(?:${nodot}${globstar(opts2)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts2)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts2)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str3);if(!match)return;let source3=create2(match[1]);return source3?source3+DOT_LITERAL+match[2]:void 0}}},output=utils.removePrefix(input,state3),source2=create2(output);return source2&&opts2.strictSlashes!==!0&&(source2+=`${SLASH_LITERAL}?`),source2};module.exports=parse8}});var require_picomatch=__commonJS({"packages/coding-agent/node_modules/picomatch/lib/picomatch.js"(exports,module){"use strict";var scan2=require_scan(),parse8=require_parse(),utils=require_utils(),constants11=require_constants(),isObject4=val=>val&&typeof val=="object"&&!Array.isArray(val),picomatch4=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map(input=>picomatch4(input,options,returnState));return str3=>{for(let isMatch of fns){let state4=isMatch(str3);if(state4)return state4}return!1}}let isState2=isObject4(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!="string"&&!isState2)throw new TypeError("Expected pattern to be a non-empty string");let opts2=options||{},posix4=opts2.windows,regex=isState2?picomatch4.compileRe(glob,options):picomatch4.makeRe(glob,options,!1,!0),state3=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts2.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch4(opts2.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch4.test(input,regex,options,{glob,posix:posix4}),result3={glob,state:state3,regex,posix:posix4,input,output,match,isMatch};return typeof opts2.onResult=="function"&&opts2.onResult(result3),isMatch===!1?(result3.isMatch=!1,returnObject?result3:!1):isIgnored(input)?(typeof opts2.onIgnore=="function"&&opts2.onIgnore(result3),result3.isMatch=!1,returnObject?result3:!1):(typeof opts2.onMatch=="function"&&opts2.onMatch(result3),returnObject?result3:!0)};return returnState&&(matcher.state=state3),matcher};picomatch4.test=(input,regex,options,{glob,posix:posix4}={})=>{if(typeof input!="string")throw new TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts2=options||{},format=opts2.format||(posix4?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;return match===!1&&(output=format?format(input):input,match=output===glob),(match===!1||opts2.capture===!0)&&(opts2.matchBase===!0||opts2.basename===!0?match=picomatch4.matchBase(input,regex,options,posix4):match=regex.exec(output)),{isMatch:!!match,match,output}};picomatch4.matchBase=(input,glob,options,posix4=options&&options.windows)=>(glob instanceof RegExp?glob:picomatch4.makeRe(glob,options)).test(utils.basename(input,{windows:posix4}));picomatch4.isMatch=(str3,patterns,options)=>picomatch4(patterns,options)(str3);picomatch4.parse=(pattern,options)=>Array.isArray(pattern)?pattern.map(p=>picomatch4.parse(p,options)):parse8(pattern,{...options,fastpaths:!1});picomatch4.scan=(input,options)=>scan2(input,options);picomatch4.compileRe=(state3,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state3.output;let opts2=options||{},prepend=opts2.contains?"":"^",append=opts2.contains?"":"$",source2=`${prepend}(?:${state3.output})${append}`;state3&&state3.negated===!0&&(source2=`^(?!${source2}).*$`);let regex=picomatch4.toRegex(source2,options);return returnState===!0&&(regex.state=state3),regex};picomatch4.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!="string")throw new TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};return options.fastpaths!==!1&&(input[0]==="."||input[0]==="*")&&(parsed.output=parse8.fastpaths(input,options)),parsed.output||(parsed=parse8(input,options)),picomatch4.compileRe(parsed,options,returnOutput,returnState)};picomatch4.toRegex=(source2,options)=>{try{let opts2=options||{};return new RegExp(source2,opts2.flags||(opts2.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch4.constants=constants11;module.exports=picomatch4}});var require_picomatch2=__commonJS({"packages/coding-agent/node_modules/picomatch/index.js"(exports,module){"use strict";var pico=require_picomatch(),utils=require_utils();function picomatch4(glob,options,returnState=!1){return options&&(options.windows===null||options.windows===void 0)&&(options={...options,windows:utils.isWindows()}),pico(glob,options,returnState)}Object.assign(picomatch4,pico);module.exports=picomatch4}});function toJsonAssistantMessageEvent(event){if(event.type==="toolcall_start"){let toolCall=event.partial.content[event.contentIndex];if(toolCall?.type!=="toolCall")throw new Error(`toolcall_start content at index ${event.contentIndex} is not a tool call`);let{partial:_partial2,...deltaEvent2}=event;return{...deltaEvent2,id:toolCall.id,toolName:toolCall.name}}if(!("partial"in event))return event;let{partial:_partial,...deltaEvent}=event;return deltaEvent}function toSeededAssistantEvent(event,capture){if(event.type==="start")return capture.message&&{type:"start",seed:{message:capture.message}};if(event.type==="done")return{type:"done",reason:event.reason,message:event.message};if(event.type==="error")return{type:"error",reason:event.reason,error:event.error};let contentIndex=capture.contentIndex??event.contentIndex;if(event.type==="text_delta"||event.type==="thinking_delta"||event.type==="toolcall_delta"){let{offset,parsedThrough:parsedThrough2}=capture;return offset===void 0?void 0:event.type!=="toolcall_delta"?{type:event.type,contentIndex,delta:event.delta,offset}:parsedThrough2===void 0?void 0:{type:event.type,contentIndex,delta:event.delta,offset,parsedThrough:parsedThrough2}}let{block,coveredCodeUnits}=capture;if(event.type==="toolcall_end")return block?.type==="toolCall"?{type:event.type,contentIndex,toolCall:block}:void 0;if(event.type==="text_end")return block?.type==="text"?{type:event.type,contentIndex,content:event.content,block}:void 0;if(event.type==="thinking_end")return block?.type==="thinking"?{type:event.type,contentIndex,content:event.content,block}:void 0;if(coveredCodeUnits===void 0)return;let seedLength=block?.type==="text"?block.text.length:block?.type==="thinking"?block.thinking.length:capture.rawArgumentPrefix?.length??0,nextOffset=seedNextOffset(capture.nextOffset,seedLength);if(event.type==="text_start")return block?.type==="text"?{type:event.type,contentIndex,seed:{block,coveredCodeUnits,nextOffset}}:void 0;if(event.type==="thinking_start")return block?.type==="thinking"?{type:event.type,contentIndex,seed:{block,coveredCodeUnits,nextOffset}}:void 0;let{rawArgumentPrefix,parsedThrough}=capture;if(!(block?.type!=="toolCall"||rawArgumentPrefix===void 0||parsedThrough===void 0))return{type:event.type,contentIndex,id:block.id,toolName:block.name,seed:{block,rawArgumentPrefix,parsedThrough,coveredCodeUnits,nextOffset}}}function toSeededJsonEvent(event){if((event.type==="message_start"||event.type==="message_end")&&event.message.role==="assistant"){let message=getAssistantCapture(event)?.message;return message?{...event,message}:event.type==="message_end"?event:void 0}if(event.type!=="message_update")return event;let capture=getAssistantCapture(event),assistantMessageEvent=capture&&toSeededAssistantEvent(event.assistantMessageEvent,capture);if(!capture||!assistantMessageEvent)return;let{message:_message,assistantMessageEvent:_event,...outer}=event,changed=capture.metadata!==void 0&&Object.keys(capture.metadata).length>0;return{...outer,usage:capture.usage,...changed?{messageMetadata:capture.metadata}:{},assistantMessageEvent}}function toJsonEvent(event,options){if(options)return toSeededJsonEvent(event);if(event.type!=="message_update")return event;if(event.message.role!=="assistant")throw new Error("message_update message is not an assistant message");return{type:"message_update",usage:event.message.usage,assistantMessageEvent:toJsonAssistantMessageEvent(event.assistantMessageEvent),...event.resolvedToolName===void 0?{}:{resolvedToolName:event.resolvedToolName}}}import{realpathSync as realpathSync2,statSync as statSync2}from"node:fs";import{homedir as homedir2}from"node:os";import{isAbsolute,join as join2,resolve as resolve2,win32}from"node:path";import{existsSync,realpathSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join,resolve}from"node:path";var PROJECT_MARKERS=[".git","pnpm-workspace.yaml","package.json","pyproject.toml","Cargo.toml","go.mod",".venv"],PROJECT_RULE_SUBDIRS=[[".pi","rules"],[".omo","rules"],[".claude","rules"],[".cursor","rules"],[".github","instructions"]],PROJECT_SINGLE_FILES=[".github/copilot-instructions.md","AGENTS.md","CLAUDE.md","CONTEXT.md"],USER_HOME_RULE_SUBDIRS=[".pi/rules",".omo/rules",".opencode/rules",".claude/rules"],USER_HOME_SINGLE_FILES=[".config/opencode/AGENTS.md",".claude/CLAUDE.md"],RULE_FILE_EXTENSIONS=[".md",".mdc"],SOURCE_PRIORITY=new Map([[".pi/rules",0],[".omo/rules",1],[".claude/rules",2],[".cursor/rules",3],[".github/instructions",4],[".github/copilot-instructions.md",5],["AGENTS.md",6],["CLAUDE.md",7],["CONTEXT.md",8],["~/.pi/rules",100],["~/.omo/rules",101],["~/.opencode/rules",102],["~/.claude/rules",103],["~/.config/opencode/AGENTS.md",104],["~/.claude/CLAUDE.md",105]]),GLOBAL_DISTANCE=9999,DEFAULT_MAX_RULE_CHARS=12e3,DEFAULT_MAX_RESULT_CHARS=4e4,TRUNCATION_NOTICE=`
|
|
3
3
|
|
|
4
4
|
[Rule truncated. Read full rule: {path}]`,TRACKED_BUILTIN_TOOLS=["read","edit","write"],TRACKED_BUILTIN_TOOL_SET=new Set(TRACKED_BUILTIN_TOOLS),PROJECT_RULES_START_MARKER="<project_rules>",PROJECT_RULES_END_MARKER="</project_rules>",PROJECT_RULES_HEADING="## Project Instructions",PROJECT_RULES_REGION_START_MARKER="<!--senpi:project-rules:1:start-->",PROJECT_RULES_REGION_END_MARKER="<!--senpi:project-rules:1:end-->",SCANNER_EXCLUDED_DIRS=["node_modules",".git","dist","build",".turbo",".next","coverage"];function findProjectRoot(startPath,markers=PROJECT_MARKERS){let normalizedStartPath=resolve(startPath);if(!existsSync(normalizedStartPath))return null;let resolvedStartPath;try{resolvedStartPath=realpathSync.native(normalizedStartPath)}catch{return null}let currentDirectory;try{currentDirectory=statSync(resolvedStartPath).isDirectory()?resolvedStartPath:dirname(resolvedStartPath)}catch{return null}let filesystemRoot=resolve("/");for(;;){for(let marker of markers)if(existsSync(join(currentDirectory,marker)))return currentDirectory;if(currentDirectory===filesystemRoot)return null;let parentDirectory=dirname(currentDirectory);if(parentDirectory===currentDirectory)return null;currentDirectory=parentDirectory}}function widenToRepositoryRoot(projectRoot2){if(projectRoot2===null)return null;let repositoryFilesystemRoot=resolve("/"),homeDirectory=resolveExistingPath(homedir()),currentDirectory=resolveExistingPath(projectRoot2);for(;;){if(currentDirectory===homeDirectory)return projectRoot2;if(existsSync(join(currentDirectory,".git")))return currentDirectory;if(currentDirectory===repositoryFilesystemRoot)return projectRoot2;let parentDirectory=dirname(currentDirectory);if(parentDirectory===currentDirectory)return projectRoot2;currentDirectory=parentDirectory}}function resolveExistingPath(path16){try{return realpathSync.native(resolve(path16))}catch{return resolve(path16)}}function isLocalMessagePath(path16,platform4=process.platform){return path16.includes("\0")?!1:platform4==="win32"?/^[A-Za-z]:[\\/]/.test(path16):isAbsolute(path16)&&!path16.startsWith("//")}function messagePathProjectRoot(cwd){let home=resolve2(homedir2()),candidate=findProjectRoot(cwd,[".git"])??findProjectRoot(cwd)??void 0;return candidate===void 0||resolve2(candidate)===home?void 0:candidate}function existing(candidate){try{let realpath4=realpathSync2.native(candidate),stats=statSync2(realpath4);return stats.isFile()?{realpath:realpath4,kind:"file"}:stats.isDirectory()?{realpath:realpath4,kind:"directory"}:void 0}catch{return}}function expandHome(path16){return path16==="~"?homedir2():path16.startsWith("~/")||path16.startsWith("~\\")?join2(homedir2(),path16.slice(2)):path16}function resolveMessagePath(input){let platform4=input.platform??process.platform,pathApi=platform4==="win32"?win32:{isAbsolute,resolve:resolve2},path16=expandHome(input.path.trim());if(path16.length===0||path16.includes("\0"))return{status:"not_found",tried:[]};let bases=pathApi.isAbsolute(path16)?[["absolute",path16]]:[["cwd",pathApi.resolve(input.cwd,path16)],...input.projectRoot!==void 0&&pathApi.resolve(input.projectRoot)!==pathApi.resolve(input.cwd)?[["project-root",pathApi.resolve(input.projectRoot,path16)]]:[]],local=bases.filter(([,candidate])=>isLocalMessagePath(candidate,platform4));if(local.length!==bases.length)return{status:"not_found",tried:[]};for(let[base,candidate]of local){let found=existing(candidate);if(found!==void 0&&isLocalMessagePath(found.realpath,platform4))return{status:"found",...found,base}}return{status:"not_found",tried:local.map(([,candidate])=>candidate)}}async function apiKeyLoginCredential(provider,key,region){if(region===void 0)return{type:"api_key",key};let login=provider?.auth.apiKey?.login;if(provider===void 0||login===void 0)throw new Error(`${provider?.name??"This provider"} does not take a region for its API key.`);let regionAsked=!1,answer3=async prompt=>{if(prompt.type==="secret")return key;if(prompt.type==="select"&&!regionAsked){if(!prompt.options.some(option=>option.id===region))throw new Error(`Unknown region "${region}" for ${provider.name}.`);return regionAsked=!0,region}throw new Error(`${provider.name} asked for more than a key and a region.`)},credential=await login({signal:AbortSignal.timeout(15e3),prompt:answer3,notify:()=>{}});if(!regionAsked){if(credential.env===void 0)throw new Error(`${provider.name} does not take a region for its API key.`);if(!Object.values(credential.env).includes(region))throw new Error(`This host's environment sets the ${provider.name} region, so "${region}" cannot be chosen here.`)}return{...credential,type:"api_key",key}}import{randomUUID}from"node:crypto";var ExtensionOwnerLifetime=class{constructor(isClassic,source2,onRetireBinding){this.generation=randomUUID(),this.captures=new Set,this.source=source2,this.onRetireBinding=onRetireBinding,this.classic=isClassic&&source2===void 0?new ExtensionTransportOwner:void 0}capture(){let owner=this.source===void 0?this.classic?.capture(this.generation):this.source();return owner&&this.captures.add(owner),owner}retireBinding(){let hadCaptures=this.captures.size>0;for(let owner of this.captures)owner.retire();this.captures.clear(),this.generation=randomUUID(),hadCaptures&&this.onRetireBinding?.()}dispose(){this.retireBinding(),this.classic?.retire()}};import*as crypto2 from"node:crypto";import{basename as basename38,dirname as dirname69,extname as extname6}from"node:path";var BUILT_IN_PROVIDER_DISPLAY_NAMES={anthropic:"Anthropic","anthropic-subscription":"Anthropic Subscription","amazon-bedrock":"Amazon Bedrock","ant-ling":"Ant Ling","azure-openai-responses":"Azure OpenAI Responses",cerebras:"Cerebras","cloudflare-ai-gateway":"Cloudflare AI Gateway","cloudflare-workers-ai":"Cloudflare Workers AI",cursor:"Cursor","cursor-cli-oauth":"Cursor CLI (OAuth)",deepseek:"DeepSeek",fireworks:"Fireworks",google:"Google Gemini","google-vertex":"Google Vertex AI",groq:"Groq",huggingface:"Hugging Face","kimi-coding":"Kimi For Coding",minimax:"MiniMax","minimax-cn":"MiniMax (China)",moonshotai:"Moonshot AI","moonshotai-cn":"Moonshot AI (China)",nvidia:"NVIDIA NIM",opencode:"OpenCode Zen","opencode-go":"OpenCode Go",openai:"OpenAI","chatgpt-subscription":"ChatGPT Subscription",opengateway:"OpenGateway",ollama:"Ollama Cloud",openrouter:"OpenRouter",together:"Together AI",venice:"Venice AI","vercel-ai-gateway":"Vercel AI Gateway",xai:"xAI",zai:"ZAI Coding Plan (Global)","zai-coding-cn":"ZAI Coding Plan (China)",xiaomi:"Xiaomi MiMo","xiaomi-token-plan-cn":"Xiaomi MiMo Token Plan (China)","xiaomi-token-plan-ams":"Xiaomi MiMo Token Plan (Amsterdam)","xiaomi-token-plan-sgp":"Xiaomi MiMo Token Plan (Singapore)","alibaba-token-plan":"Alibaba Token Plan"};var BUILT_IN_MODEL_PROVIDERS=new Set(getProviders());function isApiKeyLoginProvider(providerId,oauthProviderIds,builtInProviderIds=BUILT_IN_MODEL_PROVIDERS){return BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]?!0:builtInProviderIds.has(providerId)?!1:!oauthProviderIds.has(providerId)}function buildLoginProviderInfos(modelRegistry,authType){let oauthProviders=modelRegistry.authStorage.getOAuthProviders(),oauthProviderIds=new Set(oauthProviders.map(provider=>provider.id)),options=oauthProviders.map(provider=>({id:provider.id,name:provider.name,authType:"oauth"})),modelProviders=new Set(modelRegistry.getAll().map(model=>model.provider));for(let providerId of modelProviders)isApiKeyLoginProvider(providerId,oauthProviderIds)&&options.push({id:providerId,name:modelRegistry.getProviderDisplayName(providerId),authType:"api_key"});return(authType?options.filter(option=>option.authType===authType):options).sort((a,b)=>a.name.localeCompare(b.name))}function authMethodStatus(modelRegistry,info){if(modelRegistry.authStorage.get(info.id)?.type===info.authType)return{configured:!0,source:"stored"};let{status,signIn}=modelRegistry.resolveProviderAuth(info.id);return!status.configured||status.source==="stored"?{configured:!1}:(signIn?"oauth":"api_key")===info.authType?status:{configured:!1}}function loginRowStatus(modelRegistry,provider,authType){for(let type2 of[authType,authType==="oauth"?"api_key":"oauth"]){let status=authMethodStatus(modelRegistry,{...provider,authType:type2});if(!status.configured)continue;let source2=status.label??status.source;return source2===void 0?{type:type2}:{type:type2,source:source2}}}function storedOrder(credential){return credential?.order??[]}async function listCredentialAccounts(storage,provider,env=process.env,repository){let accounts=await getCredentialAccounts(storage,provider,env,repository),order=storedOrder(storage.get(provider));return{accounts,ordered:accounts.some(account=>order.includes(account.name))}}function assertOrderNames(names,known){if(names.length===0)throw new Error("Account order must name at least one account");let seen=new Set;for(let name of names){if(assertValidAccountName2(name),seen.has(name))throw new Error(`Duplicate provider account in order: ${name}`);if(seen.add(name),!known.some(account=>account.name===name))throw new Error(`Provider account not found: ${name}`)}}function withOrder(credential,names){let{order:_previous,...rest}=credential;return names===null?rest:{...rest,order:[...names]}}async function orderCredentialAccounts(storage,provider,names,env=process.env,repository){let repo=repository??credentialPoolRepository(storage);await storage.modify(provider,async current=>{if(current===void 0)throw new Error(`No stored credential for provider: ${provider}`);return names!==null&&assertOrderNames(names,await summarizeCredentialAccounts(provider,current,env,repo)),withOrder(current,names)}),emitProviderAccountsChanged(provider)}var EDIT_CODES={empty:"empty","not-assistant":"not_assistant","not-found":"not_found","stale-leaf":"stale_leaf"},AssistantEditError=class extends Error{constructor(reason,message){super(message),this.name="AssistantEditError",this.reason=reason}get code(){return EDIT_CODES[this.reason]}},SessionStreamingError=class extends Error{constructor(){super("Wait for the current response to finish before navigating the session tree."),this.code="streaming",this.name="SessionStreamingError"}};function assertExpectedLeaf(expectedLeafId,currentLeafId){if(!(expectedLeafId===void 0||expectedLeafId===currentLeafId))throw new AssistantEditError("stale-leaf",`Session leaf moved (expected ${expectedLeafId}, now ${currentLeafId??"root"})`)}function assistantTextEquals(original,text4){return contentText(original.content,"").trim()===text4.trim()}function buildEditedAssistantMessage(original,text4){let trimmed=text4.trim();if(trimmed.length===0)throw new AssistantEditError("empty","Edited assistant response cannot be empty");return{role:"assistant",content:[{type:"text",text:trimmed}],api:original.api,provider:original.provider,model:original.model,...original.responseModel!==void 0?{responseModel:original.responseModel}:{},usage:original.usage,stopReason:"stop",timestamp:Date.now()}}var EDIT_CODES2={empty:"empty","not-user":"not_user","not-found":"not_found","stale-leaf":"stale_leaf"},UserEditError=class extends Error{constructor(reason,message){super(message),this.name="UserEditError",this.reason=reason}get code(){return EDIT_CODES2[this.reason]}};function assertExpectedUserLeaf(expectedLeafId,currentLeafId){if(!(expectedLeafId===void 0||expectedLeafId===currentLeafId))throw new UserEditError("stale-leaf",`Session leaf moved (expected ${expectedLeafId}, now ${currentLeafId??"root"})`)}function userTextEquals(original,text4){return contentText(original.content,"").trim()===text4.trim()}function buildEditedUserMessage(original,text4){let trimmed=text4.trim();if(trimmed.length===0)throw new UserEditError("empty","Edited user message cannot be empty");let attachments=Array.isArray(original.content)?original.content.filter(block=>block.type!=="text"):[];return{role:"user",content:[{type:"text",text:trimmed},...attachments],timestamp:Date.now()}}var CODEX_FAMILY=/^x-([a-z0-9-]+)-(?:primary|secondary)-used-percent$/;function number(value){if(value===void 0||value.trim()==="")return;let parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}function iso(epochSeconds){return epochSeconds===void 0?void 0:new Date(epochSeconds*1e3).toISOString()}function windowLabel(minutes,fallback){return minutes===void 0||minutes<=0?fallback:minutes%1440===0?`${minutes/1440}d`:minutes%60===0?`${minutes/60}h`:`${minutes}m`}function lower(headers){return new Map(Object.entries(headers).map(([name,value])=>[name.toLowerCase(),value]))}function codexWindow(headers,family,slot){let used=number(headers.get(`x-${family}-${slot}-used-percent`));if(used===void 0)return;let minutes=number(headers.get(`x-${family}-${slot}-window-minutes`)),resetAt=number(headers.get(`x-${family}-${slot}-reset-at`));if(used===0&&(minutes??0)===0&&resetAt===void 0)return;let limit=family.replace(/-/g,"_"),resetsAt=iso(resetAt);return{id:`${limit}:${slot}`,label:limit==="codex"?windowLabel(minutes,slot):`${windowLabel(minutes,slot)} ${limit}`,...minutes===void 0?{}:{windowMinutes:minutes},usedPercent:used,...resetsAt===void 0?{}:{resetsAt}}}function codexWindowsFromHeaders(raw){let headers=lower(raw),families=new Set;for(let name of headers.keys()){let family=CODEX_FAMILY.exec(name)?.[1];family!==void 0&&families.add(family)}return[...families].sort().flatMap(family=>["primary","secondary"].flatMap(slot=>codexWindow(headers,family,slot)??[]))}var CLAUDE_WINDOWS=[{key:"5h",minutes:300},{key:"7d",minutes:10080}];function claudeWindowsFromHeaders(raw){let headers=lower(raw);return CLAUDE_WINDOWS.flatMap(({key,minutes})=>{let utilization=number(headers.get(`anthropic-ratelimit-unified-${key}-utilization`));if(utilization===void 0)return[];let resetsAt=iso(number(headers.get(`anthropic-ratelimit-unified-${key}-reset`)));return[{id:`claude:${key}`,label:key,windowMinutes:minutes,usedPercent:Math.round(utilization*1e4)/100,...resetsAt===void 0?{}:{resetsAt}}]})}var SDK_WINDOWS={five_hour:{id:"claude:5h",label:"5h",minutes:300},seven_day:{id:"claude:7d",label:"7d",minutes:10080},seven_day_opus:{id:"claude:7d_opus",label:"7d opus",minutes:10080},seven_day_sonnet:{id:"claude:7d_sonnet",label:"7d sonnet",minutes:10080}};function claudeWindowsFromSdkEvent(data){if(typeof data!="object"||data===null||!("type"in data)||data.type!=="rate_limit_event")return[];let info=data.rate_limit_info,window=typeof info?.rateLimitType=="string"?SDK_WINDOWS[info.rateLimitType]:void 0;if(window===void 0||typeof info?.utilization!="number")return[];let resetsAt=iso(typeof info.resetsAt=="number"?info.resetsAt:void 0);return[{id:window.id,label:window.label,windowMinutes:window.minutes,usedPercent:Math.round(info.utilization*1e4)/100,...resetsAt===void 0?{}:{resetsAt}}]}var SubscriptionLimitStore=class{#accounts=new Map;#listeners=new Set;#mirrorListeners=new Set;record(provider,account,windows,now2=new Date){if(windows.length===0)return;let key=`${provider}\0${account}`,previous=this.#accounts.get(key),merged=new Map((previous?.windows??[]).map(window=>[window.id,window]));for(let window of windows)merged.set(window.id,window);this.#write(key,previous,{provider,account,windows:[...merged.values()],reportedAt:now2.toISOString(),...previous?.plan===void 0?{}:{plan:previous.plan}})}report(provider,account,report){let key=`${provider}\0${account}`,previous=this.#accounts.get(key),reportedAt=report.reportedAt.toISOString();if(!(previous!==void 0&&reportedAt<changedAtOf(previous))){if("error"in report){if(previous?.error===report.error)return;let{updatedAt:_changedAt,revision:_revision,...base}=previous??{provider,account,windows:[],reportedAt};this.#write(key,previous,{...base,error:report.error},reportedAt);return}report.windows.length===0&&previous===void 0||this.#write(key,previous,{provider,account,windows:[...report.windows],reportedAt,...report.plan===void 0?{}:{plan:report.plan}})}}adopt(limits){this.#offer(`${limits.provider}\0${limits.account}`,limits)}#write(key,previous,limits,changedAt=limits.reportedAt){let held=previous===void 0?void 0:changedAtOf(previous),later=held===void 0||changedAt>held,time2=later?changedAt:held,revision=later?0:(previous?.revision??0)+1;this.#publish(key,{...limits,...time2===limits.reportedAt?{}:{updatedAt:time2},...revision===0?{}:{revision}})}#offer(key,limits){let previous=this.#accounts.get(key);if(previous===void 0){this.#publish(key,limits);return}if(canonical(limits)!==canonical(previous)){if(changedAtOf(limits)===changedAtOf(previous)&&(limits.revision??0)===(previous.revision??0)){let combined=combineConcurrent(previous,limits);canonical(combined)!==canonical(previous)&&this.#publish(key,combined);return}compareRecords(limits,previous)<=0||this.#publish(key,limits)}}#publish(key,limits){this.#accounts.set(key,limits);let shown=publicShape(limits),calls=[...[...this.#mirrorListeners].map(listener=>()=>listener(limits)),...[...this.#listeners].map(listener=>()=>listener(shown))];for(let call of calls)try{call()}catch(error2){process.stderr.write(`senpi subscription limits: a listener failed: ${String(error2)}
|
|
5
5
|
`)}}snapshot(){return[...this.#accounts.values()].map(publicShape)}mirrorSnapshot(){return[...this.#accounts.values()]}subscribe(listener){return this.#listeners.add(listener),()=>this.#listeners.delete(listener)}subscribeMirror(listener){return this.#mirrorListeners.add(listener),()=>this.#mirrorListeners.delete(listener)}};function changedAtOf(limits){return limits.updatedAt??limits.reportedAt}function compareRecords(a,b){let[first,second]=[changedAtOf(a),changedAtOf(b)];if(first!==second)return first<second?-1:1;let[firstRevision,secondRevision]=[a.revision??0,b.revision??0];if(firstRevision!==secondRevision)return firstRevision<secondRevision?-1:1;let[left,right]=[canonical(a),canonical(b)];return left<right?-1:left>right?1:0}function combineConcurrent(a,b){let later=(x,y)=>x===void 0?y:y===void 0||canonical(x)>=canonical(y)?x:y;if(a.reportedAt!==b.reportedAt){let newer=a.reportedAt<b.reportedAt?b:a;return concurrentRecord(a,newer.windows,newer.plan,later(a.error,b.error),newer.reportedAt)}let windows=new Map(a.windows.map(window=>[window.id,window]));for(let window of b.windows)windows.set(window.id,later(windows.get(window.id),window)??window);return concurrentRecord(a,[...windows.values()],later(a.plan,b.plan),later(a.error,b.error),a.reportedAt)}function concurrentRecord(a,windows,plan,error2,reportedAt){let updatedAt=changedAtOf(a);return{provider:a.provider,account:a.account,windows:[...windows].sort((x,y)=>x.id<y.id?-1:x.id>y.id?1:0),reportedAt,...plan===void 0?{}:{plan},...error2===void 0?{}:{error:error2},...updatedAt===reportedAt?{}:{updatedAt},...a.revision===void 0||a.revision===0?{}:{revision:a.revision}}}function publicShape({updatedAt:_changedAt,revision:_revision,...limits}){return limits}function canonical(value){return JSON.stringify(value,(_key,field3)=>field3!==null&&typeof field3=="object"&&!Array.isArray(field3)?Object.fromEntries(Object.entries(field3).sort(([a],[b])=>a<b?-1:a>b?1:0)):field3)}var subscriptionLimits=new SubscriptionLimitStore;function limitAccountOf(slotAuth){return slotAuth?.slotName!==void 0?slotAuth.slotName:slotAuth?.apiKey!==void 0?"env":"default"}function withLimitCapture(options,provider,account,store=subscriptionLimits){let inner=options.onResponse;return{...options,onResponse:(response,model)=>(store.record(provider,account,[...codexWindowsFromHeaders(response.headers),...claudeWindowsFromHeaders(response.headers)]),inner?.(response,model))}}var PROVIDER="anthropic-subscription",HOUR_MS=3600*1e3,CLAUDE_USAGE_LIMIT=/^(?:You['\u2019]ve|You have) (?:hit|reached) your (?:(session|weekly|daily|monthly|\d+-hour|usage) )?limit(?=$|\s*[\u00b7\u2219.,{(]|\s+resets?\b)|^Claude AI usage limit reached\b/i,TERMINAL_LIMIT_REASON=/\bblocking_limit\b/,NAMED_STATUS=/\b(?:HTTP|status(?: code)?)\s*(\d{3})\b/i,WINDOW_MS={session:5*HOUR_MS,daily:24*HOUR_MS,weekly:168*HOUR_MS,monthly:744*HOUR_MS},UNNAMED_WINDOW_MS=5*HOUR_MS;function namedWindowMs(word){if(word===void 0)return;let lower2=word.toLowerCase(),hours=/^(\d+)-hour$/.exec(lower2);return hours?Number(hours[1])*HOUR_MS:WINDOW_MS[lower2]}function spentWindow(accountName2,now2){let limits=subscriptionLimits.snapshot().find(entry2=>entry2.provider===PROVIDER&&entry2.account===accountName2),spent;for(let window of limits?.windows??[]){if(window.usedPercent<100||window.resetsAt===void 0)continue;let resetsAt=Date.parse(window.resetsAt);!Number.isFinite(resetsAt)||resetsAt<=now2||(spent===void 0||resetsAt-now2>spent.resetMs)&&(spent={resetMs:resetsAt-now2,windowMs:window.windowMinutes===void 0?void 0:window.windowMinutes*6e4})}return spent}function isConfirmedAccountUsageLimit(text4){let trimmed=text4.trim();if(!CLAUDE_USAGE_LIMIT.test(trimmed)&&!TERMINAL_LIMIT_REASON.test(trimmed))return!1;let status=NAMED_STATUS.exec(trimmed)?.[1];return status===void 0||status==="429"}function usageLimitBlockMs(text4,accountName2,now2){let trimmed=text4.trim();if(!isConfirmedAccountUsageLimit(trimmed))return;let shape=CLAUDE_USAGE_LIMIT.exec(trimmed),window=spentWindow(accountName2,now2),parsed=usageLimitResetMs(trimmed,now2),resetMs=parsed!==void 0&&parsed>0?parsed:window?.resetMs;if(resetMs===void 0)return;let capMs=namedWindowMs(shape?.[1])??window?.windowMs??UNNAMED_WINDOW_MS;return Math.min(resetMs,capMs)}var MAX_RATE_LIMIT_BLOCK_MS=2880*60*1e3,DEFAULT_RATE_LIMIT_BLOCK_MS=6e4,TRANSIENT_RETRIES_PER_TURN=2,TRANSIENT_RETRY_DELAY_MS=1e3,TURN_RETRY_SUPPRESSION_PREFIX2="senpi:no-turn-retry:",sessionBlocks=new Map;function isSharedVerdict(classification,error2){return classification.kind==="auth_error"||classification.kind==="billing"||classification.kind==="org_not_allowed"?!0:classification.kind==="rate_limit"&&classification.modelFamily===void 0&&isConfirmedAccountUsageLimit(errorText(error2))}function rememberSessionBlock(sessionKey,account){if(sessionKey===void 0)return;let blocks=sessionBlocks.get(sessionKey)??new Map;blocks.set(account.name,{blockedUntil:account.blockedUntil,blockReason:account.blockReason,blockedAt:account.blockedAt,modelBlocks:account.modelBlocks}),sessionBlocks.set(sessionKey,blocks)}function pruneSessionBlocks(now2){for(let[sessionKey,blocks]of sessionBlocks){for(let[name,block]of blocks)(block.blockedUntil??0)<=now2&&pruneModelBlocks(block.modelBlocks,now2)===void 0&&blocks.delete(name);blocks.size===0&&sessionBlocks.delete(sessionKey)}}function withSessionBlocks(accounts,sessionKey,now2){pruneSessionBlocks(now2);let blocks=sessionKey===void 0?void 0:sessionBlocks.get(sessionKey);return blocks===void 0?[...accounts]:accounts.map(account=>{let own=blocks.get(account.name);if(own===void 0)return account;let later=(own.blockedUntil??0)>(account.blockedUntil??0);return{...account,...later?{blockedUntil:own.blockedUntil,blockReason:own.blockReason,blockedAt:own.blockedAt}:{},modelBlocks:mergeModelBlocks(account.modelBlocks,own.modelBlocks,0)}})}function forgetSessionBlock(sessionKey,name){if(sessionKey===void 0)return;let blocks=sessionBlocks.get(sessionKey);blocks?.delete(name)&&blocks.size===0&&sessionBlocks.delete(sessionKey)}function forgetSessionBlocksFor(name){let lifted=!1;for(let[sessionKey,blocks]of[...sessionBlocks])blocks.has(name)&&(lifted=!0,forgetSessionBlock(sessionKey,name));return lifted}var ClassifiedSdkError=class extends Error{constructor(classification,original,suppressTurnRetry){let detail=original instanceof Error?original.message:String(original);super(`${suppressTurnRetry?TURN_RETRY_SUPPRESSION_PREFIX2:""}${detail}`),this.name="ClassifiedSdkError",this.classification=classification,this.original=original,this.suppressTurnRetry=suppressTurnRetry}};function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:void 0}function defaultErrorFromEvent(event){let value=record(event);return value?.type==="error"?value.error:void 0}function defaultIsVisibleDelta(event){let value=record(event);return typeof value?.type!="string"?!1:/^(?:text|thinking|toolcall)_(?:start|delta|end)$/.test(value.type)}function errorText(error2){if(typeof error2=="string")return error2;if(error2 instanceof Error)return error2.message;let value=record(error2);return typeof value?.message=="string"?value.message:String(error2)}function retryAfterMs(error2){let explicit=record(error2)?.retryAfterMs;if(typeof explicit=="number"&&Number.isFinite(explicit)&&explicit>0)return Math.ceil(explicit);let text4=errorText(error2),milliseconds=text4.match(/\bretry[-_ ]?after[-_ ]?ms\s*[:=]\s*(\d+(?:\.\d+)?)/i);if(milliseconds)return Math.ceil(Number(milliseconds[1]));let seconds2=text4.match(/\bretry[-_ ]?after\s*[:=]\s*(\d+(?:\.\d+)?)/i);return seconds2?Math.ceil(Number(seconds2[1])*1e3):void 0}function blockedAccount(account,classification,now2,attempt2,baseBlockMs,error2,model){if(classification.kind==="auth_error")return{...account,blockedUntil:now2+9e5,blockReason:"auth_error",blockedAt:now2};let fallback=Math.min(MAX_RATE_LIMIT_BLOCK_MS,baseBlockMs*2**attempt2);if(classification.modelFamily!==void 0&&model!==void 0){let resetMs=retryAfterMs(error2)??usageLimitResetMs(errorText(error2),now2),duration2=Math.min(MAX_RATE_LIMIT_BLOCK_MS,resetMs!==void 0&&resetMs>0?resetMs:fallback),key=modelBlockKey(classification.modelFamily,model);return{...account,modelBlocks:withModelBlock(account.modelBlocks,key,now2+duration2,now2)}}let hinted=retryAfterMs(error2)??usageLimitBlockMs(errorText(error2),account.name,now2),duration=Math.min(MAX_RATE_LIMIT_BLOCK_MS,hinted??fallback);return{...account,blockedUntil:now2+duration,blockReason:classification.kind,blockedAt:now2}}async function clearBlockAfterSuccess(store,providerId,name,startedAt){let clearable=slot2=>slot2?.blockedUntil!==void 0&&slot2.blockReason!=="auth_error"&&(slot2.blockedAt??0)<=startedAt,stored=await store.read(providerId);if(stored?.type!=="oauth")return;let read2=stored,slot=read2.accounts?.find(account=>account.name===name)??read2.slotState?.[name];clearable(slot)&&await store.modify(providerId,async current=>{if(current?.type!=="oauth")return current;let credential=current,state3=credential.slotState?.[name],slotState=state3===void 0||!clearable(state3)?credential.slotState:{...credential.slotState,[name]:{...state3.modelBlocks?{modelBlocks:state3.modelBlocks}:{}}};return{...credential,...slotState===void 0?{}:{slotState},accounts:(credential.accounts??[]).map(account=>{if(account.name!==name||!clearable(account))return account;let{blockedUntil:_blockedUntil,blockReason:_blockReason,blockedAt:_blockedAt,...rest}=account;return rest})}})}function isTransient(classification){return classification.kind==="overloaded"||classification.kind==="other"}function abortableSleep(ms,signal){return new Promise((resolve56,reject)=>{if(signal?.aborted){reject(signal.reason);return}let timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve56()},ms),onAbort=()=>{clearTimeout(timer),reject(signal?.reason)};signal?.addEventListener("abort",onAbort,{once:!0})})}function replaceAccount(accounts,replacement){return accounts.map(account=>account.name===replacement.name?replacement:account)}async function persistBlock(store,providerId,account,now2){let signInMaterial=slot=>slot.dirId,superseded;return await store.modify(providerId,async current=>{if(current?.type!=="oauth")return current;let credential=current;if(account.source==="env")return{...credential,slotState:{...credential.slotState,[account.name]:{blockedUntil:account.blockedUntil,blockReason:account.blockReason,...account.blockedAt===void 0?{}:{blockedAt:account.blockedAt},modelBlocks:mergeModelBlocks(credential.slotState?.[account.name]?.modelBlocks,account.modelBlocks,now2)}}};let stored=(credential.accounts??[]).find(existing2=>existing2.name===account.name);if(account.blockReason==="auth_error"&&stored!==void 0&&signInMaterial(stored)!==signInMaterial(account))return superseded=stored,current;let accounts=(credential.accounts??[]).map(existing2=>existing2.name===account.name?{...existing2,blockedUntil:account.blockedUntil,blockReason:account.blockReason,...account.blockedAt===void 0?{}:{blockedAt:account.blockedAt},modelBlocks:mergeModelBlocks(existing2.modelBlocks,account.modelBlocks,now2)}:existing2);return{...credential,accounts}}),superseded}function usable(account,now2,model){return account.blockReason===void 0&&(account.blockedUntil===void 0||account.blockedUntil<=now2)&&activeModelBlockUntil(account.modelBlocks,model,now2)===void 0}async function*runFailover(options){let now2=options.now??Date.now,baseBlockMs=options.baseBlockMs??DEFAULT_RATE_LIMIT_BLOCK_MS,accounts=clearExpiredBlocks(withSessionBlocks(options.accounts,options.sessionKey,now2()),now2()),attemptLimit=options.accountFallback===!1?Math.min(accounts.length,1):accounts.length,lastError,retriedOnStoredMaterial=new Set,transientRetriesUsed=0,longContextRetried=!1,retryAccountName;for(let attempt2=0;attempt2<attemptLimit;attempt2++){let retrySlot=retryAccountName===void 0?void 0:accounts.find(slot=>slot.name===retryAccountName);retryAccountName=void 0;let account={...retrySlot??options.selectFn(accounts)},visibleDeltaEmitted=!1,completed=!1,startedAt=now2();try{let attemptStream=await options.runAttempt(account);for await(let event of attemptStream){let failure2=(options.errorFromEvent??defaultErrorFromEvent)(event);if(failure2!==void 0)throw failure2;visibleDeltaEmitted||=(options.isVisibleDelta??defaultIsVisibleDelta)(event),yield event}completed=!0}catch(error2){let classification=options.classify(error2),classified=new ClassifiedSdkError(classification,error2,visibleDeltaEmitted);if(lastError=classified,!classification.retryable)throw classified;if(classification.kind==="long_context_unavailable"){if(visibleDeltaEmitted||longContextRetried)throw classified;longContextRetried=!0,options.onLongContextRefused?.(),retryAccountName=account.name,attempt2--;continue}if(isTransient(classification)){if(visibleDeltaEmitted||transientRetriesUsed>=TRANSIENT_RETRIES_PER_TURN)throw classified;let delayMs=TRANSIENT_RETRY_DELAY_MS*2**transientRetriesUsed;transientRetriesUsed+=1;try{await(options.sleep??abortableSleep)(delayMs,options.signal)}catch{throw classified}retryAccountName=account.name,attempt2--;continue}let blocked=blockedAccount(account,classification,now2(),attempt2,baseBlockMs,error2,options.model),persists=options.persistBlocks!==!1,shared2=isSharedVerdict(classification,error2)||options.sessionKey===void 0;persists&&!shared2&&rememberSessionBlock(options.sessionKey,blocked);let superseded=persists&&shared2?await persistBlock(options.store,options.providerId,blocked,now2()):void 0;if(superseded&&!visibleDeltaEmitted&&usable(superseded,now2(),options.model)&&!retriedOnStoredMaterial.has(account.name)){retriedOnStoredMaterial.add(account.name),accounts=replaceAccount(accounts,superseded),attempt2--;continue}accounts=replaceAccount(accounts,blocked);let event={account:blocked,classification,attempt:attempt2+1,visibleDeltaEmitted};try{!visibleDeltaEmitted&&attempt2+1<attemptLimit&&(event.nextAccount=options.selectFn(accounts))}finally{await options.onFailover?.(event)}if(visibleDeltaEmitted)throw classified}if(completed){if(options.persistBlocks===!1)return;forgetSessionBlock(options.sessionKey,account.name),await clearBlockAfterSuccess(options.store,options.providerId,account.name,startedAt).catch(error2=>{process.stderr.write(`senpi anthropic-subscription: could not clear a stored block on ${account.name}: ${error2 instanceof Error?error2.message:String(error2)}
|
|
@@ -2163,13 +2163,13 @@ Press any key to continue...`)),await new Promise(resolve56=>{process.stdin.setR
|
|
|
2163
2163
|
`)}await rebindSession(),initialMessage&&await session.prompt(initialMessage,{images:initialImages,sessionTitlePrompt:!1});for(let message of messages)await session.prompt(message,{sessionTitlePrompt:!1});await session.waitForSettledSessionWork();let lastMessage=session.state.messages.findLast(message=>message.role==="assistant"),failed=lastMessage?.role==="assistant"&&(lastMessage.stopReason==="error"||lastMessage.stopReason==="aborted"),exitCode=failed?1:0;if(mode==="text"&&lastMessage?.role==="assistant"){let assistantMsg=lastMessage;if(failed){let described=assistantMsg.errorCause?.type==="usage_limit"&&assistantMsg.errorCause.scope==="account"?assistantMsg.errorMessage:describeProviderFailureForUser(assistantMsg.errorMessage,{model:`${assistantMsg.provider}/${assistantMsg.model}`,usageLimit:usageLimitScope(assistantMsg)});console.error(described??(stripTurnRetrySuppressionPrefix(assistantMsg.errorMessage??"")||`Request ${assistantMsg.stopReason}`))}else for(let content of assistantMsg.content)content.type==="text"?writeRawStdout(`${content.text}
|
|
2164
2164
|
`):content.type==="providerNative"&&(writeRawStdout(`${formatProviderNativeSummary(assistantMsg,content,!1)}
|
|
2165
2165
|
`),writeRawStdout(`${formatProviderNativeBody(content,!1)}
|
|
2166
|
-
`))}return exitCode}catch(error2){return console.error(error2 instanceof Error?error2.message:String(error2)),1}finally{for(let cleanup of signalCleanupHandlers)cleanup();await disposeRuntime(),await flushRawStdout()}}import{readdirSync as readdirSync18,readFileSync as readFileSync43}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform4){return platform4==="darwin"||platform4==="linux"?platform4:void 0}async function loadChildReaperSyscalls(platform4=process.platform){let supported=supportedPlatform(platform4);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry2 of readdirSync18("/proc")){let pid=Number(entry2);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync43(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat19=linuxStat(pid),tail=stat19?.slice(stat19.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat19=linuxStat(pid),open12=stat19?.indexOf("(")??-1,close=stat19?.lastIndexOf(")")??-1;return stat19===void 0||open12===-1||close<=open12?"":stat19.slice(open12+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS2=1e3,CHILD_REAPER_IDLE_TICK_MS=5e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS2,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now2=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now2()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now2(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now2();continue}now2()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)},get childCount(){return tracked.size}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count2])=>`${name} x${count2}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log});return scheduleChildReaper(reaper,config.tickMs)}function scheduleChildReaper(reaper,tickMs){let timer,arm=()=>{timer=setTimeout(()=>{reaper.tick(),timer!==void 0&&arm()},reaper.childCount>0?tickMs:Math.max(tickMs,CHILD_REAPER_IDLE_TICK_MS)),timer.unref()};return arm(),()=>{timer!==void 0&&clearTimeout(timer),timer=void 0}}var orphanSyscalls;async function collectOrphanedChildren(pids){if(pids.length===0)return[];orphanSyscalls??=loadChildReaperSyscalls();let syscalls=await orphanSyscalls;return syscalls===void 0?[]:pids.filter(pid=>Number.isInteger(pid)&&pid>0&&syscalls.isWaitable(pid)&&syscalls.reapExited(pid))}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}function completeCompactFactory(factory,prepare){return Object.assign(factory,{prepare,supportsCompact:()=>!0})}var INTERNAL_SUPERVISOR_ROUTE_FLAG="--internal-rpc-host-supervisor";async function dispatchInternalSupervisor(args){if(!args.includes(INTERNAL_SUPERVISOR_ROUTE_FLAG))return!1;let{findInternalSupervisorArgs,parseSupervisorArgs,runHostSupervisor}=await import("./host-lifecycle-VW73K4WA.js"),supervisorArgs=findInternalSupervisorArgs(args);if(!supervisorArgs)return!1;let launch=parseSupervisorArgs(supervisorArgs);return launch||(console.error("invalid internal RPC host supervisor arguments"),process.exit(2)),await runHostSupervisor(launch),!0}import{randomUUID as randomUUID17}from"node:crypto";import{copyFileSync as copyFileSync3,existsSync as existsSync44,mkdirSync as mkdirSync28,renameSync as renameSync16,rmSync as rmSync16}from"node:fs";import{basename as basename34,dirname as dirname66,join as join102,relative as relative21,resolve as resolve52,toNamespacedPath}from"node:path";var QUARANTINE_DIR_NAME=".pi-native-quarantine";function normalizePath3(path16){return toNamespacedPath(resolve52(path16))}function getQuarantineRoot(packageDir){let current=resolve52(packageDir);for(;;){if(basename34(current).toLowerCase()==="node_modules")return join102(current,QUARANTINE_DIR_NAME);let parent=dirname66(current);if(parent===current)return;current=parent}}function getLoadedSharedObjectsInPackageDir(packageDir){let sharedObjects=process.report.getReport().sharedObjects;if(!Array.isArray(sharedObjects))return[];let root=normalizePath3(packageDir).toLowerCase(),seen=new Set,loadedFiles=[];for(let value of sharedObjects){if(typeof value!="string")continue;let filePath=normalizePath3(value),comparisonPath=filePath.toLowerCase();getCwdRelativePath(comparisonPath,root)===void 0||seen.has(comparisonPath)||(seen.add(comparisonPath),loadedFiles.push(filePath))}return loadedFiles}function cleanupWindowsSelfUpdateQuarantine(packageDir){let quarantineRoot=getQuarantineRoot(packageDir);if(quarantineRoot)try{rmSync16(quarantineRoot,{recursive:!0,force:!0})}catch{}}function quarantineWindowsNativeDependencies(packageDir){let resolvedPackageDir=normalizePath3(packageDir),quarantineRoot=getQuarantineRoot(resolvedPackageDir);if(!quarantineRoot)return;let loadedFiles=getLoadedSharedObjectsInPackageDir(resolvedPackageDir);if(loadedFiles.length===0)return;let quarantineRunDir=join102(quarantineRoot,`${Date.now()}-${process.pid}-${randomUUID17()}`);for(let loadedFile of loadedFiles){if(!existsSync44(loadedFile))continue;let quarantinePath=join102(quarantineRunDir,relative21(resolvedPackageDir,loadedFile));mkdirSync28(dirname66(quarantinePath),{recursive:!0}),renameSync16(loadedFile,quarantinePath),copyFileSync3(quarantinePath,loadedFile)}}var EXTENSION_LOAD_FAILURE_HINT=`Hint: Start without extensions using "${APP_NAME} -ne".`;function collectAuthDiagnostics(authStorage,context,options){return[...authStorage.drainErrors().map(error2=>error2.message),...authStorage.takePendingNotices(options).map(notice2=>notice2.message)].map(message=>({type:"warning",message:`(${context}, auth storage) ${message}`}))}function interactiveAuthNotices(authStorage){let pending=authStorage.takePendingNotices({persistSeen:!1});return{messages:[...authStorage.drainErrors().map(error2=>error2.message),...pending.map(notice2=>notice2.message)],markSeen:()=>authStorage.markNoticesSeen(pending.map(notice2=>notice2.id))}}function collectExtensionLoadDiagnostics(errors){return errors.map(({path:path16,error:error2})=>({type:"warning",message:`Failed to load extension "${path16}": ${error2}`}))}function reportDiagnostics(diagnostics){for(let diagnostic2 of diagnostics){let color=diagnostic2.type==="error"?source_default.red:diagnostic2.type==="warning"?source_default.yellow:source_default.dim,prefix=diagnostic2.type==="error"?"Error: ":diagnostic2.type==="warning"?"Warning: ":"";console.error(color(`${prefix}${diagnostic2.message}`))}}function isTruthyEnvFlag2(value){return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}function resolveAppMode(parsed,stdinIsTTY,stdoutIsTTY){return parsed.mode==="rpc"?"rpc":parsed.mode==="json"?"json":parsed.print||!stdinIsTTY||!stdoutIsTTY?"print":"interactive"}function toPrintOutputMode(appMode){return appMode==="json"?"json":"text"}function resolveAutoTitleSessions(appMode,parsed,hasContextMessages,clientCapabilities=parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),sessionAutoTitle){return hasContextMessages?!1:sessionAutoTitle!==void 0?sessionAutoTitle:appMode==="interactive"||parsed.autoTitleSessions===!0||appMode==="rpc"&&clientCapabilities.includes(AUTO_TITLE_SESSIONS_CAPABILITY)}function isPlainRuntimeMetadataCommand(parsed){return!parsed.print&&parsed.mode===void 0&&(parsed.help===!0||parsed.listModels!==void 0||parsed.listTips===!0)}async function runAuthCommand(args){if(isAuthCommandHelp(args))return printAuthCommandHelp(),!0;let command;try{command=parseAuthCommand(args)}catch(error2){let message=error2 instanceof AuthCommandError?error2.message:"Failed to parse auth command";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}if(!command)return!1;let parsed=parseArgs(command.args);if(parsed.unknownFlags.size>0){let option=parsed.unknownFlags.keys().next().value;return console.error(source_default.red(`Unknown option --${option} for "${getAuthCommandName(command.kind)}".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${getAuthCommandUsage(command.kind)}".`)),process.exitCode=1,!0}try{if(parsed.diagnostics.length>0)throw new AuthCommandError(parsed.diagnostics.map(diagnostic2=>diagnostic2.message).join(`
|
|
2166
|
+
`))}return exitCode}catch(error2){return console.error(error2 instanceof Error?error2.message:String(error2)),1}finally{for(let cleanup of signalCleanupHandlers)cleanup();await disposeRuntime(),await flushRawStdout()}}import{readdirSync as readdirSync18,readFileSync as readFileSync43}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform4){return platform4==="darwin"||platform4==="linux"?platform4:void 0}async function loadChildReaperSyscalls(platform4=process.platform){let supported=supportedPlatform(platform4);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry2 of readdirSync18("/proc")){let pid=Number(entry2);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync43(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat19=linuxStat(pid),tail=stat19?.slice(stat19.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat19=linuxStat(pid),open12=stat19?.indexOf("(")??-1,close=stat19?.lastIndexOf(")")??-1;return stat19===void 0||open12===-1||close<=open12?"":stat19.slice(open12+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS2=1e3,CHILD_REAPER_IDLE_TICK_MS=5e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS2,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now2=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now2()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now2(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now2();continue}now2()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)},get childCount(){return tracked.size}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count2])=>`${name} x${count2}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log});return scheduleChildReaper(reaper,config.tickMs)}function scheduleChildReaper(reaper,tickMs){let timer,arm=()=>{timer=setTimeout(()=>{reaper.tick(),timer!==void 0&&arm()},reaper.childCount>0?tickMs:Math.max(tickMs,CHILD_REAPER_IDLE_TICK_MS)),timer.unref()};return arm(),()=>{timer!==void 0&&clearTimeout(timer),timer=void 0}}var orphanSyscalls;async function collectOrphanedChildren(pids){if(pids.length===0)return[];orphanSyscalls??=loadChildReaperSyscalls();let syscalls=await orphanSyscalls;return syscalls===void 0?[]:pids.filter(pid=>Number.isInteger(pid)&&pid>0&&syscalls.isWaitable(pid)&&syscalls.reapExited(pid))}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}function completeCompactFactory(factory,prepare){return Object.assign(factory,{prepare,supportsCompact:()=>!0})}var INTERNAL_SUPERVISOR_ROUTE_FLAG="--internal-rpc-host-supervisor";async function dispatchInternalSupervisor(args){if(!args.includes(INTERNAL_SUPERVISOR_ROUTE_FLAG))return!1;let{findInternalSupervisorArgs,parseSupervisorArgs,runHostSupervisor}=await import("./host-lifecycle-SGTVODHB.js"),supervisorArgs=findInternalSupervisorArgs(args);if(!supervisorArgs)return!1;let launch=parseSupervisorArgs(supervisorArgs);return launch||(console.error("invalid internal RPC host supervisor arguments"),process.exit(2)),await runHostSupervisor(launch),!0}import{randomUUID as randomUUID17}from"node:crypto";import{copyFileSync as copyFileSync3,existsSync as existsSync44,mkdirSync as mkdirSync28,renameSync as renameSync16,rmSync as rmSync16}from"node:fs";import{basename as basename34,dirname as dirname66,join as join102,relative as relative21,resolve as resolve52,toNamespacedPath}from"node:path";var QUARANTINE_DIR_NAME=".pi-native-quarantine";function normalizePath3(path16){return toNamespacedPath(resolve52(path16))}function getQuarantineRoot(packageDir){let current=resolve52(packageDir);for(;;){if(basename34(current).toLowerCase()==="node_modules")return join102(current,QUARANTINE_DIR_NAME);let parent=dirname66(current);if(parent===current)return;current=parent}}function getLoadedSharedObjectsInPackageDir(packageDir){let sharedObjects=process.report.getReport().sharedObjects;if(!Array.isArray(sharedObjects))return[];let root=normalizePath3(packageDir).toLowerCase(),seen=new Set,loadedFiles=[];for(let value of sharedObjects){if(typeof value!="string")continue;let filePath=normalizePath3(value),comparisonPath=filePath.toLowerCase();getCwdRelativePath(comparisonPath,root)===void 0||seen.has(comparisonPath)||(seen.add(comparisonPath),loadedFiles.push(filePath))}return loadedFiles}function cleanupWindowsSelfUpdateQuarantine(packageDir){let quarantineRoot=getQuarantineRoot(packageDir);if(quarantineRoot)try{rmSync16(quarantineRoot,{recursive:!0,force:!0})}catch{}}function quarantineWindowsNativeDependencies(packageDir){let resolvedPackageDir=normalizePath3(packageDir),quarantineRoot=getQuarantineRoot(resolvedPackageDir);if(!quarantineRoot)return;let loadedFiles=getLoadedSharedObjectsInPackageDir(resolvedPackageDir);if(loadedFiles.length===0)return;let quarantineRunDir=join102(quarantineRoot,`${Date.now()}-${process.pid}-${randomUUID17()}`);for(let loadedFile of loadedFiles){if(!existsSync44(loadedFile))continue;let quarantinePath=join102(quarantineRunDir,relative21(resolvedPackageDir,loadedFile));mkdirSync28(dirname66(quarantinePath),{recursive:!0}),renameSync16(loadedFile,quarantinePath),copyFileSync3(quarantinePath,loadedFile)}}var EXTENSION_LOAD_FAILURE_HINT=`Hint: Start without extensions using "${APP_NAME} -ne".`;function collectAuthDiagnostics(authStorage,context,options){return[...authStorage.drainErrors().map(error2=>error2.message),...authStorage.takePendingNotices(options).map(notice2=>notice2.message)].map(message=>({type:"warning",message:`(${context}, auth storage) ${message}`}))}function interactiveAuthNotices(authStorage){let pending=authStorage.takePendingNotices({persistSeen:!1});return{messages:[...authStorage.drainErrors().map(error2=>error2.message),...pending.map(notice2=>notice2.message)],markSeen:()=>authStorage.markNoticesSeen(pending.map(notice2=>notice2.id))}}function collectExtensionLoadDiagnostics(errors){return errors.map(({path:path16,error:error2})=>({type:"warning",message:`Failed to load extension "${path16}": ${error2}`}))}function reportDiagnostics(diagnostics){for(let diagnostic2 of diagnostics){let color=diagnostic2.type==="error"?source_default.red:diagnostic2.type==="warning"?source_default.yellow:source_default.dim,prefix=diagnostic2.type==="error"?"Error: ":diagnostic2.type==="warning"?"Warning: ":"";console.error(color(`${prefix}${diagnostic2.message}`))}}function isTruthyEnvFlag2(value){return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}function resolveAppMode(parsed,stdinIsTTY,stdoutIsTTY){return parsed.mode==="rpc"?"rpc":parsed.mode==="json"?"json":parsed.print||!stdinIsTTY||!stdoutIsTTY?"print":"interactive"}function toPrintOutputMode(appMode){return appMode==="json"?"json":"text"}function resolveAutoTitleSessions(appMode,parsed,hasContextMessages,clientCapabilities=parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),sessionAutoTitle){return hasContextMessages?!1:sessionAutoTitle!==void 0?sessionAutoTitle:appMode==="interactive"||parsed.autoTitleSessions===!0||appMode==="rpc"&&clientCapabilities.includes(AUTO_TITLE_SESSIONS_CAPABILITY)}function isPlainRuntimeMetadataCommand(parsed){return!parsed.print&&parsed.mode===void 0&&(parsed.help===!0||parsed.listModels!==void 0||parsed.listTips===!0)}async function runAuthCommand(args){if(isAuthCommandHelp(args))return printAuthCommandHelp(),!0;let command;try{command=parseAuthCommand(args)}catch(error2){let message=error2 instanceof AuthCommandError?error2.message:"Failed to parse auth command";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}if(!command)return!1;let parsed=parseArgs(command.args);if(parsed.unknownFlags.size>0){let option=parsed.unknownFlags.keys().next().value;return console.error(source_default.red(`Unknown option --${option} for "${getAuthCommandName(command.kind)}".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${getAuthCommandUsage(command.kind)}".`)),process.exitCode=1,!0}try{if(parsed.diagnostics.length>0)throw new AuthCommandError(parsed.diagnostics.map(diagnostic2=>diagnostic2.message).join(`
|
|
2167
2167
|
`));if(command.kind!=="check"){let signal=AbortSignal.timeout(15e3),modelRuntime=await ModelRuntime.create({allowModelNetwork:!1,signal}),credential2=await resolveCredentialForPrint(parsed,modelRuntime,command.kind,command.minExpiryMs,signal);return process.stdout.write(`${credential2}
|
|
2168
2168
|
`),!0}let requestedAuth=validateAuthCommandArgs(parsed,command.kind),result3,credential;try{let credentials=command.noRefresh?new ReadOnlyAuthStorage:AuthStorage.create(),modelRuntime=await createAuthCheckModelRuntime(credentials);result3=await checkProviderAuth(parsed,modelRuntime,{refresh:!command.noRefresh}),command.credentials&&result3.status==="ready"&&(credential=await getProviderCredential(result3.provider,modelRuntime,credentials,{refresh:!command.noRefresh}),credential||(result3={status:"not_ready",provider:result3.provider,reason:"credential_not_available"}))}catch{result3={status:"invalid",provider:requestedAuth.provider??requestedAuth.model,reason:"invalid_state"}}let accounts=[];if(command.json&&result3.status!=="invalid")try{let credentials=command.noRefresh?new ReadOnlyAuthStorage:AuthStorage.create();accounts=await summarizeCredentialAccounts(result3.provider,await credentials.read(result3.provider))}catch{}let output=command.json?JSON.stringify({...result3,accounts,...credential?{credentials:credential}:{}}):credential??result3.status;process.stdout.write(`${output}
|
|
2169
|
-
`),process.exitCode=result3.status==="ready"?0:result3.status==="not_ready"?1:2}catch(error2){let message=error2 instanceof AuthCommandError?error2.message:"Failed to resolve credential";console.error(source_default.red(`Error: ${message}`)),process.exitCode=command.kind==="check"?2:1}return!0}async function prepareInitialMessage(parsed,autoResizeImages,stdinContent){if(parsed.fileArgs.length===0)return buildInitialMessage({parsed,stdinContent});let{text:text4,images}=await processFileArguments(parsed.fileArgs,{autoResizeImages});return buildInitialMessage({parsed,fileText:text4,fileImages:images,stdinContent})}async function findLocalSessionByExactId(sessionId,cwd,sessionDir){let localSessions=sessionDir?await SessionManager.listAll(sessionDir):await SessionManager.list(cwd),localMatch=localSessions.find(s=>s.id===sessionId)??localSessions.find(s=>sessionFileNameId(s.path)===sessionId);return localMatch?{type:"local",path:localMatch.path}:void 0}function findSessionByIdOrFileName(sessions3,arg){return sessions3.find(s=>s.id===arg)??sessions3.find(s=>sessionFileNameId(s.path)===arg)??sessions3.find(s=>s.id.startsWith(arg))}async function resolveSessionPath(sessionArg,cwd,sessionDir){if(sessionArg.includes("/")||sessionArg.includes("\\")||sessionArg.endsWith(".jsonl"))return{type:"path",path:resolvePath(sessionArg,cwd)};let localSessions=await SessionManager.list(cwd,sessionDir),localMatch=findSessionByIdOrFileName(localSessions,sessionArg);if(localMatch)return{type:"local",path:localMatch.path};let allSessions=await SessionManager.listAll(sessionDir),globalMatch=findSessionByIdOrFileName(allSessions,sessionArg);return globalMatch?{type:"global",path:globalMatch.path,cwd:globalMatch.cwd}:{type:"not_found",arg:sessionArg}}async function promptConfirm(message){return new Promise(resolve56=>{let rl=createInterface3({input:process.stdin,output:process.stdout}),settled2=!1,settle2=result3=>{settled2||(settled2=!0,resolve56(result3))};rl.question(`${message} [y/N] `,answer3=>{let normalized2=answer3.trim().toLowerCase();settle2(normalized2==="y"||normalized2==="yes"),rl.close()}),rl.once("close",()=>settle2(!1))})}function validateForkFlags(parsed){if(!parsed.fork)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateRebindFlags(parsed){if(!parsed.rebind)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.fork?"--fork":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0,parsed.sessionId!==void 0?"--session-id":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --rebind cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateSessionIdFlags(parsed){if(parsed.sessionId===void 0)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1));try{assertValidSessionId(parsed.sessionId)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function openSessionOrExit(path16,sessionDir){try{return SessionManager.open(path16,sessionDir)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function forkSessionOrExit(sourcePath,cwd,sessionDir,sessionId){try{return SessionManager.forkFrom(sourcePath,cwd,sessionDir,{id:sessionId})}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function rebindSessionOrExit(sourcePath,cwd,sessionDir){try{let reboundPath=await rebindSessionFile(sourcePath,cwd,sessionDir);return console.log(source_default.dim(`Session moved to ${cwd}`)),SessionManager.open(reboundPath,sessionDir)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function sessionCwdOrUndefined(sessionFile){try{return await readSessionCwd(sessionFile)}catch{return}}async function createSessionManager(parsed,cwd,sessionDir,settingsManager,appMode){if(parsed.spawnedBy&&(parsed.session||parsed.resume||parsed.continue||parsed.fork||parsed.rebind)&&console.error(source_default.yellow("Warning: --spawned-by is ignored when resuming or forking a session.")),parsed.noSession||parsed.help||parsed.listModels!==void 0||parsed.listTips)return SessionManager.inMemory(cwd,{id:parsed.sessionId,spawnedBy:parsed.spawnedBy});if(parsed.fork){parsed.sessionId&&await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir)&&(console.error(source_default.red(`Session already exists with id '${parsed.sessionId}'`)),process.exit(1));let resolved=await resolveSessionPath(parsed.fork,cwd,sessionDir);switch(resolved.type){case"path":case"local":case"global":return forkSessionOrExit(resolved.path,cwd,sessionDir,parsed.sessionId);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.rebind){let resolved=await resolveSessionPath(parsed.rebind,cwd,sessionDir);resolved.type==="not_found"&&(console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1));let sessionCwd=resolved.type==="global"?resolved.cwd:await sessionCwdOrUndefined(resolved.path);return resolved.type==="local"||sessionCwd===void 0||resolvePath(sessionCwd)===resolvePath(cwd)?openSessionOrExit(resolved.path,sessionDir):(await classifySessionRepository(resolved.path,sessionCwd,cwd)==="different"&&(console.error(source_default.red(`Refusing to rebind: ${cwd} is a different git repository than ${sessionCwd}. Use --fork '${parsed.rebind}' to copy the session into this directory instead.`)),process.exit(1)),rebindSessionOrExit(resolved.path,cwd,sessionDir))}if(parsed.session){let resolved=await resolveSessionPath(parsed.session,cwd,sessionDir);switch(resolved.type){case"path":case"local":return openSessionOrExit(resolved.path,sessionDir);case"global":{if(resolved.cwd!==""&&resolvePath(resolveMovedPath(resolved.cwd))===resolvePath(cwd))return openSessionOrExit(resolved.path,sessionDir);let action=await chooseCrossProjectAction({sessionArg:parsed.session,sessionCwd:resolved.cwd,cwd,match:await classifySessionRepository(resolved.path,resolved.cwd,cwd),interactive:appMode==="interactive",confirm:promptConfirm,out:line=>console.log(line),err:line=>console.error(line)});return action==="rebind"?rebindSessionOrExit(resolved.path,cwd,sessionDir):action==="fork"?forkSessionOrExit(resolved.path,cwd,sessionDir):(action==="abort"&&console.log(source_default.dim("Aborted.")),process.exit(action==="abort"?0:1))}case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.resume)try{let{selectSession}=await import("./session-picker-XLNIB75G.js"),movedOptions=sessionDir===void 0?{}:{sessionDir},selectedPath=await selectSession(onProgress=>withMovedSessions(SessionManager.list(cwd,sessionDir,onProgress),cwd,movedOptions),async onProgress=>markMovedSessions(await SessionManager.listAll(sessionDir,onProgress),cwd),settingsManager);selectedPath||(console.log(source_default.dim("No session selected")),process.exit(0));let target=await resolveResumeTarget({sessionPath:selectedPath,cwd,...movedOptions,confirm:selectedCwd=>(console.log(source_default.yellow(`Session found in different project: ${selectedCwd}`)),confirmSameRepositoryRebind({sessionArg:selectedPath,cwd,confirm:promptConfirm,out:line=>console.log(line)}))}).catch(error2=>(console.error(source_default.red(`Error: ${error2 instanceof Error?error2.message:String(error2)}`)),process.exit(1)));return target.rebound&&console.log(source_default.dim(`Session moved to ${cwd}`)),SessionManager.open(target.path,sessionDir)}finally{stopThemeWatcher()}if(parsed.continue){let movedHere=sessionDir===void 0?await movedHereSessionToContinue(cwd):void 0;if(movedHere!==void 0)return SessionManager.open(movedHere,sessionDir);let recent=SessionManager.continueRecent(cwd,sessionDir),recentFile=recent.getSessionFile();if(recentFile!==void 0&&existsSync45(recentFile))return recent;let movedChoice=await movedSessionToContinue({cwd,...sessionDir===void 0?{}:{sessionDir},interactive:appMode==="interactive",confirm:promptConfirm,out:line=>console.log(line),err:line=>console.error(line)});return movedChoice===void 0?recent:rebindSessionOrExit(movedChoice,cwd,sessionDir)}if(parsed.sessionId){let existingSession=await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir);if(existingSession)return parsed.spawnedBy&&console.error(source_default.yellow("Warning: --spawned-by is ignored when resuming an existing session.")),SessionManager.open(existingSession.path,sessionDir);console.error(source_default.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`))}return SessionManager.create(cwd,sessionDir,{id:parsed.sessionId,spawnedBy:parsed.spawnedBy})}function buildSessionOptions(parsed,scopedModels,hasExistingSession,modelRuntime,settingsManager){let options={},diagnostics=[],cliThinkingFromModel=!1;if(parsed.provider&&!parsed.model&&diagnostics.push({type:"error",message:`--provider requires --model (for example: --provider ${parsed.provider} --model <pattern>)`}),parsed.model){let resolved=resolveCliModel({cliProvider:parsed.provider,cliModel:parsed.model,cliThinking:parsed.thinking,modelRuntime});resolved.warning&&diagnostics.push({type:"warning",message:resolved.warning}),resolved.error&&diagnostics.push({type:"error",message:resolved.error,code:"model_unresolved"}),resolved.model&&(options.model=resolved.model,options.serviceTier=resolved.serviceTier,options.initialModelProvenance="cli",!parsed.thinking&&resolved.thinkingLevel&&(options.thinkingLevel=resolved.thinkingLevel,options.thinkingSelection=resolved.thinkingSelection,cliThinkingFromModel=!0))}if(!options.model&&scopedModels.length>0&&!hasExistingSession){let savedProvider=settingsManager.getDefaultProvider(),savedModelId=settingsManager.getDefaultModel(),savedModel=savedProvider&&savedModelId?modelRuntime.getModel(savedProvider,savedModelId):void 0,savedInScope=savedModel?scopedModels.find(sm=>modelsAreEqual(sm.model,savedModel)):void 0;savedInScope?(options.model=savedInScope.model,options.initialModelProvenance="scoped",!parsed.thinking&&savedInScope.thinkingLevel&&(options.thinkingLevel=savedInScope.thinkingLevel,options.thinkingSelection=savedInScope.thinkingSelection)):(options.model=scopedModels[0].model,options.initialModelProvenance="scoped",!parsed.thinking&&scopedModels[0].thinkingLevel&&(options.thinkingLevel=scopedModels[0].thinkingLevel,options.thinkingSelection=scopedModels[0].thinkingSelection))}return parsed.thinking&&(options.thinkingLevel=parsed.thinking,options.thinkingSelection={level:parsed.thinking,source:"explicit"}),scopedModels.length>0&&(options.scopedModels=scopedModels.map(sm=>({model:sm.model,thinkingLevel:sm.thinkingLevel,thinkingSelection:sm.thinkingSelection,serviceTier:sm.serviceTier}))),parsed.noTools?options.noTools="all":parsed.noBuiltinTools&&(options.noTools="builtin"),parsed.tools&&(options.tools=[...parsed.tools]),parsed.excludeTools&&(options.excludeTools=[...parsed.excludeTools]),{options,cliThinkingFromModel,diagnostics}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}async function promptForMissingSessionCwd(issue,settingsManager){return showStartupSelector(settingsManager,formatMissingSessionCwdPrompt(issue),[{label:"Continue",value:issue.fallbackCwd},{label:"Cancel",value:void 0}])}function applyGrokNeoThemeFallback(settingsManager){if(settingsManager.getThemeSetting()!==void 0)return;let getThemeSetting=settingsManager.getThemeSetting.bind(settingsManager),setTheme=settingsManager.setTheme.bind(settingsManager),fallbackActive=!0;settingsManager.getThemeSetting=()=>getThemeSetting()??(fallbackActive?"grok-night":void 0),settingsManager.setTheme=theme2=>{fallbackActive=!1,setTheme(theme2)}}function createCliRuntimeFactory(configuration,local={}){let{parsed,cwd,agentDir,appMode,toolRuntime}=configuration,extensionFactories=local.extensionFactories??builtInExtensions,startupSettingsManager=local.startupSettingsManager??SettingsManager.create(cwd,agentDir),startupLoadingIndicator=local.startupLoadingIndicator??createStartupLoadingIndicator({writer:()=>{},isTTY:!1,label:`Loading ${APP_NAME}`}),trustStore=new ProjectTrustStore(agentDir),projectTrustByCwd=new Map,trustPromptMode=parsed.help||parsed.listModels!==void 0||parsed.listTips?"print":appMode,resolvedExtensionPaths=resolveCliPaths(cwd,parsed.extensions),resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes),createServices=async({cwd:cwd2,agentDir:agentDir2,projectTrustContext,launchProfile,mcpRegistry,isInitialRuntime})=>{let projectTrustDiagnostics=[],cachedProjectTrust=projectTrustByCwd.get(cwd2),hasTrustRequiringResources=hasTrustRequiringProjectResources(cwd2),savedProjectTrust=await getSavedProjectTrust(trustStore,cwd2),fullAccessTrust=presetTrustsProject(sessionExtensionFlagValues(parsed.unknownFlags,launchProfile).get("permission-preset"),startupSettingsManager.getGlobalSettings().permissionPreset)&&savedProjectTrust!==!1,shouldResolveProjectTrust=parsed.projectTrustOverride===void 0&&cachedProjectTrust===void 0&&!fullAccessTrust&&hasTrustRequiringResources,projectTrusted=shouldResolveProjectTrust?!1:cachedProjectTrust??parsed.projectTrustOverride??(fullAccessTrust||!hasTrustRequiringResources||savedProjectTrust===!0),trustFromFullAccess=fullAccessTrust&&hasTrustRequiringResources&&cachedProjectTrust===void 0&&parsed.projectTrustOverride===void 0&&savedProjectTrust!==!0,runtimeSettingsManager=SettingsManager.create(cwd2,agentDir2,{projectTrusted,trustFromFullAccess});return launchProfile?.retryFallback&&applyRetryFallbackProfile(runtimeSettingsManager,launchProfile.retryFallback),{services:await createAgentSessionServices({cwd:cwd2,agentDir:agentDir2,settingsManager:runtimeSettingsManager,...local.modelRuntime===void 0?{}:{modelRuntime:local.modelRuntime},mcpRegistry,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:sessionExtensionFlagValues(parsed.unknownFlags,launchProfile),resourceLoaderReloadOptions:shouldResolveProjectTrust?{resolveProjectTrust:async({extensionsResult})=>{let trusted=await resolveProjectTrusted({cwd:cwd2,trustStore,trustOverride:parsed.projectTrustOverride,defaultProjectTrust:startupSettingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:projectTrustContext??pauseIndicatorDuringPrompts(createProjectTrustContext({cwd:cwd2,mode:isInitialRuntime?trustPromptMode:appMode,settingsManager:startupSettingsManager,hasUI:isInitialRuntime&&trustPromptMode==="interactive"}),startupLoadingIndicator),onExtensionError:message=>projectTrustDiagnostics.push({type:"warning",message})});return projectTrustByCwd.set(cwd2,trusted),trusted}}:void 0,resourceLoaderOptions:{sessionKind:launchProfile?.sessionKind,sessionContext:launchProfile?.sessionContext,additionalExtensionPaths:resolvedExtensionPaths,additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noExtensions:parsed.noExtensions,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,systemPrompt:parsed.systemPrompt,appendSystemPrompt:parsed.appendSystemPrompt,extensionFactories}}),projectTrustDiagnostics}};return completeCompactFactory(async({cwd:cwd2,agentDir:agentDir2,sessionManager,sessionStartEvent,projectTrustContext,launchProfile,mcpRegistry})=>{let isInitialRuntime=sessionStartEvent===void 0,markSwitch=label3=>{sessionStartEvent?.reason==="resume"&&time(label3,"switch")},{services,projectTrustDiagnostics}=await createServices({cwd:cwd2,agentDir:agentDir2,...projectTrustContext!==void 0?{projectTrustContext}:{},...launchProfile!==void 0?{launchProfile}:{},...mcpRegistry!==void 0?{mcpRegistry}:{},isInitialRuntime});markSwitch("services");let{settingsManager,modelRuntime,resourceLoader}=services,diagnostics=[...projectTrustDiagnostics,...services.diagnostics,...collectSettingsDiagnosticsWithContext(settingsManager,"runtime creation"),...collectExtensionLoadDiagnostics(resourceLoader.getExtensions().errors),...(resourceLoader.getExtensions().warnings??[]).map(({path:path16,warning})=>({type:"warning",message:`Extension package "${path16}": ${warning}`}))],modelPatterns=getModelNarrowingPatterns({cliPatterns:parsed.models,legacyEnabledPatterns:settingsManager.getEnabledModels()}),scopedModels=modelPatterns&&modelPatterns.length>0?await resolveModelScope(modelPatterns,modelRuntime,{signal:AbortSignal.timeout(15e3)}):[],runtimeParsed=launchProfile===void 0?parsed:{...parsed,...launchProfile.creationModel===void 0?{}:{provider:launchProfile.creationModel.provider,model:launchProfile.creationModel.modelId},...launchProfile.initialThinkingLevel===void 0?{}:{thinking:launchProfile.initialThinkingLevel}},{options:sessionOptions,cliThinkingFromModel,diagnostics:sessionOptionDiagnostics}=buildSessionOptions(runtimeParsed,scopedModels,sessionManager.hasContextMessages(),modelRuntime,settingsManager);diagnostics.push(...sessionOptionDiagnostics),parsed.apiKey&&(sessionOptions.model?await modelRuntime.setRuntimeApiKey(sessionOptions.model.provider,parsed.apiKey):diagnostics.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"})),isInitialRuntime&&startupLoadingIndicator.setPhase("opening session"),markSwitch("sessionOptions");let created=await createAgentSessionFromServices({services,sessionManager,sessionStartEvent,model:sessionOptions.model,initialModelProvenance:sessionOptions.initialModelProvenance,thinkingLevel:sessionOptions.thinkingLevel,thinkingSelection:sessionOptions.thinkingSelection,serviceTier:sessionOptions.serviceTier,scopedModels:sessionOptions.scopedModels,tools:sessionOptions.tools,excludeTools:sessionOptions.excludeTools,noTools:sessionOptions.noTools,customTools:sessionOptions.customTools,autoTitleSessions:resolveAutoTitleSessions(appMode,parsed,sessionManager.hasContextMessages(),parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),launchProfile?.autoTitle),promptSurface:launchProfile?.promptSurface,browserEngine:launchProfile?.browserEngine,sessionEnv:launchProfile?.sessionEnv,...toolRuntime!==void 0?{toolRuntime}:{}});markSwitch("createSession");let cliThinkingOverride=runtimeParsed.thinking!==void 0||cliThinkingFromModel;if(created.session.model&&cliThinkingOverride){let selection=created.session.thinkingSelection;created.session.setThinkingLevel(selection?.requested??created.session.thinkingLevel)}return{...created,services,diagnostics}},async options=>{await createServices({...options,isInitialRuntime:!0})})}async function main(args,options){resetTimings(),recordTiming("processStart->main",Math.round(process.uptime()*1e3));let extensionFactories=[...builtInExtensions,...options?.extensionFactories??[]],offlineMode=args.includes("--print-prompt-sizes")||args.includes("--offline")||isTruthyEnvFlag2(envValue("OFFLINE"));if(offlineMode&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await runAuthCommand(args))return;if(isModelsDiscoverCommand(args)){process.exitCode=await runModelsDiscoverCommand(args.slice(2));return}if(await dispatchInternalSupervisor(args))return;process.platform==="win32"&&cleanupWindowsSelfUpdateQuarantine(getInstallPackageDir());let cwd=process.cwd(),agentDir=getAgentDir(),fromSourceWarning=getFromSourceRealConfigWarning(agentDir);fromSourceWarning&&console.error(source_default.yellow(fromSourceWarning));let bootstrapSettingsManager=SettingsManager.create(cwd,agentDir,{projectTrusted:!1});if(applyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(),await dispatchPackageCommand(args,{extensionFactories})){let exitCode=process.exitCode??0;if(process.platform==="win32"&&exitCode===0&&args[0]==="update")return;await exitAfterOutput("",exitCode);return}if(await dispatchConfigCommand(args,{extensionFactories}))return;let hostExitCode=await dispatchHostCommand(args);hostExitCode!==void 0&&await exitAfterOutput("",hostExitCode);let scheduleExitCode=await dispatchScheduleCommand(args);scheduleExitCode!==void 0&&await exitAfterOutput("",scheduleExitCode);let parsed=parseArgs(args);if(parsed.diagnostics.length>0){for(let d of parsed.diagnostics){let color=d.type==="error"?source_default.red:source_default.yellow;console.error(color(`${d.type==="error"?"Error":"Warning"}: ${d.message}`))}parsed.diagnostics.some(d=>d.type==="error")&&process.exit(1)}let toolRuntimeResolution=resolveToolRuntime(parsed);!toolRuntimeResolution.ok&&!parsed.version&&!parsed.help&&(console.error(source_default.red(`Error: ${toolRuntimeResolution.message}`)),process.exit(1));let toolRuntime=toolRuntimeResolution.ok?toolRuntimeResolution.value:"in-process";if(time("parseArgs"),parsed.version&&await printThenExit(()=>console.log(DISPLAY_VERSION),0),parsed.attach&&parsed.session&&!parsed.help){let{runAttachedTui}=await import("./run-attached-tui-G2E4FWSV.js");try{await runAttachedTui({address:parsed.attach,session:parsed.session,tuiMode:parsed.tuiMode,theme:parsed.useTheme})}catch(error2){await printThenExit(()=>console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),1)}return}if(parsed.export){let result3;try{let outputPath=parsed.messages.length>0?parsed.messages[0]:void 0;result3=await exportFromFile(parsed.export,outputPath)}catch(error2){let message=error2 instanceof Error?error2.message:"Failed to export session";console.error(source_default.red(`Error: ${message}`)),process.exit(1)}await printThenExit(()=>console.log(`Exported to: ${result3}`),0)}let appMode=parsed.printPromptSizes?"print":resolveAppMode(parsed,process.stdin.isTTY,process.stdout.isTTY);if(appMode!=="interactive"&&(!isPlainRuntimeMetadataCommand(parsed)||parsed.help&&parsed.mode==="json")&&takeOverStdout(),parsed.mode==="json"){let log=console.log.bind(console);console.log=(...args2)=>console.error(...args2),process.once("exit",()=>{console.log=log})}parsed.mode==="rpc"&&parsed.fileArgs.length>0&&(console.error(source_default.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),validateForkFlags(parsed),validateRebindFlags(parsed),validateSessionIdFlags(parsed);let{migratedAuthProviders:migratedProviders,deprecationWarnings}=runMigrations(cwd);time("runMigrations");let startupSettingsManager=SettingsManager.create(cwd,agentDir);reportDiagnostics(collectSettingsDiagnosticsWithContext(startupSettingsManager,"startup session lookup"));let resolvedExtensionPaths=resolveCliPaths(cwd,parsed.extensions),resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes);if(isPlainHelpRequest(parsed)){let projectTrusted=resolveHelpProjectTrust(parsed,cwd,agentDir),scope=helpFlagsScope(parsed,cwd,agentDir,projectTrusted),{flags:flags2,extensionPaths}=await resolveHelpExtensionFlags({cwd,agentDir,settingsManager:SettingsManager.create(cwd,agentDir,{projectTrusted}),additionalExtensionPaths:resolvedExtensionPaths??[],noExtensions:parsed.noExtensions===!0,...extensionFactories?{extensionFactories}:{}});writeHelpFlagsCache({scope,flags:flags2,extensionPaths}),await printThenExit(()=>{printHelp(flags2),printTimings()},0)}if(parsed.listTips){let{listTips}=await import("./list-tips-3D3A6GFK.js");await printThenExit(listTips,0)}if(parsed.listModels!==void 0){let services2=await createAgentSessionServices({cwd,agentDir,settingsManager:startupSettingsManager,extensionFlagValues:parsed.unknownFlags,resourceLoaderOptions:{additionalExtensionPaths:resolvedExtensionPaths,additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noExtensions:parsed.noExtensions,noSkills:!0,noPromptTemplates:!0,noThemes:!0,noContextFiles:!0,extensionFactories}});reportDiagnostics([...services2.diagnostics,...collectSettingsDiagnosticsWithContext(services2.settingsManager,"model listing"),...collectAuthDiagnostics(services2.authStorage,"model listing",{persistSeen:!0})]);let searchPattern2=typeof parsed.listModels=="string"?parsed.listModels:void 0;await printThenExit(()=>listModels(services2.modelRuntime,searchPattern2),0)}if(appMode==="interactive"&&!parsed.help&&parsed.listModels===void 0&&!parsed.listTips&&shouldRunFirstTimeSetup()&&(await showFirstTimeSetup(startupSettingsManager),time("firstTimeSetup")),appMode==="interactive"&&parsed.useTheme!==void 0&&startupSettingsManager.applyOverrides({theme:parsed.useTheme}),installMemoryReportSignal(),appMode==="rpc"&&parsed.multiSession){if(options?.extensionFactories?.length)throw new Error("Shared RPC workers require file-backed extensions; inline factories cannot cross isolates");let{presenterBootstrapFd,mcpPresenterEnforcement,...sessionArgs}=parsed,runtimeConfiguration={parsed:sessionArgs,cwd,agentDir,appMode,toolRuntime},sessionRuntime=resolveSessionRuntime(parsed),{runMultiSessionHost}=await import("./multi-session-host-AZKJYA2X.js"),hostModelRuntime=sessionRuntime==="worker"?void 0:await ModelRuntime.create({credentials:AuthStorage.create(join103(agentDir,"auth.json")),authPath:join103(agentDir,"auth.json"),agentDir,modelsPath:join103(agentDir,"models.json"),signal:AbortSignal.timeout(15e3)});initTheme(startupSettingsManager.getTheme(),!1),offlineMode||startSubscriptionUsagePolling({agentDir,report:message=>{process.stderr.write(`${message}
|
|
2169
|
+
`),process.exitCode=result3.status==="ready"?0:result3.status==="not_ready"?1:2}catch(error2){let message=error2 instanceof AuthCommandError?error2.message:"Failed to resolve credential";console.error(source_default.red(`Error: ${message}`)),process.exitCode=command.kind==="check"?2:1}return!0}async function prepareInitialMessage(parsed,autoResizeImages,stdinContent){if(parsed.fileArgs.length===0)return buildInitialMessage({parsed,stdinContent});let{text:text4,images}=await processFileArguments(parsed.fileArgs,{autoResizeImages});return buildInitialMessage({parsed,fileText:text4,fileImages:images,stdinContent})}async function findLocalSessionByExactId(sessionId,cwd,sessionDir){let localSessions=sessionDir?await SessionManager.listAll(sessionDir):await SessionManager.list(cwd),localMatch=localSessions.find(s=>s.id===sessionId)??localSessions.find(s=>sessionFileNameId(s.path)===sessionId);return localMatch?{type:"local",path:localMatch.path}:void 0}function findSessionByIdOrFileName(sessions3,arg){return sessions3.find(s=>s.id===arg)??sessions3.find(s=>sessionFileNameId(s.path)===arg)??sessions3.find(s=>s.id.startsWith(arg))}async function resolveSessionPath(sessionArg,cwd,sessionDir){if(sessionArg.includes("/")||sessionArg.includes("\\")||sessionArg.endsWith(".jsonl"))return{type:"path",path:resolvePath(sessionArg,cwd)};let localSessions=await SessionManager.list(cwd,sessionDir),localMatch=findSessionByIdOrFileName(localSessions,sessionArg);if(localMatch)return{type:"local",path:localMatch.path};let allSessions=await SessionManager.listAll(sessionDir),globalMatch=findSessionByIdOrFileName(allSessions,sessionArg);return globalMatch?{type:"global",path:globalMatch.path,cwd:globalMatch.cwd}:{type:"not_found",arg:sessionArg}}async function promptConfirm(message){return new Promise(resolve56=>{let rl=createInterface3({input:process.stdin,output:process.stdout}),settled2=!1,settle2=result3=>{settled2||(settled2=!0,resolve56(result3))};rl.question(`${message} [y/N] `,answer3=>{let normalized2=answer3.trim().toLowerCase();settle2(normalized2==="y"||normalized2==="yes"),rl.close()}),rl.once("close",()=>settle2(!1))})}function validateForkFlags(parsed){if(!parsed.fork)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateRebindFlags(parsed){if(!parsed.rebind)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.fork?"--fork":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0,parsed.sessionId!==void 0?"--session-id":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --rebind cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateSessionIdFlags(parsed){if(parsed.sessionId===void 0)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1));try{assertValidSessionId(parsed.sessionId)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function openSessionOrExit(path16,sessionDir){try{return SessionManager.open(path16,sessionDir)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function forkSessionOrExit(sourcePath,cwd,sessionDir,sessionId){try{return SessionManager.forkFrom(sourcePath,cwd,sessionDir,{id:sessionId})}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function rebindSessionOrExit(sourcePath,cwd,sessionDir){try{let reboundPath=await rebindSessionFile(sourcePath,cwd,sessionDir);return console.log(source_default.dim(`Session moved to ${cwd}`)),SessionManager.open(reboundPath,sessionDir)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function sessionCwdOrUndefined(sessionFile){try{return await readSessionCwd(sessionFile)}catch{return}}async function createSessionManager(parsed,cwd,sessionDir,settingsManager,appMode){if(parsed.spawnedBy&&(parsed.session||parsed.resume||parsed.continue||parsed.fork||parsed.rebind)&&console.error(source_default.yellow("Warning: --spawned-by is ignored when resuming or forking a session.")),parsed.noSession||parsed.help||parsed.listModels!==void 0||parsed.listTips)return SessionManager.inMemory(cwd,{id:parsed.sessionId,spawnedBy:parsed.spawnedBy});if(parsed.fork){parsed.sessionId&&await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir)&&(console.error(source_default.red(`Session already exists with id '${parsed.sessionId}'`)),process.exit(1));let resolved=await resolveSessionPath(parsed.fork,cwd,sessionDir);switch(resolved.type){case"path":case"local":case"global":return forkSessionOrExit(resolved.path,cwd,sessionDir,parsed.sessionId);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.rebind){let resolved=await resolveSessionPath(parsed.rebind,cwd,sessionDir);resolved.type==="not_found"&&(console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1));let sessionCwd=resolved.type==="global"?resolved.cwd:await sessionCwdOrUndefined(resolved.path);return resolved.type==="local"||sessionCwd===void 0||resolvePath(sessionCwd)===resolvePath(cwd)?openSessionOrExit(resolved.path,sessionDir):(await classifySessionRepository(resolved.path,sessionCwd,cwd)==="different"&&(console.error(source_default.red(`Refusing to rebind: ${cwd} is a different git repository than ${sessionCwd}. Use --fork '${parsed.rebind}' to copy the session into this directory instead.`)),process.exit(1)),rebindSessionOrExit(resolved.path,cwd,sessionDir))}if(parsed.session){let resolved=await resolveSessionPath(parsed.session,cwd,sessionDir);switch(resolved.type){case"path":case"local":return openSessionOrExit(resolved.path,sessionDir);case"global":{if(resolved.cwd!==""&&resolvePath(resolveMovedPath(resolved.cwd))===resolvePath(cwd))return openSessionOrExit(resolved.path,sessionDir);let action=await chooseCrossProjectAction({sessionArg:parsed.session,sessionCwd:resolved.cwd,cwd,match:await classifySessionRepository(resolved.path,resolved.cwd,cwd),interactive:appMode==="interactive",confirm:promptConfirm,out:line=>console.log(line),err:line=>console.error(line)});return action==="rebind"?rebindSessionOrExit(resolved.path,cwd,sessionDir):action==="fork"?forkSessionOrExit(resolved.path,cwd,sessionDir):(action==="abort"&&console.log(source_default.dim("Aborted.")),process.exit(action==="abort"?0:1))}case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.resume)try{let{selectSession}=await import("./session-picker-XLNIB75G.js"),movedOptions=sessionDir===void 0?{}:{sessionDir},selectedPath=await selectSession(onProgress=>withMovedSessions(SessionManager.list(cwd,sessionDir,onProgress),cwd,movedOptions),async onProgress=>markMovedSessions(await SessionManager.listAll(sessionDir,onProgress),cwd),settingsManager);selectedPath||(console.log(source_default.dim("No session selected")),process.exit(0));let target=await resolveResumeTarget({sessionPath:selectedPath,cwd,...movedOptions,confirm:selectedCwd=>(console.log(source_default.yellow(`Session found in different project: ${selectedCwd}`)),confirmSameRepositoryRebind({sessionArg:selectedPath,cwd,confirm:promptConfirm,out:line=>console.log(line)}))}).catch(error2=>(console.error(source_default.red(`Error: ${error2 instanceof Error?error2.message:String(error2)}`)),process.exit(1)));return target.rebound&&console.log(source_default.dim(`Session moved to ${cwd}`)),SessionManager.open(target.path,sessionDir)}finally{stopThemeWatcher()}if(parsed.continue){let movedHere=sessionDir===void 0?await movedHereSessionToContinue(cwd):void 0;if(movedHere!==void 0)return SessionManager.open(movedHere,sessionDir);let recent=SessionManager.continueRecent(cwd,sessionDir),recentFile=recent.getSessionFile();if(recentFile!==void 0&&existsSync45(recentFile))return recent;let movedChoice=await movedSessionToContinue({cwd,...sessionDir===void 0?{}:{sessionDir},interactive:appMode==="interactive",confirm:promptConfirm,out:line=>console.log(line),err:line=>console.error(line)});return movedChoice===void 0?recent:rebindSessionOrExit(movedChoice,cwd,sessionDir)}if(parsed.sessionId){let existingSession=await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir);if(existingSession)return parsed.spawnedBy&&console.error(source_default.yellow("Warning: --spawned-by is ignored when resuming an existing session.")),SessionManager.open(existingSession.path,sessionDir);console.error(source_default.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`))}return SessionManager.create(cwd,sessionDir,{id:parsed.sessionId,spawnedBy:parsed.spawnedBy})}function buildSessionOptions(parsed,scopedModels,hasExistingSession,modelRuntime,settingsManager){let options={},diagnostics=[],cliThinkingFromModel=!1;if(parsed.provider&&!parsed.model&&diagnostics.push({type:"error",message:`--provider requires --model (for example: --provider ${parsed.provider} --model <pattern>)`}),parsed.model){let resolved=resolveCliModel({cliProvider:parsed.provider,cliModel:parsed.model,cliThinking:parsed.thinking,modelRuntime});resolved.warning&&diagnostics.push({type:"warning",message:resolved.warning}),resolved.error&&diagnostics.push({type:"error",message:resolved.error,code:"model_unresolved"}),resolved.model&&(options.model=resolved.model,options.serviceTier=resolved.serviceTier,options.initialModelProvenance="cli",!parsed.thinking&&resolved.thinkingLevel&&(options.thinkingLevel=resolved.thinkingLevel,options.thinkingSelection=resolved.thinkingSelection,cliThinkingFromModel=!0))}if(!options.model&&scopedModels.length>0&&!hasExistingSession){let savedProvider=settingsManager.getDefaultProvider(),savedModelId=settingsManager.getDefaultModel(),savedModel=savedProvider&&savedModelId?modelRuntime.getModel(savedProvider,savedModelId):void 0,savedInScope=savedModel?scopedModels.find(sm=>modelsAreEqual(sm.model,savedModel)):void 0;savedInScope?(options.model=savedInScope.model,options.initialModelProvenance="scoped",!parsed.thinking&&savedInScope.thinkingLevel&&(options.thinkingLevel=savedInScope.thinkingLevel,options.thinkingSelection=savedInScope.thinkingSelection)):(options.model=scopedModels[0].model,options.initialModelProvenance="scoped",!parsed.thinking&&scopedModels[0].thinkingLevel&&(options.thinkingLevel=scopedModels[0].thinkingLevel,options.thinkingSelection=scopedModels[0].thinkingSelection))}return parsed.thinking&&(options.thinkingLevel=parsed.thinking,options.thinkingSelection={level:parsed.thinking,source:"explicit"}),scopedModels.length>0&&(options.scopedModels=scopedModels.map(sm=>({model:sm.model,thinkingLevel:sm.thinkingLevel,thinkingSelection:sm.thinkingSelection,serviceTier:sm.serviceTier}))),parsed.noTools?options.noTools="all":parsed.noBuiltinTools&&(options.noTools="builtin"),parsed.tools&&(options.tools=[...parsed.tools]),parsed.excludeTools&&(options.excludeTools=[...parsed.excludeTools]),{options,cliThinkingFromModel,diagnostics}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}async function promptForMissingSessionCwd(issue,settingsManager){return showStartupSelector(settingsManager,formatMissingSessionCwdPrompt(issue),[{label:"Continue",value:issue.fallbackCwd},{label:"Cancel",value:void 0}])}function applyGrokNeoThemeFallback(settingsManager){if(settingsManager.getThemeSetting()!==void 0)return;let getThemeSetting=settingsManager.getThemeSetting.bind(settingsManager),setTheme=settingsManager.setTheme.bind(settingsManager),fallbackActive=!0;settingsManager.getThemeSetting=()=>getThemeSetting()??(fallbackActive?"grok-night":void 0),settingsManager.setTheme=theme2=>{fallbackActive=!1,setTheme(theme2)}}function createCliRuntimeFactory(configuration,local={}){let{parsed,cwd,agentDir,appMode,toolRuntime}=configuration,extensionFactories=local.extensionFactories??builtInExtensions,startupSettingsManager=local.startupSettingsManager??SettingsManager.create(cwd,agentDir),startupLoadingIndicator=local.startupLoadingIndicator??createStartupLoadingIndicator({writer:()=>{},isTTY:!1,label:`Loading ${APP_NAME}`}),trustStore=new ProjectTrustStore(agentDir),projectTrustByCwd=new Map,trustPromptMode=parsed.help||parsed.listModels!==void 0||parsed.listTips?"print":appMode,resolvedExtensionPaths=resolveCliPaths(cwd,parsed.extensions),resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes),createServices=async({cwd:cwd2,agentDir:agentDir2,projectTrustContext,launchProfile,mcpRegistry,isInitialRuntime})=>{let projectTrustDiagnostics=[],cachedProjectTrust=projectTrustByCwd.get(cwd2),hasTrustRequiringResources=hasTrustRequiringProjectResources(cwd2),savedProjectTrust=await getSavedProjectTrust(trustStore,cwd2),fullAccessTrust=presetTrustsProject(sessionExtensionFlagValues(parsed.unknownFlags,launchProfile).get("permission-preset"),startupSettingsManager.getGlobalSettings().permissionPreset)&&savedProjectTrust!==!1,shouldResolveProjectTrust=parsed.projectTrustOverride===void 0&&cachedProjectTrust===void 0&&!fullAccessTrust&&hasTrustRequiringResources,projectTrusted=shouldResolveProjectTrust?!1:cachedProjectTrust??parsed.projectTrustOverride??(fullAccessTrust||!hasTrustRequiringResources||savedProjectTrust===!0),trustFromFullAccess=fullAccessTrust&&hasTrustRequiringResources&&cachedProjectTrust===void 0&&parsed.projectTrustOverride===void 0&&savedProjectTrust!==!0,runtimeSettingsManager=SettingsManager.create(cwd2,agentDir2,{projectTrusted,trustFromFullAccess});return launchProfile?.retryFallback&&applyRetryFallbackProfile(runtimeSettingsManager,launchProfile.retryFallback),{services:await createAgentSessionServices({cwd:cwd2,agentDir:agentDir2,settingsManager:runtimeSettingsManager,...local.modelRuntime===void 0?{}:{modelRuntime:local.modelRuntime},mcpRegistry,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:sessionExtensionFlagValues(parsed.unknownFlags,launchProfile),resourceLoaderReloadOptions:shouldResolveProjectTrust?{resolveProjectTrust:async({extensionsResult})=>{let trusted=await resolveProjectTrusted({cwd:cwd2,trustStore,trustOverride:parsed.projectTrustOverride,defaultProjectTrust:startupSettingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:projectTrustContext??pauseIndicatorDuringPrompts(createProjectTrustContext({cwd:cwd2,mode:isInitialRuntime?trustPromptMode:appMode,settingsManager:startupSettingsManager,hasUI:isInitialRuntime&&trustPromptMode==="interactive"}),startupLoadingIndicator),onExtensionError:message=>projectTrustDiagnostics.push({type:"warning",message})});return projectTrustByCwd.set(cwd2,trusted),trusted}}:void 0,resourceLoaderOptions:{sessionKind:launchProfile?.sessionKind,sessionContext:launchProfile?.sessionContext,additionalExtensionPaths:resolvedExtensionPaths,additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noExtensions:parsed.noExtensions,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,systemPrompt:parsed.systemPrompt,appendSystemPrompt:parsed.appendSystemPrompt,extensionFactories}}),projectTrustDiagnostics}};return completeCompactFactory(async({cwd:cwd2,agentDir:agentDir2,sessionManager,sessionStartEvent,projectTrustContext,launchProfile,mcpRegistry})=>{let isInitialRuntime=sessionStartEvent===void 0,markSwitch=label3=>{sessionStartEvent?.reason==="resume"&&time(label3,"switch")},{services,projectTrustDiagnostics}=await createServices({cwd:cwd2,agentDir:agentDir2,...projectTrustContext!==void 0?{projectTrustContext}:{},...launchProfile!==void 0?{launchProfile}:{},...mcpRegistry!==void 0?{mcpRegistry}:{},isInitialRuntime});markSwitch("services");let{settingsManager,modelRuntime,resourceLoader}=services,diagnostics=[...projectTrustDiagnostics,...services.diagnostics,...collectSettingsDiagnosticsWithContext(settingsManager,"runtime creation"),...collectExtensionLoadDiagnostics(resourceLoader.getExtensions().errors),...(resourceLoader.getExtensions().warnings??[]).map(({path:path16,warning})=>({type:"warning",message:`Extension package "${path16}": ${warning}`}))],modelPatterns=getModelNarrowingPatterns({cliPatterns:parsed.models,legacyEnabledPatterns:settingsManager.getEnabledModels()}),scopedModels=modelPatterns&&modelPatterns.length>0?await resolveModelScope(modelPatterns,modelRuntime,{signal:AbortSignal.timeout(15e3)}):[],runtimeParsed=launchProfile===void 0?parsed:{...parsed,...launchProfile.creationModel===void 0?{}:{provider:launchProfile.creationModel.provider,model:launchProfile.creationModel.modelId},...launchProfile.initialThinkingLevel===void 0?{}:{thinking:launchProfile.initialThinkingLevel}},{options:sessionOptions,cliThinkingFromModel,diagnostics:sessionOptionDiagnostics}=buildSessionOptions(runtimeParsed,scopedModels,sessionManager.hasContextMessages(),modelRuntime,settingsManager);diagnostics.push(...sessionOptionDiagnostics),parsed.apiKey&&(sessionOptions.model?await modelRuntime.setRuntimeApiKey(sessionOptions.model.provider,parsed.apiKey):diagnostics.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"})),isInitialRuntime&&startupLoadingIndicator.setPhase("opening session"),markSwitch("sessionOptions");let created=await createAgentSessionFromServices({services,sessionManager,sessionStartEvent,model:sessionOptions.model,initialModelProvenance:sessionOptions.initialModelProvenance,thinkingLevel:sessionOptions.thinkingLevel,thinkingSelection:sessionOptions.thinkingSelection,serviceTier:sessionOptions.serviceTier,scopedModels:sessionOptions.scopedModels,tools:sessionOptions.tools,excludeTools:sessionOptions.excludeTools,noTools:sessionOptions.noTools,customTools:sessionOptions.customTools,autoTitleSessions:resolveAutoTitleSessions(appMode,parsed,sessionManager.hasContextMessages(),parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),launchProfile?.autoTitle),promptSurface:launchProfile?.promptSurface,browserEngine:launchProfile?.browserEngine,sessionEnv:launchProfile?.sessionEnv,...toolRuntime!==void 0?{toolRuntime}:{}});markSwitch("createSession");let cliThinkingOverride=runtimeParsed.thinking!==void 0||cliThinkingFromModel;if(created.session.model&&cliThinkingOverride){let selection=created.session.thinkingSelection;created.session.setThinkingLevel(selection?.requested??created.session.thinkingLevel)}return{...created,services,diagnostics}},async options=>{await createServices({...options,isInitialRuntime:!0})})}async function main(args,options){resetTimings(),recordTiming("processStart->main",Math.round(process.uptime()*1e3));let extensionFactories=[...builtInExtensions,...options?.extensionFactories??[]],offlineMode=args.includes("--print-prompt-sizes")||args.includes("--offline")||isTruthyEnvFlag2(envValue("OFFLINE"));if(offlineMode&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await runAuthCommand(args))return;if(isModelsDiscoverCommand(args)){process.exitCode=await runModelsDiscoverCommand(args.slice(2));return}if(await dispatchInternalSupervisor(args))return;process.platform==="win32"&&cleanupWindowsSelfUpdateQuarantine(getInstallPackageDir());let cwd=process.cwd(),agentDir=getAgentDir(),fromSourceWarning=getFromSourceRealConfigWarning(agentDir);fromSourceWarning&&console.error(source_default.yellow(fromSourceWarning));let bootstrapSettingsManager=SettingsManager.create(cwd,agentDir,{projectTrusted:!1});if(applyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(),await dispatchPackageCommand(args,{extensionFactories})){let exitCode=process.exitCode??0;if(process.platform==="win32"&&exitCode===0&&args[0]==="update")return;await exitAfterOutput("",exitCode);return}if(await dispatchConfigCommand(args,{extensionFactories}))return;let hostExitCode=await dispatchHostCommand(args);hostExitCode!==void 0&&await exitAfterOutput("",hostExitCode);let scheduleExitCode=await dispatchScheduleCommand(args);scheduleExitCode!==void 0&&await exitAfterOutput("",scheduleExitCode);let parsed=parseArgs(args);if(parsed.diagnostics.length>0){for(let d of parsed.diagnostics){let color=d.type==="error"?source_default.red:source_default.yellow;console.error(color(`${d.type==="error"?"Error":"Warning"}: ${d.message}`))}parsed.diagnostics.some(d=>d.type==="error")&&process.exit(1)}let toolRuntimeResolution=resolveToolRuntime(parsed);!toolRuntimeResolution.ok&&!parsed.version&&!parsed.help&&(console.error(source_default.red(`Error: ${toolRuntimeResolution.message}`)),process.exit(1));let toolRuntime=toolRuntimeResolution.ok?toolRuntimeResolution.value:"in-process";if(time("parseArgs"),parsed.version&&await printThenExit(()=>console.log(DISPLAY_VERSION),0),parsed.attach&&parsed.session&&!parsed.help){let{runAttachedTui}=await import("./run-attached-tui-G2E4FWSV.js");try{await runAttachedTui({address:parsed.attach,session:parsed.session,tuiMode:parsed.tuiMode,theme:parsed.useTheme})}catch(error2){await printThenExit(()=>console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),1)}return}if(parsed.export){let result3;try{let outputPath=parsed.messages.length>0?parsed.messages[0]:void 0;result3=await exportFromFile(parsed.export,outputPath)}catch(error2){let message=error2 instanceof Error?error2.message:"Failed to export session";console.error(source_default.red(`Error: ${message}`)),process.exit(1)}await printThenExit(()=>console.log(`Exported to: ${result3}`),0)}let appMode=parsed.printPromptSizes?"print":resolveAppMode(parsed,process.stdin.isTTY,process.stdout.isTTY);if(appMode!=="interactive"&&(!isPlainRuntimeMetadataCommand(parsed)||parsed.help&&parsed.mode==="json")&&takeOverStdout(),parsed.mode==="json"){let log=console.log.bind(console);console.log=(...args2)=>console.error(...args2),process.once("exit",()=>{console.log=log})}parsed.mode==="rpc"&&parsed.fileArgs.length>0&&(console.error(source_default.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),validateForkFlags(parsed),validateRebindFlags(parsed),validateSessionIdFlags(parsed);let{migratedAuthProviders:migratedProviders,deprecationWarnings}=runMigrations(cwd);time("runMigrations");let startupSettingsManager=SettingsManager.create(cwd,agentDir);reportDiagnostics(collectSettingsDiagnosticsWithContext(startupSettingsManager,"startup session lookup"));let resolvedExtensionPaths=resolveCliPaths(cwd,parsed.extensions),resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes);if(isPlainHelpRequest(parsed)){let projectTrusted=resolveHelpProjectTrust(parsed,cwd,agentDir),scope=helpFlagsScope(parsed,cwd,agentDir,projectTrusted),{flags:flags2,extensionPaths}=await resolveHelpExtensionFlags({cwd,agentDir,settingsManager:SettingsManager.create(cwd,agentDir,{projectTrusted}),additionalExtensionPaths:resolvedExtensionPaths??[],noExtensions:parsed.noExtensions===!0,...extensionFactories?{extensionFactories}:{}});writeHelpFlagsCache({scope,flags:flags2,extensionPaths}),await printThenExit(()=>{printHelp(flags2),printTimings()},0)}if(parsed.listTips){let{listTips}=await import("./list-tips-3D3A6GFK.js");await printThenExit(listTips,0)}if(parsed.listModels!==void 0){let services2=await createAgentSessionServices({cwd,agentDir,settingsManager:startupSettingsManager,extensionFlagValues:parsed.unknownFlags,resourceLoaderOptions:{additionalExtensionPaths:resolvedExtensionPaths,additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noExtensions:parsed.noExtensions,noSkills:!0,noPromptTemplates:!0,noThemes:!0,noContextFiles:!0,extensionFactories}});reportDiagnostics([...services2.diagnostics,...collectSettingsDiagnosticsWithContext(services2.settingsManager,"model listing"),...collectAuthDiagnostics(services2.authStorage,"model listing",{persistSeen:!0})]);let searchPattern2=typeof parsed.listModels=="string"?parsed.listModels:void 0;await printThenExit(()=>listModels(services2.modelRuntime,searchPattern2),0)}if(appMode==="interactive"&&!parsed.help&&parsed.listModels===void 0&&!parsed.listTips&&shouldRunFirstTimeSetup()&&(await showFirstTimeSetup(startupSettingsManager),time("firstTimeSetup")),appMode==="interactive"&&parsed.useTheme!==void 0&&startupSettingsManager.applyOverrides({theme:parsed.useTheme}),installMemoryReportSignal(),appMode==="rpc"&&parsed.multiSession){if(options?.extensionFactories?.length)throw new Error("Shared RPC workers require file-backed extensions; inline factories cannot cross isolates");let{presenterBootstrapFd,mcpPresenterEnforcement,...sessionArgs}=parsed,runtimeConfiguration={parsed:sessionArgs,cwd,agentDir,appMode,toolRuntime},sessionRuntime=resolveSessionRuntime(parsed),{runMultiSessionHost}=await import("./multi-session-host-CADYC2BS.js"),hostModelRuntime=sessionRuntime==="worker"?void 0:await ModelRuntime.create({credentials:AuthStorage.create(join103(agentDir,"auth.json")),authPath:join103(agentDir,"auth.json"),agentDir,modelsPath:join103(agentDir,"models.json"),signal:AbortSignal.timeout(15e3)});initTheme(startupSettingsManager.getTheme(),!1),offlineMode||startSubscriptionUsagePolling({agentDir,report:message=>{process.stderr.write(`${message}
|
|
2170
2170
|
`)}}),printTimings(),await runMultiSessionHost({presenterBootstrapFd,mcpPresenterEnforcement,agentDir,createRuntime:createCliRuntimeFactory(runtimeConfiguration,{...hostModelRuntime===void 0?{}:{modelRuntime:hostModelRuntime}}),...sessionRuntime==="worker"?{workerConfiguration:runtimeConfiguration}:{},cwd,creationModel:parsed.provider&&parsed.model?{provider:parsed.provider,modelId:parsed.model}:void 0,initialThinkingLevel:parsed.thinking,listen:parsed.listen,toolRuntime})}let envSessionDir=process.env[ENV_SESSION_DIR],sessionDir=(parsed.sessionDir?normalizePath(parsed.sessionDir):void 0)??(envSessionDir?expandTildePath(envSessionDir):void 0)??startupSettingsManager.getSessionDir(),sessionManager=await createSessionManager(parsed,cwd,sessionDir,startupSettingsManager,appMode),missingSessionCwdIssue=getMissingSessionCwdIssue(sessionManager,cwd);if(missingSessionCwdIssue)if(appMode==="interactive"){let selectedCwd=await promptForMissingSessionCwd(missingSessionCwdIssue,startupSettingsManager);selectedCwd||process.exit(0),sessionManager=SessionManager.open(missingSessionCwdIssue.sessionFile,sessionDir,selectedCwd)}else console.error(source_default.red(new MissingSessionCwdError(missingSessionCwdIssue).message)),process.exit(1);if(parsed.name!==void 0){let name=normalizeSessionName(parsed.name);name===void 0&&(console.error(source_default.red("Error: --name requires a non-empty value")),process.exit(1)),sessionManager.appendSessionInfo(name)}time("createSessionManager");let sessionCwd=sessionManager.getCwd(),autoTrustOnReloadCwd=parsed.projectTrustOverride===void 0&&!hasTrustRequiringProjectResources(sessionCwd)?sessionCwd:void 0,startupLoadingIndicator=createStartupLoadingIndicator({writer:chunk=>process.stdout.write(chunk),isTTY:process.stdout.isTTY===!0,label:`Loading ${APP_NAME}`});shouldShowStartupLoadingIndicator({appMode,stdoutIsTTY:process.stdout.isTTY===!0,helpRequested:parsed.help===!0})&&(startupLoadingIndicator.start(),startupLoadingIndicator.setPhase("extensions & models"));let createRuntime=createCliRuntimeFactory({parsed,cwd,agentDir,appMode,toolRuntime},{extensionFactories,startupSettingsManager,startupLoadingIndicator});time("createRuntime");let runtime=await createAgentSessionRuntime(createRuntime,{cwd:sessionManager.getCwd(),agentDir,sessionManager}).catch(error2=>{if(!(error2 instanceof ModelUsabilityBudgetError))throw error2;startupLoadingIndicator.stop(),console.error(source_default.red(error2.message)),process.exit(1)}).finally(()=>{startupLoadingIndicator.stop()});time("createAgentSessionRuntime"),parsed.printPromptSizes&&await printPromptSizes(runtime),await prepareSessionOpening(sessionManager,appMode);let{services,session,modelFallbackMessage}=runtime,{settingsManager,modelRuntime,resourceLoader}=services;setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),applyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs());let loadedExtensions2=resourceLoader.getExtensions().extensions,extensionFlags=loadedExtensions2.flatMap(extension=>Array.from(extension.flags.values()));parsed.help&&await printThenExit(()=>printHelp(extensionFlags),0),time("extensionFlags"),writeHelpFlagsCache({scope:helpFlagsScope(parsed,cwd,agentDir,settingsManager.isProjectTrusted()),flags:extensionFlags,extensionPaths:loadedExtensions2.map(extension=>extension.resolvedPath)}),time("helpFlagsCache");let stdinContent;appMode!=="rpc"&&(stdinContent=await readPipedStdin(pipedStdinOptions(parsed,process.stderr)),stdinContent!==void 0&&appMode==="interactive"&&(appMode="print")),time("readPipedStdin"),recordProcessLifetime(agentDir,appMode,{supervised:appMode==="rpc"}),time("recordProcessLifetime");let{initialMessage,initialImages,initialTitlePrompt}=await prepareInitialMessage(parsed,settingsManager.getImageAutoResize(),stdinContent);time("prepareInitialMessage"),parsed.grokNeo&&appMode==="interactive"&&applyGrokNeoThemeFallback(settingsManager),initTheme(settingsManager.getTheme(),appMode==="interactive"),time("initTheme"),appMode==="interactive"&&deprecationWarnings.length>0&&await showDeprecationWarnings(deprecationWarnings),time("resolveModelScope"),reportDiagnostics(runtime.diagnostics);let startupThinkingClamp=runtime.session.startupThinkingClamp;appMode!=="interactive"&&startupThinkingClamp&&reportDiagnostics([{type:"warning",message:formatThinkingClampWarning(startupThinkingClamp)}]),appMode!=="interactive"&&(reportDiagnostics([...resourceLoader.getAgentsFiles().diagnostics??[],...resourceLoader.getSkills().diagnostics].filter(diagnostic2=>diagnostic2.type==="warning"&&diagnostic2.category==="size-limit").map(diagnostic2=>({type:"warning",message:diagnostic2.path?`${diagnostic2.path}: ${diagnostic2.message}`:diagnostic2.message}))),reportDiagnostics(collectAuthDiagnostics(services.authStorage,"runtime creation",{persistSeen:appMode!=="rpc"}))),runtime.diagnostics.some(diagnostic2=>diagnostic2.type==="error")&&(runtime.diagnostics.some(diagnostic2=>diagnostic2.message.includes("Failed to load extension"))&&console.error(source_default.yellow(EXTENSION_LOAD_FAILURE_HINT)),process.exit(1)),time("createAgentSession"),appMode!=="interactive"&&!session.model&&(console.error(source_default.red(formatNoModelsAvailableMessage())),process.exit(1));let startupBenchmark=isTruthyEnvFlag2(envValue("STARTUP_BENCHMARK"));if(startupBenchmark&&appMode!=="interactive"&&(console.error(source_default.red("Error: PI_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),!offlineMode&&appMode==="rpc"){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);modelRuntime.refresh({signal:controller.signal}).catch(()=>{}).finally(()=>clearTimeout(timeout))}let stopChildReaper=await startHostChildReaper(appMode==="interactive"?()=>{}:message=>{process.stderr.write(`${message}
|
|
2171
2171
|
`)});if(!offlineMode&&(appMode==="rpc"||appMode==="interactive")&&startSubscriptionUsagePolling({agentDir,report:appMode==="interactive"?()=>{}:message=>{process.stderr.write(`${message}
|
|
2172
|
-
`)}}),appMode==="rpc"){let{runRpcMode:runRpcMode2}=await import("./rpc-mode-
|
|
2172
|
+
`)}}),appMode==="rpc"){let{runRpcMode:runRpcMode2}=await import("./rpc-mode-T5GVMUBQ.js");printTimings(),await runRpcMode2(runtime,toolRuntime)}else if(appMode==="interactive"){let{InteractiveMode:InteractiveMode2}=await import("./interactive-mode-TF7R35GK.js"),interactiveMode=new InteractiveMode2(runtime,{mcpPresenterEnforcement:parsed.mcpPresenterEnforcement,migratedProviders,authNotices:interactiveAuthNotices(services.authStorage),legacyPiEditNotice:legacyPiEditStartupNotice(),modelFallbackMessage,autoTrustOnReloadCwd,initialMessage,initialImages,initialTitlePrompt,initialMessages:parsed.messages,verbose:parsed.verbose,chrome:parsed.grokNeo?"grok":void 0,tuiMode:parsed.tuiMode,initialThemeSetting:parsed.useTheme});startupBenchmark&&(await interactiveMode.init(),time("interactiveMode.init"),await new Promise(resolve56=>setTimeout(resolve56,150)),interactiveMode.stop(),stopThemeWatcher(),printTimings(),process.stdout.writableLength>0&&await new Promise(resolve56=>process.stdout.once("drain",resolve56)),process.stderr.writableLength>0&&await new Promise(resolve56=>process.stderr.once("drain",resolve56)),process.exit(0)),printTimings(),await interactiveMode.run()}else{printTimings();let exitCode=await runPrintMode(runtime,{mode:toPrintOutputMode(appMode),messages:parsed.messages,initialMessage,initialImages});reportDiagnostics(collectAuthDiagnostics(services.authStorage,"print mode",{persistSeen:!0})),stopChildReaper(),stopThemeWatcher(),restoreStdout(),exitCode!==0&&(process.exitCode=exitCode);return}}import*as fs5 from"node:fs";import*as os7 from"node:os";import*as path14 from"node:path";import{spawn as spawn9}from"child_process";function detectMiss(prev,message,models){let usage3=message.usage,promptTokens=usage3.input+usage3.cacheRead+usage3.cacheWrite;if(!prev||promptTokens<=0||usage3.cacheRead+usage3.cacheWrite===0&&!prev.reportedCache)return;let missedTokens=Math.min(prev.promptTokens,promptTokens)-usage3.cacheRead;if(missedTokens<=1024)return;let paidTokens=usage3.input+usage3.cacheWrite,paidPerToken=paidTokens>0?(usage3.cost.input+usage3.cost.cacheWrite)/paidTokens:0,readPerToken=usage3.cacheRead>0?usage3.cost.cacheRead/usage3.cacheRead:(models.getModel(message.provider,message.model)?.cost.cacheRead??0)/1e6;return{missedTokens,missedCost:missedTokens*Math.max(0,paidPerToken-readPerToken),idleMs:Math.max(0,message.timestamp-prev.timestamp),modelChanged:`${message.provider}/${message.model}`!==prev.modelKey}}function asPreviousRequest(message,reportedCache){let usage3=message.usage,promptTokens=usage3.input+usage3.cacheRead+usage3.cacheWrite;if(!(promptTokens<=0))return{promptTokens,modelKey:`${message.provider}/${message.model}`,timestamp:message.timestamp,reportedCache:reportedCache||usage3.cacheRead+usage3.cacheWrite>0}}function scan(entries,models){let prev,totals2={missedTokens:0,missedCost:0,missCount:0},misses=new Map;for(let entry2 of entries){if(entry2.type==="compaction"||entry2.type==="branch_summary"){prev=void 0;continue}if(entry2.type==="usage"&&entry2.kind==="cache_warm"){let promptTokens=entry2.usage.input+entry2.usage.cacheRead+entry2.usage.cacheWrite;promptTokens>0&&(prev={promptTokens,modelKey:`${entry2.provider}/${entry2.model}`,timestamp:Date.parse(entry2.timestamp),reportedCache:!0})}else if(entry2.type==="message"&&entry2.message.role==="assistant"){let miss=detectMiss(prev,entry2.message,models);miss&&(totals2.missedTokens+=miss.missedTokens,totals2.missedCost+=miss.missedCost,totals2.missCount+=1,misses.set(entry2.message,miss)),prev=asPreviousRequest(entry2.message,prev?.reportedCache??!1)??prev}}return{prev,totals:totals2,misses}}function computeCacheWaste(entries,models){return scan(entries,models).totals}function collectCacheMisses(entries,models){return scan(entries,models).misses}function detectCacheMiss(entries,message,models){return detectMiss(scan(entries,models).prev,message,models)}function brandSource(brand){let configured=brand.changelog;return configured?{id:brand.name.toLowerCase(),path:configured.path,version:configured.version,rewriteLinks:!1}:{id:brand.name.toLowerCase(),path:getChangelogPath(),version:void 0,rewriteLinks:!1}}function resolveChangelogSource(){return BRAND?brandSource(BRAND):{id:"engine",path:getChangelogPath(),version:VERSION,rewriteLinks:!0}}var MAX_AGE=10080*60*1e3;function normalizeStackPath(value){return value.replace(/\\/g,"/").replace(/\/+$/u,"")}function stackContainsPath(stack,targetPath,includeDescendants){let target=normalizeStackPath(targetPath);if(!target||isSyntheticPath(target))return!1;let caseInsensitive=/^[a-z]:\//iu.test(target),haystack=caseInsensitive?stack.toLowerCase():stack,needle=caseInsensitive?target.toLowerCase():target;if(includeDescendants)return haystack.includes(`${needle}/`);let index=haystack.indexOf(needle);for(;index!==-1;){let next=haystack[index+needle.length];if(next===void 0||next===":"||next===")"||/\s/u.test(next))return!0;index=haystack.indexOf(needle,index+needle.length)}return!1}function findExtensionStackMatches(stack,extensions){if(!stack)return[];let normalizedStack=stack.split(`
|
|
2173
2173
|
`).slice(1).filter(line=>/^\s+at\s/u.test(line)).map(line=>{try{return decodeURI(line)}catch{return line}}).join(`
|
|
2174
2174
|
`).replace(/\\/g,"/"),matches2=[],seen=new Set;for(let extension of extensions){let resolvedPath=normalizeStackPath(extension.resolvedPath),singleFilePackage=extension.sourceInfo.origin==="package"&&!/^(?:npm:|git:|https?:\/\/|ssh:\/\/)/u.test(extension.sourceInfo.source)&&/\.[cm]?[jt]s$/u.test(extension.sourceInfo.source),packageRoot=extension.sourceInfo.origin==="package"&&!singleFilePackage&&extension.sourceInfo.baseDir?extension.sourceInfo.baseDir:void 0,slashIndex=resolvedPath.lastIndexOf("/"),directoryEntry=/\/index\.[cm]?[jt]s$/u.test(resolvedPath);if(!(packageRoot?stackContainsPath(normalizedStack,packageRoot,!0):directoryEntry&&slashIndex!==-1?stackContainsPath(normalizedStack,resolvedPath.slice(0,slashIndex),!0):stackContainsPath(normalizedStack,resolvedPath,!1)))continue;let label3=extension.sourceInfo.origin==="package"&&extension.sourceInfo.source?extension.sourceInfo.source:extension.path;seen.has(label3)||(seen.add(label3),matches2.push(label3))}return matches2}function registerLocalMcpPresenter(ui,sessionId,lifetime,admit){let authority=new McpPresenterAuthority,binding=authority.bind(sessionId,sessionId,admit),activeInput,drafts=new Map,sender=authority.connect("local_tui",frame=>{if(frame.type!=="mcp_form_request")return drafts.get(frame.dialogId)?.abort(),drafts.delete(frame.dialogId),!0;let active=activeInput;if(!active)return!1;let{input}=active,draft=new AbortController;drafts.set(frame.dialogId,draft);let signal=AbortSignal.any([input.operationSignal,input.presentationSignal,lifetime,draft.signal]),{sessionId:sessionId2,bindingEpoch,attachmentEpoch,grantId,dialogId,dialogToken,formRevision}=frame,envelope2={sessionId:sessionId2,bindingEpoch,attachmentEpoch,grantId,dialogId,dialogToken,formRevision};return collectMrtrForm({ui,signal,presented:()=>authority.receive(sender,{...envelope2,type:"mcp_form_presented"})},`${frame.server.label} (${frame.server.source})`,{message:frame.message,requestedSchema:frame.schema},signal).then(result3=>{signal.aborted||authority.receive(sender,{...envelope2,type:"mcp_form_response",...result3})},()=>active.fail()).finally(()=>drafts.delete(frame.dialogId)),!0});authority.attach(sender,binding);let owner=authority.enroll();owner.acquire(owner.register(binding,sender,{kind:"local_tui"}));let dispose=()=>{authority.dispose();for(let draft of drafts.values())draft.abort();drafts.clear()};lifetime.addEventListener("abort",dispose,{once:!0});let privateForms={epoch:binding.epoch,signal:binding.signal,capture:()=>{let presentation=binding.capture();if(presentation)return{...presentation,present:async input=>{let deadline=performance.now()+input.deadlineMs,timeout=new AbortController,timer=setTimeout(()=>timeout.abort(),Math.max(0,input.deadlineMs)),signal=AbortSignal.any([input.operationSignal,input.presentationSignal,presentation.signal,lifetime,timeout.signal]);try{return await queuedForm(binding,signal,async()=>{let failure2=new AbortController,current={input:{...input,presentationSignal:AbortSignal.any([signal,failure2.signal]),deadlineMs:Math.max(0,deadline-performance.now())},fail:()=>failure2.abort()};activeInput=current;try{return await presentation.present(current.input)}finally{activeInput===current&&(activeInput=void 0)}})}catch{return{kind:input.operationSignal.aborted||binding.signal.aborted||input.operationCurrent?.()===!1?"operation_aborted":"processing_failure",source:"host_termination",humanAdmission:!1}}finally{clearTimeout(timer)}}}},dispose};return lifetime.aborted&&dispose(),privateForms}import{spawn as spawn8,spawnSync}from"node:child_process";function checkGhAuth(){let result3=spawnSync("gh",["auth","status"],{encoding:"utf-8"});return result3.error!==void 0?"missing":result3.status===0?"ok":"logged-out"}function uploadSecretGist(html,fileName,signal){return new Promise(resolve56=>{if(signal.aborted){resolve56({code:null,stdout:"",stderr:"",aborted:!0});return}let child=spawn8("gh",["gist","create","--filename",fileName,"-"],{stdio:["pipe","pipe","pipe"]}),stdout="",stderr="",onAbort=()=>signalSpawnedChild(child);signal.addEventListener("abort",onAbort,{once:!0}),child.stdout.on("data",data=>{stdout+=data.toString()}),child.stderr.on("data",data=>{stderr+=data.toString()}),child.on("error",error2=>{signal.removeEventListener("abort",onAbort),resolve56({code:null,stdout,stderr:error2.message,aborted:signal.aborted})}),child.on("close",code=>{signal.removeEventListener("abort",onAbort),resolve56({code,stdout,stderr,aborted:signal.aborted})}),child.stdin.on("error",()=>{}),child.stdin.end(html)})}import{homedir as homedir26,hostname,userInfo}from"node:os";var RUN_CHAR="[A-Za-z0-9+/_-]",PAD2="={0,2}",GAP=String.raw`(?:\\?\r?\n[ \t]*|(?:\\r)?\\n[ \t]*|["'][ \t]*[+,]?[ \t]*(?:\r?\n[ \t]*)?["'])`,SINGLE_RUN=new RegExp(`(?<!${RUN_CHAR})${RUN_CHAR}{20,}${PAD2}(?![A-Za-z0-9+/=_-])`,"g"),SPLIT_RUN=new RegExp(`(?<!${RUN_CHAR})(${RUN_CHAR}{8,})(${GAP})(${RUN_CHAR}{8,}${PAD2})(?![A-Za-z0-9+/=_-])`,"g"),WRAPPED_TAIL=new RegExp(`(<redacted>)(${GAP})(${RUN_CHAR}{6,}${PAD2})(?![A-Za-z0-9+/=_-])`,"g"),INTEGRITY_PREFIX=/sha(?:256|384|512)-$/,INTEGRITY_RUN=/^sha(?:256|384|512)-/;function shannonBitsPerChar(text4){let counts=new Map;for(let char of text4)counts.set(char,(counts.get(char)??0)+1);let bits=0;for(let n of counts.values())bits-=n/text4.length*Math.log2(n/text4.length);return bits}var WORD_PIECE=/[A-Z]?[a-z]{3,}|[0-9]+/g,CASE_PIECE=/[A-Z]?[a-z]+|[A-Z]+(?![a-z])|[0-9]+/g;function pronounceable(piece){return/^[0-9]+$/.test(piece)?piece.length<=3:/[aeiouy]/i.test(piece)&&!/[^aeiouy]{4,}/i.test(piece)}function readsAsWords(run2,coverage=.6){let letters=run2.replace(/[^A-Za-z]/g,""),vowels=letters.replace(/[^aeiouAEIOU]/g,"").length;if(letters.length===0||vowels/letters.length<.3)return!1;let covered=[...run2.matchAll(WORD_PIECE)].map(match=>match[0]).filter(pronounceable).reduce((sum,piece)=>sum+piece.length,0),pieces=run2.match(CASE_PIECE)??[];return covered>=run2.length*coverage&&pieces.length>0&&run2.length/pieces.length>=3}function readsAsPath(run2){let segments2=run2.split("/").filter(segment=>segment.length>0);return segments2.length>=2&&segments2.every(isPlainSegment)}function isPlainSegment(segment){return/^[a-z0-9._@-]+$/.test(segment)||/^[A-Z0-9_]+$/.test(segment)||readsAsWords(segment)}function looksGenerated(run2){let body=run2.replace(/=+$/,"");if(body.length<16)return!1;let upper=body.replace(/[^A-Z]/g,"").length,lower2=body.replace(/[^a-z]/g,"").length,digits=body.replace(/[^0-9]/g,"").length,symbols=body.replace(/[^+/]/g,"").length,classes=[upper,lower2,digits,symbols].filter(n=>n>0).length;return lower2<2||upper<2&&classes<3||shannonBitsPerChar(body)<Math.min(3.8,Math.log2(body.length)-1.2)?!1:!readsAsWords(body)&&!readsAsPath(body)}function plainHalf(half3){return/^[a-z0-9._@-]+$/.test(half3)||/^[A-Z0-9_]+$/.test(half3)||readsAsPath(half3)||readsAsWords(half3,.85)}function integrityAt(run2,offset,whole){return INTEGRITY_RUN.test(run2)||INTEGRITY_PREFIX.test(whole.slice(Math.max(0,offset-7),offset))}function joinedLooksGenerated(head,tail){return!plainHalf(head)&&!plainHalf(tail)&&looksGenerated(head+tail)}function redactGeneratedValues(text4,onRedact){let result3=text4.replace(SPLIT_RUN,(match,head,gap,tail,offset,whole)=>integrityAt(head,offset,whole)||!joinedLooksGenerated(head,tail)?match:(onRedact(),`<redacted>${gap}<redacted>`));return result3=result3.replace(SINGLE_RUN,(run2,offset,whole)=>integrityAt(run2,offset,whole)||run2.length<32&&!/[+/]|=$/.test(run2)||!looksGenerated(run2)?run2:(onRedact(),"<redacted>")),result3.replace(WRAPPED_TAIL,(match,redacted,gap,tail)=>!(/[A-Za-z]/.test(tail)&&(/[0-9]/.test(tail)||/[A-Z]/.test(tail)&&/[a-z]/.test(tail)))||/^[a-z0-9._@-]+$/.test(tail)||/^[A-Z0-9_]+$/.test(tail)||readsAsPath(tail)?match:(onRedact(),`${redacted}${gap}<redacted>`))}var EDGE_START=new RegExp(`^(${RUN_CHAR}{8,}${PAD2})`),EDGE_END=new RegExp(`(?<!${RUN_CHAR})(${RUN_CHAR}{8,})$`);function redactAcrossBoundary(left,right,onRedact){let end=EDGE_END.exec(left)?.[1],start=EDGE_START.exec(right)?.[1];return end===void 0||start===void 0||!joinedLooksGenerated(end,start)?[left,right]:(onRedact(),[`${left.slice(0,-end.length)}<redacted>`,`<redacted>${right.slice(start.length)}`])}var SENSITIVE_WORDS=new Set(["key","keys","apikey","token","tokens","secret","secrets","pass","passwd","password","passwords","passphrase","pwd","auth","authorization","credential","credentials","cookie","cookies","session","sessionid","private","signature"]),ORDINARY_NAMES=new Set(["public_key","public_key_path","key_id","auth_mode","auth_type","max_tokens","max_output_tokens"]);function words3(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(word=>word.length>0)}function isSensitiveKeyName(name){let parts=words3(name);return parts.some(word=>SENSITIVE_WORDS.has(word))?!ORDINARY_NAMES.has(parts.join("_")):!1}function currentShareRedactionContext(){let userName="";try{userName=userInfo().username}catch{userName=process.env.USER??process.env.USERNAME??""}return{homeDirectory:homedir26(),userName,hostName:hostname()}}var MIN_LITERAL_LENGTH=3,IDENTITY_CHAR="[\\p{L}\\p{N}\\p{M}_.-]",WORD_CHAR="[\\p{L}\\p{N}\\p{M}]",COMMON_NAMES=new Set(["admin","user","users","test","home","root","runner","guest","default","shared"]);function escapeRegExp4(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ANY_SEPARATOR="(?:/|\\\\{1,2}|%2[Ff]|%5[Cc])";function homePattern(homeDirectory){let segments2=homeDirectory.split(/[\\/]+/).filter(segment=>segment.length>0);if(segments2.length===0)return;let drive=/^[A-Za-z]:$/.test(segments2[0]??"")?segments2.shift():void 0,body=segments2.map(segment=>escapeRegExp4(segment).replace(/ /g,"(?: |%20|\\+)")).join(ANY_SEPARATOR),prefix=drive===void 0?ANY_SEPARATOR:`${escapeRegExp4(drive)}${ANY_SEPARATOR}`;return new RegExp(`(?:file:${ANY_SEPARATOR}{0,3})?${prefix}${body}(?!${IDENTITY_CHAR})`,"giu")}var OTHER_HOME=new RegExp(`(?:[A-Za-z]:)?${ANY_SEPARATOR}(?:Users|home)${ANY_SEPARATOR}[^\\s/\\\\'"%:)<>\\]]{1,64}`,"gi");function literalPattern(value){let trimmed=value.trim();if(!(trimmed.length<MIN_LITERAL_LENGTH||COMMON_NAMES.has(trimmed.toLowerCase())))return new RegExp(`(?<!${WORD_CHAR})${escapeRegExp4(trimmed)}(?!${WORD_CHAR})`,"giu")}var PRIVATE_KEY_BLOCK=/-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----(?:[\s\S]*?-----END [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----|[\s\S]*$)/g,CREDENTIAL_REWRITES=[[/\b(Bearer|Basic|Token)(\s{1,5})(?:<redacted>)?(?=[A-Za-z]*[0-9._~+/=-])[A-Za-z0-9._~+/=-]{8,}/gi,(_m,scheme,gap)=>`${scheme}${gap}<redacted>`],[/\b([A-Za-z][A-Za-z0-9+.-]{0,20}:\/\/[^\s/:@]{1,64}:)[^\s/@]{1,256}@/g,(_m,prefix)=>`${prefix}<redacted>@`],[/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,()=>"<redacted>"],[/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g,()=>"<redacted>"],[/\bgh[pousr]_[A-Za-z0-9]{20,}/g,()=>"<redacted>"],[/\bgithub_pat_[A-Za-z0-9_]{20,}/g,()=>"<redacted>"],[/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,()=>"<redacted>"],[/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,()=>"<redacted>"],[/\bAIza[0-9A-Za-z_-]{35}\b/g,()=>"<redacted>"],[/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g,()=>"<redacted>"],[/\bhf_[A-Za-z0-9]{30,}/g,()=>"<redacted>"],[/\bnpm_[A-Za-z0-9]{36}\b/g,()=>"<redacted>"],[/\bglpat-[A-Za-z0-9_-]{20,}/g,()=>"<redacted>"],[/(?<![A-Za-z0-9-])((?:Set-)?Cookie)(\s{0,3}:\s{0,3})[^\n"]+/gi,(_m,name,sep27)=>`${name}${sep27}<redacted>`]],KEY_VALUE=/([A-Za-z0-9_.[\]-]{1,128})((?:\\?["'])?[ \t]{0,3}[:=][ \t]{0,3})(?:(\\?["'])((?:(?!\3)[^\n]){0,2000})\3|([^\s"'\\&,;}[{(=)][^\n"'\\&,;}()]{0,1999}))/g,KEY_COLLECTION=/((["']?)([A-Za-z0-9_.-]{1,128})\2[ \t]{0,3}[:=][ \t]{0,3})(\[[^\]\n]{0,2000}\]|\{[^}\n]{0,2000}\})/g,KEY_YAML_LIST=/^([ \t]*)([A-Za-z0-9_.-]{1,128}):[ \t]*\r?\n((?:\1[ \t]*-[ \t]+[^\n]*(?:\r?\n|$))+)/gm,ALREADY_REDACTED=/^(?:(?:Bearer|Basic|Token|Digest)\s+)?(?:<redacted>\s*)+$/i,QUOTED2=/"(?:[^"\\\n]|\\.)*"|'[^'\n]*'/g,DATA_URI=/data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,EMAIL=/(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,64}(?:@|%40)[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63}){1,5}/g,IPV4=/(?<!\d|\d\.)(?:\d{1,3}\.){3}\d{1,3}(?!\d|\.\d)/g;function keepsAddress(address){return address.startsWith("127.")||address==="0.0.0.0"}function count(tally,category){tally.set(category,(tally.get(category)??0)+1)}function redactQuoted(quoted,tally){let quote=quoted[0]??'"';if(quoted.length<=2)return quoted;let replaced=`${quote}<redacted>${quote}`;return replaced!==quoted&&count(tally,"credential"),replaced}var PLACEHOLDER=/<(?:redacted(?: private key)?|email|ip|host|user)>|\[image omitted from share\]/g;function replaceOutsidePlaceholders(text4,pattern,replace){let out="",last=0;for(let match of text4.matchAll(PLACEHOLDER)){let at=match.index??0;out+=text4.slice(last,at).replace(pattern,replace)+match[0],last=at+match[0].length}return out+text4.slice(last).replace(pattern,replace)}function redactShareText(text4,context,tally){if(text4.length===0)return text4;let result3=text4,home=homePattern(context.homeDirectory);home&&(result3=result3.replace(home,()=>(count(tally,"home path"),"~"))),result3=result3.replace(OTHER_HOME,match=>(count(tally,"home path"),match.replace(/[^/\\%]+$/,"<user>"))),result3=result3.replace(DATA_URI,()=>(count(tally,"image"),"[image omitted from share]")),result3=result3.replace(PRIVATE_KEY_BLOCK,()=>(count(tally,"private key"),"<redacted private key>")),result3=result3.replace(KEY_COLLECTION,(match,prefix,_quote,key,collection)=>isSensitiveKeyName(key)?prefix+collection.replace(QUOTED2,quoted=>redactQuoted(quoted,tally)):match),result3=result3.replace(KEY_YAML_LIST,(match,indent,key,items)=>{if(!isSensitiveKeyName(key))return match;let redacted=items.replace(/^([ \t]*-[ \t]+)(\S[^\n]*)/gm,(_item,bullet,item)=>(item!=="<redacted>"&&count(tally,"credential"),`${bullet}<redacted>`));return`${indent}${key}:
|
|
2175
2175
|
${redacted}`});for(let[pattern,rewrite]of CREDENTIAL_REWRITES)result3=result3.replace(pattern,(...args)=>{let match=String(args[0]),groups=args.slice(1).filter(value=>typeof value=="string"),replaced=rewrite(match,...groups);return replaced!==match&&count(tally,"credential"),replaced});result3=result3.replace(KEY_VALUE,(match,key,separator,quote,quoted,bare)=>{if(!isSensitiveKeyName(key)||quote===void 0&&bare==="<redacted>")return match;let replaced=quote===void 0?`${key}${separator}<redacted>${(bare??"").match(/\s*$/)?.[0]??""}`:`${key}${separator}${quote}<redacted>${quote}`,value=quote===void 0?bare??"":quoted;return replaced!==match&&!ALREADY_REDACTED.test(value.trim())&&count(tally,"credential"),replaced}),result3=redactGeneratedValues(result3,()=>count(tally,"credential")),result3=result3.replace(EMAIL,()=>(count(tally,"email"),"<email>")),result3=result3.replace(IPV4,address=>keepsAddress(address)?address:(count(tally,"ip address"),"<ip>"));let shortHost=context.hostName.split(".")[0]??"";for(let[value,placeholder,category]of[[context.hostName,"<host>","host name"],[shortHost,"<host>","host name"],[context.userName,"<user>","user name"],...(context.extraLiterals??[]).map(value2=>[value2,"<user>","user name"])]){let pattern=literalPattern(value);pattern&&(result3=replaceOutsidePlaceholders(result3,pattern,()=>(count(tally,category),placeholder)))}return result3}import{createHash as createHash27}from"node:crypto";import{mkdtempSync as mkdtempSync2,rmSync as rmSync17,writeFileSync as writeFileSync24}from"node:fs";import{tmpdir as tmpdir7}from"node:os";import{join as join104}from"node:path";function newOutputOmissions(){return{count:0}}var OMITTED_RESULT_HTML=["resultHtmlCollapsed","resultHtmlExpanded"];function note(label3){return{type:"text",text:`[output omitted: ${label3}]`}}function omit(omissions){omissions.count++}function projectRecord(record10,omissions){if(record10.role==="toolResult"){omit(omissions);let toolName=typeof record10.toolName=="string"?record10.toolName:"tool";return{...record10,content:[note(toolName)],details:void 0}}if(record10.role==="bashExecution")return omit(omissions),{...record10,output:"[output omitted: command]",fullOutputPath:void 0};if(record10.role==="custom"||record10.type==="custom_message"){omit(omissions);let customType=typeof record10.customType=="string"?record10.customType:"extension";return{...record10,content:[note(customType)],details:void 0}}if(record10.type==="custom")return{...record10,data:void 0};if(record10.type==="compaction")return{...record10,details:void 0,systemMessage:void 0};if(record10.type==="branch_summary")return{...record10,details:void 0};if(record10.type==="context_edit"&&record10.replacement!==null&&typeof record10.replacement=="object")return omit(omissions),{...record10,replacement:{content:[note("context edit")]}}}function projectRenderedTools(value){return value===null||typeof value!="object"?value:Object.fromEntries(Object.entries(value).map(([id,rendered])=>{if(rendered===null||typeof rendered!="object")return[id,rendered];let kept=Object.entries(rendered).filter(([key])=>!OMITTED_RESULT_HTML.some(omitted=>omitted===key));return[id,Object.fromEntries(kept)]}))}function omitToolOutputs(value,omissions){return project(value,omissions)}function project(value,omissions){if(Array.isArray(value))return value.map(item=>project(item,omissions));if(value===null||typeof value!="object")return value;let record10=value,projected=projectRecord(record10,omissions);if(projected)return projected;let out={};for(let[key,child]of Object.entries(record10))out[key]=key==="renderedTools"?projectRenderedTools(child):project(child,omissions);return out}function isImageBlock(value){if(typeof value.type=="string"&&/image/i.test(value.type))return!0;let source2=value.source;return typeof source2=="object"&&source2!==null&&Reflect.get(source2,"type")==="base64"}var SCHEMA_TYPES=new Set(["string","number","integer","boolean","object","array","null"]),SCHEMA_KEYWORDS=new Set(["type","description","title","format","enum","items","properties","required","minLength","maxLength","pattern","additionalProperties","nullable"]);function isSchemaNode(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;let type2=Reflect.get(value,"type");return typeof type2!="string"||!SCHEMA_TYPES.has(type2)?!1:Object.keys(value).every(key=>SCHEMA_KEYWORDS.has(key))}function dropAllStrings(value,tally){return typeof value=="string"?value.length===0?value:(value!=="<redacted>"&&count(tally,"credential"),"<redacted>"):Array.isArray(value)?value.map(item=>dropAllStrings(item,tally)):value===null||typeof value!="object"?value:Object.fromEntries(Object.entries(value).map(([key,child])=>[key,dropAllStrings(child,tally)]))}function redactShareValue(value,context,tally){return redactNode(value,context,tally)}function redactNode(value,context,tally){if(typeof value=="string")return redactShareText(value,context,tally);if(Array.isArray(value))return joinAdjacentText(value.map(item=>redactNode(item,context,tally)),tally);if(value===null||typeof value!="object")return value;let record10=value;if(isImageBlock(record10))return count(tally,"image"),{type:"text",text:"[image omitted from share]"};let out={};for(let[key,child]of Object.entries(record10))out[key]=isSensitiveKeyName(key)&&!isSchemaNode(child)?dropAllStrings(child,tally):redactNode(child,context,tally);return out}function textOf3(item){if(typeof item=="string")return item;if(item===null||typeof item!="object"||Reflect.get(item,"type")!=="text")return;let text4=Reflect.get(item,"text");return typeof text4=="string"?text4:void 0}function withText(item,text4){return typeof item=="string"?text4:{...item,text:text4}}function joinAdjacentText(items,tally){for(let index=0;index+1<items.length;index++){let left=textOf3(items[index]),right=textOf3(items[index+1]);if(left===void 0||right===void 0)continue;let[nextLeft,nextRight]=redactAcrossBoundary(left,right,()=>count(tally,"credential"));nextLeft!==left&&(items[index]=withText(items[index],nextLeft),items[index+1]=withText(items[index+1],nextRight))}return items}function prepareShare(render2,context,includeOutputs=!1){let tally=new Map,omittedOutputs=0,html=render2(value=>{if(includeOutputs)return redactShareValue(value,context,tally);let omissions=newOutputOmissions(),projected=omitToolOutputs(value,omissions);return omittedOutputs=Math.max(omittedOutputs,omissions.count),redactShareValue(projected,context,tally)}),sha2563=createHash27("sha256").update(html).digest("hex");return{html,sha256:sha2563,tally,includesOutputs:includeOutputs,omittedOutputs}}var CATEGORY_ORDER2=["credential","private key","home path","user name","host name","email","ip address","image"];function describeTally(tally){let parts=CATEGORY_ORDER2.flatMap(category=>{let total=tally.get(category)??0;return total===0?[]:[`${total} ${category}${total===1?"":"s"}`]});return parts.length===0?"nothing matched the redaction rules":parts.join(", ")}function describeShare(prepared,viewerBase){let kilobytes=Math.max(1,Math.round(Buffer.byteLength(prepared.html)/1024)),viewer=viewerBase===void 0?"No viewer is configured, so you get the gist link only.":`The link opens in ${viewerBase}, a viewer set by SHARE_VIEWER_URL that receives the gist id.`;return["Share this session as a secret GitHub gist?","",prepared.includesOutputs?`Uploads: the conversation, tool calls AND their outputs, system prompt and tool list, as one HTML file (${kilobytes} KB, sha256 ${prepared.sha256.slice(0,12)}).`:`Uploads: your messages and the replies, tool names and arguments (including any file content the agent wrote or edited), system prompt and tool list, as one HTML file (${kilobytes} KB, sha256 ${prepared.sha256.slice(0,12)}).`,prepared.includesOutputs?"Tool outputs are included (file contents, command output, extension messages).":`Tool outputs are left out: ${prepared.omittedOutputs} replaced by "[output omitted]".`,`Removed first: ${describeTally(prepared.tally)}. Images are always left out.`,"Who can read it: anyone with the link. A secret gist is unlisted, not private, and stays until you delete it on GitHub.",viewer,"Redaction is pattern-based and can miss things; review the exact file if the session holds anything sensitive."].join(`
|
|
@@ -2228,7 +2228,7 @@ ${skill.content}`).join(`
|
|
|
2228
2228
|
`)}function getScopeAutocompleteTag(scope){switch(scope){case"user":return"u";case"project":return"p";case"temporary":return"t";case"system":return"s";default:return assertNever3(scope)}}function getDisplaySourceInfo(sourceInfo){let source2=sourceInfo?.source??"local",scope=sourceInfo?.scope??"project";return scope==="system"?{label:"system",color:"muted"}:source2==="local"?scope==="user"?{label:"user",color:"muted"}:scope==="project"?{label:"project",color:"muted"}:{label:"path",scopeLabel:"temp",color:"muted"}:source2==="cli"?{label:"path",scopeLabel:scope==="temporary"?"temp":void 0,color:"muted"}:{label:source2,scopeLabel:scope==="user"?"user":scope==="project"?"project":"temp",color:"accent"}}function assertNever3(value){throw new Error(`Unexpected resource scope: ${String(value)}`)}var LOGIN_CANCELLED_NOTICE="Login cancelled";function isLoginCancellation(error2){return error2==null||typeof error2=="object"&&error2.name==="AbortError"?!0:errorMessage5(error2)===LOGIN_CANCELLED_NOTICE}function describeLoginFailure(error2,providerName,method){if(isLoginCancellation(error2))return{level:"status",message:LOGIN_CANCELLED_NOTICE};let message=errorMessage5(error2);return error2 instanceof CredentialSynchronizationError?{level:"error",message:`${method==="oauth"?`Logged in to ${providerName}`:`Saved API key for ${providerName}`}, but local model state could not be synchronized: ${message}`}:{level:"error",message:`${method==="oauth"?`Sign-in to ${providerName} did not finish`:`Could not save the API key for ${providerName}`}: ${message}${/[.!?]$/.test(message)?"":"."} Run /login to try again.`}}function errorMessage5(error2){return error2 instanceof Error?error2.message:String(error2)}var DEFAULT_FLAG="--default";function parseModelCommandArgument(argument){let words5=(argument??"").trim().split(/\s+/).filter(word=>word.length>0),asDefault=words5.includes(DEFAULT_FLAG);return{searchTerm:words5.filter(word=>word!==DEFAULT_FLAG).join(" "),asDefault}}function isAnnouncedElsewhere(source2){return source2==="fallback"||source2==="fallback-revert"}function describeOrigin(origin){return origin.actor===void 0?origin.source:`${origin.source}: ${origin.actor}`}function modelChangeNoticeText(input){return`\u21C4 Model changed mid-turn \xB7 ${input.from===void 0?input.to:`${input.from} \u2192 ${input.to}`} (${describeOrigin(input.origin)})`}function liveModelChangeNotice(event){if(!(!event.duringTurn||isAnnouncedElsewhere(event.origin.source)))return{type:"model_change_notice",text:modelChangeNoticeText({from:event.previousModel?.id,to:event.model.id,origin:event.origin})}}function replayedModelChangeNotice(entry2){if(!(entry2.duringTurn!==!0||entry2.source===void 0||isAnnouncedElsewhere(entry2.source)))return{type:"model_change_notice",text:modelChangeNoticeText({from:entry2.originalModelId,to:entry2.modelId,origin:entry2.actor===void 0?{source:entry2.source}:{source:entry2.source,actor:entry2.actor}})}}var PAUSE_STATUS_KEY="session-pause";function pauseFooterText(view){if(!view.paused&&!view.runPaused)return;let held=view.pausedNoticeCount===1?"1 update held":`${view.pausedNoticeCount} updates held`;return view.pauseView?.records.some(record10=>record10.key==="interrupted-run")?`Interrupted \xB7 ${view.pausedNoticeCount>0?`${held} \xB7 `:""}type to continue, /resume to resume`:view.runPaused?`Run paused \xB7 ${held} \xB7 type to continue, /resume to resume the run`:`Paused \xB7 ${held} \xB7 type to continue, /resume to resume`}function resumeCommandTarget(view){return view.paused||view.runPaused?"resume_session":"session_picker"}var envelope=external_exports.object({type:external_exports.literal("error").optional(),error:external_exports.object({type:external_exports.string(),message:external_exports.string()})}),networkFailure=/network error|service unavailable|connection (?:error|lost|reset)|fetch failed|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|socket hang up|overloaded/i,otherFailure=/auth|api.?key|permission|quota|credit|billing|rate.?limit|too many requests|429/i;function isNetworkProviderError(raw,envelopeOnly=!1){if(!raw||otherFailure.test(raw))return!1;if(!envelopeOnly)return networkFailure.test(raw);try{let parsed=envelope.safeParse(JSON.parse(raw));return parsed.success&&networkFailure.test(parsed.data.error.message)}catch(error2){if(error2 instanceof SyntaxError)return!1;throw error2}}function isRetryableProviderError(raw){return raw?isNetworkProviderError(raw)?!0:isRetryableErrorMessage(raw):!1}function isNetworkProviderMessage(message){return(message.stopReason==="error"||message.stopReason==="aborted")&&isNetworkProviderError(message.errorMessage)}var ProviderFailureNotice=class{constructor(){this.details=new Set,this.expanded=!1,this.summary="The model provider may be having trouble."}add(raw){this.details.add(raw)}setExpanded(expanded){this.expanded=expanded}setSummary(summary){this.summary=summary}render(width){let lines=[];if(this.summary&&lines.push(...new Text(theme.fg("warning",`${this.summary} (${keyText("app.tools.expand")} for details)`),1,0).render(width)),this.expanded)for(let raw of this.details)lines.push(...new Text(theme.fg("dim",sanitizeTuiErrorMessage(raw)),1,0).render(width));return lines}invalidate(){}},ProviderErrorPresentation=class{constructor(chat){this.pending=!1,this.retryAwaitingFinish=!1,this.chat=chat}record(raw,expanded=!1){this.pending=!0,this.retryAwaitingFinish=!0,this.notice||(this.notice=new ProviderFailureNotice,this.notice.setExpanded(expanded),this.chat.addChild(this.notice)),this.notice.add(raw)}retrying(raw,expanded){this.record(raw,expanded),this.notice?.setSummary(void 0)}clear(){this.pending=!1,this.retryAwaitingFinish=!1,this.notice?.setSummary(void 0)}clearTransient(){this.pending=!1,this.notice?.setSummary(void 0)}get hasActiveRetry(){return this.pending}get awaitingRetryFinish(){return this.retryAwaitingFinish}finish(raw,attempts){if(raw&&this.record(raw),!this.pending)return;this.pending=!1,this.retryAwaitingFinish=!1;let count2=attempts===void 0?"":` after ${attempts} retries`;this.notice?.setSummary(`The model provider could not complete the request${count2}. Try again or choose another model with /model.`)}newTurn(){this.finish(),this.notice=void 0}};function replayAssistantTools(message,host){let firstToolIndex=message.content.findIndex(block=>block.type==="toolCall"),lastRunStart=-1;if(firstToolIndex>=0&&message.content[message.content.length-1].type!=="toolCall")for(lastRunStart=message.content.length-1;message.content[lastRunStart-1].type!=="toolCall";)lastRunStart--;if(host.addMessage(firstToolIndex<0?message:{...message,content:message.content.slice(0,firstToolIndex+1)},firstToolIndex<0||lastRunStart<0&&message.stopReason!=="aborted"),firstToolIndex<0)return;let index=firstToolIndex;for(;index<message.content.length;){let content=message.content[index];if(content.type!=="toolCall"){let start=index;for(;index<message.content.length&&message.content[index].type!=="toolCall";)index++;host.addMessage({...message,content:message.content.slice(start,index)},start===lastRunStart);continue}index++;let component=host.createTool(content.name,content.id,content.arguments);if(component.setExpanded(host.expanded),host.addChild(component),message.stopReason==="aborted"||message.stopReason==="error"){let text4=unrunToolCallText(abortedMessageForRendering(message,0,void 0));component.updateResult({content:[{type:"text",text:text4}],isError:!0})}else host.pending.set(content.id,component)}}function sharedSessionDir(source2){return source2.usesDefaultSessionDir()?{}:{sessionDir:source2.getSessionDir()}}function currentScopeSessions(source2,onProgress,signal){let cwd=source2.getCwd();return withMovedSessions(SessionManager.list(cwd,source2.getSessionDir(),onProgress,signal),cwd,sharedSessionDir(source2))}async function allScopeSessions(source2,onProgress,signal){let sessions3=source2.usesDefaultSessionDir()?await SessionManager.listAll(onProgress,signal):await SessionManager.listAll(source2.getSessionDir(),onProgress,signal);return markMovedSessions(sessions3,source2.getCwd())}async function chooseResumePath(sessionPath,source2,ui){let cwd=source2.getCwd();try{return(await resolveResumeTarget({sessionPath,cwd,...sharedSessionDir(source2),confirm:sessionCwd=>ui.confirm(REBIND_PROMPT,`Session found in different project: ${sessionCwd}
|
|
2229
2229
|
This directory is the same git repository: ${cwd}
|
|
2230
2230
|
Choose No to open it where it is.`)})).path}catch(error2){if(!(error2 instanceof Error))throw error2;ui.showError(`Could not move session: ${error2.message}`);return}}var RISKY_MAIN_MODEL_WARNING="Not a recommended model. It can perform dangerous actions such as harming your computer and has not been tested. Please use a different model.",RISKY_MODEL_FAMILIES=["minimax","qwen"];function isRiskyMainModel(model){let searchableLabel=`${model.provider}/${model.id} ${model.name}`.toLowerCase();return RISKY_MODEL_FAMILIES.some(family=>searchableLabel.includes(family))}import{existsSync as existsSync47,mkdirSync as mkdirSync29,readFileSync as readFileSync48,realpathSync as realpathSync19,writeFileSync as writeFileSync25}from"node:fs";import{join as join106}from"node:path";var SKIP_RUNTIME_NOTICE_ENV_SUFFIX="SKIP_RUNTIME_NOTICE";function runtimePinEnvName(env){return env.OMO_NATIVE==="1"?"OMO_RUNTIME":RUNTIME_ENV_VAR}function runtimeNoticeSkipReason(gate){if(gate.versions.bun!==void 0)return"bun-runtime";if(gate.env[runtimePinEnvName(gate.env)]==="node")return"node-pinned";if(gate.hasInheritedInspectorOption)return"inspector";if(gate.skipRequested)return"skip-requested";if(gate.shownVersion===gate.engineVersion)return"already-shown"}function reinstallTarget(brand,packageName){if(brand===void 0)return{packageName,installSpec:packageName,ignoreScripts:!0};let update2=brand.update;if(update2===void 0)return;let installSpec=update2.distTag==="latest"?update2.packageName:`${update2.packageName}@${update2.distTag}`;return{packageName:update2.packageName,installSpec,ignoreScripts:!1}}function uninstallCommand(method,packageName){switch(method){case"npm":return`npm uninstall -g ${packageName}`;case"pnpm":return`pnpm remove -g ${packageName}`;case"yarn":return`yarn global remove ${packageName}`;case"bun":case"bun-binary":case"unknown":return}}function bunReinstallCommand(method,target){let install=`bun add -g ${target.ignoreScripts?"--ignore-scripts ":""}${target.installSpec}`,uninstall=uninstallCommand(method,target.packageName);return uninstall===void 0?install:`${uninstall} && ${install}`}function installBunCommand(platform4){return platform4==="win32"?'powershell -c "irm bun.sh/install.ps1 | iex"':"curl -fsSL https://bun.sh/install | bash"}function bunStep(input){switch(input.bun.kind){case"missing":return{text:`Install Bun: ${installBunCommand(input.platform)}`,tone:"accent"};case"outdated":return{text:`Upgrade Bun (found ${input.bun.version??"an unreadable version"}, needs ${MIN_BUN_VERSION}+): bun upgrade`,tone:"accent"};case"ready":return}}function reinstallStep(input,afterBunStep){let lead=afterBunStep?"Then reinstall":"Reinstall";return input.installMethod==="bun"||input.target===void 0?{text:`${afterBunStep?"Then restart":"Restart"} ${input.appCommand}.`,tone:"accent"}:{text:`${lead} with Bun: ${bunReinstallCommand(input.installMethod,input.target)}`,tone:"accent"}}function buildRuntimeNotice(input){let first=bunStep(input),extra=[...first===void 0?[]:[first],reinstallStep(input,first!==void 0),{text:`To stay on Node.js and hide this notice, set ${input.pinEnvName}=node.`}];return{title:"Running on Node.js",tone:"warning",why:`${input.appName} is running on Node.js ${input.nodeVersion}. It starts faster and every feature works on Bun ${MIN_BUN_VERSION}+.`,extra}}var RUNTIME_NOTICE_STATE_FILE="runtime-notice.json";function readShownVersion(agentDir){let parsed;try{parsed=JSON.parse(readFileSync48(join106(agentDir,RUNTIME_NOTICE_STATE_FILE),"utf8"))}catch{return}if(!(typeof parsed!="object"||parsed===null||!("shownVersion"in parsed)))return typeof parsed.shownVersion=="string"?parsed.shownVersion:void 0}function recordShownVersion(agentDir,version){try{mkdirSync29(agentDir,{recursive:!0}),writeFileSync25(join106(agentDir,RUNTIME_NOTICE_STATE_FILE),`${JSON.stringify({shownVersion:version})}
|
|
2231
|
-
`)}catch{}}function detectBunAvailability(options){let bunPath=findBunBinary(options);if(bunPath===void 0)return{kind:"missing"};let version=options.bunVersion(bunPath);return version!==void 0&&bunVersionSatisfies(version)?{kind:"ready",version}:{kind:"outdated",version}}function skipRequested(){let value=envValue(SKIP_RUNTIME_NOTICE_ENV_SUFFIX);return value!==void 0&&value!==""&&value!=="0"}function maybeShowRuntimeNotice(show){let agentDir=getAgentDir();runtimeNoticeSkipReason({versions:process.versions,env:process.env,hasInheritedInspectorOption:hasInheritedInspectorOption(),skipRequested:skipRequested(),engineVersion:VERSION,shownVersion:readShownVersion(agentDir)})===void 0&&(show(buildRuntimeNotice({appName:APP_NAME,appCommand:APP_COMMAND,nodeVersion:process.version,platform:process.platform,installMethod:detectInstallMethod(),target:reinstallTarget(BRAND,PACKAGE_NAME),bun:detectBunAvailability(processBunRuntimeOptions(existsSync47,realpathSync19)),pinEnvName:runtimePinEnvName(process.env)})),recordShownVersion(agentDir,VERSION))}var TuiSessionControlHost=class{constructor(context){this.editorRevision=0,this.hadDraft=!1,this.submitting=!1,this.openTickets=0,this.bufferedElsewhere=!1,this.registering=Promise.resolve(),this.context=context}register(options){let next=this.registering.then(()=>this.registerNow(options));return this.registering=next.catch(()=>{}),next}async registerNow(options){await this.disposeActive().catch(error2=>this.context().surface.notice(`control endpoint teardown failed: ${error2 instanceof Error?error2.message:String(error2)}`));let{registerSessionControlEndpoint}=await import("./session-control-endpoint-
|
|
2231
|
+
`)}catch{}}function detectBunAvailability(options){let bunPath=findBunBinary(options);if(bunPath===void 0)return{kind:"missing"};let version=options.bunVersion(bunPath);return version!==void 0&&bunVersionSatisfies(version)?{kind:"ready",version}:{kind:"outdated",version}}function skipRequested(){let value=envValue(SKIP_RUNTIME_NOTICE_ENV_SUFFIX);return value!==void 0&&value!==""&&value!=="0"}function maybeShowRuntimeNotice(show){let agentDir=getAgentDir();runtimeNoticeSkipReason({versions:process.versions,env:process.env,hasInheritedInspectorOption:hasInheritedInspectorOption(),skipRequested:skipRequested(),engineVersion:VERSION,shownVersion:readShownVersion(agentDir)})===void 0&&(show(buildRuntimeNotice({appName:APP_NAME,appCommand:APP_COMMAND,nodeVersion:process.version,platform:process.platform,installMethod:detectInstallMethod(),target:reinstallTarget(BRAND,PACKAGE_NAME),bun:detectBunAvailability(processBunRuntimeOptions(existsSync47,realpathSync19)),pinEnvName:runtimePinEnvName(process.env)})),recordShownVersion(agentDir,VERSION))}var TuiSessionControlHost=class{constructor(context){this.editorRevision=0,this.hadDraft=!1,this.submitting=!1,this.openTickets=0,this.bufferedElsewhere=!1,this.registering=Promise.resolve(),this.context=context}register(options){let next=this.registering.then(()=>this.registerNow(options));return this.registering=next.catch(()=>{}),next}async registerNow(options){await this.disposeActive().catch(error2=>this.context().surface.notice(`control endpoint teardown failed: ${error2 instanceof Error?error2.message:String(error2)}`));let{registerSessionControlEndpoint}=await import("./session-control-endpoint-PREVS5UO.js"),outcome=await registerSessionControlEndpoint({...this.context(),editorRevision:()=>this.editorRevision},options);if(!("endpoint"in outcome))return outcome.registration;let endpoint=outcome.endpoint;return this.active=endpoint,{...outcome.registration,dispose:async()=>{await endpoint.dispose(),this.active===endpoint&&(this.active=void 0)}}}attachEditor(editor,hasDraft){let change=editor.onChange;editor.onChange=text4=>{change?.(text4),this.editorChanged(hasDraft())};let submit2=editor.onSubmit;editor.onSubmit=(text4,...details)=>{this.submitting=!0,queueMicrotask(()=>{this.submitting=!1});let ticket=this.openTicket();this.handoff=ticket;try{submit2?.(text4,...details)}finally{let claimed=this.handoff!==ticket;this.handoff=void 0,claimed||ticket.release()}}}claimHandoff(){let ticket=this.handoff;return this.handoff=void 0,ticket}submissionInFlight(){return this.openTickets>0||this.bufferedElsewhere}noteBufferedElsewhere(held){let released=this.bufferedElsewhere&&!held;this.bufferedElsewhere=held,released&&this.wakeIfUnheld()}questionsChanged(){this.active?.noteQuestions()}async disposeActive(){let active=this.active;this.active=void 0,await active?.dispose()}openTicket(){this.openTickets+=1;let released=!1;return{release:()=>{released||(released=!0,this.openTickets-=1,this.wakeIfUnheld())}}}wakeIfUnheld(){queueMicrotask(()=>{this.submissionInFlight()||this.active?.wake("submission")})}editorChanged(hasDraft){this.editorRevision+=1;let cleared=this.hadDraft&&!hasDraft;this.hadDraft=hasDraft,this.active?.noteState(),cleared&&queueMicrotask(()=>{this.submitting||this.active?.wake("draft_cleared")})}};function formatSessionFailureInfo(report){if(!report||report.erroredRequests+report.abortedRequests===0)return"";let label3=text4=>theme.fg("dim",text4),share=`${(report.failureShare*100).toFixed(1)}% failed`,info=`
|
|
2232
2232
|
${theme.bold("Failures")}
|
|
2233
2233
|
`;if(info+=`${label3("Requests:")} ${report.requests} ${label3(`(${report.erroredRequests} errored, ${report.abortedRequests} aborted, ${share})`)}
|
|
2234
2234
|
`,info+=`${label3("Time in failed requests:")} ${formatDuration(report.failedDurationMs)}
|
|
@@ -2352,7 +2352,7 @@ ${theme.fg("dim","Cache Re-billed:")} ${detail}`}}return info+=formatSessionFail
|
|
|
2352
2352
|
`}}this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder),this.chatContainer.addChild(new ThemedText(()=>theme.bold(theme.fg("accent","Keyboard Shortcuts")),1,0)),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Markdown(hotkeys.trim(),1,1,this.getMarkdownThemeWithSettings())),this.chatContainer.addChild(new DynamicBorder),this.ui.requestRender()}async handleClearCommand(){this.clearStatusIndicator();try{if((await this.runtimeHost.newSession()).cancelled)return;this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("accent","\u2713 New session started"),1,1)),this.ui.requestRender()}catch(error2){await this.handleFatalRuntimeError("Failed to create session",error2)}}handleDebugCommand(){let width=this.ui.terminal.columns,height=this.ui.terminal.rows,allLines=this.ui.render(width),debugLogPath=getDebugLogPath(),debugData=[`Debug output at ${new Date().toISOString()}`,`Terminal: ${width}x${height}`,`Total lines: ${allLines.length}`,"","=== All rendered lines with visible widths ===",...allLines.map((line,idx)=>{let vw=visibleWidth(line),escaped=JSON.stringify(line);return`[${idx}] (w=${vw}) ${escaped}`}),"","=== Agent messages (JSONL) ===",...this.session.messages.map(msg=>JSON.stringify(msg)),""].join(`
|
|
2353
2353
|
`);fs5.mkdirSync(path14.dirname(debugLogPath),{recursive:!0}),fs5.writeFileSync(debugLogPath,debugData),this.showNoticeBox({title:"\u2713 Debug log written",tone:"success",why:debugLogPath})}handleArminSaysHi(){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ArminComponent(this.ui)),this.ui.requestRender()}handleDementedDelves(){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new EarendilAnnouncementComponent),this.ui.requestRender()}handleDaxnuts(){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DaxnutsComponent(this.ui)),this.ui.requestRender()}checkDaxnutsEasterEgg(model){model.provider==="opencode"&&model.id.toLowerCase().includes("kimi-k2.5")&&this.handleDaxnuts()}async handleBashCommand(command,excludeFromContext=!1){let extensionRunner=this.session.extensionRunner,eventResult;try{eventResult=await extensionRunner.emitUserBash({type:"user_bash",command,excludeFromContext,cwd:this.sessionManager.getCwd()})}catch{return}if(eventResult?.result){let result3=eventResult.result;this.bashComponent=new BashExecutionComponent(command,this.ui,excludeFromContext),this.session.isStreaming?(this.pendingMessagesContainer.addChild(this.bashComponent),this.pendingBashComponents.push(this.bashComponent)):this.chatContainer.addChild(this.bashComponent),result3.output&&this.bashComponent.appendOutput(result3.output),this.bashComponent.setComplete(result3.exitCode,result3.cancelled,result3.truncated?{truncated:!0,content:result3.output}:void 0,result3.fullOutputPath),this.session.recordBashResult(command,result3,{excludeFromContext}),this.bashComponent=void 0,this.ui.requestRender();return}let isDeferred=this.session.isStreaming;this.bashComponent=new BashExecutionComponent(command,this.ui,excludeFromContext),isDeferred?(this.pendingMessagesContainer.addChild(this.bashComponent),this.pendingBashComponents.push(this.bashComponent)):this.chatContainer.addChild(this.bashComponent),this.ui.requestRender();try{let result3=await this.session.executeBash(command,chunk=>{this.bashComponent&&(this.bashComponent.appendOutput(chunk),this.ui.requestRender())},{excludeFromContext,operations:eventResult?.operations});this.bashComponent&&this.bashComponent.setComplete(result3.exitCode,result3.cancelled,result3.truncated?{truncated:!0,content:result3.output}:void 0,result3.fullOutputPath)}catch(error2){this.bashComponent&&this.bashComponent.setComplete(void 0,!1),this.showError(`Bash command failed: ${error2 instanceof Error?error2.message:"Unknown error"}`)}this.bashComponent=void 0,this.ui.requestRender()}async handleCompactCommand(customInstructions){if(this.sessionManager.getEntries().filter(e=>e.type==="message").length<2){this.showWarning("Nothing to compact (no messages yet)");return}this.clearStatusIndicator();try{await this.session.compact(customInstructions)}catch{}}stop(options){let fullscreenExitOutput=typeof options=="string"?options:void 0,restoreStderr=typeof options=="string"||options?.restoreStderr!==!1;if(_InteractiveMode.restoreCompactionEscapeOverride(this),this.streamingReveal.stop(),this.toolResultReveal.stop(),this.disposeActiveSelector(),this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.clearStatusIndicator(),this.clearPendingTools(),this.stopChatToolAnimations(),this.clearActiveToolExecutionStatus(),this.clearToolHookStatuses(),this.themeController.disableAutoSync(),this.clearExtensionTerminalInputListeners(),this.footer.dispose(),this.footerDataProvider.dispose(),this.agentSubscriptionGeneration++,this.footerDataProvider.setExtensionStatus(LIFECYCLE_STATUS_KEY,void 0),this.unsubscribe&&this.unsubscribe(),this.isInitialized)try{this.stopInteractiveTui(fullscreenExitOutput??this.settingsManager.getFullscreenExitOutput())}finally{this.isInitialized=!1,restoreStderr&&restoreInteractiveStderr()}else restoreStderr&&restoreInteractiveStderr();this.unregisterSignalHandlers()}};function parseDiffLine(line){let match=line.match(/^([+-\s])(\s*\d*)\s(.*)$/);return match?{prefix:match[1],lineNum:match[2],content:match[3]}:null}function replaceTabs2(text4){return text4.replace(/\t/g," ")}function renderIntraLineDiffWithDiffWords(oldContent,newContent){let wordDiff=diffWords(oldContent,newContent),removedLine="",addedLine="",isFirstRemoved=!0,isFirstAdded=!0;for(let part of wordDiff)if(part.removed){let value=part.value;if(isFirstRemoved){let leadingWs=value.match(/^(\s*)/)?.[1]||"";value=value.slice(leadingWs.length),removedLine+=leadingWs,isFirstRemoved=!1}value&&(removedLine+=theme.inverse(value))}else if(part.added){let value=part.value;if(isFirstAdded){let leadingWs=value.match(/^(\s*)/)?.[1]||"";value=value.slice(leadingWs.length),addedLine+=leadingWs,isFirstAdded=!1}value&&(addedLine+=theme.inverse(value))}else removedLine+=part.value,addedLine+=part.value;return{removedLine,addedLine}}function renderIntraLineDiff(oldContent,newContent){return renderIntraLineDiffFastPath(oldContent,newContent)??renderIntraLineDiffWithDiffWords(oldContent,newContent)}function renderIntraLineDiffFastPath(oldContent,newContent){return oldContent===newContent?{removedLine:oldContent,addedLine:newContent}:renderSingleSpanIntraLineDiff(oldContent,newContent)}function renderSingleSpanIntraLineDiff(oldContent,newContent){let span=findSingleDiffWordsReplacement(oldContent,newContent);return span?{removedLine:`${span.prefix}${theme.inverse(span.removed)}${span.suffix}`,addedLine:`${span.prefix}${theme.inverse(span.added)}${span.suffix}`}:null}function findSingleDiffWordsReplacement(oldContent,newContent){let start=0;for(;start<oldContent.length&&start<newContent.length&&oldContent[start]===newContent[start];)start++;let oldEnd=oldContent.length,newEnd=newContent.length;for(;oldEnd>start&&newEnd>start&&oldContent[oldEnd-1]===newContent[newEnd-1];)oldEnd--,newEnd--;for(;start>0&&(isAsciiWordCode(oldContent.charCodeAt(start-1))||isAsciiWordCode(newContent.charCodeAt(start-1)));)start--;for(;oldEnd<oldContent.length&&newEnd<newContent.length&&(isAsciiWordCode(oldContent.charCodeAt(oldEnd))||isAsciiWordCode(newContent.charCodeAt(newEnd)));)oldEnd++,newEnd++;let prefix=oldContent.slice(0,start),removed=oldContent.slice(start,oldEnd),added=newContent.slice(start,newEnd),oldSuffix=oldContent.slice(oldEnd),newSuffix=newContent.slice(newEnd);return oldSuffix!==newSuffix||!isSingleDiffWordsReplacement(removed,added)?null:{prefix,removed,added,suffix:oldSuffix}}function isSingleDiffWordsReplacement(removed,added){return removed.length>0&&added.length>0&&isSimpleDiffToken(removed)&&isSimpleDiffToken(added)}function isSimpleDiffToken(value){for(let i=0;i<value.length;i++){let code=value.charCodeAt(i);if(!isAsciiWordCode(code))return!1}return!0}function isAsciiWordCode(code){return code>=48&&code<=57||code>=65&&code<=90||code===95||code>=97&&code<=122}function renderDiff(diffText,_options={}){let lines=diffText.split(`
|
|
2354
2354
|
`),result3=[],i=0;for(;i<lines.length;){let line=lines[i],parsed=parseDiffLine(line);if(!parsed){result3.push(theme.fg("toolDiffContext",line)),i++;continue}if(parsed.prefix==="-"){let removedLines=[];for(;i<lines.length;){let p=parseDiffLine(lines[i]);if(p?.prefix!=="-")break;removedLines.push({lineNum:p.lineNum,content:p.content}),i++}let addedLines=[];for(;i<lines.length;){let p=parseDiffLine(lines[i]);if(p?.prefix!=="+")break;addedLines.push({lineNum:p.lineNum,content:p.content}),i++}if(removedLines.length===1&&addedLines.length===1){let removed=removedLines[0],added=addedLines[0],{removedLine,addedLine}=renderIntraLineDiff(replaceTabs2(removed.content),replaceTabs2(added.content));result3.push(theme.fg("toolDiffRemoved",`-${removed.lineNum} ${removedLine}`)),result3.push(theme.fg("toolDiffAdded",`+${added.lineNum} ${addedLine}`))}else{for(let removed of removedLines)result3.push(theme.fg("toolDiffRemoved",`-${removed.lineNum} ${replaceTabs2(removed.content)}`));for(let added of addedLines)result3.push(theme.fg("toolDiffAdded",`+${added.lineNum} ${replaceTabs2(added.content)}`))}}else parsed.prefix==="+"?(result3.push(theme.fg("toolDiffAdded",`+${parsed.lineNum} ${replaceTabs2(parsed.content)}`)),i++):(result3.push(theme.fg("toolDiffContext",` ${parsed.lineNum} ${replaceTabs2(parsed.content)}`)),i++)}return result3.join(`
|
|
2355
|
-
`)}var SHOW_IMAGES_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ShowImagesSelectorComponent=class extends Container{constructor(currentValue,onSelect,onCancel){super();let items=[{value:"yes",label:"Yes",description:"Show images inline in terminal"},{value:"no",label:"No",description:"Show text placeholder instead"}];this.addChild(new DynamicBorder),this.selectList=new SelectList(items,5,getSelectListTheme(),SHOW_IMAGES_SELECT_LIST_LAYOUT),this.selectList.setSelectedIndex(currentValue?0:1),this.selectList.onSelect=item=>{onSelect(item.value==="yes")},this.selectList.onCancel=()=>{onCancel()},this.addChild(this.selectList),this.addChild(new DynamicBorder)}getSelectList(){return this.selectList}};var THEME_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ThemeSelectorComponent=class extends Container{constructor(currentTheme,onSelect,onCancel,onPreview){super(),this.onPreview=onPreview;let themes=getAvailableThemes(),themeItems2=themes.map(name=>({value:name,label:name,description:name===currentTheme?"(current)":void 0}));this.addChild(new DynamicBorder),this.selectList=new SelectList(themeItems2,10,getSelectListTheme(),THEME_SELECT_LIST_LAYOUT);let currentIndex=themes.indexOf(currentTheme);currentIndex!==-1&&this.selectList.setSelectedIndex(currentIndex),this.selectList.onSelect=item=>{onSelect(item.value)},this.selectList.onCancel=()=>{onCancel()},this.selectList.onSelectionChange=item=>{this.onPreview(item.value)},this.addChild(this.selectList),this.addChild(new DynamicBorder)}getSelectList(){return this.selectList}};var session_worker_data_exports={};__export(session_worker_data_exports,{SessionWorkerDataRegistry:()=>SessionWorkerDataRegistry,provideSessionWorkerData:()=>provideSessionWorkerData,readSessionWorkerData:()=>readSessionWorkerData,sessionWorkerData:()=>sessionWorkerData,sessionWorkerDataRegistry:()=>sessionWorkerDataRegistry});import{isMainThread as isMainThread3,workerData}from"node:worker_threads";var disposeAll=grants=>{for(let grant of grants)grant.dispose?.()},SessionWorkerDataRegistry=class{constructor(state3={providers:new Map,sealed:!1}){this.state=state3}provide(name,create2){if(!isMainThread3)throw new Error("provideSessionWorkerData runs on the main thread only");if(this.state.sealed)throw new Error(`session worker data "${name}" was provided after the first session worker`);if(this.state.providers.has(name))throw new Error(`session worker data "${name}" is already provided`);this.state.providers.set(name,create2)}spawn(start){this.state.sealed=!0;let grants=[],extensionData={};try{for(let[name,create2]of this.state.providers){let grant=create2();grants.push(grant),extensionData[name]=grant.value}}catch(cause){throw disposeAll(grants),cause}let disposed=!1,issued={extensionData,transfer:grants.flatMap(grant=>grant.transfer??[]),dispose:()=>{disposed||(disposed=!0,disposeAll(grants))}};try{return{result:start(issued),issued}}catch(cause){throw issued.dispose(),cause}}},REGISTRY_KEY=Symbol.for("senpi.session-worker-data.registry");function sharedState(){let existing2=Reflect.get(globalThis,REGISTRY_KEY);if(isRegistryState(existing2))return existing2;let state3={providers:new Map,sealed:!1};return Reflect.set(globalThis,REGISTRY_KEY,state3),state3}function isRegistryState(value){return value!==null&&typeof value=="object"&&Reflect.get(value,"providers")instanceof Map&&typeof Reflect.get(value,"sealed")=="boolean"}var sessionWorkerDataRegistry=new SessionWorkerDataRegistry(sharedState());function provideSessionWorkerData(name,create2){sessionWorkerDataRegistry.provide(name,create2)}function readSessionWorkerData(data,name){let extensionData=data!==null&&typeof data=="object"?Reflect.get(data,"extensionData"):void 0;if(!(extensionData===null||typeof extensionData!="object"||!Object.hasOwn(extensionData,name)))return Reflect.get(extensionData,name)}function sessionWorkerData(name){return isMainThread3?void 0:readSessionWorkerData(workerData,name)}import{spawn as spawn10}from"node:child_process";async function execCommand(command,args,cwd,options){return new Promise(resolve56=>{let proc=spawn10(command,args,{cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),stdout="",stderr="",killed=!1,timeoutId,killProcess=()=>{if(!killed){if(killed=!0,!signalSpawnedChild(proc,"SIGTERM")&&proc.pid===void 0)return;setTimeout(()=>{proc.killed||signalSpawnedChild(proc,"SIGKILL")},5e3)}};options?.signal&&(options.signal.aborted?killProcess():options.signal.addEventListener("abort",killProcess,{once:!0})),options?.timeout&&options.timeout>0&&(timeoutId=setTimeout(()=>{killProcess()},options.timeout)),proc.stdout?.on("data",data=>{stdout+=data.toString()}),proc.stderr?.on("data",data=>{stderr+=data.toString()}),waitForChildProcess(proc).then(code=>{timeoutId&&clearTimeout(timeoutId),options?.signal&&options.signal.removeEventListener("abort",killProcess),resolve56({stdout,stderr,code:code??0,killed})}).catch(_err=>{timeoutId&&clearTimeout(timeoutId),options?.signal&&options.signal.removeEventListener("abort",killProcess),resolve56({stdout,stderr,code:1,killed})})})}function redactForUpload(text4,options={}){let tally=new Map,context=currentShareRedactionContext(),extra=(options.extraLiterals??[]).filter(value=>value.trim().length>0);return{text:redactShareText(text4,extra.length===0?context:{...context,extraLiterals:extra},tally),counts:Object.fromEntries(tally)}}var McpServerRegistry=class{#loaded=[];#bound;#warnedClashes=new Set;#changeListener;track(extension){this.#loaded.push(extension)}untrack(extension){let index=this.#loaded.indexOf(extension);index>=0&&this.#loaded.splice(index,1)}bind(extensions){this.#bound=extensions}changed(){this.#changeListener?.()}declarations(){let byName=new Map;for(let extension of this.#bound??this.#loaded)for(let declaration of extension.mcpServers.values()){let existing2=byName.get(declaration.name);existing2===void 0?byName.set(declaration.name,declaration):this.#warnClash(existing2,declaration)}return[...byName.values()]}list(){return this.declarations().map(({name,config,extensionPath})=>({name,config:structuredClone(config),extensionPath}))}setChangeListener(listener){this.#changeListener=listener}#warnClash(winner,loser){let key=`${winner.name}\0${winner.extensionPath}\0${loser.extensionPath}`;this.#warnedClashes.has(key)||(this.#warnedClashes.add(key),console.warn(`MCP server '${winner.name}' declared by both ${winner.extensionPath} and ${loser.extensionPath}; keeping first declaration from ${winner.extensionPath}.`))}};import{createHash as createHash29}from"node:crypto";import{readFileSync as readFileSync49}from"node:fs";var generation,pendingImporter,generationsCreated=0;function fingerprintOf(file){try{return createHash29("sha256").update(readFileSync49(file,"utf8")).digest("hex")}catch{return}}function sourcesUnchanged(live){for(let[file,fingerprint]of live.importer.compiledSources?.()??[])if(fingerprintOf(file)!==fingerprint)return!1;return!0}function dropGeneration(){generation=void 0,pendingImporter=void 0}function cachedExtensionFactory(resolvedPath){if(generation){if(!sourcesUnchanged(generation)){dropGeneration();return}return generation.factories.get(resolvedPath)}}async function extensionModuleImporter(create2){return generation?generation.importer:(pendingImporter??=create2().then(importer=>(generation={importer,factories:new Map},generationsCreated++,pendingImporter=void 0,importer)),pendingImporter)}function rememberExtensionFactory(resolvedPath,factory,compiledBy){!generation||generation.importer!==compiledBy||generation.importer.compiledSources!==void 0&&generation.factories.set(resolvedPath,factory)}function withProviderLoginStart(provider,config,emit){let oauth=config.oauth;return oauth?{...config,oauth:{...oauth,login:async callbacks=>(await emit({type:"provider_login_start",provider,signal:callbacks.signal??new AbortController().signal,progress:message=>callbacks.onProgress?.(message)}),oauth.login(callbacks))}}:config}var __rewriteRelativeImportExtension2=function(path16,preserveJsx){return typeof path16=="string"&&/^\.\.?\//.test(path16)?path16.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path16};function sessionProfile(options){return{sessionKind:options?.sessionKind??"interactive",sessionContext:options?.sessionContext??EMPTY_SESSION_CONTEXT}}var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports2,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports2,"@earendil-works/pi-agent-core":dist_exports,"@earendil-works/pi-tui":dist_exports2,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-works/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports,"@mariozechner/pi-tui":dist_exports2,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3,"@code-yeongyu/senpi":dist_exports3,"@code-yeongyu/senpi/session-worker-data":session_worker_data_exports},require3=createRequire2(import.meta.url),isNodeSeaBinary="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,isTypeScriptSourceRuntime=!isBunBinary&&path15.extname(fileURLToPath6(import.meta.url))===".ts",usesNativeBunImports=isBunBinary||isBunRuntime,_aliases=null;function getAliases(){if(_aliases)return _aliases;let __dirname=path15.dirname(fileURLToPath6(import.meta.url)),typeboxEntry=require3.resolve("typebox"),typeboxCompileEntry=require3.resolve("typebox/compile"),typeboxValueEntry=require3.resolve("typebox/value"),codingAgentPackageRoot=path15.resolve(__dirname,"../../.."),packagesRoot=path15.dirname(codingAgentPackageRoot),resolveWorkspaceOrBundled=(packageName,packageEntryRelativePath,workspaceRelativePath,sourceRelativePath,specifier)=>{let bundledPath=path15.join(codingAgentPackageRoot,"node_modules",packageName,packageEntryRelativePath);if(fs6.existsSync(bundledPath))return bundledPath;let workspacePath=path15.join(packagesRoot,workspaceRelativePath);if(fs6.existsSync(workspacePath))return workspacePath;let sourcePath=path15.join(packagesRoot,sourceRelativePath);return fs6.existsSync(sourcePath)?sourcePath:typeof import.meta.resolve=="function"?fileURLToPath6(import.meta.resolve(specifier)):require3.resolve(specifier)},piCodingAgentDistEntry=path15.join(codingAgentPackageRoot,"dist/index.js"),piCodingAgentSourceEntry=path15.join(codingAgentPackageRoot,"src/index.ts"),piCodingAgentEntry=fs6.existsSync(piCodingAgentDistEntry)?piCodingAgentDistEntry:piCodingAgentSourceEntry,sessionWorkerDataDistEntry=path15.join(codingAgentPackageRoot,"dist/modes/rpc/session-worker-data.js"),sessionWorkerDataEntry=fs6.existsSync(sessionWorkerDataDistEntry)?sessionWorkerDataDistEntry:path15.join(codingAgentPackageRoot,"src/modes/rpc/session-worker-data.ts"),piAgentCoreEntry=resolveWorkspaceOrBundled("@earendil-works/pi-agent-core","dist/index.js","agent/dist/index.js","agent/src/index.ts","@earendil-works/pi-agent-core"),piTuiEntry=resolveWorkspaceOrBundled("@earendil-works/pi-tui","dist/index.js","tui/dist/index.js","tui/src/index.ts","@earendil-works/pi-tui"),piAiCompatEntry=resolveWorkspaceOrBundled("@earendil-works/pi-ai","dist/compat.js","ai/dist/compat.js","ai/src/compat.ts","@earendil-works/pi-ai/compat"),piAiOauthEntry=resolveWorkspaceOrBundled("@earendil-works/pi-ai","dist/oauth.js","ai/dist/oauth.js","ai/src/oauth.ts","@earendil-works/pi-ai/oauth"),piAiProvidersEntry=resolveWorkspaceOrBundled("@earendil-works/pi-ai","dist/providers/all.js","ai/dist/providers/all.js","ai/src/providers/all.ts","@earendil-works/pi-ai/providers/all");return _aliases={"@earendil-works/pi-coding-agent":piCodingAgentEntry,"@earendil-works/pi-agent-core":piAgentCoreEntry,"@earendil-works/pi-tui":piTuiEntry,"@earendil-works/pi-ai/providers/all":piAiProvidersEntry,"@earendil-works/pi-ai/compat":piAiCompatEntry,"@earendil-works/pi-ai/oauth":piAiOauthEntry,"@earendil-works/pi-ai":piAiCompatEntry,"@code-yeongyu/senpi":piCodingAgentEntry,"@code-yeongyu/senpi/session-worker-data":sessionWorkerDataEntry,"@mariozechner/pi-coding-agent":piCodingAgentEntry,"@mariozechner/pi-agent-core":piAgentCoreEntry,"@mariozechner/pi-tui":piTuiEntry,"@mariozechner/pi-ai/providers/all":piAiProvidersEntry,"@mariozechner/pi-ai/compat":piAiCompatEntry,"@mariozechner/pi-ai/oauth":piAiOauthEntry,"@mariozechner/pi-ai":piAiCompatEntry,typebox:typeboxEntry,"typebox/compile":typeboxCompileEntry,"typebox/value":typeboxValueEntry,"@sinclair/typebox":typeboxEntry,"@sinclair/typebox/compile":typeboxCompileEntry,"@sinclair/typebox/value":typeboxValueEntry},_aliases}var runtimeFactories=new WeakMap;function createExtensionRuntime(){let notInitialized=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},state3={},nextProviderRegistrationOrder=0,eventBusUnsubscribers=new Set,assertActive=()=>{if(state3.staleMessage)throw new StaleExtensionContextError(state3.staleMessage)},runtime={sendMessage:notInitialized,sendUserMessage:notInitialized,appendEntry:notInitialized,setSessionName:notInitialized,getSessionName:notInitialized,setLabel:notInitialized,executeTool:()=>Promise.reject(new Error("Extension runtime not initialized")),getActiveTools:notInitialized,getAllTools:notInitialized,getSettings:notInitialized,setActiveTools:notInitialized,refreshTools:()=>{},registerRemovedToolHint:()=>{},registerLazyToolActivator:()=>{},getCommands:notInitialized,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:notInitialized,setThinkingLevel:notInitialized,setSessionModel:()=>Promise.reject(new Error("Extension runtime not initialized")),setSessionThinkingLevel:notInitialized,setSessionFastMode:notInitialized,sessionControl:unboundSessionControlActions(),flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],pendingVirtualModelRegistrations:[],mcpServers:new McpServerRegistry,createContext:notInitialized,assertActive,invalidate:message=>{if(!state3.staleMessage){state3.staleMessage=message??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let unsubscribe of eventBusUnsubscribers)unsubscribe();eventBusUnsubscribers.clear(),runtime.evalHandleHost=void 0,runtimeFactories.delete(runtime)}},trackEventBusSubscription:unsubscribe=>{let active=!0,trackedUnsubscribe=()=>{active&&(active=!1,eventBusUnsubscribers.delete(trackedUnsubscribe),unsubscribe())};return eventBusUnsubscribers.add(trackedUnsubscribe),trackedUnsubscribe},registerProvider:(name,config,extensionPath="<unknown>")=>{runtime.pendingProviderRegistrations.push({name,config,extensionPath,order:nextProviderRegistrationOrder++})},registerNativeProvider:(provider,extensionPath="<unknown>")=>{runtime.pendingNativeProviderRegistrations.push({provider,extensionPath,order:nextProviderRegistrationOrder++})},unregisterProvider:name=>{runtime.pendingProviderRegistrations=runtime.pendingProviderRegistrations.filter(r=>r.name!==name),runtime.pendingNativeProviderRegistrations=runtime.pendingNativeProviderRegistrations.filter(r=>r.provider.id!==name)},registerVirtualModel:(definition,extensionPath="<unknown>")=>{runtime.pendingVirtualModelRegistrations.push({definition,extensionPath})},unregisterVirtualModel:(provider,id)=>{runtime.pendingVirtualModelRegistrations=runtime.pendingVirtualModelRegistrations.filter(({definition})=>definition.provider!==provider||definition.id!==id)},emitProviderLoginStart:async()=>{}};return runtime}var unboundSessionControl=unboundSessionControlActions();function sessionControlOf(runtime){return runtime.sessionControl??unboundSessionControl}function drainPendingProviderRegistrations(runtime){let drained=[...runtime.pendingProviderRegistrations.map(entry2=>({kind:"config",...entry2})),...runtime.pendingNativeProviderRegistrations.map(entry2=>({kind:"native",...entry2}))];return drained.sort((a,b)=>a.order-b.order),runtime.pendingProviderRegistrations=[],runtime.pendingNativeProviderRegistrations=[],drained}function handlerSessionId(context){if(!(!context||!("sessionManager"in context)))try{return context.sessionManager?.getSessionId()}catch(error2){if(error2 instanceof StaleExtensionContextError)return;throw error2}}function createExtensionAPI(extension,runtime,cwd,eventBus,session){let pendingFlagValues=new Map,pendingRuntimeChanges=[],loadingUnsubscribers=[],state3="loading",assertActive=()=>{if(state3==="failed")throw new Error(`Extension "${extension.path}" failed to load and its API is no longer active.`);runtime.assertActive()},applyRuntimeChange=change=>{state3==="loading"?pendingRuntimeChanges.push(change):change()},clearPending=()=>{pendingFlagValues.clear(),pendingRuntimeChanges.length=0,loadingUnsubscribers.length=0},api={cwd,sessionKind:session.sessionKind,sessionContext:session.sessionContext,on(event,handler,options){assertActive();let registeredHandler=ownedBy(extension,(...args)=>{let sessionId=handlerSessionId(args[1]),invoke=()=>handler(...args);return sessionId?kernelToolInvokerStorage.run({sessionId},invoke):kernelToolInvokerStorage.exit(invoke)}),list3=extension.handlers.get(event)??[];return list3.push(registeredHandler),extension.handlers.set(event,list3),event==="before_agent_start"&&options?.previewSafe===!0&&(extension.previewSafeHandlers??=new WeakSet,extension.previewSafeHandlers.add(registeredHandler)),event==="before_agent_start"&&options?.runLast===!0&&(extension.runLastHandlers??=new WeakSet,extension.runLastHandlers.add(registeredHandler)),(event==="context"||event==="context_with_system")&&options?.mutatesMessages===!1&&(extension.nonMutatingContextHandlers??=new WeakSet,extension.nonMutatingContextHandlers.add(registeredHandler)),()=>{let handlers=extension.handlers.get(event);if(!handlers)return;let handlerIndex=handlers.indexOf(registeredHandler);handlerIndex!==-1&&(handlers.splice(handlerIndex,1),handlers.length===0&&extension.handlers.delete(event))}},registerTool(tool){if(runtime.assertActive(),tool.name==="tool_search"&&extension.sourceInfo.source!=="builtin")throw new Error('Tool name "tool_search" is reserved for the builtin tool-search extension.');if(typeof tool.parameters!="object"||tool.parameters===null||Array.isArray(tool.parameters))throw new Error(`Tool "${tool.name}" registered by extension "${extension.path}" must define an object parameter schema.`);extension.tools.set(tool.name,{definition:Object.assign(Object.create(Object.getPrototypeOf(tool)),tool,{execute:ownedBy(extension,tool.execute)}),sourceInfo:extension.sourceInfo}),runtime.refreshTools()},registerLazyToolActivator(activator){runtime.assertActive();let activators=extension.lazyToolActivators??[];activators.push(activator),extension.lazyToolActivators=activators,runtime.registerLazyToolActivator(activator)},provideEvalHandleHost(host){runtime.assertActive(),runtime.evalHandleHost=host},registerRemovedToolHint(name,hint){runtime.assertActive();let hints=extension.removedToolHints;hints||(hints=new Map,extension.removedToolHints=hints),hints.set(name,hint),runtime.registerRemovedToolHint(name,hint)},registerChildModule(registration){runtime.assertActive(),validateChildModuleRegistration(registration);let modules=extension.childModules??new Map;modules.set(registration.id,{registration:{...registration},sourceInfo:extension.sourceInfo}),extension.childModules=modules},registerFilesystemPolicy(policy){runtime.assertActive();let policies2=extension.filesystemPolicies??[];policies2.push(policy),extension.filesystemPolicies=policies2},registerCommand(name,options){if(assertActive(),typeof name!="string"||name.length===0)throw new Error(`Command registered by extension "${extension.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof options?.handler!="function")throw new Error(`Command "/${name}" registered by extension "${extension.path}" must define handler().`);extension.commands.set(name,{name,sourceInfo:extension.sourceInfo,...options,handler:ownedBy(extension,options.handler)})},registerShortcut(shortcut,options){assertActive(),extension.shortcuts.set(shortcut,{shortcut,extensionPath:extension.path,...options,handler:ownedBy(extension,options.handler)})},registerFlag(name,options){if(assertActive(),options.default!==void 0&&typeof options.default!==options.type)throw new Error(`Invalid default for flag "${name}": expected ${options.type}, got ${typeof options.default}`);extension.flags.set(name,{name,extensionPath:extension.path,...options}),options.default!==void 0&&!runtime.flagValues.has(name)&&(state3==="loading"?pendingFlagValues.has(name)||pendingFlagValues.set(name,options.default):runtime.flagValues.set(name,options.default))},registerMessageRenderer(customType,renderer){assertActive(),extension.messageRenderers.set(customType,renderer)},registerMemoryReporter(name,reporter){if(assertActive(),RESERVED_MEMORY_REPORT_KEYS.has(name))throw new Error(`Memory reporter name "${name}" is reserved by the memory report`);extension.memoryReporters??=new Map,extension.memoryReporters.set(name,reporter)},registerMarkdownTransformer(transformer){assertActive(),extension.markdownTransformer=transformer},registerEntryRenderer(customType,renderer,options){assertActive(),extension.entryRenderers??=new Map,extension.entryRenderers.set(customType,renderer),extension.entryRendererOptions??=new Map,options===void 0?extension.entryRendererOptions.delete(customType):extension.entryRendererOptions.set(customType,options)},registerReadClassifier(classifier){assertActive();let unregister=runtime.trackEventBusSubscription(registerReadClassifier(classifier));return state3==="loading"&&loadingUnsubscribers.push(unregister),unregister},registerMcpServer(name,config){assertActive();let error2=validateMcpServerDeclaration(name,config);if(error2)throw new Error(error2);extension.mcpServers.set(name,{name,config:structuredClone(config),extensionPath:extension.path,registrationCwd:extension.registrationCwd}),runtime.mcpServers.changed()},unregisterMcpServer(name){assertActive(),extension.mcpServers.delete(name)&&runtime.mcpServers.changed()},getMcpServers(){return assertActive(),runtime.mcpServers.list()},getFlag(name){if(assertActive(),!!extension.flags.has(name))return runtime.flagValues.has(name)?runtime.flagValues.get(name):pendingFlagValues.get(name)},getPermissionPreset(){assertActive();let sessionManager;try{sessionManager=runtime.createContext().sessionManager}catch{return}return readPermissionPreset(sessionManager)},getSubscriptionLimits(){return assertActive(),subscriptionLimits.snapshot()},onSubscriptionLimits(listener){return assertActive(),subscriptionLimits.subscribe(listener)},lifecycle:createLifecycleApi(()=>{if(assertActive(),!runtime.lifecycle)throw new Error("Extension lifecycle is not bound to a session");return runtime.lifecycle}),sendMessage:((message,options)=>{assertActive();let items=options?.items;if(items===void 0){runtime.sendMessage(message,options);return}let itemized=runtime.sendItemizedMessage;return itemized===void 0?(runtime.sendMessage(message,options),Promise.resolve(void 0)):itemized(message,{...options,items})}),sendUserMessage(content,options){assertActive(),runtime.sendUserMessage(content,options)},appendEntry(customType,data,options){assertActive(),runtime.appendEntry(customType,data,options)},setSessionName(name){assertActive(),runtime.setSessionName(name)},getSessionName(){return assertActive(),runtime.getSessionName()},setLabel(entryId,label3){assertActive(),runtime.setLabel(entryId,label3)},exec(command,args,options){return assertActive(),execCommand(command,args,options?.cwd??cwd,options)},redactForUpload(text4,options){return assertActive(),redactForUpload(text4,options)},hostVersion:VERSION,executeTool(toolName,params,options){return runtime.assertActive(),runtime.executeTool(toolName,params,options)},getActiveTools(){return assertActive(),runtime.getActiveTools()},armToolBarrier(spec2){if(assertActive(),!runtime.armToolBarrier)throw new Error("This runtime has no tool barrier (senpi#3717).");runtime.armToolBarrier(spec2)},releaseToolBarrier(id){return assertActive(),runtime.releaseToolBarrier?.(id)??!1},getAllTools(){return assertActive(),runtime.getAllTools()},getSettings(){return assertActive(),runtime.getSettings()},setActiveTools(toolNames){assertActive(),runtime.setActiveTools(toolNames)},getCommands(){return assertActive(),runtime.getCommands()},setModel(model){return assertActive(),runtime.setModel(model,{source:"extension",actor:extension.path})},getThinkingLevel(){return assertActive(),runtime.getThinkingLevel()},setThinkingLevel(level){assertActive(),runtime.setThinkingLevel(level)},setSessionModel(model){return runtime.assertActive(),runtime.setSessionModel(model,{source:"extension",actor:extension.path})},setSessionThinkingLevel(level){runtime.assertActive(),runtime.setSessionThinkingLevel(level)},setSessionFastMode(enabled){runtime.assertActive(),runtime.setSessionFastMode(enabled)},registerProvider(providerOrName,config){if(assertActive(),typeof providerOrName=="string"){if(!config)throw new Error("Provider config is required when registering by name");let wrapped=withProviderLoginStart(providerOrName,config,event=>runtime.emitProviderLoginStart(event));applyRuntimeChange(()=>runtime.registerProvider(providerOrName,wrapped,extension.path));return}applyRuntimeChange(()=>runtime.registerNativeProvider(providerOrName,extension.path))},unregisterProvider(name){assertActive(),applyRuntimeChange(()=>runtime.unregisterProvider(name,extension.path))},session:{registerControlEndpoint(options){return runtime.assertActive(),sessionControlOf(runtime).registerControlEndpoint(options)},admissionGate(){return runtime.assertActive(),sessionControlOf(runtime).admissionGate()},admitExternalMessage(input){return runtime.assertActive(),sessionControlOf(runtime).admitExternalMessage(input)},listAdmittedDeliveries(){return runtime.assertActive(),sessionControlOf(runtime).listAdmittedDeliveries()},persistHeaderNow(){return runtime.assertActive(),sessionControlOf(runtime).persistHeaderNow()},relocationOffered(){return runtime.assertActive(),sessionControlOf(runtime).relocationOffered()},relocationTargets(signal){return runtime.assertActive(),sessionControlOf(runtime).relocationTargets(signal)},requestRelocation(request2,signal){return runtime.assertActive(),sessionControlOf(runtime).requestRelocation(request2,signal)}},rpc:{emit(name,data){runtime.assertActive();let normalizedName=name.trim();if(normalizedName.length===0)throw new Error("RPC extension event name must not be empty");eventBus.emit(EXTENSION_RPC_EVENT_CHANNEL,{name:normalizedName,data})},handle(name,handler){runtime.assertActive();let normalizedName=name.trim();if(normalizedName.length===0)throw new Error("RPC extension request name must not be empty");let handlers=extension.rpcHandlers??new Map;if(handlers.has(normalizedName))throw new Error(`RPC extension request handler already registered: ${normalizedName}`);handlers.set(normalizedName,ownedBy(extension,handler)),extension.rpcHandlers=handlers}},registerVirtualModel(model){assertActive();let definition={...model,route:request2=>model.route(request2,runtime.createContext())};applyRuntimeChange(()=>runtime.registerVirtualModel(definition,extension.path))},unregisterVirtualModel(provider,id){assertActive(),applyRuntimeChange(()=>runtime.unregisterVirtualModel(provider,id))},events:{emit(channel,data){assertActive(),eventBus.emit(channel,data)},on(channel,handler){assertActive();let unsubscribe=runtime.trackEventBusSubscription(eventBus.on(channel,handler));return state3==="loading"&&loadingUnsubscribers.push(unsubscribe),unsubscribe}}};return recordExtensionLoadKey(api,runtime),{api,commit:()=>{if(state3==="loading"){runtime.assertActive();for(let[name,value]of pendingFlagValues)runtime.flagValues.has(name)||runtime.flagValues.set(name,value);for(let apply of pendingRuntimeChanges)apply();state3="active",clearPending()}},discard:()=>{if(state3==="loading"){state3="failed";for(let unsubscribe of loadingUnsubscribers)unsubscribe();clearPending()}}}}var importNodeOnlyApi=specifier=>import(__rewriteRelativeImportExtension2(specifier));async function createExtensionModuleImporter(){if(usesNativeBunImports){let{createBunExtensionImporter}=await import("./bun-extension-importer-RCGPQTI2.js");return createBunExtensionImporter(VIRTUAL_MODULES,{},{preparedCache:{dir:path15.join(getAgentDir(),"cache","extension-modules"),release:VERSION}})}let{createJiti}=await importNodeOnlyApi("jiti/static");return createJiti(import.meta.url,{moduleCache:!1,...isNodeSeaBinary||isBundledNode?{virtualModules:VIRTUAL_MODULES,tryNative:!1}:isTypeScriptSourceRuntime?{alias:getAliases(),virtualModules:VIRTUAL_MODULES,tsconfigPaths:!0}:{alias:getAliases()}})}async function loadExtensionModule(extensionPath,getImporter){let cachedFactory=cachedExtensionFactory(extensionPath);if(cachedFactory)return cachedFactory;let importer=await getImporter(),factory=await importer.import(extensionPath,{default:!0});if(typeof factory=="function")return rememberExtensionFactory(extensionPath,factory,importer),factory}function createExtension(extensionPath,resolvedPath,registrationCwd){let source2=getSyntheticPathSource(extensionPath)??"local",baseDir=isSyntheticPath(extensionPath)?void 0:path15.dirname(resolvedPath);return{path:extensionPath,resolvedPath,sourceInfo:createSyntheticSourceInfo(extensionPath,{source:source2,baseDir,scope:source2==="builtin"?"system":"temporary"}),handlers:new Map,tools:new Map,removedToolHints:new Map,lazyToolActivators:[],filesystemPolicies:[],messageRenderers:new Map,memoryReporters:new Map,entryRenderers:void 0,commands:new Map,rpcHandlers:new Map,flags:new Map,shortcuts:new Map,mcpServers:new Map,registrationCwd}}async function initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime,session){let extension=createExtension(extensionPath,resolvedPath,cwd),load2=createExtensionAPI(extension,runtime,cwd,eventBus,session);runtime.mcpServers.track(extension);try{if(await runOwnedBy(extension,()=>factory(load2.api)),load2.commit(),usesNativeBunImports){let factories=runtimeFactories.get(runtime)??new Set;factories.add(factory),runtimeFactories.set(runtime,factories)}}catch(error2){throw runtime.mcpServers.untrack(extension),load2.discard(),error2}return time(`${extensionPath} factory`,"extensions"),extension}async function loadExtension(extensionPath,cwd,eventBus,runtime,getImporter,factoryResolver,session=DEFAULT_EXTENSION_SESSION_PROFILE){let resolvedPath=resolvePath(extensionPath,cwd,{normalizeUnicodeSpaces:!0});try{let factory=factoryResolver?.(extensionPath,resolvedPath)??await loadExtensionModule(resolvedPath,getImporter);return time(`${extensionPath} module import`,"extensions"),factory?{extension:await initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime,session),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${extensionPath}`}}catch(err){return{extension:null,error:`Failed to load extension: ${err instanceof Error?err.message:String(err)}`}}}async function loadExtensionFromFactory(factory,cwd,eventBus,runtime,extensionPath="<inline>",session=DEFAULT_EXTENSION_SESSION_PROFILE){let resolvedCwd=resolvePath(cwd);return initializeExtension(factory,extensionPath,extensionPath,resolvedCwd,eventBus,runtime,session)}async function loadExtensionsInternal(paths,cwd,eventBus,runtime,options){let session=sessionProfile(options),extensions=[],errors=[],warnings=[],resolvedCwd=resolvePath(cwd),resolvedEventBus=eventBus??createEventBus(),resolvedRuntime=runtime??createExtensionRuntime(),getImporter=()=>extensionModuleImporter(createExtensionModuleImporter);for(let extPath of paths){let{extension,error:error2}=await loadExtension(extPath,resolvedCwd,resolvedEventBus,resolvedRuntime,getImporter,options?.factoryResolver,session);if(error2){errors.push({path:extPath,error:error2});continue}extension&&extensions.push(extension)}return{extensions,errors,warnings,runtime:resolvedRuntime,eventBus:resolvedEventBus}}async function loadExtensions(paths,cwd,eventBus,runtime,options){return loadExtensionsInternal(paths,cwd,eventBus,runtime,options)}function isExtensionFile(name){return name.endsWith(".ts")||name.endsWith(".js")}function resolveExtensionEntries(dir){let packageJsonPath=path15.join(dir,"package.json");if(fs6.existsSync(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=path15.resolve(dir,extPath);fs6.existsSync(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=path15.join(dir,"index.ts"),indexJs=path15.join(dir,"index.js");return fs6.existsSync(indexTs)?[indexTs]:fs6.existsSync(indexJs)?[indexJs]:null}function discoverExtensionsInDir(dir){if(!fs6.existsSync(dir))return[];let discovered=[];try{let entries=fs6.readdirSync(dir,{withFileTypes:!0}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(let entry2 of entries){let entryPath=path15.join(dir,entry2.name);if((entry2.isFile()||entry2.isSymbolicLink())&&isExtensionFile(entry2.name)){discovered.push(entryPath);continue}if(entry2.isDirectory()||entry2.isSymbolicLink()){let entries2=resolveExtensionEntries(entryPath);entries2&&discovered.push(...entries2)}}}catch{return[]}return discovered}async function discoverAndLoadExtensions(configuredPaths,cwd,agentDir=getAgentDir(),eventBus){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),allPaths=[],seen=new Set,addPaths=paths=>{for(let p of paths){let resolved=path15.resolve(p);seen.has(resolved)||(seen.add(resolved),allPaths.push(p))}},localExtDir=path15.join(resolvedCwd,CONFIG_DIR_NAME,"extensions");addPaths(discoverExtensionsInDir(localExtDir));let globalExtDir=path15.join(resolvedAgentDir,"extensions");addPaths(discoverExtensionsInDir(globalExtDir));for(let p of configuredPaths){let resolved=resolvePath(p,resolvedCwd,{normalizeUnicodeSpaces:!0});if(fs6.existsSync(resolved)&&fs6.statSync(resolved).isDirectory()){let entries=resolveExtensionEntries(resolved);if(entries){addPaths(entries);continue}addPaths(discoverExtensionsInDir(resolved));continue}addPaths([resolved])}return loadExtensions(allPaths,resolvedCwd,eventBus)}function warnStall(event,budget,stall){if(stall.stage!=="warn")return;let capNote=budget.timeoutMs>0?` (hard cap ${budget.timeoutMs}ms)`:"";console.warn(`Extension ${stall.extensionPath} is still running its ${event} handler after ${stall.elapsedMs}ms${capNote}.`)}async function runSessionMoveHandlers(event,calls,budget){let failures=[];for(let{extensionPath,call}of calls){let outcome=await runBudgetedHandler({extensionPath,event,budget,run:call,onStall:stall=>warnStall(event,budget,stall)});switch(outcome.kind){case"settled":break;case"failed":{let{error:error2}=outcome;failures.push({extensionPath,error:error2 instanceof Error?error2.message:String(error2),...error2 instanceof Error&&error2.stack!==void 0?{stack:error2.stack}:{}});break}case"timed_out":failures.push({extensionPath,error:`handler timed out after ${budget.timeoutMs}ms`});break;case"released":failures.push({extensionPath,error:"handler released before it finished"});break}}return failures}var SessionStartTurnGate=class{constructor(onStartError){this.onStartError=onStartError}get holding(){return this.held!==void 0}admit(start){this.held?this.held.push(start):start()}async dispatch(run2){if(this.held)return run2();let held=[];this.held=held;try{return await run2()}finally{this.held=void 0;for(let start of held)try{start()}catch(error2){this.onStartError(error2)}}}};var QuitDeadline=class{constructor(totalMs,now2,startedAt=now2()){this.now=now2,this.deadline=startedAt+totalMs}budgetFor(base){let remaining=Math.max(1,this.deadline-this.now());return base.timeoutMs>0&&base.timeoutMs<=remaining?{budget:base,endsAtQuitDeadline:!1}:{budget:{warnMs:base.warnMs<remaining?base.warnMs:0,timeoutMs:remaining},endsAtQuitDeadline:!0}}};var RUNTIME_CONTEXT_MEMBERS=new Set(["offload","ui","mode","hasUI","cwd","agentDir","loadedExtensionPaths","modelRegistry","isProjectTrusted","kernelTools","evalHandleHost","shutdown","getLookAtSettings","getAskUserSettings","getImageSettings","getRegisteredMcpServers","extensionConnectsMcpServers"]),SESSION_IDENTITY_MEMBERS=new Set(["sessionManager","goalStoreFile"]);function loopSideUnbound(member){return new Error(`${member} is loop-side and not bound: this extension runtime has no session`)}function withoutSession(context){for(let key of Reflect.ownKeys(context))if(!(typeof key!="string"||RUNTIME_CONTEXT_MEMBERS.has(key))){if(SESSION_IDENTITY_MEMBERS.has(key)){Reflect.deleteProperty(context,key);continue}Object.defineProperty(context,key,{configurable:!0,enumerable:!0,get(){throw loopSideUnbound(key)}})}}var RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS=["app.interrupt","app.clear","app.exit","app.suspend","app.thinking.cycle","app.model.cycleForward","app.model.cycleBackward","app.model.select","app.tools.expand","app.thinking.toggle","app.editor.external","app.message.copy","app.message.followUp","tui.input.submit","tui.select.confirm","tui.select.cancel","tui.input.copy","tui.editor.deleteToLineEnd"],buildBuiltinKeybindings=resolvedKeybindings=>{let builtinKeybindings={};for(let[keybinding,keys]of Object.entries(resolvedKeybindings)){if(keys===void 0)continue;let keyList=Array.isArray(keys)?keys:[keys],restrictOverride=RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS.includes(keybinding);for(let key of keyList){let normalizedKey=key.toLowerCase();builtinKeybindings[normalizedKey]?.restrictOverride&&!restrictOverride||(builtinKeybindings[normalizedKey]={keybinding,restrictOverride})}}return builtinKeybindings};function isUserBashEventResult(value){if(typeof value!="object"||value===null)return!1;let candidate=value,hasOperations=candidate.operations!==void 0,hasResult=candidate.result!==void 0;if(hasOperations===hasResult)return!1;if(hasOperations){let operations=candidate.operations;return typeof operations!="object"||operations===null?!1:typeof operations.exec=="function"}let result3=candidate.result;if(typeof result3!="object"||result3===null)return!1;let resultRecord=result3;return typeof resultRecord.output=="string"&&"exitCode"in resultRecord&&(resultRecord.exitCode===void 0||typeof resultRecord.exitCode=="number")&&typeof resultRecord.cancelled=="boolean"&&typeof resultRecord.truncated=="boolean"&&(resultRecord.fullOutputPath===void 0||typeof resultRecord.fullOutputPath=="string")}function sharedPrefixLength(before,after2){if(after2.startsWith(before))return before.length;let limit=Math.min(before.length,after2.length),index=0;for(;index<limit&&before.charCodeAt(index)===after2.charCodeAt(index);)index++;return index}var EXTENSION_EVENT_PLACEMENT={project_trust:"runtime",resources_discover:"runtime",mcp_servers_change:"runtime",session_start:"split",held_wakes_released:"loop",session_hold_changed:"loop",session_info_changed:"loop",session_parked:"split",session_resumed:"split",session_before_switch:"loop",session_before_fork:"loop",session_before_reload:"runtime",session_before_compact:"loop",session_compact:"loop",session_compact_failed:"loop",session_shutdown:"split",session_abort:"split",session_extensions_removed:"runtime",session_move_export:"loop",session_move_import:"loop",session_before_tree:"loop",session_tree:"loop",context:"loop",context_with_system:"loop",before_provider_request:"loop",before_provider_headers:"loop",after_provider_response:"loop",provider_stream_event:"loop",before_agent_start:"split",agent_start:"loop",agent_end:"split",agent_before_settle:"loop",agent_settled:"split",session_control_wake:"loop",ui_prompt_start:"runtime",ui_prompt_end:"runtime",turn_start:"split",turn_end:"loop",message_start:"loop",message_update:"loop",message_end:"split",tool_execution_start:"runtime",tool_execution_update:"runtime",tool_execution_end:"runtime",model_select:"loop",provider_login_start:"split",system_prompt_change:"loop",thinking_level_select:"loop",tool_activated:"runtime",user_bash:"runtime",input:"split",input_disposition:"loop",tool_call:"runtime",tool_result:"runtime"};function boundedToolHookStatusMessage(message){return message.length<=79?message:`${message.slice(0,76)}...`}function sanitizedToolHookStatusMessage(message){return boundedToolHookStatusMessage(stripAnsi(message).replace(/[\r\n\t]+/g," ").replace(/[\u0000-\u001f\u007f]+/g,"").replace(/\s+/g," ").trim())}var QUEUED_LIFECYCLE_EVENTS=new Set(["agent_start","agent_end","agent_settled","turn_start","message_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end"]),UNBOUNDED_HANDLER_BUDGET={warnMs:0,timeoutMs:0};async function emitSessionShutdownEvent(extensionRunner,event,options={}){options.processExit&&event.reason==="quit"&&extensionRunner.armProcessExitBudget();let emitted=extensionRunner.hasHandlers("session_shutdown");return emitted&&await extensionRunner.emit(event),reclaimRunnerHandles(extensionRunner),emitted}function snapshotEventHandlers(extensions,event){return extensions.map(ext=>({ext,handlers:ext.handlers.get(event)?.slice()??[]}))}function beforeAgentStartDispatchOrder(extensions){let snapshot2=snapshotEventHandlers(extensions,"before_agent_start"),runsLast=(ext,handler)=>ext.runLastHandlers?.has(handler)===!0,isBuiltin=ext=>ext.path.startsWith("<builtin:"),phase=keep=>snapshot2.map(({ext,handlers})=>({ext,handlers:handlers.filter(handler=>keep(ext,handler))}));return[...phase((ext,handler)=>!runsLast(ext,handler)),...phase((ext,handler)=>runsLast(ext,handler)&&!isBuiltin(ext)),...phase((ext,handler)=>runsLast(ext,handler)&&isBuiltin(ext))]}function flattenHandlers(extensions,event){return snapshotEventHandlers(extensions,event).flatMap(({ext,handlers})=>handlers.map(handler=>({path:ext.path,handler})))}function entryAt(entries,index){let entry2=entries[index];if(entry2===void 0)throw new RangeError(`no extension handler at index ${index}`);return entry2}async function emitProjectTrustEvent(extensionsResult,event,ctx){let errors=[];for(let{ext,handlers}of snapshotEventHandlers(extensionsResult.extensions,"project_trust"))for(let handler of handlers)try{let handlerResult=await handler(event,ctx);if(handlerResult.trusted==="undecided")continue;return{result:handlerResult,errors}}catch(error2){errors.push({extensionPath:ext.path,event:event.type,error:error2 instanceof Error?error2.message:String(error2),stack:error2 instanceof Error?error2.stack:void 0})}return{errors}}function createNoOpSessionSettings(){let settings=SettingsManager.inMemory();return{getRetryFallbackSettings:()=>settings.getRetryFallbackSettings(),setFallbackChain:async(key,entries)=>{settings.setFallbackChain(key,[...entries]),await settings.flush()},removeFallbackChain:async key=>{settings.removeFallbackChain(key),await settings.flush()},setModelFallbackEnabled:async enabled=>{settings.setModelFallbackEnabled(enabled),await settings.flush()},setFallbackRevertPolicy:async policy=>{settings.setFallbackRevertPolicy(policy),await settings.flush()},reload:()=>settings.reload(),getFallbackStatus:()=>{}}}var noOpUIContext={capabilities:{secretInput:!0},select:async()=>{},confirm:async()=>!1,input:async(_title,_placeholder,opts2)=>{if(!opts2?.signal?.aborted&&opts2?.secret)throw new SecretInputUnavailableError("headless")},notify:()=>{},onTerminalInput:()=>()=>{},setStatus:()=>{},setSubagentCost:()=>{},setWorkingMessage:()=>{},setWorkingVisible:()=>{},setWorkingIndicator:()=>{},setHiddenThinkingLabel:()=>{},setWidget:()=>{},setFooter:()=>{},setHeader:()=>{},setTitle:()=>{},custom:async()=>{},pasteToEditor:()=>{},setEditorText:()=>{},getEditorText:()=>"",editor:async()=>{},addAutocompleteProvider:()=>{},setEditorComponent:()=>{},getEditorComponent:()=>{},get theme(){return theme},getAllThemes:()=>[],getTheme:()=>{},setTheme:_theme=>({success:!1,error:"UI not available"}),getToolsExpanded:()=>!1,setToolsExpanded:()=>{}},ExtensionRunner=class{constructor(extensions,runtime,cwd,sessionManager,modelRegistry,eventBus=createEventBus()){this.brokerUIContexts=new WeakMap,this.mode="print",this.errorListeners=new Set,this.eventHandlerBudget=()=>UNBOUNDED_HANDLER_BUDGET,this.handlerTurnScope=()=>0,this.reportedInvalidHandlerBudget=!1,this.heldHandlerWaits=new HeldHandlerWaits,this.getModel=()=>{},this.getServiceTier=()=>{},this.getEffectiveServiceTier=()=>this.getServiceTier(),this.getScopedModels=()=>[],this.isIdleFn=()=>!0,this.engineTurnsHeldFn=()=>!1,this.noteHeldWakeFn=()=>{},this.pauseActions={},this.personAnswerPending=!1,this.isProjectTrustedFn=()=>!0,this.getSignalFn=()=>{},this.waitForIdleFn=async()=>{},this.abortFn=()=>{},this.hasPendingMessagesFn=()=>!1,this.hasQueuedPersonInputFn=()=>!1,this.isCompactingFn=()=>!1,this.getContextUsageFn=()=>{},this.getCompactionSettingsFn=()=>({enabled:!0,reserveTokens:16384,keepRecentTokens:2e4}),this.getPromptCacheSafeWaitSecondsFn=()=>{},this.getPromptCacheGoalBackstopMaxSecondsFn=()=>270,this.getPromptCacheKeepAliveSettingsFn=()=>({enabled:!1,maxRequestsPerSession:3,maxCostUsdPerSession:.05,marginSeconds:60}),this.getLookAtSettingsFn=()=>({enabled:!0,models:void 0}),this.getAskUserSettingsFn=()=>({enabled:!0,timeoutMinutes:30}),this.getBrowserEngineFn=()=>{},this.getSessionEnvFn=()=>{},this.getImageSettingsFn=()=>({autoResize:!0,blockImages:!1}),this.sessionSettingsFn=createNoOpSessionSettings(),this.compactFn=()=>{},this.beginCompactionFn=void 0,this.updateCompactionFn=void 0,this.endCompactionFn=void 0,this.getMessageRevisionFn=()=>0,this.applyCompactionFn=async()=>({applied:!1,reason:"rejected"}),this.getSystemPromptFn=()=>"",this.getSystemPromptStablePrefixFn=()=>{},this.getLoadedHookSourcesFn=()=>({agentDir:"",cwd:this.cwd,globalHookSourcePaths:[],globalHooksPath:"",preSessionHookSourcePaths:[],projectHookSourcePaths:[],projectHooksPath:"",runtimeHookSourcePaths:[]}),this.getSystemPromptOptionsFn=()=>({cwd:this.cwd}),this.getPromptCachePrefixRequestFn=void 0,this.getAgentDirFn=()=>getAgentDir(),this.getCallableToolsFn=()=>[],this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.editAssistantMessageHandler=async()=>({cancelled:!1}),this.editUserMessageHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.shutdownHandler=()=>{},this.sessionStartTurns=new SessionStartTurnGate(error2=>this.emitError({extensionPath:RUNTIME_EXTENSION_PATH,event:"session_start",error:error2 instanceof Error?error2.message:String(error2)})),this.shortcutDiagnostics=[],this.commandDiagnostics=[],this.nextToolHookRunIndex=0,this.uiPromptDepth=0,this.#reportedChildModuleReplacements=new Set,this.extensions=extensions,registerRunnerExtensions(this,extensions),this.runtime=runtime,runtime.mcpServers.bind(extensions),runtime.emitProviderLoginStart=event=>this.emitProviderLoginStart(event),this.uiContext=noOpUIContext,this.cwd=cwd,this.sessionManager=sessionManager,this.modelRegistry=modelRegistry,this.eventBus=eventBus}bindCore(actions,contextActions,providerActions){actions.lifecycle&&(this.runtime.lifecycle=actions.lifecycle),this.runtime.sendMessage=(message,options)=>{options?.triggerTurn===!0?this.sessionStartTurns.admit(()=>actions.sendMessage(message,options)):actions.sendMessage(message,options)},this.runtime.sendItemizedMessage=(message,options)=>{let receipts=Promise.withResolvers(),send=()=>{let itemized=actions.sendItemizedMessage;itemized===void 0?(actions.sendMessage(message,options),receipts.resolve(void 0)):itemized(message,options).then(receipts.resolve,receipts.reject)};return options.triggerTurn===!0?this.sessionStartTurns.admit(send):send(),receipts.promise},this.runtime.sendUserMessage=(content,options)=>{let inputOrigin=this.personAnswerPending?"person":"extension";this.personAnswerPending=!1,this.sessionStartTurns.admit(()=>actions.sendUserMessage(content,options,inputOrigin))},this.runtime.appendEntry=actions.appendEntry,this.runtime.setSessionName=actions.setSessionName,this.runtime.getSessionName=actions.getSessionName,this.runtime.setLabel=actions.setLabel,this.runtime.executeTool=actions.executeTool,this.runtime.getActiveTools=actions.getActiveTools,this.runtime.getAllTools=actions.getAllTools,this.runtime.getSettings=actions.getSettings,this.runtime.setActiveTools=actions.setActiveTools,this.runtime.refreshTools=actions.refreshTools,this.runtime.registerRemovedToolHint=actions.registerRemovedToolHint,this.runtime.registerLazyToolActivator=actions.registerLazyToolActivator,this.runtime.getCommands=actions.getCommands,this.runtime.setModel=actions.setModel,this.runtime.getThinkingLevel=actions.getThinkingLevel,this.runtime.setThinkingLevel=actions.setThinkingLevel,this.runtime.setSessionModel=actions.setSessionModel,this.runtime.setSessionThinkingLevel=actions.setSessionThinkingLevel,this.runtime.setSessionFastMode=actions.setSessionFastMode,actions.sessionControl&&(this.runtime.sessionControl=actions.sessionControl),actions.armToolBarrier&&(this.runtime.armToolBarrier=actions.armToolBarrier),actions.releaseToolBarrier&&(this.runtime.releaseToolBarrier=actions.releaseToolBarrier),this.runtime.createContext=()=>this.createContext(),this.offloadFn=contextActions.offload,this.getModel=contextActions.getModel,this.getServiceTier=contextActions.getServiceTier,this.getEffectiveServiceTier=contextActions.getEffectiveServiceTier??contextActions.getServiceTier,this.getScopedModels=contextActions.getScopedModels,this.isIdleFn=contextActions.isIdle,this.engineTurnsHeldFn=contextActions.engineTurnsHeld??(()=>!1),this.noteHeldWakeFn=contextActions.noteHeldWake??(()=>{}),this.pauseActions={getPauseState:contextActions.getPauseState,fenceRun:contextActions.fenceRun,releaseRunFence:contextActions.releaseRunFence},this.questionInput=contextActions.questionInput,this.isProjectTrustedFn=contextActions.isProjectTrusted,this.getSignalFn=contextActions.getSignal,this.abortFn=contextActions.abort,this.hasPendingMessagesFn=contextActions.hasPendingMessages,this.hasQueuedPersonInputFn=contextActions.hasQueuedPersonInput??(()=>!1),this.isCompactingFn=contextActions.isCompacting,this.checkReloadVetoFn=contextActions.checkReloadVeto,this.shutdownHandler=contextActions.shutdown,this.getContextUsageFn=contextActions.getContextUsage,this.getCompactionSettingsFn=contextActions.getCompactionSettings,this.getCompactionModelFn=contextActions.getCompactionModel,contextActions.getPromptCacheSafeWaitSeconds&&(this.getPromptCacheSafeWaitSecondsFn=contextActions.getPromptCacheSafeWaitSeconds),contextActions.getPromptCacheGoalBackstopMaxSeconds&&(this.getPromptCacheGoalBackstopMaxSecondsFn=contextActions.getPromptCacheGoalBackstopMaxSeconds),contextActions.getPromptCacheKeepAliveSettings&&(this.getPromptCacheKeepAliveSettingsFn=contextActions.getPromptCacheKeepAliveSettings),this.getLookAtSettingsFn=contextActions.getLookAtSettings,contextActions.getAskUserSettings&&(this.getAskUserSettingsFn=contextActions.getAskUserSettings),contextActions.getBrowserEngine&&(this.getBrowserEngineFn=contextActions.getBrowserEngine),contextActions.getSessionEnv&&(this.getSessionEnvFn=contextActions.getSessionEnv),this.getImageSettingsFn=contextActions.getImageSettings,this.sessionSettingsFn=contextActions.sessionSettings,this.compactFn=contextActions.compact,this.beginCompactionFn=contextActions.beginCompaction,this.updateCompactionFn=contextActions.updateCompaction,this.endCompactionFn=contextActions.endCompaction,this.getMessageRevisionFn=contextActions.getMessageRevision,this.applyCompactionFn=contextActions.applyCompaction,this.getSystemPromptFn=contextActions.getSystemPrompt,this.getSystemPromptStablePrefixFn=contextActions.getSystemPromptStablePrefix??(()=>{}),this.getLoadedHookSourcesFn=contextActions.getLoadedHookSources,contextActions.getAgentDir&&(this.getAgentDirFn=contextActions.getAgentDir),this.getSystemPromptOptionsFn=contextActions.getSystemPromptOptions??(()=>({cwd:this.cwd})),this.getPromptCachePrefixRequestFn=contextActions.getPromptCachePrefixRequest,this.onUserActivityFn=contextActions.onUserActivity,this.executeToolFn=contextActions.executeTool,this.getCallableToolsFn=contextActions.getCallableTools??(()=>[]),this.runtime.mcpServers.setChangeListener(()=>{this.emit({type:"mcp_servers_change",servers:this.runtime.mcpServers.list()})});for(let extension of this.extensions){for(let[name,hint]of extension.removedToolHints??[])actions.registerRemovedToolHint(name,hint);for(let activator of extension.lazyToolActivators??[])actions.registerLazyToolActivator(activator)}for(let registration of drainPendingProviderRegistrations(this.runtime))try{registration.kind==="config"?providerActions?.registerProvider?providerActions.registerProvider(registration.name,registration.config,registration.extensionPath):this.modelRegistry.registerProvider(registration.name,registration.config):providerActions?.registerNativeProvider?providerActions.registerNativeProvider(registration.provider,registration.extensionPath):this.modelRegistry.registerProvider(registration.provider)}catch(err){this.emitError({extensionPath:registration.extensionPath,event:"register_provider",error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}let registerVirtualModel=definition=>{providerActions?.registerVirtualModel?providerActions.registerVirtualModel(definition):this.modelRegistry.registerVirtualModel(definition)};for(let{definition,extensionPath}of this.runtime.pendingVirtualModelRegistrations)try{registerVirtualModel(definition)}catch(err){this.emitError({extensionPath,event:"register_virtual_model",error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}this.runtime.pendingVirtualModelRegistrations=[],this.runtime.registerProvider=(name,config,extensionPath)=>{if(providerActions?.registerProvider){providerActions.registerProvider(name,config,extensionPath);return}this.modelRegistry.registerProvider(name,config)},this.runtime.registerNativeProvider=(provider,extensionPath)=>{if(providerActions?.registerNativeProvider){providerActions.registerNativeProvider(provider,extensionPath);return}this.modelRegistry.registerProvider(provider)},this.runtime.unregisterProvider=name=>{if(providerActions?.unregisterProvider){providerActions.unregisterProvider(name);return}this.modelRegistry.unregisterProvider(name)},this.runtime.registerVirtualModel=registerVirtualModel,this.runtime.unregisterVirtualModel=(provider,id)=>{providerActions?.unregisterVirtualModel?providerActions.unregisterVirtualModel(provider,id):this.modelRegistry.unregisterVirtualModel(provider,id)}}bindCommandContext(actions){if(actions){this.waitForIdleFn=actions.waitForIdle,this.newSessionHandler=actions.newSession,this.forkHandler=actions.fork,this.navigateTreeHandler=actions.navigateTree,this.editAssistantMessageHandler=actions.editAssistantMessage,this.editUserMessageHandler=actions.editUserMessage,this.switchSessionHandler=actions.switchSession,this.reloadHandler=actions.reload;return}this.waitForIdleFn=async()=>{},this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.editAssistantMessageHandler=async()=>({cancelled:!1}),this.editUserMessageHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.reloadHandler=void 0}requestReload(){return this.reloadHandler?(this.reloadRequestPromise||(this.reloadRequestPromise=this.reloadHandler().finally(()=>{this.reloadRequestPromise=void 0})),this.reloadRequestPromise):Promise.resolve()}setUIContext(uiContext,mode="print"){this.uiContext=uiContext?this.wrapUIPromptContext(uiContext):noOpUIContext,this.mode=mode}setUiBroker(broker){this.uiBroker=broker}currentUIContext(){if(this.uiBroker===void 0)return this.uiContext;let presenter=this.uiBroker.presenter;if(presenter===void 0)return noOpUIContext;let wrapped=this.brokerUIContexts.get(presenter);return wrapped===void 0&&(wrapped=this.wrapUIPromptContext(presenter),this.brokerUIContexts.set(presenter,wrapped)),wrapped}setToolHookLifecycleObserver(observer){this.toolHookLifecycleObserver=observer}setLifecycleAttentionObserver(observer){this.lifecycleAttentionObserver=observer}getLifecycleHumanWait(){let prompt=this.activeUIPrompt;if(!(this.mode==="rpc"||!prompt))return{kind:prompt.kind==="confirm"?"approval":"question",requestId:prompt.requestId,revision:1,since:prompt.since}}wrapUIPromptContext(ui){let questionFn=ui.question;return inheritMcpMrtrPresentation(ui,{...ui,select:(title,options,opts2)=>this.withUIPrompt("select",title,()=>ui.select(title,options,opts2)),confirm:(title,message,opts2)=>this.withUIPrompt("confirm",title,()=>ui.confirm(title,message,opts2)),input:(title,placeholder,opts2)=>this.withUIPrompt("input",opts2?.secret?void 0:title,()=>ui.input(title,placeholder,opts2)),editor:(title,prefill)=>this.withUIPrompt("editor",title,()=>ui.editor(title,prefill)),custom:(factory,options)=>this.withUIPrompt("custom",void 0,()=>ui.custom(factory,options)),...questionFn?{question:(request2,opts2)=>this.withUIPrompt("question",request2.questions[0]?.header,()=>questionFn(request2,opts2),request2.requestId)}:{}})}withUIPrompt(kind,title,run2,requestId=crypto.randomUUID()){this.uiPromptDepth++===0&&(this.activeUIPrompt={kind,title,requestId,since:new Date().toISOString()},this.lifecycleAttentionObserver?.(),this.emitUIPromptEvent({type:"ui_prompt_start",reason:"ui_prompt",kind,...title?{title}:{}}));let finish=()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;let prompt=this.activeUIPrompt??{kind,title};this.activeUIPrompt=void 0,this.lifecycleAttentionObserver?.(),this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:prompt.kind,...prompt.title?{title:prompt.title}:{}})};try{return run2().finally(finish)}catch(err){throw finish(),err}}emitUIPromptEvent(event){queueMicrotask(()=>{this.emit(event)})}getUIContext(){return this.currentUIContext()}sessionStartTurnsHeld(){return this.sessionStartTurns.holding}hasUI(){return this.currentUIContext()!==noOpUIContext}getExtensionPaths(){return this.extensions.map(e=>e.path)}getExtensionIdentities(){return this.extensions.map(({path:path16,resolvedPath})=>({path:path16,resolvedPath}))}#reportedChildModuleReplacements;getAllChildModules(){let modules=new Map;for(let ext of this.extensions)for(let[id,entry2]of ext.childModules??[]){let earlier=modules.get(id),replacement=`${id}\0${earlier?.sourceInfo.path}\0${entry2.sourceInfo.path}`;earlier!==void 0&&earlier.sourceInfo.path!==entry2.sourceInfo.path&&!this.#reportedChildModuleReplacements.has(replacement)&&(this.#reportedChildModuleReplacements.add(replacement),console.warn(`Child module "${id}" from ${entry2.sourceInfo.path} replaces the one from ${earlier.sourceInfo.path}`)),modules.set(id,entry2)}return modules}getAllRegisteredTools(){let toolsByName=new Map;for(let ext of this.extensions)for(let tool of ext.tools.values()){let existing2=toolsByName.get(tool.definition.name);(!existing2||existing2.sourceInfo.source==="builtin"&&tool.sourceInfo.source!=="builtin")&&toolsByName.set(tool.definition.name,tool)}return Array.from(toolsByName.values())}getFilesystemPolicyDeniedRoots(){return this.extensions.flatMap(extension=>(extension.filesystemPolicies??[]).flatMap(policy=>policy.deniedRoots??[]))}onRpcEvent(handler){let off=this.eventBus.on(EXTENSION_RPC_EVENT_CHANNEL,data=>{handler(data)});return this.eventBus.emit(EXTENSION_RPC_SUBSCRIBED_CHANNEL,void 0),off}onBusEvent(channel,handler){return this.eventBus.on(channel,handler)}emitBusEvent(channel,data){this.eventBus.emit(channel,data)}getRegisteredMcpServers(){return this.runtime.mcpServers.declarations()}extensionConnectsMcpServers(){return this.hasHandlers("mcp_servers_change")}getToolDefinition(toolName){for(let ext of this.extensions){let tool=ext.tools.get(toolName);if(tool)return tool.definition}}getFlags(){let allFlags=new Map;for(let ext of this.extensions)for(let[name,flag]of ext.flags)allFlags.has(name)||allFlags.set(name,flag);return allFlags}setFlagValue(name,value){this.runtime.flagValues.set(name,value)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(resolvedKeybindings){this.shortcutDiagnostics=[];let builtinKeybindings=buildBuiltinKeybindings(resolvedKeybindings),extensionShortcuts=new Map,addDiagnostic=(message,extensionPath)=>{this.shortcutDiagnostics.push({type:"warning",message,path:extensionPath}),this.hasUI()||console.warn(message)};for(let ext of this.extensions)for(let[key,shortcut]of ext.shortcuts){let normalizedKey=key.toLowerCase(),builtInKeybinding=builtinKeybindings[normalizedKey];if(builtInKeybinding?.restrictOverride===!0){addDiagnostic(`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,shortcut.extensionPath);continue}builtInKeybinding?.restrictOverride===!1&&addDiagnostic(`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,shortcut.extensionPath);let existingExtensionShortcut=extensionShortcuts.get(normalizedKey);existingExtensionShortcut&&addDiagnostic(`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,shortcut.extensionPath),extensionShortcuts.set(normalizedKey,shortcut)}return extensionShortcuts}getShortcutDiagnostics(){return this.shortcutDiagnostics}invalidate(message="This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."){this.staleMessage||(this.staleMessage=message,this.runtime.invalidate(message))}get isActive(){return this.staleMessage===void 0}runAfterSessionStart(publish2){if(this.staleMessage)return;let report=error2=>{error2 instanceof StaleExtensionContextError||this.emitError({extensionPath:RUNTIME_EXTENSION_PATH,event:"session_start",error:error2 instanceof Error?error2.message:String(error2)})};try{Promise.resolve(publish2()).catch(report)}catch(error2){report(error2)}}assertActive(){if(this.staleMessage)throw new StaleExtensionContextError(this.staleMessage)}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}setEventHandlerBudget(budget,onStall,turnScope=()=>0){this.eventHandlerBudget=budget,this.handlerStallListener=onStall,this.handlerTurnScope=turnScope}releaseHeldHandlers(turn,verdict="released"){return this.heldHandlerWaits.release(turn,verdict)}resolveEventHandlerBudget(){try{return this.eventHandlerBudget()}catch(err){return this.reportedInvalidHandlerBudget||(this.reportedInvalidHandlerBudget=!0,console.warn(`Using the default extension event handler budget (warn ${DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS}ms, hard cap ${DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS}ms): ${err instanceof Error?err.message:String(err)}`)),{warnMs:DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS,timeoutMs:DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS}}}walkHandlers(sequence2){return runBudgetedSequence(sequence2,{budget:this.resolveEventHandlerBudget(),held:{waits:this.heldHandlerWaits,scope:this.handlerTurnScope},onStall:stall=>this.handlerStallListener?.(stall)})}reportStoppedHandler(extensionPath,event,verdict,budget){if(verdict==="yielded")return;let error2=verdict==="timed_out"?`handler timed out after ${budget.timeoutMs}ms`:"handler released when the turn was stopped";this.emitError({extensionPath,event,error:error2})}reportHandlerFailure(extensionPath,event,err){this.emitError({extensionPath,event,error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}dispatchLifecycle(event){let entries=flattenHandlers(this.extensions,event.type);return this.walkHandlers({event:event.type,length:entries.length,extensionPath:index=>entryAt(entries,index).path,start:index=>{let{path:path16,handler}=entryAt(entries,index);return handler(event,this.createContext(path16))},settle:(index,outcome)=>{outcome.ok||this.reportHandlerFailure(entryAt(entries,index).path,event.type,outcome.error)},skip:(index,verdict,budget)=>this.reportStoppedHandler(entryAt(entries,index).path,event.type,verdict,budget),finish:()=>{}})}emitError(error2){for(let listener of this.errorListeners)listener(error2)}hasHandlers(eventType){for(let ext of this.extensions){let handlers=ext.handlers.get(eventType);if(handlers&&handlers.length>0)return!0}return!1}getToolHookStatusMessage(extensionPath,hookName){let builtinName=/^<builtin:([^>]+)>$/.exec(extensionPath)?.[1];if(builtinName==="permission-system")return"matching project rules";if(builtinName==="bash-timeout")return"applying bash timeout";if(builtinName==="compaction")return hookName==="PreToolUse"?"checking compaction state":"checking tool result size";if(builtinName==="tool-pair-guard")return"checking tool/result pairs";let extensionName=builtinName??(extensionPath.startsWith("<")&&extensionPath.endsWith(">")?extensionPath.slice(1,-1):basename37(extensionPath).replace(/\.(?:c|m)?[jt]sx?$/,""));return boundedToolHookStatusMessage(`running ${extensionName}`)}emitToolHookLifecycleEvent(event){this.toolHookLifecycleObserver?.(event)}beginToolHookRun(baseContext,run2){let base={type:"tool_hook_status",hookRunId:`${run2.toolCallId}:${run2.hookName}:${this.nextToolHookRunIndex++}`,hookName:run2.hookName,toolName:run2.toolName,toolCallId:run2.toolCallId,extensionPath:run2.extensionPath,startedAt:Date.now()},statusMessage=this.getToolHookStatusMessage(run2.extensionPath,run2.hookName),ended=!1;this.emitToolHookLifecycleEvent({...base,phase:"start",statusMessage});let context=Object.defineProperties({},Object.getOwnPropertyDescriptors(baseContext));return context.updateToolHookStatus=update2=>{ended||(statusMessage=sanitizedToolHookStatusMessage(update2),this.emitToolHookLifecycleEvent({...base,phase:"update",statusMessage}))},{context,end:(status,errorMessage6)=>{ended||(ended=!0,this.emitToolHookLifecycleEvent({...base,phase:"end",statusMessage,completedAt:Date.now(),status,...errorMessage6!==void 0?{errorMessage:errorMessage6}:{}}))}}}getMessageRenderer(customType){for(let ext of this.extensions){let renderer=ext.messageRenderers.get(customType);if(renderer)return renderer}}getMemoryReporters(){return this.extensions.flatMap(ext=>[...ext.memoryReporters??new Map].map(([name,reporter])=>({name,reporter})))}getMarkdownTransformers(){return this.extensions.flatMap(ext=>ext.markdownTransformer?[ext.markdownTransformer]:[])}getEntryRenderer(customType){for(let ext of this.extensions){let renderer=ext.entryRenderers?.get(customType);if(renderer)return renderer}}getEntryRendererOptions(customType){return this.extensions.find(ext=>ext.entryRenderers?.has(customType))?.entryRendererOptions?.get(customType)}resolveRegisteredCommands(){let commands=[],counts=new Map;for(let ext of this.extensions)for(let command of ext.commands.values())commands.push(command),counts.set(command.name,(counts.get(command.name)??0)+1);let seen=new Map,takenInvocationNames=new Set;return commands.map(command=>{let occurrence=(seen.get(command.name)??0)+1;seen.set(command.name,occurrence);let invocationName=(counts.get(command.name)??0)>1?`${command.name}:${occurrence}`:command.name;if(takenInvocationNames.has(invocationName)){let suffix=occurrence;do suffix++,invocationName=`${command.name}:${suffix}`;while(takenInvocationNames.has(invocationName))}return takenInvocationNames.add(invocationName),{...command,invocationName}})}getModelRegistry(){return this.modelRegistry}getRegisteredCommands(){return this.commandDiagnostics=[],this.resolveRegisteredCommands()}getCommandDiagnostics(){return this.commandDiagnostics}getCommand(name){return this.resolveRegisteredCommands().find(command=>command.invocationName===name)}async requestRpc(name,data,context){return requestExtensionRpc(this.extensions,name,data,context,()=>this.assertActive())}shutdown(){this.shutdownHandler()}getActiveTools(){return this.assertActive(),this.sessionManager===void 0?[]:this.runtime.getActiveTools()}boundSessionManager(){if(this.sessionManager===void 0)throw loopSideUnbound("sessionManager");return this.sessionManager}createContext(excludeBeforeProviderRequestExtensionPath){let runner=this,getModel=this.getModel,getServiceTier=this.getServiceTier,getEffectiveServiceTier=this.getEffectiveServiceTier,getScopedModels=this.getScopedModels,compactionSignal,context={offload:(id,args,options)=>(runner.assertActive(),runner.offloadFn===void 0?Promise.reject(new Error(`offload_unavailable: no session backs this context (offload ${id})`)):runner.offloadFn(id,args,options)),get ui(){return runner.assertActive(),runner.currentUIContext()},get mode(){return runner.assertActive(),runner.mode},get hasUI(){return runner.assertActive(),runner.hasUI()},get cwd(){return runner.assertActive(),runner.cwd},get agentDir(){return runner.assertActive(),runner.getAgentDirFn()},get loadedExtensionPaths(){return runner.assertActive(),runner.extensions.map(extension=>extension.resolvedPath)},get sessionManager(){return runner.assertActive(),runner.boundSessionManager()},get goalStoreFile(){return runner.assertActive(),goalFilePath(goalStoreRef(runner.boundSessionManager(),runner.cwd))},get browserEngine(){return runner.assertActive(),runner.getBrowserEngineFn()},get sessionEnv(){return runner.assertActive(),runner.getSessionEnvFn()},get modelRegistry(){return runner.assertActive(),runner.modelRegistry},get model(){return runner.assertActive(),getModel()},get serviceTier(){return runner.assertActive(),getServiceTier()},get effectiveServiceTier(){return runner.assertActive(),getEffectiveServiceTier()},get scopedModels(){return runner.assertActive(),getScopedModels()},get thinkingLevel(){return runner.assertActive(),runner.runtime.getThinkingLevel()},isIdle:()=>(runner.assertActive(),runner.isIdleFn()),engineTurnsHeld:()=>(runner.assertActive(),runner.engineTurnsHeldFn()),noteHeldWake:source2=>{runner.assertActive(),runner.noteHeldWakeFn(source2)},getPauseState:()=>(runner.assertActive(),runner.pauseActions.getPauseState?.()??{pauseSeq:0,holds:[]}),fenceRun:runRef=>{runner.assertActive(),runner.pauseActions.fenceRun?.(runRef)},releaseRunFence:runRef=>{runner.assertActive(),runner.pauseActions.releaseRunFence?.(runRef)},isProjectTrusted:()=>(runner.assertActive(),runner.isProjectTrustedFn()),get signal(){return runner.assertActive(),runner.getSignalFn()},get kernelTools(){runner.assertActive();let tools=kernelToolsStorage.getStore();if(tools)return{capabilities:tools.capabilities,describe:names=>tools.describe(names),invoke:(request2,options)=>(runner.assertActive(),tools.invoke(request2,{...options&&("aborted"in options?{signal:options}:options),invoker:kernelToolInvokerStorage.getStore()??{sessionId:runner.boundSessionManager().getSessionId()}}))}},get evalHandleHost(){return runner.assertActive(),runner.runtime.evalHandleHost},abort:source2=>{runner.assertActive(),runner.abortFn(source2)},hasPendingMessages:()=>(runner.assertActive(),runner.hasPendingMessagesFn()),hasQueuedPersonInput:()=>(runner.assertActive(),runner.hasQueuedPersonInputFn()),get requestReload(){return runner.assertActive(),runner.reloadHandler?()=>runner.requestReload():void 0},get checkReloadVeto(){runner.assertActive();let probe=runner.checkReloadVetoFn;return probe?()=>probe():void 0},isCompacting:()=>(runner.assertActive(),runner.isCompactingFn()),shutdown:()=>{runner.assertActive(),runner.shutdownHandler()},getContextUsage:()=>(runner.assertActive(),runner.getContextUsageFn()),getCompactionSettings:()=>(runner.assertActive(),runner.getCompactionSettingsFn()),get getCompactionModel(){return runner.assertActive(),runner.getCompactionModelFn?()=>(runner.assertActive(),runner.getCompactionModelFn?.()):void 0},getPromptCacheSafeWaitSeconds:()=>(runner.assertActive(),runner.getPromptCacheSafeWaitSecondsFn()),getPromptCacheGoalBackstopMaxSeconds:()=>(runner.assertActive(),runner.getPromptCacheGoalBackstopMaxSecondsFn()),getPromptCacheKeepAliveSettings:()=>(runner.assertActive(),runner.getPromptCacheKeepAliveSettingsFn()),onUserActivity:listener=>{runner.assertActive();let unsubscribe=runner.onUserActivityFn?.(kind=>{try{listener(kind)}catch(error2){runner.emitError({extensionPath:excludeBeforeProviderRequestExtensionPath??RUNTIME_EXTENSION_PATH,event:"user_activity",error:error2 instanceof Error?error2.message:String(error2)})}});return runner.runtime.trackEventBusSubscription(unsubscribe??(()=>{}))},getLookAtSettings:()=>(runner.assertActive(),runner.getLookAtSettingsFn()),getAskUserSettings:()=>(runner.assertActive(),runner.getAskUserSettingsFn()),afterSessionStart:publish2=>{runner.assertActive(),runner.sessionStartTurns.admit(()=>runner.runAfterSessionStart(publish2))},getImageSettings:()=>(runner.assertActive(),runner.getImageSettingsFn()),get sessionSettings(){return runner.assertActive(),runner.sessionSettingsFn},compact:options=>{runner.assertActive(),runner.compactFn(options)},prepareProviderRequest:async(messages,options)=>(runner.assertActive(),runner.prepareProviderRequest(messages,excludeBeforeProviderRequestExtensionPath,options)),getPromptCachePrefixRequest:async options=>{runner.assertActive();let build=runner.getPromptCachePrefixRequestFn;return build===void 0?{status:"skipped",reason:"the host builds no prompt-cache prefix"}:await build(options)},beginCompaction:options=>(runner.assertActive(),compactionSignal=runner.beginCompactionFn?.(options),compactionSignal),updateCompaction:options=>{runner.assertActive(),runner.updateCompactionFn?.({...options,signal:options.signal??compactionSignal})},endCompaction:options=>{runner.assertActive(),runner.endCompactionFn?.({...options,signal:options.signal??compactionSignal})},getMessageRevision:()=>(runner.assertActive(),runner.getMessageRevisionFn()),applyCompaction:(precomputed,options)=>(runner.assertActive(),runner.applyCompactionFn(precomputed,{...options,signal:options.signal??compactionSignal})),getSystemPrompt:()=>(runner.assertActive(),runner.getSystemPromptFn()),getSystemPromptStablePrefix:()=>(runner.assertActive(),runner.getSystemPromptStablePrefixFn()),getSystemPromptOptions:()=>(runner.assertActive(),runner.getSystemPromptOptionsFn()),getLoadedHookSources:()=>(runner.assertActive(),runner.getLoadedHookSourcesFn()),getRegisteredMcpServers:()=>(runner.assertActive(),runner.getRegisteredMcpServers()),extensionConnectsMcpServers:()=>(runner.assertActive(),runner.extensionConnectsMcpServers())};return this.questionInput&&bindQuestionInput(context,()=>{runner.assertActive(),runner.personAnswerPending=!0,queueMicrotask(()=>{runner.personAnswerPending=!1}),runner.questionInput?.()}),this.sessionManager===void 0&&withoutSession(context),context}createToolContext(toolCallId,signal,baseContext=this.createContext()){let runner=this;return Object.defineProperties(baseContext,{tools:{get(){return runner.assertActive(),runner.getCallableToolsFn()}},executeTool:{value:async(name,args,options={})=>(runner.assertActive(),runner.executeToolFn?runner.executeToolFn(toolCallId,name,args,{...options,signal:options.signal??signal}):{toolCall:{type:"toolCall",id:`${toolCallId}/0`,name,arguments:{}},result:{content:[{type:"text",text:"Nested tool calls are not available in this context"}],details:{}},isError:!0})}})}createCommandContext(){let context=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));return context.waitForIdle=()=>(this.assertActive(),this.waitForIdleFn()),context.newSession=options=>(this.assertActive(),this.newSessionHandler(options)),context.fork=(entryId,options)=>(this.assertActive(),this.forkHandler(entryId,options)),context.navigateTree=(targetId,options)=>{if(this.assertActive(),typeof targetId=="string")return this.navigateTreeHandler(targetId,options);let{entryId,...navigationOptions}=targetId;return this.navigateTreeHandler(entryId,navigationOptions)},context.editAssistantMessage=(entryId,text4,options)=>(this.assertActive(),this.editAssistantMessageHandler(entryId,text4,options)),context.editUserMessage=(entryId,text4,options)=>(this.assertActive(),this.editUserMessageHandler(entryId,text4,options)),context.switchSession=(sessionPath,options)=>(this.assertActive(),this.switchSessionHandler(sessionPath,options)),context.reload=()=>(this.assertActive(),this.requestReload()),context}async emitBoundary(baseEvent,buildContext2){let ctx=this.createContext(),entries=[],shouldContinue=!1,context={contextEntries:[],contextMessages:[],llmMessages:[],pendingMessages:[],canContinue:!1},retired=()=>({entries:[],continue:!1,context,valid:!1});try{context=await buildContext2(entries)}catch(err){if(!this.isActive)return retired();throw err}let valid2=!0,handlers=this.dropsLoopEvent(baseEvent.type)?[]:flattenHandlers(this.extensions,baseEvent.type);return this.walkHandlers({event:baseEvent.type,length:handlers.length,extensionPath:index=>entryAt(handlers,index).path,halted:()=>!this.isActive,start:index=>{let event={...baseEvent,entries,continue:shouldContinue,context};return entryAt(handlers,index).handler(event,ctx)},settle:async(index,outcome)=>{if(!this.isActive)return;let{path:path16}=entryAt(handlers,index);if(outcome.ok){let handlerResult=outcome.value;handlerResult?.entries!==void 0&&(entries=handlerResult.entries),handlerResult?.continue!==void 0&&(shouldContinue=handlerResult.continue)}else this.reportHandlerFailure(path16,baseEvent.type,outcome.error);try{context=await buildContext2(entries),valid2=!0}catch(err){if(!this.isActive)return;valid2=!1,this.emitError({extensionPath:path16,event:baseEvent.type,error:`Invalid boundary entries: ${err instanceof Error?err.message:String(err)}`,stack:err instanceof Error?err.stack:void 0})}},skip:(index,verdict,budget)=>this.reportStoppedHandler(entryAt(handlers,index).path,baseEvent.type,verdict,budget),finish:()=>valid2&&this.isActive?{entries,continue:shouldContinue,context,valid:!0}:retired()})}isSessionBeforeEvent(event){return event.type==="session_before_switch"||event.type==="session_before_fork"||event.type==="session_before_reload"||event.type==="session_before_compact"||event.type==="session_before_tree"}armProcessExitBudget(){this.processExitRequestedAt??=Date.now()}resolveSessionShutdownBudget(){try{let settings=SettingsManager.create(this.cwd,this.getAgentDirFn(),{projectTrusted:this.isProjectTrustedFn()});return{handler:{warnMs:settings.getSessionShutdownHandlerWarnMs(),timeoutMs:settings.getSessionShutdownHandlerTimeoutMs()},quitMs:settings.getSessionShutdownQuitBudgetMs()}}catch(err){let message=err instanceof Error?err.message:String(err);return console.warn(`Using the default session_shutdown handler budget (warn ${DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS}ms, hard cap ${DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS}ms, quit ${DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS}ms): ${message}`),{handler:{warnMs:DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS,timeoutMs:DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS},quitMs:DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS}}}async runSessionShutdownHandler(extensionPath,event,handler,{budget,endsAtQuitDeadline}){let startedAt=Date.now(),outcome=await runBudgetedHandler({extensionPath,event:"session_shutdown",budget,run:signal=>handler({...event,signal},this.createContext(extensionPath)),onStall:stall=>{if(stall.stage!=="warn")return;let capNote=budget.timeoutMs>0?` (hard cap ${budget.timeoutMs}ms)`:"";console.warn(`Extension ${extensionPath} is still running its session_shutdown handler after ${stall.elapsedMs}ms${capNote}.`)}});if(outcome.kind==="failed")throw outcome.error;outcome.kind==="timed_out"&&endsAtQuitDeadline?console.warn(`Extension ${extensionPath} session_shutdown handler overran the quit budget after ${Date.now()-startedAt}ms; quitting without it.`):outcome.kind==="timed_out"&&this.emitError({extensionPath,event:"session_shutdown",error:`handler timed out after ${budget.timeoutMs}ms`})}emitHeldWakesReleased(sources){return this.emit({type:"held_wakes_released",sources})}dropsLoopEvent(type2){return this.sessionManager===void 0&&EXTENSION_EVENT_PLACEMENT[type2]==="loop"}emit(event){return this.dropsLoopEvent(event.type)?Promise.resolve(void 0):event.type==="session_start"?this.sessionStartTurns.dispatch(()=>this.dispatchEmit(event)):QUEUED_LIFECYCLE_EVENTS.has(event.type)?this.dispatchLifecycle(event):this.dispatchEmit(event)}async emitSessionMove(event){let calls=(this.dropsLoopEvent(event.type)?[]:flattenHandlers(this.extensions,event.type)).map(({path:path16,handler})=>({extensionPath:path16,call:signal=>handler({...event,signal},this.createContext(path16))})),failures=await runSessionMoveHandlers(event.type,calls,this.resolveSessionShutdownBudget().handler);for(let failure2 of failures)this.emitError({...failure2,event:event.type});return failures}async dispatchEmit(event){let result3,isSessionShutdown=event.type==="session_shutdown",shutdownBudget,quitDeadline;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,event.type))for(let handler of handlers)try{if(isSessionShutdown){let shutdownEvent=event;shutdownBudget||(shutdownBudget=this.resolveSessionShutdownBudget(),shutdownEvent.reason==="quit"&&this.processExitRequestedAt!==void 0&&shutdownBudget.quitMs>0&&(quitDeadline=new QuitDeadline(shutdownBudget.quitMs,Date.now,this.processExitRequestedAt))),await this.runSessionShutdownHandler(ext.path,shutdownEvent,handler,quitDeadline?.budgetFor(shutdownBudget.handler)??{budget:shutdownBudget.handler,endsAtQuitDeadline:!1});continue}let handlerResult=await handler(event,this.createContext(ext.path));if(this.isSessionBeforeEvent(event)&&handlerResult&&(result3=handlerResult,result3.cancel))return result3}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:event.type,error:message,stack})}return result3}async emitModelSelect(event){if(this.dropsLoopEvent("model_select"))return;let result3;for(let ext of this.extensions){let handlers=ext.handlers.get("model_select");if(!(!handlers||handlers.length===0))for(let handler of handlers)try{let liveEvent={...event,systemPromptOptions:this.getSystemPromptOptionsFn()},handlerResult=await handler(liveEvent,this.createContext(ext.path));if(handlerResult){let nextResult=handlerResult;if(nextResult.systemPrompt!==void 0||nextResult.systemPromptName!==void 0){let combinedResult={};nextResult.systemPrompt!==void 0?combinedResult.systemPrompt=nextResult.systemPrompt:result3?.systemPrompt!==void 0&&(combinedResult.systemPrompt=result3.systemPrompt),nextResult.systemPromptName!==void 0?combinedResult.systemPromptName=nextResult.systemPromptName:result3?.systemPromptName!==void 0&&(combinedResult.systemPromptName=result3.systemPromptName),result3=combinedResult}}}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"model_select",error:message,stack})}}return result3}emitMessageEnd(event){let currentMessage=event.message,modified=!1,entries=flattenHandlers(this.extensions,"message_end");return this.walkHandlers({event:"message_end",length:entries.length,extensionPath:index=>entryAt(entries,index).path,start:index=>{let{path:path16,handler}=entryAt(entries,index),currentEvent={...event,message:currentMessage};return handler(currentEvent,this.createContext(path16))},settle:(index,outcome)=>{let{path:path16}=entryAt(entries,index);if(!outcome.ok){this.reportHandlerFailure(path16,"message_end",outcome.error);return}let handlerResult=outcome.value;if(handlerResult?.message){if(handlerResult.message.role!==currentMessage.role){this.emitError({extensionPath:path16,event:"message_end",error:"message_end handlers must return a message with the same role"});return}currentMessage=handlerResult.message,modified=!0}},skip:(index,verdict,budget)=>this.reportStoppedHandler(entryAt(entries,index).path,"message_end",verdict,budget),finish:()=>modified?currentMessage:void 0})}async emitToolResult(event){let currentEvent={...event},modified=!1;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"tool_result"))for(let handler of handlers){let hookRun=this.beginToolHookRun(this.createContext(),{hookName:"PostToolUse",toolName:event.toolName,toolCallId:event.toolCallId,extensionPath:ext.path}),endStatus="completed",errorMessage6;try{let handlerResult=await handler(currentEvent,hookRun.context);if(!handlerResult)continue;handlerResult.content!==void 0&&(currentEvent.content=handlerResult.content,handlerResult.structuredContent===void 0&&delete currentEvent.structuredContent,modified=!0),handlerResult.details!==void 0&&(currentEvent.details=handlerResult.details,modified=!0),handlerResult.structuredContent!==void 0&&(currentEvent.structuredContent=handlerResult.structuredContent,modified=!0),handlerResult.isError!==void 0&&(currentEvent.isError=handlerResult.isError,modified=!0),handlerResult.usage!==void 0&&(currentEvent.usage=handlerResult.usage,modified=!0)}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;endStatus="failed",errorMessage6=message,this.emitError({extensionPath:ext.path,event:"tool_result",error:message,stack})}finally{hookRun.end(endStatus,errorMessage6)}}if(modified)return{content:currentEvent.content,details:currentEvent.details,structuredContent:currentEvent.structuredContent,isError:currentEvent.isError,usage:currentEvent.usage}}async emitToolCall(event){let result3;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"tool_call"))for(let handler of handlers){let hookRun=this.beginToolHookRun(this.createContext(),{hookName:"PreToolUse",toolName:event.toolName,toolCallId:event.toolCallId,extensionPath:ext.path}),endStatus="completed",errorMessage6;try{let handlerResult=await handler(event,hookRun.context);if(handlerResult&&(result3=handlerResult,result3.block))return endStatus="blocked",result3}catch(err){throw endStatus="failed",errorMessage6=err instanceof Error?err.message:String(err),err}finally{hookRun.end(endStatus,errorMessage6)}}return result3}async emitUserBash(event){for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"user_bash"))for(let handler of handlers)try{let handlerResult=await handler(event,this.createContext());if(handlerResult===void 0)continue;if(!isUserBashEventResult(handlerResult))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return handlerResult}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;throw this.emitError({extensionPath:ext.path,event:"user_bash",error:message,stack}),err}}async emitContext(messages,excludeExtensionPath,source2="agent"){return dispatchContextMessages(messages,{contextHandlers:this.dropsLoopEvent("context")?[]:snapshotEventHandlers(this.extensions,"context"),contextWithSystemHandlers:this.dropsLoopEvent("context_with_system")?[]:snapshotEventHandlers(this.extensions,"context_with_system"),createContext:path16=>this.createContext(path16),emitError:error2=>this.emitError(error2),excludeExtensionPath,source:source2})}async prepareProviderRequest(messages,excludeExtensionPath,options){return{messages:await this.emitContext(messages,excludeExtensionPath,"projection"),transformPayload:async payload=>await this.emitBeforeProviderRequest(options?.allowServerSearch?payload:disableServerSearch(payload),excludeExtensionPath),transformHeaders:async headers=>await this.emitBeforeProviderHeaders(headers)}}async emitBeforeProviderRequest(payload,excludeExtensionPath,request2){let currentPayload=payload,requestHandlers=this.dropsLoopEvent("before_provider_request")?[]:snapshotEventHandlers(this.extensions,"before_provider_request");for(let{ext,handlers}of requestHandlers)if(ext.path!==excludeExtensionPath)for(let handler of handlers)try{let event={type:"before_provider_request",payload:currentPayload,...request2?{model:request2.model,headers:request2.headers}:{}},handlerResult=await handler(event,this.createContext(ext.path));handlerResult!==void 0&&(currentPayload=handlerResult)}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"before_provider_request",error:message,stack})}return currentPayload}async emitBeforeProviderHeaders(headers){let headerHandlers=this.dropsLoopEvent("before_provider_headers")?[]:snapshotEventHandlers(this.extensions,"before_provider_headers");for(let{ext,handlers}of headerHandlers)for(let handler of handlers)try{await handler({type:"before_provider_headers",headers},this.createContext(ext.path))}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"before_provider_headers",error:message,stack})}return headers}getThirdPartySessionStartPaths(){return this.extensions.filter(ext=>ext.sourceInfo.source!=="builtin"&&(ext.handlers.get("session_start")?.length??0)>0).map(ext=>ext.path)}getPreviewUnsafeBeforeAgentStartPaths(){let paths=[];for(let ext of this.extensions)(ext.handlers.get("before_agent_start")??[]).some(handler=>ext.previewSafeHandlers?.has(handler)!==!0)&&paths.push(ext.path);return paths}async emitBeforeAgentStart(prompt,images,systemPrompt,systemPromptOptions,options={}){let currentSystemPrompt=systemPrompt,messages=[],systemPromptModified=!1,stableLength=systemPrompt.length;dispatch:for(let{ext,handlers}of beforeAgentStartDispatchOrder(this.extensions))for(let handler of handlers){if(options.signal?.aborted===!0)break dispatch;if(!(options.preview===!0&&ext.previewSafeHandlers?.has(handler)!==!0))try{let ctx=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext(ext.path)));ctx.getSystemPrompt=()=>(this.assertActive(),currentSystemPrompt);let event={type:"before_agent_start",prompt,trigger:options.trigger??"prompt",images,systemPrompt:currentSystemPrompt,systemPromptOptions,...options.preview===!0?{preview:!0}:{}},promptBefore=currentSystemPrompt,handlerResult=await handler(event,ctx),parts;if(handlerResult){let result3=handlerResult;result3.message&&messages.push(result3.message),result3.systemPrompt!==void 0&&(stableLength=(result3.systemPromptCache??(ext.path.startsWith("<builtin:")?"stable":"volatile"))==="stable"&&stableLength===currentSystemPrompt.length?result3.systemPrompt.length:Math.min(stableLength,sharedPrefixLength(currentSystemPrompt,result3.systemPrompt)),currentSystemPrompt=result3.systemPrompt,systemPromptModified=!0,parts=result3.systemPromptParts)}options.preview===!0&&options.observePrompt?.({path:ext.path,before:promptBefore,after:currentSystemPrompt,...parts===void 0?{}:{parts}})}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"before_agent_start",error:message,stack})}}if(messages.length>0||systemPromptModified)return{messages:messages.length>0?messages:void 0,systemPrompt:systemPromptModified?currentSystemPrompt:void 0,...systemPromptModified&&stableLength<currentSystemPrompt.length?{systemPromptStablePrefix:currentSystemPrompt.slice(0,stableLength)}:{}}}async emitResourcesDiscover(cwd,reason){let skillPaths=[],promptPaths=[],themePaths=[],hookPaths=[],toEntry=(entry2,extensionPath)=>typeof entry2=="string"?{path:entry2,extensionPath}:entry2.scope===void 0?{path:entry2.path,extensionPath}:{path:entry2.path,extensionPath,scope:entry2.scope};for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"resources_discover"))for(let handler of handlers)try{let result3=await handler({type:"resources_discover",cwd,reason,scopedEntries:!0},this.createContext(ext.path));result3?.skillPaths?.length&&skillPaths.push(...result3.skillPaths.map(entry2=>toEntry(entry2,ext.path))),result3?.promptPaths?.length&&promptPaths.push(...result3.promptPaths.map(entry2=>toEntry(entry2,ext.path))),result3?.themePaths?.length&&themePaths.push(...result3.themePaths.map(entry2=>toEntry(entry2,ext.path))),result3?.hookPaths?.length&&hookPaths.push(...result3.hookPaths.map(entry2=>toEntry(entry2,ext.path)))}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"resources_discover",error:message,stack})}return{skillPaths,promptPaths,themePaths,hookPaths}}async emitProviderLoginStart(event){for(let{path:path16,handler}of flattenHandlers(this.extensions,event.type))try{await handler(event,this.createContext(path16))}catch(err){this.reportHandlerFailure(path16,event.type,err)}}async emitInput(text4,images,source2,streamingBehavior,inputId="input",attribution=inputAttributionOf({origin:inputOriginOf(source2),source:source2})){let currentText=text4,currentImages=images;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"input"))for(let handler of handlers)try{let result3=await handler({type:"input",inputId,text:currentText,images:currentImages,source:source2,attribution,streamingBehavior},this.createContext(ext.path));if(result3?.action==="handled")return result3;result3?.action==="transform"&&(currentText=result3.text,currentImages=result3.images??currentImages)}catch(err){this.emitError({extensionPath:ext.path,event:"input",error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}return currentText!==text4||currentImages!==images?{action:"transform",text:currentText,images:currentImages}:{action:"continue"}}};var trimSlash=value=>value.replace(/\/+$/,""),UNCHECKABLE_CONTROL_KEY="senpi-verify-control-not-a-real-key",AUTH_HEADERS=new Set(["authorization","x-api-key","x-goog-api-key"]);function probeFor(model,key){let base=trimSlash(model.baseUrl),extra=Object.fromEntries(Object.entries(model.headers??{}).filter(([name])=>!AUTH_HEADERS.has(name.toLowerCase())));switch(model.api){case"openai-completions":case"openai-responses":return{url:`${base}/models`,headers:{...extra,authorization:`Bearer ${key}`}};case"mistral-conversations":return{url:`${base.replace(/\/v1$/,"")}/v1/models`,headers:{...extra,authorization:`Bearer ${key}`}};case"anthropic-messages":return{url:`${base.replace(/\/v1$/,"")}/v1/models`,headers:{...extra,"x-api-key":key,"anthropic-version":"2023-06-01"}};case"google-generative-ai":return{url:`${base}/models`,headers:{...extra,"x-goog-api-key":key}};default:return}}async function verifyApiKey(input){let model=input.models.find(candidate=>candidate.provider===input.provider);if(model===void 0)return{ok:!1,reason:"unknown-provider"};if(probeFor(model,input.key)===void 0)return{ok:!1,reason:"unsupported"};let ask=async candidate=>{let target=probeFor(model,candidate);if(target===void 0)return"no-answer";try{let response=await(input.fetch??globalThis.fetch)(target.url,{method:"GET",headers:target.headers,redirect:"manual",signal:input.signal});return await response.body?.cancel().catch(()=>{}),response.status}catch{return"no-answer"}},temporary=status2=>status2==="no-answer"?{ok:!1,reason:"unreachable"}:status2===429||status2>=500?{ok:!1,reason:"unreachable",status:status2}:void 0,status=await ask(input.key);if(status==="no-answer")return{ok:!1,reason:"unreachable"};let failedFirst=temporary(status);if(failedFirst!==void 0)return failedFirst;if(status===401||status===403)return{ok:!1,reason:"rejected",status};if(status<200||status>=300)return{ok:!1,reason:"unsupported",status};let control=await ask(UNCHECKABLE_CONTROL_KEY);if(control===401||control===403)return{ok:!0};let failedControl=temporary(control);return failedControl!==void 0?failedControl:{ok:!1,reason:"unsupported"}}function storedKeyHint(modelRegistry,info){if(info.authType!=="api_key")return{};let credential=modelRegistry.authStorage.get(info.id);if(credential?.type!=="api_key"||credential.key===void 0)return{};let key=credential.key;return isCommandConfigValue(key)||getConfigValueEnvVarNames(key).length>0||key.length<12?{}:{keyHint:key.slice(-4)}}function holdAutomaticInput(session,command,interactiveUser){return interactiveUser?!1:session.noteAutomaticInput(command.message)}var MODEL_NOT_READY_ERROR_CODES={provider_credentials_missing:RPC_ERROR_PROVIDER_CREDENTIALS_MISSING,provider_credentials_expired:RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED,no_model_selected:RPC_ERROR_NO_MODEL_SELECTED};async function handleClientInput(session,command,io,client={interactiveUser:!1}){try{let admissions=ClientAdmissions.forSession(session),disposition,responded=!1,respond=admission2=>{responded=!0;let finalDisposition=admission2?.disposition??disposition;io.output({id:command.id,type:"response",command:command.type,success:!0,data:{disposition:finalDisposition,...clientMessageIdentity(command),...admission2?{admission:admission2}:{},...command.type==="prompt"&&command.toolBarrier!==void 0?{toolBarrier:finalDisposition==="started"?"armed":"ignored"}:{}}})},admission=await clientInputContext.run(clientMessageIdentity(command),()=>admissions.admit(command,async hooks=>{let promptPath=options=>{let accepted=Promise.withResolvers(),preflightSucceeded=!1,acceptedAdmission,call=session.prompt(command.message,{...clientMessageIdentity(command),images:command.images,...options,source:"rpc",interactiveUser:client.interactiveUser,onQueuedInput:hooks.queued,promptDisposition:next=>{disposition=next,acceptedAdmission=hooks.accepted(next)},preflightResult:succeeded=>{succeeded&&disposition!==void 0&&(preflightSucceeded=!0,accepted.resolve(disposition),respond(acceptedAdmission))}}).catch(error2=>{preflightSucceeded||accepted.reject(error2)});return io.promptCalls.add(call),call.finally(()=>io.promptCalls.delete(call)),accepted.promise};switch(command.type){case"prompt":{if(command.thinkingLevel!==void 0&&session.isStreaming&&command.streamingBehavior!==void 0)throw new Error("Cannot set thinkingLevel on a queued prompt; set it after the current turn completes.");return promptPath({streamingBehavior:command.streamingBehavior,thinkingLevel:command.thinkingLevel,sessionTitlePrompt:command.sessionTitlePrompt,expandPromptTemplates:command.expandPromptTemplates,unknownCommandAsText:command.unknownCommandAsText,toolBarrier:command.toolBarrier})}case"steer":case"follow_up":{if(command.whenIdle==="start")return promptPath({streamingBehavior:command.type==="steer"?"steer":"followUp",enqueueOrder:command.enqueueOrder});let options={...clientMessageIdentity(hooks.identity),enqueueOrder:command.enqueueOrder,source:"rpc",interactiveUser:client.interactiveUser,onQueuedInput:hooks.queued};return disposition=command.type==="steer"?await session.steer(command.message,command.images,options):await session.followUp(command.message,command.images,options),hooks.accepted(disposition),disposition}}}));responded||respond(admission)}catch(error2){let unknownCommand=error2 instanceof UnknownCommandError;io.output({id:command.id,type:"response",command:command.type,success:!1,error:unknownCommand?`${error2.message} ${UNKNOWN_COMMAND_CONFIRM_HINT}`:error2 instanceof Error?error2.message:String(error2),...error2 instanceof ClientMessageIdConflict||error2 instanceof AgentBusyError?{errorCode:error2.code}:{},...error2 instanceof ModelNotReadyError?{errorCode:MODEL_NOT_READY_ERROR_CODES[error2.code],...error2.provider===void 0?{}:{errorData:{provider:error2.provider}}}:{},...unknownCommand?{errorCode:RPC_ERROR_UNKNOWN_COMMAND,errorData:{command:error2.command,suggestions:error2.suggestions,reason:error2.reason}}:{}})}}function createRpcEventOutputBuffer(writeRaw,scheduleFlush=queueMicrotask){let pendingEventLines=[],flushScheduled=!1,flushEvents=()=>{flushScheduled=!1,pendingEventLines.length!==0&&(writeRaw(pendingEventLines.join("")),pendingEventLines=[])};return{enqueueEvent(event){pendingEventLines.push(serializeJsonLine(event)),!flushScheduled&&(flushScheduled=!0,scheduleFlush(flushEvents))},writeImmediate(value){flushEvents(),writeRaw(serializeJsonLine(value))},flushEvents}}import{randomUUID as randomUUID19}from"node:crypto";var SecretInputRequests=class{constructor(route,admit){this.pending=new Map,this.receipts=new Map,this.route=route,this.admit=admit}input(title,placeholder,opts2){if(opts2?.signal?.aborted)return Promise.resolve(void 0);let timeout=resolveSecretInputTimeout(opts2),id=randomUUID19(),refused2=this.route.select(id,()=>this.pending.get(id)?.finish("unavailable"));return refused2?Promise.reject(new SecretInputUnavailableError(refused2)):new Promise(resolve56=>{let deadline=Date.now()+timeout,disarm,onAbort=()=>finish("cancelled"),finish=(outcome,value)=>{this.pending.delete(id)&&(disarm?.(),opts2?.signal?.removeEventListener("abort",onAbort),this.remember(id),this.route.send(id,{type:"secret_input_settled",id,outcome}),this.route.settled(id),resolve56(value))};if(this.pending.set(id,{deadline,finish}),opts2?.signal?.addEventListener("abort",onAbort,{once:!0}),disarm=armSecretInputDeadline(deadline,()=>finish("timed_out")),opts2?.signal?.aborted)return finish("cancelled");this.route.send(id,{type:"extension_ui_request",id,method:"input",secret:!0,title,...placeholder===void 0?{}:{placeholder},timeout,deadlineAtMs:deadline,...opts2?.toolCallId===void 0?{}:{toolCallId:opts2.toolCallId},...opts2?.parentToolCallId===void 0?{}:{parentToolCallId:opts2.parentToolCallId}})})}has(id){return this.pending.has(id)||this.receipts.has(id)}answered(){return[...this.receipts].filter(entry2=>entry2[1]!==void 0&&this.route.accepts(entry2[0])).slice(-64).map(([uiRequestId,answerId])=>({uiRequestId,answerId}))}respond(frame){let id=typeof frame.id=="string"?frame.id:"",requestId=answeredUiRequestId(frame);if(!requestId||!this.route.accepts(requestId))return refusedExtensionUiResponse(id,"secret_answer_refused");if(!this.has(requestId))return refusedExtensionUiResponse(id,"unknown_extension_ui_request");let allowed=new Set(["type","id","uiRequestId","answerId","sessionId","secret","value","cancelled"]);if(frame.secret!==!0||typeof frame.id!="string"||typeof frame.answerId!="string"||frame.answerId.length<1||frame.answerId.length>256||Object.keys(frame).some(key=>!allowed.has(key))||!("value"in frame?!("cancelled"in frame)&&typeof frame.value=="string"&&isSecretInputValue(frame.value):frame.cancelled===!0))return refusedExtensionUiResponse(id,"invalid_secret_response");let pending=this.pending.get(requestId),reply={type:"response",command:"extension_ui_response",id};if(!pending){let answerId=this.receipts.get(requestId);return answerId===frame.answerId?{...reply,success:!0,disposition:"replay"}:answerId===void 0?refusedExtensionUiResponse(id,"unknown_extension_ui_request"):{...reply,success:!1,error:"already_answered",disposition:"already_answered"}}return Date.now()>=pending.deadline?(pending.finish("timed_out"),refusedExtensionUiResponse(id,"unknown_extension_ui_request")):(this.admit(),pending.finish(frame.cancelled===!0?"cancelled":"answered",typeof frame.value=="string"?frame.value:void 0),this.receipts.set(requestId,frame.answerId),{...reply,success:!0,disposition:"applied"})}cancelAll(outcome="cancelled"){for(let pending of[...this.pending.values()])pending.finish(outcome)}recheck(){for(let[id,pending]of this.pending)this.route.available(id)||pending.finish("unavailable")}close(){this.cancelAll();for(let id of this.receipts.keys())this.route.forget(id);this.receipts.clear()}remember(id){if(this.receipts.set(id,void 0),this.receipts.size>1024){let oldest=this.receipts.keys().next().value;oldest!==void 0&&(this.receipts.delete(oldest),this.route.forget(oldest))}}};function runHoldInput(session,command,roles){if(!roles.interactiveUser){if(!roles.taskParent)return{ok:!1,error:"hold_input_requires_interactive_client"};if(!session.pauseView.records.some(record10=>record10.kind==="inherited_hold"&&record10.parentSessionId===command.parentSessionId))return{ok:!1,error:"wrong_parent: this child is not paused for that parent session's run"}}let result3=session.holdInput({inputId:command.inputId,revision:command.revision,text:command.text});switch(result3.kind){case"held":return{ok:!0,data:{entryId:result3.entryId,duplicate:result3.duplicate}};case"already_delivered":return{ok:!0,data:{alreadyDelivered:!0}};case"input_id_conflict":return{ok:!1,error:`input_id_conflict: input ${command.inputId} is held at revision ${result3.heldRevision}`}}}var HostSessionControl=class{constructor(session,socket,report){this.disposed=!1,this.session=session,this.socket=socket,this.report=report}async register(options){if(this.releaseActive(),this.disposed||this.socket===void 0)return{status:"unsupported",reason:"unsupported_mode"};let{session}=this,failing,scheduler=new WakeScheduler(async event=>{await session.extensionRunner.emit(event);let result3=await options.drain(event)??{admitted:[]};return failing=void 0,result3},error2=>{let reason=errorText5(error2);reason!==failing&&(failing=reason,this.report(`control drain failed: ${reason}`))}),wake=reason=>{scheduler.request(reason)},unsubscribeIdle=session.subscribe(event=>{event.type==="agent_idle"&&wake("idle")}),unsubscribeEmitted=session.externalAdmission.onEmitted(()=>wake("emitted")),inbox,registration={scheduler,release:()=>{unsubscribeIdle(),unsubscribeEmitted(),inbox?.stop(),scheduler.dispose()}};try{inbox=await watchInbox(options.inboxDir,()=>wake("inbox"),error2=>this.report(`control inbox watch failed: ${errorText5(error2)}`))}catch(error2){return registration.release(),{status:"failed",reason:errorText5(error2)}}return this.disposed?(registration.release(),{status:"unsupported",reason:"unsupported_mode"}):(this.releaseActive(),this.active=registration,wake("inbox"),inbox.armed.then(()=>wake("inbox")),{status:"registered",socket:this.socket,dispose:async()=>{this.active===registration&&this.releaseActive()}})}async wake(deliveryIds){let active=this.active;if(active!==void 0)return active.scheduler.request("command",deliveryIds);let ids=deliveryIds===void 0||deliveryIds.length===0?{}:{delivery_ids:deliveryIds};return await this.session.extensionRunner.emit({type:"session_control_wake",reason:"command",reasons:["command"],...ids}),{admitted:[]}}dispose(){this.disposed=!0,this.releaseActive()}releaseActive(){let active=this.active;this.active=void 0,active?.release()}};function errorText5(error2){return error2 instanceof Error?error2.message:String(error2)}function createRpcLoginPromptCallbacks(ui,signal){let dialogSignalFor=promptSignal=>promptSignal?AbortSignal.any([signal,promptSignal]):signal;return{async onPrompt(prompt){let dialogSignal2=dialogSignalFor(prompt.signal);if(dialogSignal2.aborted)throw new Error("Login cancelled");let value=await ui.input(prompt.message,prompt.placeholder,{signal:dialogSignal2,...prompt.type==="secret"&&ui.capabilities?.secretInput===!0?{secret:!0}:{}});if(dialogSignal2.aborted||value===void 0)throw new Error("Login cancelled");return value},async onSelect(prompt){let dialogSignal2=dialogSignalFor(prompt.signal);if(dialogSignal2.aborted)throw new Error("Login cancelled");let value=await ui.select(prompt.message,prompt.options.map(option=>option.label),{signal:dialogSignal2});if(dialogSignal2.aborted)throw new Error("Login cancelled");if(value!==void 0)return prompt.options.find(option=>option.label===value)?.id}}}async function answerMemoryReport(session){let source2=memoryReportSessionFor(session);if(source2===void 0)return{ok:!1,error:"memory_report_disabled: start the host with SENPI_MEMORY_REPORT=1"};let[outcome]=await writeMemoryReports([source2]);return outcome===void 0||!outcome.ok?{ok:!1,error:`memory_report_failed: ${outcome?.ok===!1?outcome.error:"no report written"}`}:{ok:!0,data:{path:outcome.path,...outcome.heapSnapshot===void 0?{}:{heapSnapshot:outcome.heapSnapshot}}}}function buildRpcCommands(input){return[...input.extensionCommands.map(command=>({...command,source:"extension",syntax:"slash"})),...input.promptTemplates.map(template=>({...template,source:"prompt",syntax:"slash"})),...input.skills.map(skill=>({...skill,name:`skill:${skill.name}`,source:"skill",syntax:"dollar"}))]}function buildRpcCommandsForSession(session){return buildRpcCommands({extensionCommands:session.extensionRunner.getRegisteredCommands().map(command=>({name:command.invocationName,description:command.description,sourceInfo:command.sourceInfo})),promptTemplates:session.promptTemplates,skills:session.resourceLoader.getSkills().skills})}function rpcCommandListDigest(commands){return JSON.stringify(commands)}function createCommandsChangedEvent(previousDigest,commands){if(!(previousDigest===void 0||previousDigest===rpcCommandListDigest(commands)))return{type:"commands_changed",commands}}var NOT_TASK_PARENT="task_parent_required: only the connection that owns this task child may pause or resume it for a run";async function runPauseForRun(session,command,taskParent){if(!taskParent)return{ok:!1,error:NOT_TASK_PARENT};let result3=await session.pauseForRun(command);return"refused"in result3?{ok:!1,error:"wrong_parent: this child is paused for another parent session"}:{ok:!0,data:{held:!0,childSeq:result3.childSeq}}}async function runResumeForRun(session,command,taskParent){if(!taskParent)return{ok:!1,error:NOT_TASK_PARENT};let result3=await session.resumeForRun(command);return result3.released?{ok:!0,data:{released:!0,otherHoldLive:result3.otherHoldLive,...result3.turnId===void 0?{}:{turnId:result3.turnId}}}:result3.reason==="wrong_parent"?{ok:!1,error:"wrong_parent: this child is paused for another parent session"}:{ok:!0,data:{released:!1,reason:result3.reason}}}function structuredLaneEnabled(){return compactUpdatesEnabled()}var SEEDS={blockSeeds:1},SeededBlockGate=class{constructor(){this.nextOffsets=new Map}accept(record10){if(record10.type==="message_block_state"||record10.type==="message_block_metadata")return this.control(record10,record10.type==="message_block_state"?record10.phase:void 0);if(record10.type==="message_tool_arguments_reset"){let accepted=this.control(record10);return accepted&&this.nextOffsets.set(record10.contentIndex,record10.rawArgumentPrefix.length),accepted}if(record10.type==="message_start"&&record10.message.role==="assistant"){let seeded2=toJsonEvent(record10,SEEDS);return this.blocks=seeded2&&new Map,this.nextOffsets.clear(),seeded2}if(record10.type==="message_end"&&record10.message.role==="assistant")return this.end(record10);if(record10.type!=="message_update")return toJsonEvent(record10,SEEDS);if(!this.blocks)return;let update2=record10.assistantMessageEvent;if(!("contentIndex"in update2)){let seeded2=toJsonEvent(record10,SEEDS),rewrittenFrom=getAssistantCapture(record10)?.rewrittenFrom;return seeded2&&rewrittenFrom!==void 0?{...seeded2,rewrittenFrom}:seeded2}let index=getAssistantCapture(record10)?.contentIndex??update2.contentIndex,starts=update2.type==="text_start"||update2.type==="thinking_start"||update2.type==="toolcall_start";if(starts&&this.nextOffsets.has(index)){this.blocks.set(index,"invalid");return}if(this.blocks.get(index)==="invalid"||!starts&&this.blocks.get(index)!=="open")return;let seeded;try{seeded=toJsonEvent(record10,SEEDS)}catch(error2){if(!(error2 instanceof SeedFrontierError))throw error2;this.blocks.set(index,"invalid");return}let capture=getAssistantCapture(record10);if(starts&&seeded&&capture?.nextOffset!==void 0&&this.nextOffsets.set(index,capture.nextOffset),"delta"in update2&&seeded){if(capture?.offset!==this.nextOffsets.get(index)||capture?.offset===void 0){this.blocks.set(index,"invalid");return}this.nextOffsets.set(index,capture.offset+update2.delta.length)}let ends=update2.type==="text_end"||update2.type==="thinking_end"||update2.type==="toolcall_end";return this.blocks.set(index,seeded?ends?"ended":"open":"invalid"),seeded}control(record10,phase){let state3=this.blocks?.get(record10.contentIndex);if(!(!this.blocks||state3==="invalid")){if(phase==="insert")this.blocks.set(record10.contentIndex,"open");else{if(state3===void 0||phase==="end"&&state3!=="open")return;phase==="end"&&this.blocks.set(record10.contentIndex,"ended")}return record10}}end(record10){let capture=getAssistantCapture(record10),rewrittenFrom=capture?.message===void 0?0:capture.rewrittenFrom??Number.POSITIVE_INFINITY,invalidatedBlocks=[...this.blocks??[]].flatMap(([index,state3])=>state3==="ended"&&index<rewrittenFrom?[]:[index]);this.blocks=void 0,this.nextOffsets.clear();let seeded=toJsonEvent(record10,SEEDS)??record10;return invalidatedBlocks.length===0?seeded:{...seeded,invalidatedBlocks:invalidatedBlocks.sort((a,b)=>a-b)}}};function subscribeStructuredSessionRecords(session,output,failed){let gate=new SeededBlockGate;return subscribeSessionRecords(session,output,void 0,listener=>session.subscribeStructured(record10=>{try{let accepted=gate.accept(record10);accepted&&listener(carryRecovery(record10,accepted))}catch(cause){failed(cause)}},failed))}var HOST_ANSWER_TIMEOUT_MS=6e4,refused=(reason,detail)=>({status:"refused",reason,detail}),record9=value=>typeof value=="object"&&value!==null&&!Array.isArray(value)?{...value}:void 0;function parseTarget2(value){let fields=record9(value);if(!(typeof fields?.name!="string"||fields.name===""||typeof fields.online!="boolean"))return{name:fields.name,online:fields.online,...typeof fields.capacity=="string"?{capacity:fields.capacity}:{},...typeof fields.aboutToSleep=="boolean"?{aboutToSleep:fields.aboutToSleep}:{}}}var RpcSessionRelocation=class{constructor(deps){this.pending=new Map,this.requesting=!1,this.deps=deps,this.unsubscribe=deps.session.subscribe(event=>{event.type==="agent_end"&&deps.session.currentAbortSource==="user"&&this.scheduled!==void 0&&(this.scheduled={...this.scheduled,dropReason:"aborted"}),event.type==="agent_settled"&&this.scheduled?.dropReason!==void 0?this.dropScheduled(this.scheduled.dropReason):event.type==="agent_idle"&&this.scheduled!==void 0&&this.scheduled.dropReason===void 0&&this.announceWhenReleasable()})}offered(){return this.deps.channel.offerer()!==void 0}async targets(signal){let connection=this.deps.channel.offerer();if(connection===void 0)return RELOCATION_NOT_OFFERED;let answer3=await this.ask({method:"list_relocation_targets"},connection,signal);if("status"in answer3)return answer3;let raw=record9(answer3.data)?.targets,targets2=Array.isArray(raw)?raw.map(parseTarget2):void 0;return targets2===void 0||targets2.some(target=>target===void 0)?refused("invalid_host_answer","the app sent a list of computers this session cannot read"):{status:"listed",targets:targets2.filter(target=>target!==void 0)}}async request(request2,signal){let connection=this.deps.channel.offerer();if(connection===void 0)return RELOCATION_NOT_OFFERED;if(this.deps.session.sessionFile===void 0)return{status:"unavailable",reason:"not_releasable",detail:"this session is not saved to a file"};if(this.scheduled!==void 0||this.requesting)return refused("already_scheduled",`a move to ${this.scheduled?.target??"another computer"} is already set for the end of this turn`);this.requesting=!0;try{let ask={method:"relocate_session",target:request2.target,reason:request2.reason},answer3=await this.ask(ask,connection,signal);return"status"in answer3?answer3:this.settleRequest(request2,record9(answer3.data),connection)}finally{this.requesting=!1}}respond(frame){let pending=this.pending.get(frame.id);return pending===void 0?"unknown":this.deps.channel.current()!==pending.connection?"not_offering_connection":(pending.finish(typeof frame.error=="string"?refused("host_error",frame.error):{data:frame.data}),"answered")}connectionDetached(connectionId){this.scheduled?.connection===connectionId&&this.scheduled.dropReason===void 0&&this.dropScheduled("disconnected");for(let pending of[...this.pending.values()])pending.connection===connectionId&&pending.finish(refused("app_disconnected","the app that was asked left this session"))}dispose(){this.unsubscribe(),this.scheduled=void 0;for(let{finish}of[...this.pending.values()])finish(refused("session_closed","this session was closed"))}dropScheduled(reason){let scheduled=this.scheduled;if(scheduled===void 0)return;this.scheduled=void 0;let{moveId,target}=scheduled;this.deps.session.sendCustomMessage({customType:"session_relocation",content:`The session will not continue on ${target} (${reason}). The session stays on this computer; keep working here.`,display:!1,details:{status:"dropped",reason,moveId,target}},{triggerTurn:!1})}settleRequest(request2,data,connection){if(data?.accepted===!1)return refused(typeof data.reason=="string"&&data.reason!==""?data.reason:"declined",typeof data.detail=="string"&&data.detail!==""?data.detail:"the app declined the move");if(data?.accepted!==!0||!isPlainId(data.moveId))return refused("invalid_host_answer","the app accepted the move without a usable move id");let target=typeof data.target=="string"&&data.target!==""?data.target:request2.target;return this.scheduled={moveId:data.moveId,target,reason:request2.reason,connection},{status:"scheduled",target,moveId:data.moveId}}async announceWhenReleasable(){for(let calls=this.deps.pendingPrompts();calls.length>0;calls=this.deps.pendingPrompts())await Promise.allSettled(calls);let due=this.scheduled;if(due===void 0||this.deps.session.isStreaming)return;if(this.deps.channel.offerer()!==due.connection){this.dropScheduled("withdrawn");return}this.scheduled=void 0;let{connection,moveId,target,reason}=due;this.deps.channel.send(connection,{type:"relocation_due",moveId,target,reason},"event")}ask(fields,connection,signal){if(signal?.aborted)return Promise.resolve(refused("cancelled","the request was cancelled"));let id=`hr_${crypto.randomUUID()}`;return new Promise(resolve56=>{let finish=answer3=>{clearTimeout(timer),signal?.removeEventListener("abort",onAbort),this.pending.delete(id),resolve56(answer3)},onAbort=()=>finish(refused("cancelled","the request was cancelled")),timer=setTimeout(()=>finish(refused("no_answer","the app did not answer in time")),HOST_ANSWER_TIMEOUT_MS);this.pending.set(id,{connection,finish}),signal?.addEventListener("abort",onAbort,{once:!0}),this.deps.channel.send(connection,{type:"host_request",id,...fields},"request")})}};var SOLE_CONNECTION="sole";function relocationChannel(options){let{clientInfo}=options;if(clientInfo===void 0)return{offerer:()=>options.capabilities()?.includes(SESSION_RELOCATION_CAPABILITY)?SOLE_CONNECTION:void 0,current:()=>SOLE_CONNECTION,send:(_connection,record10,kind)=>kind==="event"?options.outputEvent(record10):options.output(record10)};let{relocationConnection,deliverTo}=clientInfo;return{offerer:()=>deliverTo===void 0?void 0:relocationConnection?.(),current:()=>clientInfo.connectionId(),send:(connection,record10)=>deliverTo?.(connection,()=>options.output(record10))}}function answerHostResponse(frame,respond){let reply={id:frame.id,type:"response",command:"host_response"};if(typeof frame.id!="string"||frame.id==="")return{...reply,success:!1,error:"invalid_host_response"};let outcome=respond?.(frame)??"unknown";return outcome==="answered"?{...reply,success:!0}:{...reply,success:!1,error:outcome==="unknown"?"unknown_host_request":outcome}}function isHostResponse(value){return typeof value=="object"&&value!==null&&"type"in value&&value.type==="host_response"}function dialogCall(opts2){return opts2?.toolCallId===void 0?{}:{toolCallId:opts2.toolCallId,...opts2.parentToolCallId===void 0?{}:{parentToolCallId:opts2.parentToolCallId}}}function loadedExtensionName(path16){let synthetic=/^<(?:builtin|inline):([^>]+)>$/.exec(path16);if(synthetic)return synthetic[1];let withoutExtension=basename38(path16,extname6(path16));if(withoutExtension!=="index")return withoutExtension;let parent=dirname69(path16),parentName=basename38(parent);return parentName==="src"||parentName==="dist"?basename38(dirname69(parent)):parentName}function loadedExtensions(session){return session.resourceLoader.getExtensions().extensions.map(extension=>({name:loadedExtensionName(extension.path),path:extension.path,sourceInfo:extension.sourceInfo,enabled:!0}))}function loadedMcpStatus(server){return server.status!==void 0?server.status:server.serverInfo!==null?"connected":server.authStatus==="notLoggedIn"?"needs_auth":"enabled"}function loadedMcpServers(snapshot2){return snapshot2.servers.map(server=>({name:server.name,toolCount:server.tools.length,status:loadedMcpStatus(server),authStatus:server.authStatus,...server.lastError===void 0?{}:{lastError:server.lastError}}))}var MCP_STARTUP_PENDING_DIGEST="mcp-startup-pending";function loadedSurfacesFingerprint(session,extensions,mcpServers){return JSON.stringify({skills:session.resourceLoader.getSkills().skills.map(skill=>({name:skill.name,path:skill.filePath,sourceInfo:skill.sourceInfo,enabled:!skill.disableModelInvocation})),extensions,mcpServers})}function findToolResultMedia(session,toolCallId,contentIndex){let fromContent=content=>{if(!Array.isArray(content))return;let block=content[contentIndex];return block?.type==="image"?block:void 0},matches2=message=>{let candidate=message;return candidate?.role==="toolResult"&&candidate.toolCallId===toolCallId};for(let entry2 of session.sessionManager.getEntries()){if(entry2.type!=="message"||!matches2(entry2.message))continue;let found=fromContent(entry2.message.content);if(found)return found}for(let message of session.messages){if(!matches2(message))continue;let found=fromContent(message.content);if(found)return found}}function createRpcConnectionHandler(runtimeHost,sink,options={}){let clientCapabilities=options.capabilities,unsubscribeSecurityNotices,detachGrantPresentation,grantPresentationAbort=new AbortController,securityBoundByHost=!1,connectionRoles=options.connectionRoles??new ConnectionRoles,currentConnectionId=()=>roleConnection(options.clientInfo?.connectionId()),hasRole=role=>connectionRoles.has(currentConnectionId(),role),routingSessionId=options.sessionId,replacementIssuedHere=!1,session=runtimeHost.session,rpcOwners=new ExtensionOwnerLifetime(options.sessionId===void 0,options.rpcOwner,options.retireRpcBinding),sessionControl,relocation,promptCalls=new Set,turnRequested=!1,unsubscribe,unsubscribeStructured,unsubscribeBackpressure,unsubscribeLoadedSurfaces,unsubscribeExtensionEvents,mcpWireStatus={servers:[]},lastAbortSource,loadedSurfacesDigest,rpcCommandsDigest,suppressLoadedSurfaceEvents=!1,mcpStartupSettledPending=!1,eventOutput=sink.writeRecord?void 0:createRpcEventOutputBuffer(sink.writeRaw,options.eventFlushScheduler),effectContext=()=>({session,by:{connectionId:options.clientInfo?.connectionId()??"local"},...routingSessionId===void 0?{}:{sessionId:routingSessionId}}),tagSessionRecord=value=>routingSessionId===void 0?value:carryRecovery(value,{...value,sessionId:routingSessionId}),output=obj=>{let record10=tagSessionRecord(obj);sink.writeRecord?sink.writeRecord(record10):eventOutput?.writeImmediate(record10)},outputEvent=event=>{let record10=tagSessionRecord(event);sink.writeRecord?sink.writeRecord(record10):eventOutput?.enqueueEvent(record10)},currentLoadedSurfaces=()=>{let extensions=loadedExtensions(session),mcpServers=loadedMcpServers(mcpWireStatus);return{data:{extensions,mcpServers},digest:loadedSurfacesFingerprint(session,extensions,mcpServers)}},recordLoadedSurfaces=emitChange=>{let current=currentLoadedSurfaces(),previous=loadedSurfacesDigest,changed=previous!==void 0&&previous!==current.digest;return loadedSurfacesDigest=current.digest,emitChange&&changed&&!suppressLoadedSurfaceEvents&&emitLoadedSurfacesChanged(previous,current.digest),current},emitLoadedSurfacesChanged=(previous,digest3)=>{options.publishLoadedSurfacesChanged?options.publishLoadedSurfacesChanged(previous,digest3):outputEvent({type:"loaded_surfaces_changed"})},announceMcpStartupSettled=()=>{if(suppressLoadedSurfaceEvents){mcpStartupSettledPending=!0;return}mcpStartupSettledPending=!1,loadedSurfacesDigest=currentLoadedSurfaces().digest,emitLoadedSurfacesChanged(MCP_STARTUP_PENDING_DIGEST,loadedSurfacesDigest)},requestMcpWireStatus=async()=>{let response,request2={sessionId:session.sessionId,respond(snapshot2){response??=snapshot2}};session.resourceLoader.emitExtensionEvent?.(MCP_CONTROL_INVENTORY_REQUEST_EVENT,request2),mcpWireStatus=response===void 0?{servers:[]}:await response},subscribeLoadedSurfaceEvents=()=>{unsubscribeLoadedSurfaces?.(),unsubscribeLoadedSurfaces=session.resourceLoader.onExtensionEvent?.(MCP_CONTROL_INVENTORY_CHANGED_EVENT,data=>{!isMcpControlInventoryChanged(data)||data.sessionId!==session.sessionId||(mcpWireStatus=data.snapshot,data.startupSettled===!0?announceMcpStartupSettled():suppressLoadedSurfaceEvents||recordLoadedSurfaces(!0))})},unsubscribeProviderAccountEvents=subscribeProviderAccountEvents(event=>{if(event.type==="accounts_changed"){outputEvent({type:"auth_accounts_changed",provider:event.provider});return}outputEvent({type:"account_failover",provider:event.provider,from:event.from,to:event.to,reason:event.reason})}),waitForRpcBackpressure=async()=>{eventOutput?.flushEvents(),await sink.waitForBackpressure()},success=(id,command,data)=>data===void 0?{id,type:"response",command,success:!0}:{id,type:"response",command,success:!0,data},error2=(id,command,message,errorCode4,errorData)=>{let details=errorData===void 0&&(command==="edit_user_message"||command==="navigate_tree")?{leafId:session.sessionManager.getLeafId()}:errorData;return{id,type:"response",command,success:!1,error:message,...errorCode4?{errorCode:errorCode4}:{},...details===void 0?{}:{errorData:details}}},uiRequestChanged=change=>{session.refreshLifecycle(),change&&routingSessionId!==void 0&&output(change)},pendingExtensionRequests=new SessionExtensionUiRequests(uiRequestChanged),grantRequests=new Map;sessionDialogRequests.set(session,pendingExtensionRequests);let questions=new ConnectionQuestionBridge(output,uiRequestChanged),secretHandshake=!1,secretOwners=new Map,secretCapable=connection=>connectionRoles.has(connection,INTERACTIVE_USER_CAPABILITY)&&(connection===void 0?secretHandshake&&clientCapabilities?.includes("secret_input_v1")===!0:options.clientInfo?.hasCapability?.(connection,"secret_input_v1")===!0),secretRoute=options.secretInputRoute??{presenter:id=>secretOwners.get(id)?.connection,select:(id,cancel3)=>{let connection=options.clientInfo?.connectionId();if(!secretCapable(connection))return"client_unsupported";secretOwners.set(id,{connection,cancel:cancel3})},accepts:id=>secretOwners.has(id)&&secretOwners.get(id)?.connection===options.clientInfo?.connectionId()&&secretCapable(secretOwners.get(id)?.connection),available:id=>secretOwners.has(id)&&secretCapable(secretOwners.get(id)?.connection),send:(_id,record10)=>output(record10),settled:id=>{let owner=secretOwners.get(id);owner&&(owner.cancel=void 0)},forget:id=>{secretOwners.delete(id)}},secretInputs=new SecretInputRequests(secretRoute,()=>session.admitHumanAnswer()),shutdownRequested=!1,activeLogins=new Map;function createDialogPromise(opts2,defaultValue,request2,parseResponse){if(opts2?.signal?.aborted)return Promise.resolve(defaultValue);let id=crypto2.randomUUID();return new Promise((resolve56,reject)=>{let timeoutId,cleanup=()=>{timeoutId&&clearTimeout(timeoutId),opts2?.signal?.removeEventListener("abort",onAbort),pendingExtensionRequests.delete(id),grantRequests.delete(id)&&options.grantDialogSettled?.(id)},onAbort=()=>{cleanup(),resolve56(defaultValue)};opts2?.signal?.addEventListener("abort",onAbort,{once:!0}),opts2?.timeout&&(timeoutId=setTimeout(()=>{cleanup(),resolve56(defaultValue)},opts2.timeout)),pendingExtensionRequests.set(id,{frame:{type:"extension_ui_request",id,...request2},resolve:response=>{cleanup(),resolve56(parseResponse(response))},reject}),request2.grantSelect===!0&&grantRequests.set(id,options.clientInfo?.connectionId()),output({type:"extension_ui_request",id,...request2})})}let selectGrantDialog=(title,choices,opts2)=>createDialogPromise(opts2,void 0,{method:"select",title,options:choices,timeout:opts2?.timeout,grantSelect:!0},response=>"cancelled"in response&&response.cancelled?void 0:"value"in response?response.value:void 0),createExtensionUIContext=()=>({capabilities:{secretInput:!0},question:(request2,opts2)=>clientCapabilities?.includes(QUESTION_CAPABILITY)?questions.ask(request2,opts2):degradeQuestion(createExtensionUIContext(),request2,opts2),select:(title,options2,opts2)=>createDialogPromise(opts2,void 0,{method:"select",title,options:options2,timeout:opts2?.timeout,...dialogCall(opts2)},r=>"cancelled"in r&&r.cancelled?void 0:"value"in r?r.value:void 0),confirm:(title,message,opts2)=>createDialogPromise(opts2,!1,{method:"confirm",title,message,timeout:opts2?.timeout},r=>"cancelled"in r&&r.cancelled?!1:"confirmed"in r?r.confirmed:!1),input:(title,placeholder,opts2)=>opts2?.secret?secretInputs.input(title,placeholder,opts2):createDialogPromise(opts2,void 0,{method:"input",title,placeholder,timeout:opts2?.timeout,...dialogCall(opts2)},r=>"cancelled"in r&&r.cancelled?void 0:"value"in r?r.value:void 0),notify(message,type2){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"notify",message,notifyType:type2})},onTerminalInput(){return()=>{}},setStatus(key,text4){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setStatus",statusKey:key,statusText:text4})},setSubagentCost(costUsd){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setSubagentCost",costUsd:costUsd!==void 0&&Number.isFinite(costUsd)&&costUsd>=0?costUsd:void 0})},setWorkingMessage(_message){},setWorkingVisible(_visible){},setWorkingIndicator(_options){},setHiddenThinkingLabel(_label){},setWidget(key,content,options2){(content===void 0||Array.isArray(content))&&output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setWidget",widgetKey:key,widgetLines:content,widgetPlacement:options2?.placement,...content!==void 0&&options2?.actions!==void 0&&options2.actions.length>0?{widgetActions:options2.actions.map(({label:label3,command})=>({label:label3,command}))}:{}})},setFooter(_factory){},setHeader(_factory){},setTitle(title){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setTitle",title})},async custom(){let request2=buildCustomUnsupportedRequest(clientCapabilities,DEFAULT_CUSTOM_EXTENSION_LABEL);request2&&output(request2)},pasteToEditor(text4){this.setEditorText(text4)},setEditorText(text4){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"set_editor_text",text:text4})},getEditorText(){return""},async editor(title,prefill){let id=crypto2.randomUUID();return new Promise((resolve56,reject)=>{pendingExtensionRequests.set(id,{frame:{type:"extension_ui_request",id,method:"editor",title,prefill},resolve:response=>{"cancelled"in response&&response.cancelled?resolve56(void 0):"value"in response?resolve56(response.value):resolve56(void 0)},reject}),output({type:"extension_ui_request",id,method:"editor",title,prefill})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return theme},getAllThemes(){return[]},getTheme(_name){},setTheme(_theme){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(_expanded){}}),refreshLoadedSurfacesAfter=async(operation,resetMcp)=>{let previousDigest=loadedSurfacesDigest,wasSuppressed=suppressLoadedSurfaceEvents;suppressLoadedSurfaceEvents=!0,resetMcp&&(mcpWireStatus={servers:[]});let commandsChanged;try{await operation(),await requestMcpWireStatus(),loadedSurfacesDigest=currentLoadedSurfaces().digest;let commands=buildRpcCommandsForSession(session);commandsChanged=createCommandsChangedEvent(rpcCommandsDigest,commands),rpcCommandsDigest=rpcCommandListDigest(commands)}finally{suppressLoadedSurfaceEvents=wasSuppressed}!wasSuppressed&&commandsChanged&&outputEvent(commandsChanged),!wasSuppressed&&mcpStartupSettledPending?announceMcpStartupSettled():!wasSuppressed&&previousDigest!==void 0&&previousDigest!==loadedSurfacesDigest&&emitLoadedSurfacesChanged(previousDigest,loadedSurfacesDigest)};runtimeHost.setRebindSession(async()=>{await rebindSession(!0)});let rebindAfterLocalReplacement=async()=>{replacementIssuedHere=!0;try{await rebindSession()}finally{replacementIssuedHere=!1}},refreshGrantPresentation=()=>{if(grantPresentationAbort.abort(),detachGrantPresentation?.(),detachGrantPresentation=void 0,grantPresentationAbort=new AbortController,securityBoundByHost||!clientCapabilities?.includes("grant_select"))return;let signal=grantPresentationAbort.signal;detachGrantPresentation=attachMcpGrantPresentation(session.sessionId,(title,choices,opts2)=>selectGrantDialog(title,choices,{...opts2,signal:opts2?.signal===void 0?signal:AbortSignal.any([opts2.signal,signal])}))},subscribeExtensionEvents=()=>{unsubscribeExtensionEvents=clientCapabilities?.includes(EXTENSION_EVENTS_CAPABILITY)?session.extensionRunner.onRpcEvent(({name,data})=>{outputEvent({type:"extension_event",name,data})}):void 0},replaceClientCapabilities=next=>{let hadEvents=clientCapabilities?.includes(EXTENSION_EVENTS_CAPABILITY)??!1,hadQuestion=clientCapabilities?.includes(QUESTION_CAPABILITY)??!1;clientCapabilities=next,hadQuestion&&!next.includes(QUESTION_CAPABILITY)&&questions.cancelAll(),hadEvents!==next.includes(EXTENSION_EVENTS_CAPABILITY)&&(unsubscribeExtensionEvents?.(),subscribeExtensionEvents())},rebindSession=async(deferRefresh=!1)=>{secretInputs.close(),rpcOwners.retireBinding(),unbindMcpForms?.(),unbindMcpForms=void 0,unsubscribeSecurityNotices?.(),unsubscribeLoadedSurfaces?.(),unsubscribeExtensionEvents?.();let replacedSession=session!==runtimeHost.session;session=runtimeHost.session;let hostedSecurity=options.bindSecurityPresentation?.(session,{...createExtensionUIContext(),select:selectGrantDialog});securityBoundByHost=hostedSecurity!==void 0,refreshGrantPresentation(),unsubscribeSecurityNotices=hostedSecurity??session.securityNotices?.subscribe(snapshot2=>{for(let notice2 of snapshot2.notices)output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"notify",notifyType:"warning",message:notice2.message})}),sessionQuestionBridges.set(session,questions),sessionDialogRequests.set(session,pendingExtensionRequests),sessionControl?.dispose(),sessionControl=new HostSessionControl(session,runtimeHost.launchProfile?.sessionContext?.host_socket,line=>{process.stderr.write(`senpi rpc session ${routingSessionId??"classic"}: ${line}
|
|
2355
|
+
`)}var SHOW_IMAGES_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ShowImagesSelectorComponent=class extends Container{constructor(currentValue,onSelect,onCancel){super();let items=[{value:"yes",label:"Yes",description:"Show images inline in terminal"},{value:"no",label:"No",description:"Show text placeholder instead"}];this.addChild(new DynamicBorder),this.selectList=new SelectList(items,5,getSelectListTheme(),SHOW_IMAGES_SELECT_LIST_LAYOUT),this.selectList.setSelectedIndex(currentValue?0:1),this.selectList.onSelect=item=>{onSelect(item.value==="yes")},this.selectList.onCancel=()=>{onCancel()},this.addChild(this.selectList),this.addChild(new DynamicBorder)}getSelectList(){return this.selectList}};var THEME_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ThemeSelectorComponent=class extends Container{constructor(currentTheme,onSelect,onCancel,onPreview){super(),this.onPreview=onPreview;let themes=getAvailableThemes(),themeItems2=themes.map(name=>({value:name,label:name,description:name===currentTheme?"(current)":void 0}));this.addChild(new DynamicBorder),this.selectList=new SelectList(themeItems2,10,getSelectListTheme(),THEME_SELECT_LIST_LAYOUT);let currentIndex=themes.indexOf(currentTheme);currentIndex!==-1&&this.selectList.setSelectedIndex(currentIndex),this.selectList.onSelect=item=>{onSelect(item.value)},this.selectList.onCancel=()=>{onCancel()},this.selectList.onSelectionChange=item=>{this.onPreview(item.value)},this.addChild(this.selectList),this.addChild(new DynamicBorder)}getSelectList(){return this.selectList}};var session_worker_data_exports={};__export(session_worker_data_exports,{SessionWorkerDataRegistry:()=>SessionWorkerDataRegistry,provideSessionWorkerData:()=>provideSessionWorkerData,readSessionWorkerData:()=>readSessionWorkerData,sessionWorkerData:()=>sessionWorkerData,sessionWorkerDataRegistry:()=>sessionWorkerDataRegistry});import{isMainThread as isMainThread3,workerData}from"node:worker_threads";var disposeAll=grants=>{for(let grant of grants)grant.dispose?.()},SessionWorkerDataRegistry=class{constructor(state3={providers:new Map,sealed:!1}){this.state=state3}provide(name,create2){if(!isMainThread3)throw new Error("provideSessionWorkerData runs on the main thread only");if(this.state.sealed)throw new Error(`session worker data "${name}" was provided after the first session worker`);if(this.state.providers.has(name))throw new Error(`session worker data "${name}" is already provided`);this.state.providers.set(name,create2)}spawn(start){this.state.sealed=!0;let grants=[],extensionData={};try{for(let[name,create2]of this.state.providers){let grant=create2();grants.push(grant),extensionData[name]=grant.value}}catch(cause){throw disposeAll(grants),cause}let disposed=!1,issued={extensionData,transfer:grants.flatMap(grant=>grant.transfer??[]),dispose:()=>{disposed||(disposed=!0,disposeAll(grants))}};try{return{result:start(issued),issued}}catch(cause){throw issued.dispose(),cause}}},REGISTRY_KEY=Symbol.for("senpi.session-worker-data.registry");function sharedState(){let existing2=Reflect.get(globalThis,REGISTRY_KEY);if(isRegistryState(existing2))return existing2;let state3={providers:new Map,sealed:!1};return Reflect.set(globalThis,REGISTRY_KEY,state3),state3}function isRegistryState(value){return value!==null&&typeof value=="object"&&Reflect.get(value,"providers")instanceof Map&&typeof Reflect.get(value,"sealed")=="boolean"}var sessionWorkerDataRegistry=new SessionWorkerDataRegistry(sharedState());function provideSessionWorkerData(name,create2){sessionWorkerDataRegistry.provide(name,create2)}function readSessionWorkerData(data,name){let extensionData=data!==null&&typeof data=="object"?Reflect.get(data,"extensionData"):void 0;if(!(extensionData===null||typeof extensionData!="object"||!Object.hasOwn(extensionData,name)))return Reflect.get(extensionData,name)}function sessionWorkerData(name){return isMainThread3?void 0:readSessionWorkerData(workerData,name)}import{spawn as spawn10}from"node:child_process";async function execCommand(command,args,cwd,options){return new Promise(resolve56=>{let proc=spawn10(command,args,{cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),stdout="",stderr="",killed=!1,timeoutId,killProcess=()=>{if(!killed){if(killed=!0,!signalSpawnedChild(proc,"SIGTERM")&&proc.pid===void 0)return;setTimeout(()=>{proc.killed||signalSpawnedChild(proc,"SIGKILL")},5e3)}};options?.signal&&(options.signal.aborted?killProcess():options.signal.addEventListener("abort",killProcess,{once:!0})),options?.timeout&&options.timeout>0&&(timeoutId=setTimeout(()=>{killProcess()},options.timeout)),proc.stdout?.on("data",data=>{stdout+=data.toString()}),proc.stderr?.on("data",data=>{stderr+=data.toString()}),waitForChildProcess(proc).then(code=>{timeoutId&&clearTimeout(timeoutId),options?.signal&&options.signal.removeEventListener("abort",killProcess),resolve56({stdout,stderr,code:code??0,killed})}).catch(_err=>{timeoutId&&clearTimeout(timeoutId),options?.signal&&options.signal.removeEventListener("abort",killProcess),resolve56({stdout,stderr,code:1,killed})})})}function redactForUpload(text4,options={}){let tally=new Map,context=currentShareRedactionContext(),extra=(options.extraLiterals??[]).filter(value=>value.trim().length>0);return{text:redactShareText(text4,extra.length===0?context:{...context,extraLiterals:extra},tally),counts:Object.fromEntries(tally)}}var McpServerRegistry=class{#loaded=[];#bound;#warnedClashes=new Set;#changeListener;track(extension){this.#loaded.push(extension)}untrack(extension){let index=this.#loaded.indexOf(extension);index>=0&&this.#loaded.splice(index,1)}bind(extensions){this.#bound=extensions}changed(){this.#changeListener?.()}declarations(){let byName=new Map;for(let extension of this.#bound??this.#loaded)for(let declaration of extension.mcpServers.values()){let existing2=byName.get(declaration.name);existing2===void 0?byName.set(declaration.name,declaration):this.#warnClash(existing2,declaration)}return[...byName.values()]}list(){return this.declarations().map(({name,config,extensionPath})=>({name,config:structuredClone(config),extensionPath}))}setChangeListener(listener){this.#changeListener=listener}#warnClash(winner,loser){let key=`${winner.name}\0${winner.extensionPath}\0${loser.extensionPath}`;this.#warnedClashes.has(key)||(this.#warnedClashes.add(key),console.warn(`MCP server '${winner.name}' declared by both ${winner.extensionPath} and ${loser.extensionPath}; keeping first declaration from ${winner.extensionPath}.`))}};import{createHash as createHash29}from"node:crypto";import{readFileSync as readFileSync49}from"node:fs";var generation,pendingImporter,generationsCreated=0;function fingerprintOf(file){try{return createHash29("sha256").update(readFileSync49(file,"utf8")).digest("hex")}catch{return}}function sourcesUnchanged(live){for(let[file,fingerprint]of live.importer.compiledSources?.()??[])if(fingerprintOf(file)!==fingerprint)return!1;return!0}function dropGeneration(){generation=void 0,pendingImporter=void 0}function cachedExtensionFactory(resolvedPath){if(generation){if(!sourcesUnchanged(generation)){dropGeneration();return}return generation.factories.get(resolvedPath)}}async function extensionModuleImporter(create2){return generation?generation.importer:(pendingImporter??=create2().then(importer=>(generation={importer,factories:new Map},generationsCreated++,pendingImporter=void 0,importer)),pendingImporter)}function rememberExtensionFactory(resolvedPath,factory,compiledBy){!generation||generation.importer!==compiledBy||generation.importer.compiledSources!==void 0&&generation.factories.set(resolvedPath,factory)}function withProviderLoginStart(provider,config,emit){let oauth=config.oauth;return oauth?{...config,oauth:{...oauth,login:async callbacks=>(await emit({type:"provider_login_start",provider,signal:callbacks.signal??new AbortController().signal,progress:message=>callbacks.onProgress?.(message)}),oauth.login(callbacks))}}:config}var __rewriteRelativeImportExtension2=function(path16,preserveJsx){return typeof path16=="string"&&/^\.\.?\//.test(path16)?path16.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path16};function sessionProfile(options){return{sessionKind:options?.sessionKind??"interactive",sessionContext:options?.sessionContext??EMPTY_SESSION_CONTEXT}}var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports2,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports2,"@earendil-works/pi-agent-core":dist_exports,"@earendil-works/pi-tui":dist_exports2,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-works/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports,"@mariozechner/pi-tui":dist_exports2,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3,"@code-yeongyu/senpi":dist_exports3,"@code-yeongyu/senpi/session-worker-data":session_worker_data_exports},require3=createRequire2(import.meta.url),isNodeSeaBinary="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,isTypeScriptSourceRuntime=!isBunBinary&&path15.extname(fileURLToPath6(import.meta.url))===".ts",usesNativeBunImports=isBunBinary||isBunRuntime,_aliases=null;function getAliases(){if(_aliases)return _aliases;let __dirname=path15.dirname(fileURLToPath6(import.meta.url)),typeboxEntry=require3.resolve("typebox"),typeboxCompileEntry=require3.resolve("typebox/compile"),typeboxValueEntry=require3.resolve("typebox/value"),codingAgentPackageRoot=path15.resolve(__dirname,"../../.."),packagesRoot=path15.dirname(codingAgentPackageRoot),resolveWorkspaceOrBundled=(packageName,packageEntryRelativePath,workspaceRelativePath,sourceRelativePath,specifier)=>{let bundledPath=path15.join(codingAgentPackageRoot,"node_modules",packageName,packageEntryRelativePath);if(fs6.existsSync(bundledPath))return bundledPath;let workspacePath=path15.join(packagesRoot,workspaceRelativePath);if(fs6.existsSync(workspacePath))return workspacePath;let sourcePath=path15.join(packagesRoot,sourceRelativePath);return fs6.existsSync(sourcePath)?sourcePath:typeof import.meta.resolve=="function"?fileURLToPath6(import.meta.resolve(specifier)):require3.resolve(specifier)},piCodingAgentDistEntry=path15.join(codingAgentPackageRoot,"dist/index.js"),piCodingAgentSourceEntry=path15.join(codingAgentPackageRoot,"src/index.ts"),piCodingAgentEntry=fs6.existsSync(piCodingAgentDistEntry)?piCodingAgentDistEntry:piCodingAgentSourceEntry,sessionWorkerDataDistEntry=path15.join(codingAgentPackageRoot,"dist/modes/rpc/session-worker-data.js"),sessionWorkerDataEntry=fs6.existsSync(sessionWorkerDataDistEntry)?sessionWorkerDataDistEntry:path15.join(codingAgentPackageRoot,"src/modes/rpc/session-worker-data.ts"),piAgentCoreEntry=resolveWorkspaceOrBundled("@earendil-works/pi-agent-core","dist/index.js","agent/dist/index.js","agent/src/index.ts","@earendil-works/pi-agent-core"),piTuiEntry=resolveWorkspaceOrBundled("@earendil-works/pi-tui","dist/index.js","tui/dist/index.js","tui/src/index.ts","@earendil-works/pi-tui"),piAiCompatEntry=resolveWorkspaceOrBundled("@earendil-works/pi-ai","dist/compat.js","ai/dist/compat.js","ai/src/compat.ts","@earendil-works/pi-ai/compat"),piAiOauthEntry=resolveWorkspaceOrBundled("@earendil-works/pi-ai","dist/oauth.js","ai/dist/oauth.js","ai/src/oauth.ts","@earendil-works/pi-ai/oauth"),piAiProvidersEntry=resolveWorkspaceOrBundled("@earendil-works/pi-ai","dist/providers/all.js","ai/dist/providers/all.js","ai/src/providers/all.ts","@earendil-works/pi-ai/providers/all");return _aliases={"@earendil-works/pi-coding-agent":piCodingAgentEntry,"@earendil-works/pi-agent-core":piAgentCoreEntry,"@earendil-works/pi-tui":piTuiEntry,"@earendil-works/pi-ai/providers/all":piAiProvidersEntry,"@earendil-works/pi-ai/compat":piAiCompatEntry,"@earendil-works/pi-ai/oauth":piAiOauthEntry,"@earendil-works/pi-ai":piAiCompatEntry,"@code-yeongyu/senpi":piCodingAgentEntry,"@code-yeongyu/senpi/session-worker-data":sessionWorkerDataEntry,"@mariozechner/pi-coding-agent":piCodingAgentEntry,"@mariozechner/pi-agent-core":piAgentCoreEntry,"@mariozechner/pi-tui":piTuiEntry,"@mariozechner/pi-ai/providers/all":piAiProvidersEntry,"@mariozechner/pi-ai/compat":piAiCompatEntry,"@mariozechner/pi-ai/oauth":piAiOauthEntry,"@mariozechner/pi-ai":piAiCompatEntry,typebox:typeboxEntry,"typebox/compile":typeboxCompileEntry,"typebox/value":typeboxValueEntry,"@sinclair/typebox":typeboxEntry,"@sinclair/typebox/compile":typeboxCompileEntry,"@sinclair/typebox/value":typeboxValueEntry},_aliases}var runtimeFactories=new WeakMap;function createExtensionRuntime(){let notInitialized=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},state3={},nextProviderRegistrationOrder=0,eventBusUnsubscribers=new Set,assertActive=()=>{if(state3.staleMessage)throw new StaleExtensionContextError(state3.staleMessage)},runtime={sendMessage:notInitialized,sendUserMessage:notInitialized,appendEntry:notInitialized,setSessionName:notInitialized,getSessionName:notInitialized,setLabel:notInitialized,executeTool:()=>Promise.reject(new Error("Extension runtime not initialized")),getActiveTools:notInitialized,getAllTools:notInitialized,getSettings:notInitialized,setActiveTools:notInitialized,refreshTools:()=>{},registerRemovedToolHint:()=>{},registerLazyToolActivator:()=>{},getCommands:notInitialized,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:notInitialized,setThinkingLevel:notInitialized,setSessionModel:()=>Promise.reject(new Error("Extension runtime not initialized")),setSessionThinkingLevel:notInitialized,setSessionFastMode:notInitialized,sessionControl:unboundSessionControlActions(),flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],pendingVirtualModelRegistrations:[],mcpServers:new McpServerRegistry,createContext:notInitialized,assertActive,invalidate:message=>{if(!state3.staleMessage){state3.staleMessage=message??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let unsubscribe of eventBusUnsubscribers)unsubscribe();eventBusUnsubscribers.clear(),runtime.evalHandleHost=void 0,runtimeFactories.delete(runtime)}},trackEventBusSubscription:unsubscribe=>{let active=!0,trackedUnsubscribe=()=>{active&&(active=!1,eventBusUnsubscribers.delete(trackedUnsubscribe),unsubscribe())};return eventBusUnsubscribers.add(trackedUnsubscribe),trackedUnsubscribe},registerProvider:(name,config,extensionPath="<unknown>")=>{runtime.pendingProviderRegistrations.push({name,config,extensionPath,order:nextProviderRegistrationOrder++})},registerNativeProvider:(provider,extensionPath="<unknown>")=>{runtime.pendingNativeProviderRegistrations.push({provider,extensionPath,order:nextProviderRegistrationOrder++})},unregisterProvider:name=>{runtime.pendingProviderRegistrations=runtime.pendingProviderRegistrations.filter(r=>r.name!==name),runtime.pendingNativeProviderRegistrations=runtime.pendingNativeProviderRegistrations.filter(r=>r.provider.id!==name)},registerVirtualModel:(definition,extensionPath="<unknown>")=>{runtime.pendingVirtualModelRegistrations.push({definition,extensionPath})},unregisterVirtualModel:(provider,id)=>{runtime.pendingVirtualModelRegistrations=runtime.pendingVirtualModelRegistrations.filter(({definition})=>definition.provider!==provider||definition.id!==id)},emitProviderLoginStart:async()=>{}};return runtime}var unboundSessionControl=unboundSessionControlActions();function sessionControlOf(runtime){return runtime.sessionControl??unboundSessionControl}function drainPendingProviderRegistrations(runtime){let drained=[...runtime.pendingProviderRegistrations.map(entry2=>({kind:"config",...entry2})),...runtime.pendingNativeProviderRegistrations.map(entry2=>({kind:"native",...entry2}))];return drained.sort((a,b)=>a.order-b.order),runtime.pendingProviderRegistrations=[],runtime.pendingNativeProviderRegistrations=[],drained}function handlerSessionId(context){if(!(!context||!("sessionManager"in context)))try{return context.sessionManager?.getSessionId()}catch(error2){if(error2 instanceof StaleExtensionContextError)return;throw error2}}function createExtensionAPI(extension,runtime,cwd,eventBus,session){let pendingFlagValues=new Map,pendingRuntimeChanges=[],loadingUnsubscribers=[],state3="loading",assertActive=()=>{if(state3==="failed")throw new Error(`Extension "${extension.path}" failed to load and its API is no longer active.`);runtime.assertActive()},applyRuntimeChange=change=>{state3==="loading"?pendingRuntimeChanges.push(change):change()},clearPending=()=>{pendingFlagValues.clear(),pendingRuntimeChanges.length=0,loadingUnsubscribers.length=0},api={cwd,sessionKind:session.sessionKind,sessionContext:session.sessionContext,on(event,handler,options){assertActive();let registeredHandler=ownedBy(extension,(...args)=>{let sessionId=handlerSessionId(args[1]),invoke=()=>handler(...args);return sessionId?kernelToolInvokerStorage.run({sessionId},invoke):kernelToolInvokerStorage.exit(invoke)}),list3=extension.handlers.get(event)??[];return list3.push(registeredHandler),extension.handlers.set(event,list3),event==="before_agent_start"&&options?.previewSafe===!0&&(extension.previewSafeHandlers??=new WeakSet,extension.previewSafeHandlers.add(registeredHandler)),event==="before_agent_start"&&options?.runLast===!0&&(extension.runLastHandlers??=new WeakSet,extension.runLastHandlers.add(registeredHandler)),(event==="context"||event==="context_with_system")&&options?.mutatesMessages===!1&&(extension.nonMutatingContextHandlers??=new WeakSet,extension.nonMutatingContextHandlers.add(registeredHandler)),()=>{let handlers=extension.handlers.get(event);if(!handlers)return;let handlerIndex=handlers.indexOf(registeredHandler);handlerIndex!==-1&&(handlers.splice(handlerIndex,1),handlers.length===0&&extension.handlers.delete(event))}},registerTool(tool){if(runtime.assertActive(),tool.name==="tool_search"&&extension.sourceInfo.source!=="builtin")throw new Error('Tool name "tool_search" is reserved for the builtin tool-search extension.');if(typeof tool.parameters!="object"||tool.parameters===null||Array.isArray(tool.parameters))throw new Error(`Tool "${tool.name}" registered by extension "${extension.path}" must define an object parameter schema.`);extension.tools.set(tool.name,{definition:Object.assign(Object.create(Object.getPrototypeOf(tool)),tool,{execute:ownedBy(extension,tool.execute)}),sourceInfo:extension.sourceInfo}),runtime.refreshTools()},registerLazyToolActivator(activator){runtime.assertActive();let activators=extension.lazyToolActivators??[];activators.push(activator),extension.lazyToolActivators=activators,runtime.registerLazyToolActivator(activator)},provideEvalHandleHost(host){runtime.assertActive(),runtime.evalHandleHost=host},registerRemovedToolHint(name,hint){runtime.assertActive();let hints=extension.removedToolHints;hints||(hints=new Map,extension.removedToolHints=hints),hints.set(name,hint),runtime.registerRemovedToolHint(name,hint)},registerChildModule(registration){runtime.assertActive(),validateChildModuleRegistration(registration);let modules=extension.childModules??new Map;modules.set(registration.id,{registration:{...registration},sourceInfo:extension.sourceInfo}),extension.childModules=modules},registerFilesystemPolicy(policy){runtime.assertActive();let policies2=extension.filesystemPolicies??[];policies2.push(policy),extension.filesystemPolicies=policies2},registerCommand(name,options){if(assertActive(),typeof name!="string"||name.length===0)throw new Error(`Command registered by extension "${extension.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof options?.handler!="function")throw new Error(`Command "/${name}" registered by extension "${extension.path}" must define handler().`);extension.commands.set(name,{name,sourceInfo:extension.sourceInfo,...options,handler:ownedBy(extension,options.handler)})},registerShortcut(shortcut,options){assertActive(),extension.shortcuts.set(shortcut,{shortcut,extensionPath:extension.path,...options,handler:ownedBy(extension,options.handler)})},registerFlag(name,options){if(assertActive(),options.default!==void 0&&typeof options.default!==options.type)throw new Error(`Invalid default for flag "${name}": expected ${options.type}, got ${typeof options.default}`);extension.flags.set(name,{name,extensionPath:extension.path,...options}),options.default!==void 0&&!runtime.flagValues.has(name)&&(state3==="loading"?pendingFlagValues.has(name)||pendingFlagValues.set(name,options.default):runtime.flagValues.set(name,options.default))},registerMessageRenderer(customType,renderer){assertActive(),extension.messageRenderers.set(customType,renderer)},registerMemoryReporter(name,reporter){if(assertActive(),RESERVED_MEMORY_REPORT_KEYS.has(name))throw new Error(`Memory reporter name "${name}" is reserved by the memory report`);extension.memoryReporters??=new Map,extension.memoryReporters.set(name,reporter)},registerMarkdownTransformer(transformer){assertActive(),extension.markdownTransformer=transformer},registerEntryRenderer(customType,renderer,options){assertActive(),extension.entryRenderers??=new Map,extension.entryRenderers.set(customType,renderer),extension.entryRendererOptions??=new Map,options===void 0?extension.entryRendererOptions.delete(customType):extension.entryRendererOptions.set(customType,options)},registerReadClassifier(classifier){assertActive();let unregister=runtime.trackEventBusSubscription(registerReadClassifier(classifier));return state3==="loading"&&loadingUnsubscribers.push(unregister),unregister},registerMcpServer(name,config){assertActive();let error2=validateMcpServerDeclaration(name,config);if(error2)throw new Error(error2);extension.mcpServers.set(name,{name,config:structuredClone(config),extensionPath:extension.path,registrationCwd:extension.registrationCwd}),runtime.mcpServers.changed()},unregisterMcpServer(name){assertActive(),extension.mcpServers.delete(name)&&runtime.mcpServers.changed()},getMcpServers(){return assertActive(),runtime.mcpServers.list()},getFlag(name){if(assertActive(),!!extension.flags.has(name))return runtime.flagValues.has(name)?runtime.flagValues.get(name):pendingFlagValues.get(name)},getPermissionPreset(){assertActive();let sessionManager;try{sessionManager=runtime.createContext().sessionManager}catch{return}return readPermissionPreset(sessionManager)},getSubscriptionLimits(){return assertActive(),subscriptionLimits.snapshot()},onSubscriptionLimits(listener){return assertActive(),subscriptionLimits.subscribe(listener)},lifecycle:createLifecycleApi(()=>{if(assertActive(),!runtime.lifecycle)throw new Error("Extension lifecycle is not bound to a session");return runtime.lifecycle}),sendMessage:((message,options)=>{assertActive();let items=options?.items;if(items===void 0){runtime.sendMessage(message,options);return}let itemized=runtime.sendItemizedMessage;return itemized===void 0?(runtime.sendMessage(message,options),Promise.resolve(void 0)):itemized(message,{...options,items})}),sendUserMessage(content,options){assertActive(),runtime.sendUserMessage(content,options)},appendEntry(customType,data,options){assertActive(),runtime.appendEntry(customType,data,options)},setSessionName(name){assertActive(),runtime.setSessionName(name)},getSessionName(){return assertActive(),runtime.getSessionName()},setLabel(entryId,label3){assertActive(),runtime.setLabel(entryId,label3)},exec(command,args,options){return assertActive(),execCommand(command,args,options?.cwd??cwd,options)},redactForUpload(text4,options){return assertActive(),redactForUpload(text4,options)},hostVersion:VERSION,executeTool(toolName,params,options){return runtime.assertActive(),runtime.executeTool(toolName,params,options)},getActiveTools(){return assertActive(),runtime.getActiveTools()},armToolBarrier(spec2){if(assertActive(),!runtime.armToolBarrier)throw new Error("This runtime has no tool barrier (senpi#3717).");runtime.armToolBarrier(spec2)},releaseToolBarrier(id){return assertActive(),runtime.releaseToolBarrier?.(id)??!1},getAllTools(){return assertActive(),runtime.getAllTools()},getSettings(){return assertActive(),runtime.getSettings()},setActiveTools(toolNames){assertActive(),runtime.setActiveTools(toolNames)},getCommands(){return assertActive(),runtime.getCommands()},setModel(model){return assertActive(),runtime.setModel(model,{source:"extension",actor:extension.path})},getThinkingLevel(){return assertActive(),runtime.getThinkingLevel()},setThinkingLevel(level){assertActive(),runtime.setThinkingLevel(level)},setSessionModel(model){return runtime.assertActive(),runtime.setSessionModel(model,{source:"extension",actor:extension.path})},setSessionThinkingLevel(level){runtime.assertActive(),runtime.setSessionThinkingLevel(level)},setSessionFastMode(enabled){runtime.assertActive(),runtime.setSessionFastMode(enabled)},registerProvider(providerOrName,config){if(assertActive(),typeof providerOrName=="string"){if(!config)throw new Error("Provider config is required when registering by name");let wrapped=withProviderLoginStart(providerOrName,config,event=>runtime.emitProviderLoginStart(event));applyRuntimeChange(()=>runtime.registerProvider(providerOrName,wrapped,extension.path));return}applyRuntimeChange(()=>runtime.registerNativeProvider(providerOrName,extension.path))},unregisterProvider(name){assertActive(),applyRuntimeChange(()=>runtime.unregisterProvider(name,extension.path))},session:{registerControlEndpoint(options){return runtime.assertActive(),sessionControlOf(runtime).registerControlEndpoint(options)},admissionGate(){return runtime.assertActive(),sessionControlOf(runtime).admissionGate()},admitExternalMessage(input){return runtime.assertActive(),sessionControlOf(runtime).admitExternalMessage(input)},listAdmittedDeliveries(){return runtime.assertActive(),sessionControlOf(runtime).listAdmittedDeliveries()},persistHeaderNow(){return runtime.assertActive(),sessionControlOf(runtime).persistHeaderNow()},relocationOffered(){return runtime.assertActive(),sessionControlOf(runtime).relocationOffered()},relocationTargets(signal){return runtime.assertActive(),sessionControlOf(runtime).relocationTargets(signal)},requestRelocation(request2,signal){return runtime.assertActive(),sessionControlOf(runtime).requestRelocation(request2,signal)}},rpc:{emit(name,data){runtime.assertActive();let normalizedName=name.trim();if(normalizedName.length===0)throw new Error("RPC extension event name must not be empty");eventBus.emit(EXTENSION_RPC_EVENT_CHANNEL,{name:normalizedName,data})},handle(name,handler){runtime.assertActive();let normalizedName=name.trim();if(normalizedName.length===0)throw new Error("RPC extension request name must not be empty");let handlers=extension.rpcHandlers??new Map;if(handlers.has(normalizedName))throw new Error(`RPC extension request handler already registered: ${normalizedName}`);handlers.set(normalizedName,ownedBy(extension,handler)),extension.rpcHandlers=handlers}},registerVirtualModel(model){assertActive();let definition={...model,route:request2=>model.route(request2,runtime.createContext())};applyRuntimeChange(()=>runtime.registerVirtualModel(definition,extension.path))},unregisterVirtualModel(provider,id){assertActive(),applyRuntimeChange(()=>runtime.unregisterVirtualModel(provider,id))},events:{emit(channel,data){assertActive(),eventBus.emit(channel,data)},on(channel,handler){assertActive();let unsubscribe=runtime.trackEventBusSubscription(eventBus.on(channel,handler));return state3==="loading"&&loadingUnsubscribers.push(unsubscribe),unsubscribe}}};return recordExtensionLoadKey(api,runtime),{api,commit:()=>{if(state3==="loading"){runtime.assertActive();for(let[name,value]of pendingFlagValues)runtime.flagValues.has(name)||runtime.flagValues.set(name,value);for(let apply of pendingRuntimeChanges)apply();state3="active",clearPending()}},discard:()=>{if(state3==="loading"){state3="failed";for(let unsubscribe of loadingUnsubscribers)unsubscribe();clearPending()}}}}var importNodeOnlyApi=specifier=>import(__rewriteRelativeImportExtension2(specifier));async function createExtensionModuleImporter(){if(usesNativeBunImports){let{createBunExtensionImporter}=await import("./bun-extension-importer-RCGPQTI2.js");return createBunExtensionImporter(VIRTUAL_MODULES,{},{preparedCache:{dir:path15.join(getAgentDir(),"cache","extension-modules"),release:VERSION}})}let{createJiti}=await importNodeOnlyApi("jiti/static");return createJiti(import.meta.url,{moduleCache:!1,...isNodeSeaBinary||isBundledNode?{virtualModules:VIRTUAL_MODULES,tryNative:!1}:isTypeScriptSourceRuntime?{alias:getAliases(),virtualModules:VIRTUAL_MODULES,tsconfigPaths:!0}:{alias:getAliases()}})}async function loadExtensionModule(extensionPath,getImporter){let cachedFactory=cachedExtensionFactory(extensionPath);if(cachedFactory)return cachedFactory;let importer=await getImporter(),factory=await importer.import(extensionPath,{default:!0});if(typeof factory=="function")return rememberExtensionFactory(extensionPath,factory,importer),factory}function createExtension(extensionPath,resolvedPath,registrationCwd){let source2=getSyntheticPathSource(extensionPath)??"local",baseDir=isSyntheticPath(extensionPath)?void 0:path15.dirname(resolvedPath);return{path:extensionPath,resolvedPath,sourceInfo:createSyntheticSourceInfo(extensionPath,{source:source2,baseDir,scope:source2==="builtin"?"system":"temporary"}),handlers:new Map,tools:new Map,removedToolHints:new Map,lazyToolActivators:[],filesystemPolicies:[],messageRenderers:new Map,memoryReporters:new Map,entryRenderers:void 0,commands:new Map,rpcHandlers:new Map,flags:new Map,shortcuts:new Map,mcpServers:new Map,registrationCwd}}async function initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime,session){let extension=createExtension(extensionPath,resolvedPath,cwd),load2=createExtensionAPI(extension,runtime,cwd,eventBus,session);runtime.mcpServers.track(extension);try{if(await runOwnedBy(extension,()=>factory(load2.api)),load2.commit(),usesNativeBunImports){let factories=runtimeFactories.get(runtime)??new Set;factories.add(factory),runtimeFactories.set(runtime,factories)}}catch(error2){throw runtime.mcpServers.untrack(extension),load2.discard(),error2}return time(`${extensionPath} factory`,"extensions"),extension}async function loadExtension(extensionPath,cwd,eventBus,runtime,getImporter,factoryResolver,session=DEFAULT_EXTENSION_SESSION_PROFILE){let resolvedPath=resolvePath(extensionPath,cwd,{normalizeUnicodeSpaces:!0});try{let factory=factoryResolver?.(extensionPath,resolvedPath)??await loadExtensionModule(resolvedPath,getImporter);return time(`${extensionPath} module import`,"extensions"),factory?{extension:await initializeExtension(factory,extensionPath,resolvedPath,cwd,eventBus,runtime,session),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${extensionPath}`}}catch(err){return{extension:null,error:`Failed to load extension: ${err instanceof Error?err.message:String(err)}`}}}async function loadExtensionFromFactory(factory,cwd,eventBus,runtime,extensionPath="<inline>",session=DEFAULT_EXTENSION_SESSION_PROFILE){let resolvedCwd=resolvePath(cwd);return initializeExtension(factory,extensionPath,extensionPath,resolvedCwd,eventBus,runtime,session)}async function loadExtensionsInternal(paths,cwd,eventBus,runtime,options){let session=sessionProfile(options),extensions=[],errors=[],warnings=[],resolvedCwd=resolvePath(cwd),resolvedEventBus=eventBus??createEventBus(),resolvedRuntime=runtime??createExtensionRuntime(),getImporter=()=>extensionModuleImporter(createExtensionModuleImporter);for(let extPath of paths){let{extension,error:error2}=await loadExtension(extPath,resolvedCwd,resolvedEventBus,resolvedRuntime,getImporter,options?.factoryResolver,session);if(error2){errors.push({path:extPath,error:error2});continue}extension&&extensions.push(extension)}return{extensions,errors,warnings,runtime:resolvedRuntime,eventBus:resolvedEventBus}}async function loadExtensions(paths,cwd,eventBus,runtime,options){return loadExtensionsInternal(paths,cwd,eventBus,runtime,options)}function isExtensionFile(name){return name.endsWith(".ts")||name.endsWith(".js")}function resolveExtensionEntries(dir){let packageJsonPath=path15.join(dir,"package.json");if(fs6.existsSync(packageJsonPath)){let manifest=readPiManifest(packageJsonPath);if(manifest?.extensions?.length){let entries=[];for(let extPath of manifest.extensions){let resolvedExtPath=path15.resolve(dir,extPath);fs6.existsSync(resolvedExtPath)&&entries.push(resolvedExtPath)}if(entries.length>0)return entries}}let indexTs=path15.join(dir,"index.ts"),indexJs=path15.join(dir,"index.js");return fs6.existsSync(indexTs)?[indexTs]:fs6.existsSync(indexJs)?[indexJs]:null}function discoverExtensionsInDir(dir){if(!fs6.existsSync(dir))return[];let discovered=[];try{let entries=fs6.readdirSync(dir,{withFileTypes:!0}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(let entry2 of entries){let entryPath=path15.join(dir,entry2.name);if((entry2.isFile()||entry2.isSymbolicLink())&&isExtensionFile(entry2.name)){discovered.push(entryPath);continue}if(entry2.isDirectory()||entry2.isSymbolicLink()){let entries2=resolveExtensionEntries(entryPath);entries2&&discovered.push(...entries2)}}}catch{return[]}return discovered}async function discoverAndLoadExtensions(configuredPaths,cwd,agentDir=getAgentDir(),eventBus){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),allPaths=[],seen=new Set,addPaths=paths=>{for(let p of paths){let resolved=path15.resolve(p);seen.has(resolved)||(seen.add(resolved),allPaths.push(p))}},localExtDir=path15.join(resolvedCwd,CONFIG_DIR_NAME,"extensions");addPaths(discoverExtensionsInDir(localExtDir));let globalExtDir=path15.join(resolvedAgentDir,"extensions");addPaths(discoverExtensionsInDir(globalExtDir));for(let p of configuredPaths){let resolved=resolvePath(p,resolvedCwd,{normalizeUnicodeSpaces:!0});if(fs6.existsSync(resolved)&&fs6.statSync(resolved).isDirectory()){let entries=resolveExtensionEntries(resolved);if(entries){addPaths(entries);continue}addPaths(discoverExtensionsInDir(resolved));continue}addPaths([resolved])}return loadExtensions(allPaths,resolvedCwd,eventBus)}function warnStall(event,budget,stall){if(stall.stage!=="warn")return;let capNote=budget.timeoutMs>0?` (hard cap ${budget.timeoutMs}ms)`:"";console.warn(`Extension ${stall.extensionPath} is still running its ${event} handler after ${stall.elapsedMs}ms${capNote}.`)}async function runSessionMoveHandlers(event,calls,budget){let failures=[];for(let{extensionPath,call}of calls){let outcome=await runBudgetedHandler({extensionPath,event,budget,run:call,onStall:stall=>warnStall(event,budget,stall)});switch(outcome.kind){case"settled":break;case"failed":{let{error:error2}=outcome;failures.push({extensionPath,error:error2 instanceof Error?error2.message:String(error2),...error2 instanceof Error&&error2.stack!==void 0?{stack:error2.stack}:{}});break}case"timed_out":failures.push({extensionPath,error:`handler timed out after ${budget.timeoutMs}ms`});break;case"released":failures.push({extensionPath,error:"handler released before it finished"});break}}return failures}var SessionStartTurnGate=class{constructor(onStartError){this.onStartError=onStartError}get holding(){return this.held!==void 0}admit(start){this.held?this.held.push(start):start()}async dispatch(run2){if(this.held)return run2();let held=[];this.held=held;try{return await run2()}finally{this.held=void 0;for(let start of held)try{start()}catch(error2){this.onStartError(error2)}}}};var QuitDeadline=class{constructor(totalMs,now2,startedAt=now2()){this.now=now2,this.deadline=startedAt+totalMs}budgetFor(base){let remaining=Math.max(1,this.deadline-this.now());return base.timeoutMs>0&&base.timeoutMs<=remaining?{budget:base,endsAtQuitDeadline:!1}:{budget:{warnMs:base.warnMs<remaining?base.warnMs:0,timeoutMs:remaining},endsAtQuitDeadline:!0}}};var RUNTIME_CONTEXT_MEMBERS=new Set(["offload","ui","mode","hasUI","cwd","agentDir","loadedExtensionPaths","modelRegistry","isProjectTrusted","kernelTools","evalHandleHost","shutdown","getLookAtSettings","getAskUserSettings","getImageSettings","getRegisteredMcpServers","extensionConnectsMcpServers"]),SESSION_IDENTITY_MEMBERS=new Set(["sessionManager","goalStoreFile"]);function loopSideUnbound(member){return new Error(`${member} is loop-side and not bound: this extension runtime has no session`)}function withoutSession(context){for(let key of Reflect.ownKeys(context))if(!(typeof key!="string"||RUNTIME_CONTEXT_MEMBERS.has(key))){if(SESSION_IDENTITY_MEMBERS.has(key)){Reflect.deleteProperty(context,key);continue}Object.defineProperty(context,key,{configurable:!0,enumerable:!0,get(){throw loopSideUnbound(key)}})}}var RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS=["app.interrupt","app.clear","app.exit","app.suspend","app.thinking.cycle","app.model.cycleForward","app.model.cycleBackward","app.model.select","app.tools.expand","app.thinking.toggle","app.editor.external","app.message.copy","app.message.followUp","tui.input.submit","tui.select.confirm","tui.select.cancel","tui.input.copy","tui.editor.deleteToLineEnd"],buildBuiltinKeybindings=resolvedKeybindings=>{let builtinKeybindings={};for(let[keybinding,keys]of Object.entries(resolvedKeybindings)){if(keys===void 0)continue;let keyList=Array.isArray(keys)?keys:[keys],restrictOverride=RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS.includes(keybinding);for(let key of keyList){let normalizedKey=key.toLowerCase();builtinKeybindings[normalizedKey]?.restrictOverride&&!restrictOverride||(builtinKeybindings[normalizedKey]={keybinding,restrictOverride})}}return builtinKeybindings};function isUserBashEventResult(value){if(typeof value!="object"||value===null)return!1;let candidate=value,hasOperations=candidate.operations!==void 0,hasResult=candidate.result!==void 0;if(hasOperations===hasResult)return!1;if(hasOperations){let operations=candidate.operations;return typeof operations!="object"||operations===null?!1:typeof operations.exec=="function"}let result3=candidate.result;if(typeof result3!="object"||result3===null)return!1;let resultRecord=result3;return typeof resultRecord.output=="string"&&"exitCode"in resultRecord&&(resultRecord.exitCode===void 0||typeof resultRecord.exitCode=="number")&&typeof resultRecord.cancelled=="boolean"&&typeof resultRecord.truncated=="boolean"&&(resultRecord.fullOutputPath===void 0||typeof resultRecord.fullOutputPath=="string")}function sharedPrefixLength(before,after2){if(after2.startsWith(before))return before.length;let limit=Math.min(before.length,after2.length),index=0;for(;index<limit&&before.charCodeAt(index)===after2.charCodeAt(index);)index++;return index}var EXTENSION_EVENT_PLACEMENT={project_trust:"runtime",resources_discover:"runtime",mcp_servers_change:"runtime",session_start:"split",held_wakes_released:"loop",session_hold_changed:"loop",session_info_changed:"loop",session_parked:"split",session_resumed:"split",session_before_switch:"loop",session_before_fork:"loop",session_before_reload:"runtime",session_before_compact:"loop",session_compact:"loop",session_compact_failed:"loop",session_shutdown:"split",session_abort:"split",session_extensions_removed:"runtime",session_move_export:"loop",session_move_import:"loop",session_before_tree:"loop",session_tree:"loop",context:"loop",context_with_system:"loop",before_provider_request:"loop",before_provider_headers:"loop",after_provider_response:"loop",provider_stream_event:"loop",before_agent_start:"split",agent_start:"loop",agent_end:"split",agent_before_settle:"loop",agent_settled:"split",session_control_wake:"loop",ui_prompt_start:"runtime",ui_prompt_end:"runtime",turn_start:"split",turn_end:"loop",message_start:"loop",message_update:"loop",message_end:"split",tool_execution_start:"runtime",tool_execution_update:"runtime",tool_execution_end:"runtime",model_select:"loop",provider_login_start:"split",system_prompt_change:"loop",thinking_level_select:"loop",tool_activated:"runtime",user_bash:"runtime",input:"split",input_disposition:"loop",tool_call:"runtime",tool_result:"runtime"};function boundedToolHookStatusMessage(message){return message.length<=79?message:`${message.slice(0,76)}...`}function sanitizedToolHookStatusMessage(message){return boundedToolHookStatusMessage(stripAnsi(message).replace(/[\r\n\t]+/g," ").replace(/[\u0000-\u001f\u007f]+/g,"").replace(/\s+/g," ").trim())}var QUEUED_LIFECYCLE_EVENTS=new Set(["agent_start","agent_end","agent_settled","turn_start","message_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end"]),UNBOUNDED_HANDLER_BUDGET={warnMs:0,timeoutMs:0};async function emitSessionShutdownEvent(extensionRunner,event,options={}){options.processExit&&event.reason==="quit"&&extensionRunner.armProcessExitBudget();let emitted=extensionRunner.hasHandlers("session_shutdown");return emitted&&await extensionRunner.emit(event),reclaimRunnerHandles(extensionRunner),emitted}function snapshotEventHandlers(extensions,event){return extensions.map(ext=>({ext,handlers:ext.handlers.get(event)?.slice()??[]}))}function beforeAgentStartDispatchOrder(extensions){let snapshot2=snapshotEventHandlers(extensions,"before_agent_start"),runsLast=(ext,handler)=>ext.runLastHandlers?.has(handler)===!0,isBuiltin=ext=>ext.path.startsWith("<builtin:"),phase=keep=>snapshot2.map(({ext,handlers})=>({ext,handlers:handlers.filter(handler=>keep(ext,handler))}));return[...phase((ext,handler)=>!runsLast(ext,handler)),...phase((ext,handler)=>runsLast(ext,handler)&&!isBuiltin(ext)),...phase((ext,handler)=>runsLast(ext,handler)&&isBuiltin(ext))]}function flattenHandlers(extensions,event){return snapshotEventHandlers(extensions,event).flatMap(({ext,handlers})=>handlers.map(handler=>({path:ext.path,handler})))}function entryAt(entries,index){let entry2=entries[index];if(entry2===void 0)throw new RangeError(`no extension handler at index ${index}`);return entry2}async function emitProjectTrustEvent(extensionsResult,event,ctx){let errors=[];for(let{ext,handlers}of snapshotEventHandlers(extensionsResult.extensions,"project_trust"))for(let handler of handlers)try{let handlerResult=await handler(event,ctx);if(handlerResult.trusted==="undecided")continue;return{result:handlerResult,errors}}catch(error2){errors.push({extensionPath:ext.path,event:event.type,error:error2 instanceof Error?error2.message:String(error2),stack:error2 instanceof Error?error2.stack:void 0})}return{errors}}function createNoOpSessionSettings(){let settings=SettingsManager.inMemory();return{getRetryFallbackSettings:()=>settings.getRetryFallbackSettings(),setFallbackChain:async(key,entries)=>{settings.setFallbackChain(key,[...entries]),await settings.flush()},removeFallbackChain:async key=>{settings.removeFallbackChain(key),await settings.flush()},setModelFallbackEnabled:async enabled=>{settings.setModelFallbackEnabled(enabled),await settings.flush()},setFallbackRevertPolicy:async policy=>{settings.setFallbackRevertPolicy(policy),await settings.flush()},reload:()=>settings.reload(),getFallbackStatus:()=>{}}}var noOpUIContext={capabilities:{secretInput:!0},select:async()=>{},confirm:async()=>!1,input:async(_title,_placeholder,opts2)=>{if(!opts2?.signal?.aborted&&opts2?.secret)throw new SecretInputUnavailableError("headless")},notify:()=>{},onTerminalInput:()=>()=>{},setStatus:()=>{},setSubagentCost:()=>{},setWorkingMessage:()=>{},setWorkingVisible:()=>{},setWorkingIndicator:()=>{},setHiddenThinkingLabel:()=>{},setWidget:()=>{},setFooter:()=>{},setHeader:()=>{},setTitle:()=>{},custom:async()=>{},pasteToEditor:()=>{},setEditorText:()=>{},getEditorText:()=>"",editor:async()=>{},addAutocompleteProvider:()=>{},setEditorComponent:()=>{},getEditorComponent:()=>{},get theme(){return theme},getAllThemes:()=>[],getTheme:()=>{},setTheme:_theme=>({success:!1,error:"UI not available"}),getToolsExpanded:()=>!1,setToolsExpanded:()=>{}},ExtensionRunner=class{constructor(extensions,runtime,cwd,sessionManager,modelRegistry,eventBus=createEventBus()){this.brokerUIContexts=new WeakMap,this.mode="print",this.errorListeners=new Set,this.eventHandlerBudget=()=>UNBOUNDED_HANDLER_BUDGET,this.handlerTurnScope=()=>0,this.reportedInvalidHandlerBudget=!1,this.heldHandlerWaits=new HeldHandlerWaits,this.getModel=()=>{},this.getServiceTier=()=>{},this.getEffectiveServiceTier=()=>this.getServiceTier(),this.getScopedModels=()=>[],this.isIdleFn=()=>!0,this.engineTurnsHeldFn=()=>!1,this.noteHeldWakeFn=()=>{},this.pauseActions={},this.personAnswerPending=!1,this.isProjectTrustedFn=()=>!0,this.getSignalFn=()=>{},this.waitForIdleFn=async()=>{},this.abortFn=()=>{},this.hasPendingMessagesFn=()=>!1,this.hasQueuedPersonInputFn=()=>!1,this.isCompactingFn=()=>!1,this.getContextUsageFn=()=>{},this.getCompactionSettingsFn=()=>({enabled:!0,reserveTokens:16384,keepRecentTokens:2e4}),this.getPromptCacheSafeWaitSecondsFn=()=>{},this.getPromptCacheGoalBackstopMaxSecondsFn=()=>270,this.getPromptCacheKeepAliveSettingsFn=()=>({enabled:!1,maxRequestsPerSession:3,maxCostUsdPerSession:.05,marginSeconds:60}),this.getLookAtSettingsFn=()=>({enabled:!0,models:void 0}),this.getAskUserSettingsFn=()=>({enabled:!0,timeoutMinutes:30}),this.getBrowserEngineFn=()=>{},this.getSessionEnvFn=()=>{},this.getImageSettingsFn=()=>({autoResize:!0,blockImages:!1}),this.sessionSettingsFn=createNoOpSessionSettings(),this.compactFn=()=>{},this.beginCompactionFn=void 0,this.updateCompactionFn=void 0,this.endCompactionFn=void 0,this.getMessageRevisionFn=()=>0,this.applyCompactionFn=async()=>({applied:!1,reason:"rejected"}),this.getSystemPromptFn=()=>"",this.getSystemPromptStablePrefixFn=()=>{},this.getLoadedHookSourcesFn=()=>({agentDir:"",cwd:this.cwd,globalHookSourcePaths:[],globalHooksPath:"",preSessionHookSourcePaths:[],projectHookSourcePaths:[],projectHooksPath:"",runtimeHookSourcePaths:[]}),this.getSystemPromptOptionsFn=()=>({cwd:this.cwd}),this.getPromptCachePrefixRequestFn=void 0,this.getAgentDirFn=()=>getAgentDir(),this.getCallableToolsFn=()=>[],this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.editAssistantMessageHandler=async()=>({cancelled:!1}),this.editUserMessageHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.shutdownHandler=()=>{},this.sessionStartTurns=new SessionStartTurnGate(error2=>this.emitError({extensionPath:RUNTIME_EXTENSION_PATH,event:"session_start",error:error2 instanceof Error?error2.message:String(error2)})),this.shortcutDiagnostics=[],this.commandDiagnostics=[],this.nextToolHookRunIndex=0,this.uiPromptDepth=0,this.#reportedChildModuleReplacements=new Set,this.extensions=extensions,registerRunnerExtensions(this,extensions),this.runtime=runtime,runtime.mcpServers.bind(extensions),runtime.emitProviderLoginStart=event=>this.emitProviderLoginStart(event),this.uiContext=noOpUIContext,this.cwd=cwd,this.sessionManager=sessionManager,this.modelRegistry=modelRegistry,this.eventBus=eventBus}bindCore(actions,contextActions,providerActions){actions.lifecycle&&(this.runtime.lifecycle=actions.lifecycle),this.runtime.sendMessage=(message,options)=>{options?.triggerTurn===!0?this.sessionStartTurns.admit(()=>actions.sendMessage(message,options)):actions.sendMessage(message,options)},this.runtime.sendItemizedMessage=(message,options)=>{let receipts=Promise.withResolvers(),send=()=>{let itemized=actions.sendItemizedMessage;itemized===void 0?(actions.sendMessage(message,options),receipts.resolve(void 0)):itemized(message,options).then(receipts.resolve,receipts.reject)};return options.triggerTurn===!0?this.sessionStartTurns.admit(send):send(),receipts.promise},this.runtime.sendUserMessage=(content,options)=>{let inputOrigin=this.personAnswerPending?"person":"extension";this.personAnswerPending=!1,this.sessionStartTurns.admit(()=>actions.sendUserMessage(content,options,inputOrigin))},this.runtime.appendEntry=actions.appendEntry,this.runtime.setSessionName=actions.setSessionName,this.runtime.getSessionName=actions.getSessionName,this.runtime.setLabel=actions.setLabel,this.runtime.executeTool=actions.executeTool,this.runtime.getActiveTools=actions.getActiveTools,this.runtime.getAllTools=actions.getAllTools,this.runtime.getSettings=actions.getSettings,this.runtime.setActiveTools=actions.setActiveTools,this.runtime.refreshTools=actions.refreshTools,this.runtime.registerRemovedToolHint=actions.registerRemovedToolHint,this.runtime.registerLazyToolActivator=actions.registerLazyToolActivator,this.runtime.getCommands=actions.getCommands,this.runtime.setModel=actions.setModel,this.runtime.getThinkingLevel=actions.getThinkingLevel,this.runtime.setThinkingLevel=actions.setThinkingLevel,this.runtime.setSessionModel=actions.setSessionModel,this.runtime.setSessionThinkingLevel=actions.setSessionThinkingLevel,this.runtime.setSessionFastMode=actions.setSessionFastMode,actions.sessionControl&&(this.runtime.sessionControl=actions.sessionControl),actions.armToolBarrier&&(this.runtime.armToolBarrier=actions.armToolBarrier),actions.releaseToolBarrier&&(this.runtime.releaseToolBarrier=actions.releaseToolBarrier),this.runtime.createContext=()=>this.createContext(),this.offloadFn=contextActions.offload,this.getModel=contextActions.getModel,this.getServiceTier=contextActions.getServiceTier,this.getEffectiveServiceTier=contextActions.getEffectiveServiceTier??contextActions.getServiceTier,this.getScopedModels=contextActions.getScopedModels,this.isIdleFn=contextActions.isIdle,this.engineTurnsHeldFn=contextActions.engineTurnsHeld??(()=>!1),this.noteHeldWakeFn=contextActions.noteHeldWake??(()=>{}),this.pauseActions={getPauseState:contextActions.getPauseState,fenceRun:contextActions.fenceRun,releaseRunFence:contextActions.releaseRunFence},this.questionInput=contextActions.questionInput,this.isProjectTrustedFn=contextActions.isProjectTrusted,this.getSignalFn=contextActions.getSignal,this.abortFn=contextActions.abort,this.hasPendingMessagesFn=contextActions.hasPendingMessages,this.hasQueuedPersonInputFn=contextActions.hasQueuedPersonInput??(()=>!1),this.isCompactingFn=contextActions.isCompacting,this.checkReloadVetoFn=contextActions.checkReloadVeto,this.shutdownHandler=contextActions.shutdown,this.getContextUsageFn=contextActions.getContextUsage,this.getCompactionSettingsFn=contextActions.getCompactionSettings,this.getCompactionModelFn=contextActions.getCompactionModel,contextActions.getPromptCacheSafeWaitSeconds&&(this.getPromptCacheSafeWaitSecondsFn=contextActions.getPromptCacheSafeWaitSeconds),contextActions.getPromptCacheGoalBackstopMaxSeconds&&(this.getPromptCacheGoalBackstopMaxSecondsFn=contextActions.getPromptCacheGoalBackstopMaxSeconds),contextActions.getPromptCacheKeepAliveSettings&&(this.getPromptCacheKeepAliveSettingsFn=contextActions.getPromptCacheKeepAliveSettings),this.getLookAtSettingsFn=contextActions.getLookAtSettings,contextActions.getAskUserSettings&&(this.getAskUserSettingsFn=contextActions.getAskUserSettings),contextActions.getBrowserEngine&&(this.getBrowserEngineFn=contextActions.getBrowserEngine),contextActions.getSessionEnv&&(this.getSessionEnvFn=contextActions.getSessionEnv),this.getImageSettingsFn=contextActions.getImageSettings,this.sessionSettingsFn=contextActions.sessionSettings,this.compactFn=contextActions.compact,this.beginCompactionFn=contextActions.beginCompaction,this.updateCompactionFn=contextActions.updateCompaction,this.endCompactionFn=contextActions.endCompaction,this.getMessageRevisionFn=contextActions.getMessageRevision,this.applyCompactionFn=contextActions.applyCompaction,this.getSystemPromptFn=contextActions.getSystemPrompt,this.getSystemPromptStablePrefixFn=contextActions.getSystemPromptStablePrefix??(()=>{}),this.getLoadedHookSourcesFn=contextActions.getLoadedHookSources,contextActions.getAgentDir&&(this.getAgentDirFn=contextActions.getAgentDir),this.getSystemPromptOptionsFn=contextActions.getSystemPromptOptions??(()=>({cwd:this.cwd})),this.getPromptCachePrefixRequestFn=contextActions.getPromptCachePrefixRequest,this.onUserActivityFn=contextActions.onUserActivity,this.executeToolFn=contextActions.executeTool,this.getCallableToolsFn=contextActions.getCallableTools??(()=>[]),this.runtime.mcpServers.setChangeListener(()=>{this.emit({type:"mcp_servers_change",servers:this.runtime.mcpServers.list()})});for(let extension of this.extensions){for(let[name,hint]of extension.removedToolHints??[])actions.registerRemovedToolHint(name,hint);for(let activator of extension.lazyToolActivators??[])actions.registerLazyToolActivator(activator)}for(let registration of drainPendingProviderRegistrations(this.runtime))try{registration.kind==="config"?providerActions?.registerProvider?providerActions.registerProvider(registration.name,registration.config,registration.extensionPath):this.modelRegistry.registerProvider(registration.name,registration.config):providerActions?.registerNativeProvider?providerActions.registerNativeProvider(registration.provider,registration.extensionPath):this.modelRegistry.registerProvider(registration.provider)}catch(err){this.emitError({extensionPath:registration.extensionPath,event:"register_provider",error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}let registerVirtualModel=definition=>{providerActions?.registerVirtualModel?providerActions.registerVirtualModel(definition):this.modelRegistry.registerVirtualModel(definition)};for(let{definition,extensionPath}of this.runtime.pendingVirtualModelRegistrations)try{registerVirtualModel(definition)}catch(err){this.emitError({extensionPath,event:"register_virtual_model",error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}this.runtime.pendingVirtualModelRegistrations=[],this.runtime.registerProvider=(name,config,extensionPath)=>{if(providerActions?.registerProvider){providerActions.registerProvider(name,config,extensionPath);return}this.modelRegistry.registerProvider(name,config)},this.runtime.registerNativeProvider=(provider,extensionPath)=>{if(providerActions?.registerNativeProvider){providerActions.registerNativeProvider(provider,extensionPath);return}this.modelRegistry.registerProvider(provider)},this.runtime.unregisterProvider=name=>{if(providerActions?.unregisterProvider){providerActions.unregisterProvider(name);return}this.modelRegistry.unregisterProvider(name)},this.runtime.registerVirtualModel=registerVirtualModel,this.runtime.unregisterVirtualModel=(provider,id)=>{providerActions?.unregisterVirtualModel?providerActions.unregisterVirtualModel(provider,id):this.modelRegistry.unregisterVirtualModel(provider,id)}}bindCommandContext(actions){if(actions){this.waitForIdleFn=actions.waitForIdle,this.newSessionHandler=actions.newSession,this.forkHandler=actions.fork,this.navigateTreeHandler=actions.navigateTree,this.editAssistantMessageHandler=actions.editAssistantMessage,this.editUserMessageHandler=actions.editUserMessage,this.switchSessionHandler=actions.switchSession,this.reloadHandler=actions.reload;return}this.waitForIdleFn=async()=>{},this.newSessionHandler=async()=>({cancelled:!1}),this.forkHandler=async()=>({cancelled:!1}),this.navigateTreeHandler=async()=>({cancelled:!1}),this.editAssistantMessageHandler=async()=>({cancelled:!1}),this.editUserMessageHandler=async()=>({cancelled:!1}),this.switchSessionHandler=async()=>({cancelled:!1}),this.reloadHandler=void 0}requestReload(){return this.reloadHandler?(this.reloadRequestPromise||(this.reloadRequestPromise=this.reloadHandler().finally(()=>{this.reloadRequestPromise=void 0})),this.reloadRequestPromise):Promise.resolve()}setUIContext(uiContext,mode="print"){this.uiContext=uiContext?this.wrapUIPromptContext(uiContext):noOpUIContext,this.mode=mode}setUiBroker(broker){this.uiBroker=broker}currentUIContext(){if(this.uiBroker===void 0)return this.uiContext;let presenter=this.uiBroker.presenter;if(presenter===void 0)return noOpUIContext;let wrapped=this.brokerUIContexts.get(presenter);return wrapped===void 0&&(wrapped=this.wrapUIPromptContext(presenter),this.brokerUIContexts.set(presenter,wrapped)),wrapped}setToolHookLifecycleObserver(observer){this.toolHookLifecycleObserver=observer}setLifecycleAttentionObserver(observer){this.lifecycleAttentionObserver=observer}getLifecycleHumanWait(){let prompt=this.activeUIPrompt;if(!(this.mode==="rpc"||!prompt))return{kind:prompt.kind==="confirm"?"approval":"question",requestId:prompt.requestId,revision:1,since:prompt.since}}wrapUIPromptContext(ui){let questionFn=ui.question;return inheritMcpMrtrPresentation(ui,{...ui,select:(title,options,opts2)=>this.withUIPrompt("select",title,()=>ui.select(title,options,opts2)),confirm:(title,message,opts2)=>this.withUIPrompt("confirm",title,()=>ui.confirm(title,message,opts2)),input:(title,placeholder,opts2)=>this.withUIPrompt("input",opts2?.secret?void 0:title,()=>ui.input(title,placeholder,opts2)),editor:(title,prefill)=>this.withUIPrompt("editor",title,()=>ui.editor(title,prefill)),custom:(factory,options)=>this.withUIPrompt("custom",void 0,()=>ui.custom(factory,options)),...questionFn?{question:(request2,opts2)=>this.withUIPrompt("question",request2.questions[0]?.header,()=>questionFn(request2,opts2),request2.requestId)}:{}})}withUIPrompt(kind,title,run2,requestId=crypto.randomUUID()){this.uiPromptDepth++===0&&(this.activeUIPrompt={kind,title,requestId,since:new Date().toISOString()},this.lifecycleAttentionObserver?.(),this.emitUIPromptEvent({type:"ui_prompt_start",reason:"ui_prompt",kind,...title?{title}:{}}));let finish=()=>{if(--this.uiPromptDepth>0)return;this.uiPromptDepth=0;let prompt=this.activeUIPrompt??{kind,title};this.activeUIPrompt=void 0,this.lifecycleAttentionObserver?.(),this.emitUIPromptEvent({type:"ui_prompt_end",reason:"ui_prompt",kind:prompt.kind,...prompt.title?{title:prompt.title}:{}})};try{return run2().finally(finish)}catch(err){throw finish(),err}}emitUIPromptEvent(event){queueMicrotask(()=>{this.emit(event)})}getUIContext(){return this.currentUIContext()}sessionStartTurnsHeld(){return this.sessionStartTurns.holding}hasUI(){return this.currentUIContext()!==noOpUIContext}getExtensionPaths(){return this.extensions.map(e=>e.path)}getExtensionIdentities(){return this.extensions.map(({path:path16,resolvedPath})=>({path:path16,resolvedPath}))}#reportedChildModuleReplacements;getAllChildModules(){let modules=new Map;for(let ext of this.extensions)for(let[id,entry2]of ext.childModules??[]){let earlier=modules.get(id),replacement=`${id}\0${earlier?.sourceInfo.path}\0${entry2.sourceInfo.path}`;earlier!==void 0&&earlier.sourceInfo.path!==entry2.sourceInfo.path&&!this.#reportedChildModuleReplacements.has(replacement)&&(this.#reportedChildModuleReplacements.add(replacement),console.warn(`Child module "${id}" from ${entry2.sourceInfo.path} replaces the one from ${earlier.sourceInfo.path}`)),modules.set(id,entry2)}return modules}getAllRegisteredTools(){let toolsByName=new Map;for(let ext of this.extensions)for(let tool of ext.tools.values()){let existing2=toolsByName.get(tool.definition.name);(!existing2||existing2.sourceInfo.source==="builtin"&&tool.sourceInfo.source!=="builtin")&&toolsByName.set(tool.definition.name,tool)}return Array.from(toolsByName.values())}getFilesystemPolicyDeniedRoots(){return this.extensions.flatMap(extension=>(extension.filesystemPolicies??[]).flatMap(policy=>policy.deniedRoots??[]))}onRpcEvent(handler){let off=this.eventBus.on(EXTENSION_RPC_EVENT_CHANNEL,data=>{handler(data)});return this.eventBus.emit(EXTENSION_RPC_SUBSCRIBED_CHANNEL,void 0),off}onBusEvent(channel,handler){return this.eventBus.on(channel,handler)}emitBusEvent(channel,data){this.eventBus.emit(channel,data)}getRegisteredMcpServers(){return this.runtime.mcpServers.declarations()}extensionConnectsMcpServers(){return this.hasHandlers("mcp_servers_change")}getToolDefinition(toolName){for(let ext of this.extensions){let tool=ext.tools.get(toolName);if(tool)return tool.definition}}getFlags(){let allFlags=new Map;for(let ext of this.extensions)for(let[name,flag]of ext.flags)allFlags.has(name)||allFlags.set(name,flag);return allFlags}setFlagValue(name,value){this.runtime.flagValues.set(name,value)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(resolvedKeybindings){this.shortcutDiagnostics=[];let builtinKeybindings=buildBuiltinKeybindings(resolvedKeybindings),extensionShortcuts=new Map,addDiagnostic=(message,extensionPath)=>{this.shortcutDiagnostics.push({type:"warning",message,path:extensionPath}),this.hasUI()||console.warn(message)};for(let ext of this.extensions)for(let[key,shortcut]of ext.shortcuts){let normalizedKey=key.toLowerCase(),builtInKeybinding=builtinKeybindings[normalizedKey];if(builtInKeybinding?.restrictOverride===!0){addDiagnostic(`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,shortcut.extensionPath);continue}builtInKeybinding?.restrictOverride===!1&&addDiagnostic(`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,shortcut.extensionPath);let existingExtensionShortcut=extensionShortcuts.get(normalizedKey);existingExtensionShortcut&&addDiagnostic(`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,shortcut.extensionPath),extensionShortcuts.set(normalizedKey,shortcut)}return extensionShortcuts}getShortcutDiagnostics(){return this.shortcutDiagnostics}invalidate(message="This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."){this.staleMessage||(this.staleMessage=message,this.runtime.invalidate(message))}get isActive(){return this.staleMessage===void 0}runAfterSessionStart(publish2){if(this.staleMessage)return;let report=error2=>{error2 instanceof StaleExtensionContextError||this.emitError({extensionPath:RUNTIME_EXTENSION_PATH,event:"session_start",error:error2 instanceof Error?error2.message:String(error2)})};try{Promise.resolve(publish2()).catch(report)}catch(error2){report(error2)}}assertActive(){if(this.staleMessage)throw new StaleExtensionContextError(this.staleMessage)}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}setEventHandlerBudget(budget,onStall,turnScope=()=>0){this.eventHandlerBudget=budget,this.handlerStallListener=onStall,this.handlerTurnScope=turnScope}releaseHeldHandlers(turn,verdict="released"){return this.heldHandlerWaits.release(turn,verdict)}resolveEventHandlerBudget(){try{return this.eventHandlerBudget()}catch(err){return this.reportedInvalidHandlerBudget||(this.reportedInvalidHandlerBudget=!0,console.warn(`Using the default extension event handler budget (warn ${DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS}ms, hard cap ${DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS}ms): ${err instanceof Error?err.message:String(err)}`)),{warnMs:DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS,timeoutMs:DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS}}}walkHandlers(sequence2){return runBudgetedSequence(sequence2,{budget:this.resolveEventHandlerBudget(),held:{waits:this.heldHandlerWaits,scope:this.handlerTurnScope},onStall:stall=>this.handlerStallListener?.(stall)})}reportStoppedHandler(extensionPath,event,verdict,budget){if(verdict==="yielded")return;let error2=verdict==="timed_out"?`handler timed out after ${budget.timeoutMs}ms`:"handler released when the turn was stopped";this.emitError({extensionPath,event,error:error2})}reportHandlerFailure(extensionPath,event,err){this.emitError({extensionPath,event,error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}dispatchLifecycle(event){let entries=flattenHandlers(this.extensions,event.type);return this.walkHandlers({event:event.type,length:entries.length,extensionPath:index=>entryAt(entries,index).path,start:index=>{let{path:path16,handler}=entryAt(entries,index);return handler(event,this.createContext(path16))},settle:(index,outcome)=>{outcome.ok||this.reportHandlerFailure(entryAt(entries,index).path,event.type,outcome.error)},skip:(index,verdict,budget)=>this.reportStoppedHandler(entryAt(entries,index).path,event.type,verdict,budget),finish:()=>{}})}emitError(error2){for(let listener of this.errorListeners)listener(error2)}hasHandlers(eventType){for(let ext of this.extensions){let handlers=ext.handlers.get(eventType);if(handlers&&handlers.length>0)return!0}return!1}getToolHookStatusMessage(extensionPath,hookName){let builtinName=/^<builtin:([^>]+)>$/.exec(extensionPath)?.[1];if(builtinName==="permission-system")return"matching project rules";if(builtinName==="bash-timeout")return"applying bash timeout";if(builtinName==="compaction")return hookName==="PreToolUse"?"checking compaction state":"checking tool result size";if(builtinName==="tool-pair-guard")return"checking tool/result pairs";let extensionName=builtinName??(extensionPath.startsWith("<")&&extensionPath.endsWith(">")?extensionPath.slice(1,-1):basename37(extensionPath).replace(/\.(?:c|m)?[jt]sx?$/,""));return boundedToolHookStatusMessage(`running ${extensionName}`)}emitToolHookLifecycleEvent(event){this.toolHookLifecycleObserver?.(event)}beginToolHookRun(baseContext,run2){let base={type:"tool_hook_status",hookRunId:`${run2.toolCallId}:${run2.hookName}:${this.nextToolHookRunIndex++}`,hookName:run2.hookName,toolName:run2.toolName,toolCallId:run2.toolCallId,extensionPath:run2.extensionPath,startedAt:Date.now()},statusMessage=this.getToolHookStatusMessage(run2.extensionPath,run2.hookName),ended=!1;this.emitToolHookLifecycleEvent({...base,phase:"start",statusMessage});let context=Object.defineProperties({},Object.getOwnPropertyDescriptors(baseContext));return context.updateToolHookStatus=update2=>{ended||(statusMessage=sanitizedToolHookStatusMessage(update2),this.emitToolHookLifecycleEvent({...base,phase:"update",statusMessage}))},{context,end:(status,errorMessage6)=>{ended||(ended=!0,this.emitToolHookLifecycleEvent({...base,phase:"end",statusMessage,completedAt:Date.now(),status,...errorMessage6!==void 0?{errorMessage:errorMessage6}:{}}))}}}getMessageRenderer(customType){for(let ext of this.extensions){let renderer=ext.messageRenderers.get(customType);if(renderer)return renderer}}getMemoryReporters(){return this.extensions.flatMap(ext=>[...ext.memoryReporters??new Map].map(([name,reporter])=>({name,reporter})))}getMarkdownTransformers(){return this.extensions.flatMap(ext=>ext.markdownTransformer?[ext.markdownTransformer]:[])}getEntryRenderer(customType){for(let ext of this.extensions){let renderer=ext.entryRenderers?.get(customType);if(renderer)return renderer}}getEntryRendererOptions(customType){return this.extensions.find(ext=>ext.entryRenderers?.has(customType))?.entryRendererOptions?.get(customType)}resolveRegisteredCommands(){let commands=[],counts=new Map;for(let ext of this.extensions)for(let command of ext.commands.values())commands.push(command),counts.set(command.name,(counts.get(command.name)??0)+1);let seen=new Map,takenInvocationNames=new Set;return commands.map(command=>{let occurrence=(seen.get(command.name)??0)+1;seen.set(command.name,occurrence);let invocationName=(counts.get(command.name)??0)>1?`${command.name}:${occurrence}`:command.name;if(takenInvocationNames.has(invocationName)){let suffix=occurrence;do suffix++,invocationName=`${command.name}:${suffix}`;while(takenInvocationNames.has(invocationName))}return takenInvocationNames.add(invocationName),{...command,invocationName}})}getModelRegistry(){return this.modelRegistry}getRegisteredCommands(){return this.commandDiagnostics=[],this.resolveRegisteredCommands()}getCommandDiagnostics(){return this.commandDiagnostics}getCommand(name){return this.resolveRegisteredCommands().find(command=>command.invocationName===name)}async requestRpc(name,data,context){return requestExtensionRpc(this.extensions,name,data,context,()=>this.assertActive())}shutdown(){this.shutdownHandler()}getActiveTools(){return this.assertActive(),this.sessionManager===void 0?[]:this.runtime.getActiveTools()}boundSessionManager(){if(this.sessionManager===void 0)throw loopSideUnbound("sessionManager");return this.sessionManager}createContext(excludeBeforeProviderRequestExtensionPath){let runner=this,getModel=this.getModel,getServiceTier=this.getServiceTier,getEffectiveServiceTier=this.getEffectiveServiceTier,getScopedModels=this.getScopedModels,compactionSignal,context={offload:(id,args,options)=>(runner.assertActive(),runner.offloadFn===void 0?Promise.reject(new Error(`offload_unavailable: no session backs this context (offload ${id})`)):runner.offloadFn(id,args,options)),get ui(){return runner.assertActive(),runner.currentUIContext()},get mode(){return runner.assertActive(),runner.mode},get hasUI(){return runner.assertActive(),runner.hasUI()},get cwd(){return runner.assertActive(),runner.cwd},get agentDir(){return runner.assertActive(),runner.getAgentDirFn()},get loadedExtensionPaths(){return runner.assertActive(),runner.extensions.map(extension=>extension.resolvedPath)},get sessionManager(){return runner.assertActive(),runner.boundSessionManager()},get goalStoreFile(){return runner.assertActive(),goalFilePath(goalStoreRef(runner.boundSessionManager(),runner.cwd))},get browserEngine(){return runner.assertActive(),runner.getBrowserEngineFn()},get sessionEnv(){return runner.assertActive(),runner.getSessionEnvFn()},get modelRegistry(){return runner.assertActive(),runner.modelRegistry},get model(){return runner.assertActive(),getModel()},get serviceTier(){return runner.assertActive(),getServiceTier()},get effectiveServiceTier(){return runner.assertActive(),getEffectiveServiceTier()},get scopedModels(){return runner.assertActive(),getScopedModels()},get thinkingLevel(){return runner.assertActive(),runner.runtime.getThinkingLevel()},isIdle:()=>(runner.assertActive(),runner.isIdleFn()),engineTurnsHeld:()=>(runner.assertActive(),runner.engineTurnsHeldFn()),noteHeldWake:source2=>{runner.assertActive(),runner.noteHeldWakeFn(source2)},getPauseState:()=>(runner.assertActive(),runner.pauseActions.getPauseState?.()??{pauseSeq:0,holds:[]}),fenceRun:runRef=>{runner.assertActive(),runner.pauseActions.fenceRun?.(runRef)},releaseRunFence:runRef=>{runner.assertActive(),runner.pauseActions.releaseRunFence?.(runRef)},isProjectTrusted:()=>(runner.assertActive(),runner.isProjectTrustedFn()),get signal(){return runner.assertActive(),runner.getSignalFn()},get kernelTools(){runner.assertActive();let tools=kernelToolsStorage.getStore();if(tools)return{capabilities:tools.capabilities,describe:names=>tools.describe(names),invoke:(request2,options)=>(runner.assertActive(),tools.invoke(request2,{...options&&("aborted"in options?{signal:options}:options),invoker:kernelToolInvokerStorage.getStore()??{sessionId:runner.boundSessionManager().getSessionId()}}))}},get evalHandleHost(){return runner.assertActive(),runner.runtime.evalHandleHost},abort:source2=>{runner.assertActive(),runner.abortFn(source2)},hasPendingMessages:()=>(runner.assertActive(),runner.hasPendingMessagesFn()),hasQueuedPersonInput:()=>(runner.assertActive(),runner.hasQueuedPersonInputFn()),get requestReload(){return runner.assertActive(),runner.reloadHandler?()=>runner.requestReload():void 0},get checkReloadVeto(){runner.assertActive();let probe=runner.checkReloadVetoFn;return probe?()=>probe():void 0},isCompacting:()=>(runner.assertActive(),runner.isCompactingFn()),shutdown:()=>{runner.assertActive(),runner.shutdownHandler()},getContextUsage:()=>(runner.assertActive(),runner.getContextUsageFn()),getCompactionSettings:()=>(runner.assertActive(),runner.getCompactionSettingsFn()),get getCompactionModel(){return runner.assertActive(),runner.getCompactionModelFn?()=>(runner.assertActive(),runner.getCompactionModelFn?.()):void 0},getPromptCacheSafeWaitSeconds:()=>(runner.assertActive(),runner.getPromptCacheSafeWaitSecondsFn()),getPromptCacheGoalBackstopMaxSeconds:()=>(runner.assertActive(),runner.getPromptCacheGoalBackstopMaxSecondsFn()),getPromptCacheKeepAliveSettings:()=>(runner.assertActive(),runner.getPromptCacheKeepAliveSettingsFn()),onUserActivity:listener=>{runner.assertActive();let unsubscribe=runner.onUserActivityFn?.(kind=>{try{listener(kind)}catch(error2){runner.emitError({extensionPath:excludeBeforeProviderRequestExtensionPath??RUNTIME_EXTENSION_PATH,event:"user_activity",error:error2 instanceof Error?error2.message:String(error2)})}});return runner.runtime.trackEventBusSubscription(unsubscribe??(()=>{}))},getLookAtSettings:()=>(runner.assertActive(),runner.getLookAtSettingsFn()),getAskUserSettings:()=>(runner.assertActive(),runner.getAskUserSettingsFn()),afterSessionStart:publish2=>{runner.assertActive(),runner.sessionStartTurns.admit(()=>runner.runAfterSessionStart(publish2))},getImageSettings:()=>(runner.assertActive(),runner.getImageSettingsFn()),get sessionSettings(){return runner.assertActive(),runner.sessionSettingsFn},compact:options=>{runner.assertActive(),runner.compactFn(options)},prepareProviderRequest:async(messages,options)=>(runner.assertActive(),runner.prepareProviderRequest(messages,excludeBeforeProviderRequestExtensionPath,options)),getPromptCachePrefixRequest:async options=>{runner.assertActive();let build=runner.getPromptCachePrefixRequestFn;return build===void 0?{status:"skipped",reason:"the host builds no prompt-cache prefix"}:await build(options)},beginCompaction:options=>(runner.assertActive(),compactionSignal=runner.beginCompactionFn?.(options),compactionSignal),updateCompaction:options=>{runner.assertActive(),runner.updateCompactionFn?.({...options,signal:options.signal??compactionSignal})},endCompaction:options=>{runner.assertActive(),runner.endCompactionFn?.({...options,signal:options.signal??compactionSignal})},getMessageRevision:()=>(runner.assertActive(),runner.getMessageRevisionFn()),applyCompaction:(precomputed,options)=>(runner.assertActive(),runner.applyCompactionFn(precomputed,{...options,signal:options.signal??compactionSignal})),getSystemPrompt:()=>(runner.assertActive(),runner.getSystemPromptFn()),getSystemPromptStablePrefix:()=>(runner.assertActive(),runner.getSystemPromptStablePrefixFn()),getSystemPromptOptions:()=>(runner.assertActive(),runner.getSystemPromptOptionsFn()),getLoadedHookSources:()=>(runner.assertActive(),runner.getLoadedHookSourcesFn()),getRegisteredMcpServers:()=>(runner.assertActive(),runner.getRegisteredMcpServers()),extensionConnectsMcpServers:()=>(runner.assertActive(),runner.extensionConnectsMcpServers())};return this.questionInput&&bindQuestionInput(context,()=>{runner.assertActive(),runner.personAnswerPending=!0,queueMicrotask(()=>{runner.personAnswerPending=!1}),runner.questionInput?.()}),this.sessionManager===void 0&&withoutSession(context),context}createToolContext(toolCallId,signal,baseContext=this.createContext()){let runner=this;return Object.defineProperties(baseContext,{tools:{get(){return runner.assertActive(),runner.getCallableToolsFn()}},executeTool:{value:async(name,args,options={})=>(runner.assertActive(),runner.executeToolFn?runner.executeToolFn(toolCallId,name,args,{...options,signal:options.signal??signal}):{toolCall:{type:"toolCall",id:`${toolCallId}/0`,name,arguments:{}},result:{content:[{type:"text",text:"Nested tool calls are not available in this context"}],details:{}},isError:!0})}})}createCommandContext(){let context=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext()));return context.waitForIdle=()=>(this.assertActive(),this.waitForIdleFn()),context.newSession=options=>(this.assertActive(),this.newSessionHandler(options)),context.fork=(entryId,options)=>(this.assertActive(),this.forkHandler(entryId,options)),context.navigateTree=(targetId,options)=>{if(this.assertActive(),typeof targetId=="string")return this.navigateTreeHandler(targetId,options);let{entryId,...navigationOptions}=targetId;return this.navigateTreeHandler(entryId,navigationOptions)},context.editAssistantMessage=(entryId,text4,options)=>(this.assertActive(),this.editAssistantMessageHandler(entryId,text4,options)),context.editUserMessage=(entryId,text4,options)=>(this.assertActive(),this.editUserMessageHandler(entryId,text4,options)),context.switchSession=(sessionPath,options)=>(this.assertActive(),this.switchSessionHandler(sessionPath,options)),context.reload=()=>(this.assertActive(),this.requestReload()),context}async emitBoundary(baseEvent,buildContext2){let ctx=this.createContext(),entries=[],shouldContinue=!1,context={contextEntries:[],contextMessages:[],llmMessages:[],pendingMessages:[],canContinue:!1},retired=()=>({entries:[],continue:!1,context,valid:!1});try{context=await buildContext2(entries)}catch(err){if(!this.isActive)return retired();throw err}let valid2=!0,handlers=this.dropsLoopEvent(baseEvent.type)?[]:flattenHandlers(this.extensions,baseEvent.type);return this.walkHandlers({event:baseEvent.type,length:handlers.length,extensionPath:index=>entryAt(handlers,index).path,halted:()=>!this.isActive,start:index=>{let event={...baseEvent,entries,continue:shouldContinue,context};return entryAt(handlers,index).handler(event,ctx)},settle:async(index,outcome)=>{if(!this.isActive)return;let{path:path16}=entryAt(handlers,index);if(outcome.ok){let handlerResult=outcome.value;handlerResult?.entries!==void 0&&(entries=handlerResult.entries),handlerResult?.continue!==void 0&&(shouldContinue=handlerResult.continue)}else this.reportHandlerFailure(path16,baseEvent.type,outcome.error);try{context=await buildContext2(entries),valid2=!0}catch(err){if(!this.isActive)return;valid2=!1,this.emitError({extensionPath:path16,event:baseEvent.type,error:`Invalid boundary entries: ${err instanceof Error?err.message:String(err)}`,stack:err instanceof Error?err.stack:void 0})}},skip:(index,verdict,budget)=>this.reportStoppedHandler(entryAt(handlers,index).path,baseEvent.type,verdict,budget),finish:()=>valid2&&this.isActive?{entries,continue:shouldContinue,context,valid:!0}:retired()})}isSessionBeforeEvent(event){return event.type==="session_before_switch"||event.type==="session_before_fork"||event.type==="session_before_reload"||event.type==="session_before_compact"||event.type==="session_before_tree"}armProcessExitBudget(){this.processExitRequestedAt??=Date.now()}resolveSessionShutdownBudget(){try{let settings=SettingsManager.create(this.cwd,this.getAgentDirFn(),{projectTrusted:this.isProjectTrustedFn()});return{handler:{warnMs:settings.getSessionShutdownHandlerWarnMs(),timeoutMs:settings.getSessionShutdownHandlerTimeoutMs()},quitMs:settings.getSessionShutdownQuitBudgetMs()}}catch(err){let message=err instanceof Error?err.message:String(err);return console.warn(`Using the default session_shutdown handler budget (warn ${DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS}ms, hard cap ${DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS}ms, quit ${DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS}ms): ${message}`),{handler:{warnMs:DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS,timeoutMs:DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS},quitMs:DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS}}}async runSessionShutdownHandler(extensionPath,event,handler,{budget,endsAtQuitDeadline}){let startedAt=Date.now(),outcome=await runBudgetedHandler({extensionPath,event:"session_shutdown",budget,run:signal=>handler({...event,signal},this.createContext(extensionPath)),onStall:stall=>{if(stall.stage!=="warn")return;let capNote=budget.timeoutMs>0?` (hard cap ${budget.timeoutMs}ms)`:"";console.warn(`Extension ${extensionPath} is still running its session_shutdown handler after ${stall.elapsedMs}ms${capNote}.`)}});if(outcome.kind==="failed")throw outcome.error;outcome.kind==="timed_out"&&endsAtQuitDeadline?console.warn(`Extension ${extensionPath} session_shutdown handler overran the quit budget after ${Date.now()-startedAt}ms; quitting without it.`):outcome.kind==="timed_out"&&this.emitError({extensionPath,event:"session_shutdown",error:`handler timed out after ${budget.timeoutMs}ms`})}emitHeldWakesReleased(sources){return this.emit({type:"held_wakes_released",sources})}dropsLoopEvent(type2){return this.sessionManager===void 0&&EXTENSION_EVENT_PLACEMENT[type2]==="loop"}emit(event){return this.dropsLoopEvent(event.type)?Promise.resolve(void 0):event.type==="session_start"?this.sessionStartTurns.dispatch(()=>this.dispatchEmit(event)):QUEUED_LIFECYCLE_EVENTS.has(event.type)?this.dispatchLifecycle(event):this.dispatchEmit(event)}async emitSessionMove(event){let calls=(this.dropsLoopEvent(event.type)?[]:flattenHandlers(this.extensions,event.type)).map(({path:path16,handler})=>({extensionPath:path16,call:signal=>handler({...event,signal},this.createContext(path16))})),failures=await runSessionMoveHandlers(event.type,calls,this.resolveSessionShutdownBudget().handler);for(let failure2 of failures)this.emitError({...failure2,event:event.type});return failures}async dispatchEmit(event){let result3,isSessionShutdown=event.type==="session_shutdown",shutdownBudget,quitDeadline;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,event.type))for(let handler of handlers)try{if(isSessionShutdown){let shutdownEvent=event;shutdownBudget||(shutdownBudget=this.resolveSessionShutdownBudget(),shutdownEvent.reason==="quit"&&this.processExitRequestedAt!==void 0&&shutdownBudget.quitMs>0&&(quitDeadline=new QuitDeadline(shutdownBudget.quitMs,Date.now,this.processExitRequestedAt))),await this.runSessionShutdownHandler(ext.path,shutdownEvent,handler,quitDeadline?.budgetFor(shutdownBudget.handler)??{budget:shutdownBudget.handler,endsAtQuitDeadline:!1});continue}let handlerResult=await handler(event,this.createContext(ext.path));if(this.isSessionBeforeEvent(event)&&handlerResult&&(result3=handlerResult,result3.cancel))return result3}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:event.type,error:message,stack})}return result3}async emitModelSelect(event){if(this.dropsLoopEvent("model_select"))return;let result3;for(let ext of this.extensions){let handlers=ext.handlers.get("model_select");if(!(!handlers||handlers.length===0))for(let handler of handlers)try{let liveEvent={...event,systemPromptOptions:this.getSystemPromptOptionsFn()},handlerResult=await handler(liveEvent,this.createContext(ext.path));if(handlerResult){let nextResult=handlerResult;if(nextResult.systemPrompt!==void 0||nextResult.systemPromptName!==void 0){let combinedResult={};nextResult.systemPrompt!==void 0?combinedResult.systemPrompt=nextResult.systemPrompt:result3?.systemPrompt!==void 0&&(combinedResult.systemPrompt=result3.systemPrompt),nextResult.systemPromptName!==void 0?combinedResult.systemPromptName=nextResult.systemPromptName:result3?.systemPromptName!==void 0&&(combinedResult.systemPromptName=result3.systemPromptName),result3=combinedResult}}}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"model_select",error:message,stack})}}return result3}emitMessageEnd(event){let currentMessage=event.message,modified=!1,entries=flattenHandlers(this.extensions,"message_end");return this.walkHandlers({event:"message_end",length:entries.length,extensionPath:index=>entryAt(entries,index).path,start:index=>{let{path:path16,handler}=entryAt(entries,index),currentEvent={...event,message:currentMessage};return handler(currentEvent,this.createContext(path16))},settle:(index,outcome)=>{let{path:path16}=entryAt(entries,index);if(!outcome.ok){this.reportHandlerFailure(path16,"message_end",outcome.error);return}let handlerResult=outcome.value;if(handlerResult?.message){if(handlerResult.message.role!==currentMessage.role){this.emitError({extensionPath:path16,event:"message_end",error:"message_end handlers must return a message with the same role"});return}currentMessage=handlerResult.message,modified=!0}},skip:(index,verdict,budget)=>this.reportStoppedHandler(entryAt(entries,index).path,"message_end",verdict,budget),finish:()=>modified?currentMessage:void 0})}async emitToolResult(event){let currentEvent={...event},modified=!1;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"tool_result"))for(let handler of handlers){let hookRun=this.beginToolHookRun(this.createContext(),{hookName:"PostToolUse",toolName:event.toolName,toolCallId:event.toolCallId,extensionPath:ext.path}),endStatus="completed",errorMessage6;try{let handlerResult=await handler(currentEvent,hookRun.context);if(!handlerResult)continue;handlerResult.content!==void 0&&(currentEvent.content=handlerResult.content,handlerResult.structuredContent===void 0&&delete currentEvent.structuredContent,modified=!0),handlerResult.details!==void 0&&(currentEvent.details=handlerResult.details,modified=!0),handlerResult.structuredContent!==void 0&&(currentEvent.structuredContent=handlerResult.structuredContent,modified=!0),handlerResult.isError!==void 0&&(currentEvent.isError=handlerResult.isError,modified=!0),handlerResult.usage!==void 0&&(currentEvent.usage=handlerResult.usage,modified=!0)}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;endStatus="failed",errorMessage6=message,this.emitError({extensionPath:ext.path,event:"tool_result",error:message,stack})}finally{hookRun.end(endStatus,errorMessage6)}}if(modified)return{content:currentEvent.content,details:currentEvent.details,structuredContent:currentEvent.structuredContent,isError:currentEvent.isError,usage:currentEvent.usage}}async emitToolCall(event){let result3;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"tool_call"))for(let handler of handlers){let hookRun=this.beginToolHookRun(this.createContext(),{hookName:"PreToolUse",toolName:event.toolName,toolCallId:event.toolCallId,extensionPath:ext.path}),endStatus="completed",errorMessage6;try{let handlerResult=await handler(event,hookRun.context);if(handlerResult&&(result3=handlerResult,result3.block))return endStatus="blocked",result3}catch(err){throw endStatus="failed",errorMessage6=err instanceof Error?err.message:String(err),err}finally{hookRun.end(endStatus,errorMessage6)}}return result3}async emitUserBash(event){for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"user_bash"))for(let handler of handlers)try{let handlerResult=await handler(event,this.createContext());if(handlerResult===void 0)continue;if(!isUserBashEventResult(handlerResult))throw new Error("Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object");return handlerResult}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;throw this.emitError({extensionPath:ext.path,event:"user_bash",error:message,stack}),err}}async emitContext(messages,excludeExtensionPath,source2="agent"){return dispatchContextMessages(messages,{contextHandlers:this.dropsLoopEvent("context")?[]:snapshotEventHandlers(this.extensions,"context"),contextWithSystemHandlers:this.dropsLoopEvent("context_with_system")?[]:snapshotEventHandlers(this.extensions,"context_with_system"),createContext:path16=>this.createContext(path16),emitError:error2=>this.emitError(error2),excludeExtensionPath,source:source2})}async prepareProviderRequest(messages,excludeExtensionPath,options){return{messages:await this.emitContext(messages,excludeExtensionPath,"projection"),transformPayload:async payload=>await this.emitBeforeProviderRequest(options?.allowServerSearch?payload:disableServerSearch(payload),excludeExtensionPath),transformHeaders:async headers=>await this.emitBeforeProviderHeaders(headers)}}async emitBeforeProviderRequest(payload,excludeExtensionPath,request2){let currentPayload=payload,requestHandlers=this.dropsLoopEvent("before_provider_request")?[]:snapshotEventHandlers(this.extensions,"before_provider_request");for(let{ext,handlers}of requestHandlers)if(ext.path!==excludeExtensionPath)for(let handler of handlers)try{let event={type:"before_provider_request",payload:currentPayload,...request2?{model:request2.model,headers:request2.headers}:{}},handlerResult=await handler(event,this.createContext(ext.path));handlerResult!==void 0&&(currentPayload=handlerResult)}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"before_provider_request",error:message,stack})}return currentPayload}async emitBeforeProviderHeaders(headers){let headerHandlers=this.dropsLoopEvent("before_provider_headers")?[]:snapshotEventHandlers(this.extensions,"before_provider_headers");for(let{ext,handlers}of headerHandlers)for(let handler of handlers)try{await handler({type:"before_provider_headers",headers},this.createContext(ext.path))}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"before_provider_headers",error:message,stack})}return headers}getThirdPartySessionStartPaths(){return this.extensions.filter(ext=>ext.sourceInfo.source!=="builtin"&&(ext.handlers.get("session_start")?.length??0)>0).map(ext=>ext.path)}getPreviewUnsafeBeforeAgentStartPaths(){let paths=[];for(let ext of this.extensions)(ext.handlers.get("before_agent_start")??[]).some(handler=>ext.previewSafeHandlers?.has(handler)!==!0)&&paths.push(ext.path);return paths}async emitBeforeAgentStart(prompt,images,systemPrompt,systemPromptOptions,options={}){let currentSystemPrompt=systemPrompt,messages=[],systemPromptModified=!1,stableLength=systemPrompt.length;dispatch:for(let{ext,handlers}of beforeAgentStartDispatchOrder(this.extensions))for(let handler of handlers){if(options.signal?.aborted===!0)break dispatch;if(!(options.preview===!0&&ext.previewSafeHandlers?.has(handler)!==!0))try{let ctx=Object.defineProperties({},Object.getOwnPropertyDescriptors(this.createContext(ext.path)));ctx.getSystemPrompt=()=>(this.assertActive(),currentSystemPrompt);let event={type:"before_agent_start",prompt,trigger:options.trigger??"prompt",images,systemPrompt:currentSystemPrompt,systemPromptOptions,...options.preview===!0?{preview:!0}:{}},promptBefore=currentSystemPrompt,handlerResult=await handler(event,ctx),parts;if(handlerResult){let result3=handlerResult;result3.message&&messages.push(result3.message),result3.systemPrompt!==void 0&&(stableLength=(result3.systemPromptCache??(ext.path.startsWith("<builtin:")?"stable":"volatile"))==="stable"&&stableLength===currentSystemPrompt.length?result3.systemPrompt.length:Math.min(stableLength,sharedPrefixLength(currentSystemPrompt,result3.systemPrompt)),currentSystemPrompt=result3.systemPrompt,systemPromptModified=!0,parts=result3.systemPromptParts)}options.preview===!0&&options.observePrompt?.({path:ext.path,before:promptBefore,after:currentSystemPrompt,...parts===void 0?{}:{parts}})}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"before_agent_start",error:message,stack})}}if(messages.length>0||systemPromptModified)return{messages:messages.length>0?messages:void 0,systemPrompt:systemPromptModified?currentSystemPrompt:void 0,...systemPromptModified&&stableLength<currentSystemPrompt.length?{systemPromptStablePrefix:currentSystemPrompt.slice(0,stableLength)}:{}}}async emitResourcesDiscover(cwd,reason){let skillPaths=[],promptPaths=[],themePaths=[],hookPaths=[],toEntry=(entry2,extensionPath)=>typeof entry2=="string"?{path:entry2,extensionPath}:entry2.scope===void 0?{path:entry2.path,extensionPath}:{path:entry2.path,extensionPath,scope:entry2.scope};for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"resources_discover"))for(let handler of handlers)try{let result3=await handler({type:"resources_discover",cwd,reason,scopedEntries:!0},this.createContext(ext.path));result3?.skillPaths?.length&&skillPaths.push(...result3.skillPaths.map(entry2=>toEntry(entry2,ext.path))),result3?.promptPaths?.length&&promptPaths.push(...result3.promptPaths.map(entry2=>toEntry(entry2,ext.path))),result3?.themePaths?.length&&themePaths.push(...result3.themePaths.map(entry2=>toEntry(entry2,ext.path))),result3?.hookPaths?.length&&hookPaths.push(...result3.hookPaths.map(entry2=>toEntry(entry2,ext.path)))}catch(err){let message=err instanceof Error?err.message:String(err),stack=err instanceof Error?err.stack:void 0;this.emitError({extensionPath:ext.path,event:"resources_discover",error:message,stack})}return{skillPaths,promptPaths,themePaths,hookPaths}}async emitProviderLoginStart(event){for(let{path:path16,handler}of flattenHandlers(this.extensions,event.type))try{await handler(event,this.createContext(path16))}catch(err){this.reportHandlerFailure(path16,event.type,err)}}async emitInput(text4,images,source2,streamingBehavior,inputId="input",attribution=inputAttributionOf({origin:inputOriginOf(source2),source:source2})){let currentText=text4,currentImages=images;for(let{ext,handlers}of snapshotEventHandlers(this.extensions,"input"))for(let handler of handlers)try{let result3=await handler({type:"input",inputId,text:currentText,images:currentImages,source:source2,attribution,streamingBehavior},this.createContext(ext.path));if(result3?.action==="handled")return result3;result3?.action==="transform"&&(currentText=result3.text,currentImages=result3.images??currentImages)}catch(err){this.emitError({extensionPath:ext.path,event:"input",error:err instanceof Error?err.message:String(err),stack:err instanceof Error?err.stack:void 0})}return currentText!==text4||currentImages!==images?{action:"transform",text:currentText,images:currentImages}:{action:"continue"}}};var trimSlash=value=>value.replace(/\/+$/,""),UNCHECKABLE_CONTROL_KEY="senpi-verify-control-not-a-real-key",AUTH_HEADERS=new Set(["authorization","x-api-key","x-goog-api-key"]);function probeFor(model,key){let base=trimSlash(model.baseUrl),extra=Object.fromEntries(Object.entries(model.headers??{}).filter(([name])=>!AUTH_HEADERS.has(name.toLowerCase())));switch(model.api){case"openai-completions":case"openai-responses":return{url:`${base}/models`,headers:{...extra,authorization:`Bearer ${key}`}};case"mistral-conversations":return{url:`${base.replace(/\/v1$/,"")}/v1/models`,headers:{...extra,authorization:`Bearer ${key}`}};case"anthropic-messages":return{url:`${base.replace(/\/v1$/,"")}/v1/models`,headers:{...extra,"x-api-key":key,"anthropic-version":"2023-06-01"}};case"google-generative-ai":return{url:`${base}/models`,headers:{...extra,"x-goog-api-key":key}};default:return}}async function verifyApiKey(input){let model=input.models.find(candidate=>candidate.provider===input.provider);if(model===void 0)return{ok:!1,reason:"unknown-provider"};if(probeFor(model,input.key)===void 0)return{ok:!1,reason:"unsupported"};let ask=async candidate=>{let target=probeFor(model,candidate);if(target===void 0)return"no-answer";try{let response=await(input.fetch??globalThis.fetch)(target.url,{method:"GET",headers:target.headers,redirect:"manual",signal:input.signal});return await response.body?.cancel().catch(()=>{}),response.status}catch{return"no-answer"}},temporary=status2=>status2==="no-answer"?{ok:!1,reason:"unreachable"}:status2===429||status2>=500?{ok:!1,reason:"unreachable",status:status2}:void 0,status=await ask(input.key);if(status==="no-answer")return{ok:!1,reason:"unreachable"};let failedFirst=temporary(status);if(failedFirst!==void 0)return failedFirst;if(status===401||status===403)return{ok:!1,reason:"rejected",status};if(status<200||status>=300)return{ok:!1,reason:"unsupported",status};let control=await ask(UNCHECKABLE_CONTROL_KEY);if(control===401||control===403)return{ok:!0};let failedControl=temporary(control);return failedControl!==void 0?failedControl:{ok:!1,reason:"unsupported"}}function storedKeyHint(modelRegistry,info){if(info.authType!=="api_key")return{};let credential=modelRegistry.authStorage.get(info.id);if(credential?.type!=="api_key"||credential.key===void 0)return{};let key=credential.key;return isCommandConfigValue(key)||getConfigValueEnvVarNames(key).length>0||key.length<12?{}:{keyHint:key.slice(-4)}}function holdAutomaticInput(session,command,interactiveUser){return interactiveUser?!1:session.noteAutomaticInput(command.message)}var MODEL_NOT_READY_ERROR_CODES={provider_credentials_missing:RPC_ERROR_PROVIDER_CREDENTIALS_MISSING,provider_credentials_expired:RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED,no_model_selected:RPC_ERROR_NO_MODEL_SELECTED};async function handleClientInput(session,command,io,client={interactiveUser:!1}){try{let admissions=ClientAdmissions.forSession(session),disposition,responded=!1,respond=admission2=>{responded=!0;let finalDisposition=admission2?.disposition??disposition;io.output({id:command.id,type:"response",command:command.type,success:!0,data:{disposition:finalDisposition,...clientMessageIdentity(command),...admission2?{admission:admission2}:{},...command.type==="prompt"&&command.toolBarrier!==void 0?{toolBarrier:finalDisposition==="started"?"armed":"ignored"}:{}}})},admission=await clientInputContext.run(clientMessageIdentity(command),()=>admissions.admit(command,async hooks=>{let promptPath=options=>{let accepted=Promise.withResolvers(),preflightSucceeded=!1,acceptedAdmission,call=session.prompt(command.message,{...clientMessageIdentity(command),images:command.images,...options,source:"rpc",interactiveUser:client.interactiveUser,onQueuedInput:hooks.queued,promptDisposition:next=>{disposition=next,acceptedAdmission=hooks.accepted(next)},preflightResult:succeeded=>{succeeded&&disposition!==void 0&&(preflightSucceeded=!0,accepted.resolve(disposition),respond(acceptedAdmission))}}).catch(error2=>{preflightSucceeded||accepted.reject(error2)});return io.promptCalls.add(call),call.finally(()=>io.promptCalls.delete(call)),accepted.promise};switch(command.type){case"prompt":{if(command.thinkingLevel!==void 0&&session.isStreaming&&command.streamingBehavior!==void 0)throw new Error("Cannot set thinkingLevel on a queued prompt; set it after the current turn completes.");return promptPath({streamingBehavior:command.streamingBehavior,thinkingLevel:command.thinkingLevel,sessionTitlePrompt:command.sessionTitlePrompt,expandPromptTemplates:command.expandPromptTemplates,unknownCommandAsText:command.unknownCommandAsText,toolBarrier:command.toolBarrier})}case"steer":case"follow_up":{if(command.whenIdle==="start")return promptPath({streamingBehavior:command.type==="steer"?"steer":"followUp",enqueueOrder:command.enqueueOrder});let options={...clientMessageIdentity(hooks.identity),enqueueOrder:command.enqueueOrder,source:"rpc",interactiveUser:client.interactiveUser,onQueuedInput:hooks.queued};return disposition=command.type==="steer"?await session.steer(command.message,command.images,options):await session.followUp(command.message,command.images,options),hooks.accepted(disposition),disposition}}}));responded||respond(admission)}catch(error2){let unknownCommand=error2 instanceof UnknownCommandError;io.output({id:command.id,type:"response",command:command.type,success:!1,error:unknownCommand?`${error2.message} ${UNKNOWN_COMMAND_CONFIRM_HINT}`:error2 instanceof Error?error2.message:String(error2),...error2 instanceof ClientMessageIdConflict||error2 instanceof AgentBusyError?{errorCode:error2.code}:{},...error2 instanceof ModelNotReadyError?{errorCode:MODEL_NOT_READY_ERROR_CODES[error2.code],...error2.provider===void 0?{}:{errorData:{provider:error2.provider}}}:{},...unknownCommand?{errorCode:RPC_ERROR_UNKNOWN_COMMAND,errorData:{command:error2.command,suggestions:error2.suggestions,reason:error2.reason}}:{}})}}function createRpcEventOutputBuffer(writeRaw,scheduleFlush=queueMicrotask){let pendingEventLines=[],flushScheduled=!1,flushEvents=()=>{flushScheduled=!1,pendingEventLines.length!==0&&(writeRaw(pendingEventLines.join("")),pendingEventLines=[])};return{enqueueEvent(event){pendingEventLines.push(serializeJsonLine(event)),!flushScheduled&&(flushScheduled=!0,scheduleFlush(flushEvents))},writeImmediate(value){flushEvents(),writeRaw(serializeJsonLine(value))},flushEvents}}import{randomUUID as randomUUID19}from"node:crypto";var SecretInputRequests=class{constructor(route,admit){this.pending=new Map,this.receipts=new Map,this.route=route,this.admit=admit}input(title,placeholder,opts2){if(opts2?.signal?.aborted)return Promise.resolve(void 0);let timeout=resolveSecretInputTimeout(opts2),id=randomUUID19(),refused2=this.route.select(id,()=>this.pending.get(id)?.finish("unavailable"));return refused2?Promise.reject(new SecretInputUnavailableError(refused2)):new Promise(resolve56=>{let deadline=Date.now()+timeout,disarm,onAbort=()=>finish("cancelled"),finish=(outcome,value)=>{this.pending.delete(id)&&(disarm?.(),opts2?.signal?.removeEventListener("abort",onAbort),this.remember(id),this.route.send(id,{type:"secret_input_settled",id,outcome}),this.route.settled(id),resolve56(value))};if(this.pending.set(id,{deadline,finish}),opts2?.signal?.addEventListener("abort",onAbort,{once:!0}),disarm=armSecretInputDeadline(deadline,()=>finish("timed_out")),opts2?.signal?.aborted)return finish("cancelled");this.route.send(id,{type:"extension_ui_request",id,method:"input",secret:!0,title,...placeholder===void 0?{}:{placeholder},timeout,deadlineAtMs:deadline,...opts2?.toolCallId===void 0?{}:{toolCallId:opts2.toolCallId},...opts2?.parentToolCallId===void 0?{}:{parentToolCallId:opts2.parentToolCallId}})})}has(id){return this.pending.has(id)||this.receipts.has(id)}answered(){return[...this.receipts].filter(entry2=>entry2[1]!==void 0&&this.route.accepts(entry2[0])).slice(-64).map(([uiRequestId,answerId])=>({uiRequestId,answerId}))}respond(frame){let id=typeof frame.id=="string"?frame.id:"",requestId=answeredUiRequestId(frame);if(!requestId||!this.route.accepts(requestId))return refusedExtensionUiResponse(id,"secret_answer_refused");if(!this.has(requestId))return refusedExtensionUiResponse(id,"unknown_extension_ui_request");let allowed=new Set(["type","id","uiRequestId","answerId","sessionId","secret","value","cancelled"]);if(frame.secret!==!0||typeof frame.id!="string"||typeof frame.answerId!="string"||frame.answerId.length<1||frame.answerId.length>256||Object.keys(frame).some(key=>!allowed.has(key))||!("value"in frame?!("cancelled"in frame)&&typeof frame.value=="string"&&isSecretInputValue(frame.value):frame.cancelled===!0))return refusedExtensionUiResponse(id,"invalid_secret_response");let pending=this.pending.get(requestId),reply={type:"response",command:"extension_ui_response",id};if(!pending){let answerId=this.receipts.get(requestId);return answerId===frame.answerId?{...reply,success:!0,disposition:"replay"}:answerId===void 0?refusedExtensionUiResponse(id,"unknown_extension_ui_request"):{...reply,success:!1,error:"already_answered",disposition:"already_answered"}}return Date.now()>=pending.deadline?(pending.finish("timed_out"),refusedExtensionUiResponse(id,"unknown_extension_ui_request")):(this.admit(),pending.finish(frame.cancelled===!0?"cancelled":"answered",typeof frame.value=="string"?frame.value:void 0),this.receipts.set(requestId,frame.answerId),{...reply,success:!0,disposition:"applied"})}cancelAll(outcome="cancelled"){for(let pending of[...this.pending.values()])pending.finish(outcome)}recheck(){for(let[id,pending]of this.pending)this.route.available(id)||pending.finish("unavailable")}close(){this.cancelAll();for(let id of this.receipts.keys())this.route.forget(id);this.receipts.clear()}remember(id){if(this.receipts.set(id,void 0),this.receipts.size>1024){let oldest=this.receipts.keys().next().value;oldest!==void 0&&(this.receipts.delete(oldest),this.route.forget(oldest))}}};function runHoldInput(session,command,roles){if(!roles.interactiveUser){if(!roles.taskParent)return{ok:!1,error:"hold_input_requires_interactive_client"};if(!session.pauseView.records.some(record10=>record10.kind==="inherited_hold"&&record10.parentSessionId===command.parentSessionId))return{ok:!1,error:"wrong_parent: this child is not paused for that parent session's run"}}let result3=session.holdInput({inputId:command.inputId,revision:command.revision,text:command.text});switch(result3.kind){case"held":return{ok:!0,data:{entryId:result3.entryId,duplicate:result3.duplicate}};case"already_delivered":return{ok:!0,data:{alreadyDelivered:!0}};case"input_id_conflict":return{ok:!1,error:`input_id_conflict: input ${command.inputId} is held at revision ${result3.heldRevision}`}}}var HostSessionControl=class{constructor(session,socket,report){this.disposed=!1,this.session=session,this.socket=socket,this.report=report}async register(options){if(this.releaseActive(),this.disposed||this.socket===void 0)return{status:"unsupported",reason:"unsupported_mode"};let{session}=this,failing,scheduler=new WakeScheduler(async event=>{await session.extensionRunner.emit(event);let result3=await options.drain(event)??{admitted:[]};return failing=void 0,result3},error2=>{let reason=errorText5(error2);reason!==failing&&(failing=reason,this.report(`control drain failed: ${reason}`))}),wake=reason=>{scheduler.request(reason)},unsubscribeIdle=session.subscribe(event=>{event.type==="agent_idle"&&wake("idle")}),unsubscribeEmitted=session.externalAdmission.onEmitted(()=>wake("emitted")),inbox,registration={scheduler,release:()=>{unsubscribeIdle(),unsubscribeEmitted(),inbox?.stop(),scheduler.dispose()}};try{inbox=await watchInbox(options.inboxDir,()=>wake("inbox"),error2=>this.report(`control inbox watch failed: ${errorText5(error2)}`))}catch(error2){return registration.release(),{status:"failed",reason:errorText5(error2)}}return this.disposed?(registration.release(),{status:"unsupported",reason:"unsupported_mode"}):(this.releaseActive(),this.active=registration,wake("inbox"),inbox.armed.then(()=>wake("inbox")),{status:"registered",socket:this.socket,dispose:async()=>{this.active===registration&&this.releaseActive()}})}async wake(deliveryIds){let active=this.active;if(active!==void 0)return active.scheduler.request("command",deliveryIds);let ids=deliveryIds===void 0||deliveryIds.length===0?{}:{delivery_ids:deliveryIds};return await this.session.extensionRunner.emit({type:"session_control_wake",reason:"command",reasons:["command"],...ids}),{admitted:[]}}dispose(){this.disposed=!0,this.releaseActive()}releaseActive(){let active=this.active;this.active=void 0,active?.release()}};function errorText5(error2){return error2 instanceof Error?error2.message:String(error2)}function createRpcLoginPromptCallbacks(ui,signal){let dialogSignalFor=promptSignal=>promptSignal?AbortSignal.any([signal,promptSignal]):signal;return{async onPrompt(prompt){let dialogSignal2=dialogSignalFor(prompt.signal);if(dialogSignal2.aborted)throw new Error("Login cancelled");let value=await ui.input(prompt.message,prompt.placeholder,{signal:dialogSignal2,...prompt.type==="secret"&&ui.capabilities?.secretInput===!0?{secret:!0}:{}});if(dialogSignal2.aborted||value===void 0)throw new Error("Login cancelled");return value},async onSelect(prompt){let dialogSignal2=dialogSignalFor(prompt.signal);if(dialogSignal2.aborted)throw new Error("Login cancelled");let value=await ui.select(prompt.message,prompt.options.map(option=>option.label),{signal:dialogSignal2});if(dialogSignal2.aborted)throw new Error("Login cancelled");if(value!==void 0)return prompt.options.find(option=>option.label===value)?.id}}}async function answerMemoryReport(session){let source2=memoryReportSessionFor(session);if(source2===void 0)return{ok:!1,error:"memory_report_disabled: start the host with SENPI_MEMORY_REPORT=1"};let[outcome]=await writeMemoryReports([source2]);return outcome===void 0||!outcome.ok?{ok:!1,error:`memory_report_failed: ${outcome?.ok===!1?outcome.error:"no report written"}`}:{ok:!0,data:{path:outcome.path,...outcome.heapSnapshot===void 0?{}:{heapSnapshot:outcome.heapSnapshot}}}}function buildRpcCommands(input){return[...input.extensionCommands.map(command=>({...command,source:"extension",syntax:"slash"})),...input.promptTemplates.map(template=>({...template,source:"prompt",syntax:"slash"})),...input.skills.map(skill=>({...skill,name:`skill:${skill.name}`,source:"skill",syntax:"dollar"}))]}function buildRpcCommandsForSession(session){return buildRpcCommands({extensionCommands:session.extensionRunner.getRegisteredCommands().map(command=>({name:command.invocationName,description:command.description,sourceInfo:command.sourceInfo})),promptTemplates:session.promptTemplates,skills:session.resourceLoader.getSkills().skills})}function rpcCommandListDigest(commands){return JSON.stringify(commands)}function createCommandsChangedEvent(previousDigest,commands){if(!(previousDigest===void 0||previousDigest===rpcCommandListDigest(commands)))return{type:"commands_changed",commands}}var NOT_TASK_PARENT="task_parent_required: only the connection that owns this task child may pause or resume it for a run";async function runPauseForRun(session,command,taskParent){if(!taskParent)return{ok:!1,error:NOT_TASK_PARENT};let result3=await session.pauseForRun(command);return"refused"in result3?{ok:!1,error:"wrong_parent: this child is paused for another parent session"}:{ok:!0,data:{held:!0,childSeq:result3.childSeq}}}async function runResumeForRun(session,command,taskParent){if(!taskParent)return{ok:!1,error:NOT_TASK_PARENT};let result3=await session.resumeForRun(command);return result3.released?{ok:!0,data:{released:!0,otherHoldLive:result3.otherHoldLive,...result3.turnId===void 0?{}:{turnId:result3.turnId}}}:result3.reason==="wrong_parent"?{ok:!1,error:"wrong_parent: this child is paused for another parent session"}:{ok:!0,data:{released:!1,reason:result3.reason}}}function structuredLaneEnabled(){return compactUpdatesEnabled()}var SEEDS={blockSeeds:1},SeededBlockGate=class{constructor(){this.nextOffsets=new Map}accept(record10){if(record10.type==="message_block_state"||record10.type==="message_block_metadata")return this.control(record10,record10.type==="message_block_state"?record10.phase:void 0);if(record10.type==="message_tool_arguments_reset"){let accepted=this.control(record10);return accepted&&this.nextOffsets.set(record10.contentIndex,record10.rawArgumentPrefix.length),accepted}if(record10.type==="message_start"&&record10.message.role==="assistant"){let seeded2=toJsonEvent(record10,SEEDS);return this.blocks=seeded2&&new Map,this.nextOffsets.clear(),seeded2}if(record10.type==="message_end"&&record10.message.role==="assistant")return this.end(record10);if(record10.type!=="message_update")return toJsonEvent(record10,SEEDS);if(!this.blocks)return;let update2=record10.assistantMessageEvent;if(!("contentIndex"in update2)){let seeded2=toJsonEvent(record10,SEEDS),rewrittenFrom=getAssistantCapture(record10)?.rewrittenFrom;return seeded2&&rewrittenFrom!==void 0?{...seeded2,rewrittenFrom}:seeded2}let index=getAssistantCapture(record10)?.contentIndex??update2.contentIndex,starts=update2.type==="text_start"||update2.type==="thinking_start"||update2.type==="toolcall_start";if(starts&&this.nextOffsets.has(index)){this.blocks.set(index,"invalid");return}if(this.blocks.get(index)==="invalid"||!starts&&this.blocks.get(index)!=="open")return;let seeded;try{seeded=toJsonEvent(record10,SEEDS)}catch(error2){if(!(error2 instanceof SeedFrontierError))throw error2;this.blocks.set(index,"invalid");return}let capture=getAssistantCapture(record10);if(starts&&seeded&&capture?.nextOffset!==void 0&&this.nextOffsets.set(index,capture.nextOffset),"delta"in update2&&seeded){if(capture?.offset!==this.nextOffsets.get(index)||capture?.offset===void 0){this.blocks.set(index,"invalid");return}this.nextOffsets.set(index,capture.offset+update2.delta.length)}let ends=update2.type==="text_end"||update2.type==="thinking_end"||update2.type==="toolcall_end";return this.blocks.set(index,seeded?ends?"ended":"open":"invalid"),seeded}control(record10,phase){let state3=this.blocks?.get(record10.contentIndex);if(!(!this.blocks||state3==="invalid")){if(phase==="insert")this.blocks.set(record10.contentIndex,"open");else{if(state3===void 0||phase==="end"&&state3!=="open")return;phase==="end"&&this.blocks.set(record10.contentIndex,"ended")}return record10}}end(record10){let capture=getAssistantCapture(record10),rewrittenFrom=capture?.message===void 0?0:capture.rewrittenFrom??Number.POSITIVE_INFINITY,invalidatedBlocks=[...this.blocks??[]].flatMap(([index,state3])=>state3==="ended"&&index<rewrittenFrom?[]:[index]);this.blocks=void 0,this.nextOffsets.clear();let seeded=toJsonEvent(record10,SEEDS)??record10;return invalidatedBlocks.length===0?seeded:{...seeded,invalidatedBlocks:invalidatedBlocks.sort((a,b)=>a-b)}}};function subscribeStructuredSessionRecords(session,output,failed){let gate=new SeededBlockGate;return subscribeSessionRecords(session,output,void 0,listener=>session.subscribeStructured(record10=>{try{let accepted=gate.accept(record10);accepted&&listener(carryRecovery(record10,accepted))}catch(cause){failed(cause)}},failed))}var HOST_ANSWER_TIMEOUT_MS=6e4,refused=(reason,detail)=>({status:"refused",reason,detail}),record9=value=>typeof value=="object"&&value!==null&&!Array.isArray(value)?{...value}:void 0;function parseTarget2(value){let fields=record9(value);if(!(typeof fields?.name!="string"||fields.name===""||typeof fields.online!="boolean"))return{name:fields.name,online:fields.online,...typeof fields.capacity=="string"?{capacity:fields.capacity}:{},...typeof fields.aboutToSleep=="boolean"?{aboutToSleep:fields.aboutToSleep}:{}}}var RpcSessionRelocation=class{constructor(deps){this.pending=new Map,this.requesting=!1,this.deps=deps,this.unsubscribe=deps.session.subscribe(event=>{event.type==="agent_end"&&deps.session.currentAbortSource==="user"&&this.scheduled!==void 0&&(this.scheduled={...this.scheduled,dropReason:"aborted"}),event.type==="agent_settled"&&this.scheduled?.dropReason!==void 0?this.dropScheduled(this.scheduled.dropReason):event.type==="agent_idle"&&this.scheduled!==void 0&&this.scheduled.dropReason===void 0&&this.announceWhenReleasable()})}offered(){return this.deps.channel.offerer()!==void 0}async targets(signal){let connection=this.deps.channel.offerer();if(connection===void 0)return RELOCATION_NOT_OFFERED;let answer3=await this.ask({method:"list_relocation_targets"},connection,signal);if("status"in answer3)return answer3;let raw=record9(answer3.data)?.targets,targets2=Array.isArray(raw)?raw.map(parseTarget2):void 0;return targets2===void 0||targets2.some(target=>target===void 0)?refused("invalid_host_answer","the app sent a list of computers this session cannot read"):{status:"listed",targets:targets2.filter(target=>target!==void 0)}}async request(request2,signal){let connection=this.deps.channel.offerer();if(connection===void 0)return RELOCATION_NOT_OFFERED;if(this.deps.session.sessionFile===void 0)return{status:"unavailable",reason:"not_releasable",detail:"this session is not saved to a file"};if(this.scheduled!==void 0||this.requesting)return refused("already_scheduled",`a move to ${this.scheduled?.target??"another computer"} is already set for the end of this turn`);this.requesting=!0;try{let ask={method:"relocate_session",target:request2.target,reason:request2.reason},answer3=await this.ask(ask,connection,signal);return"status"in answer3?answer3:this.settleRequest(request2,record9(answer3.data),connection)}finally{this.requesting=!1}}respond(frame){let pending=this.pending.get(frame.id);return pending===void 0?"unknown":this.deps.channel.current()!==pending.connection?"not_offering_connection":(pending.finish(typeof frame.error=="string"?refused("host_error",frame.error):{data:frame.data}),"answered")}connectionDetached(connectionId){this.scheduled?.connection===connectionId&&this.scheduled.dropReason===void 0&&this.dropScheduled("disconnected");for(let pending of[...this.pending.values()])pending.connection===connectionId&&pending.finish(refused("app_disconnected","the app that was asked left this session"))}dispose(){this.unsubscribe(),this.scheduled=void 0;for(let{finish}of[...this.pending.values()])finish(refused("session_closed","this session was closed"))}dropScheduled(reason){let scheduled=this.scheduled;if(scheduled===void 0)return;this.scheduled=void 0;let{moveId,target}=scheduled;this.deps.session.sendCustomMessage({customType:"session_relocation",content:`The session will not continue on ${target} (${reason}). The session stays on this computer; keep working here.`,display:!1,details:{status:"dropped",reason,moveId,target}},{triggerTurn:!1})}settleRequest(request2,data,connection){if(data?.accepted===!1)return refused(typeof data.reason=="string"&&data.reason!==""?data.reason:"declined",typeof data.detail=="string"&&data.detail!==""?data.detail:"the app declined the move");if(data?.accepted!==!0||!isPlainId(data.moveId))return refused("invalid_host_answer","the app accepted the move without a usable move id");let target=typeof data.target=="string"&&data.target!==""?data.target:request2.target;return this.scheduled={moveId:data.moveId,target,reason:request2.reason,connection},{status:"scheduled",target,moveId:data.moveId}}async announceWhenReleasable(){for(let calls=this.deps.pendingPrompts();calls.length>0;calls=this.deps.pendingPrompts())await Promise.allSettled(calls);let due=this.scheduled;if(due===void 0||this.deps.session.isStreaming)return;if(this.deps.channel.offerer()!==due.connection){this.dropScheduled("withdrawn");return}this.scheduled=void 0;let{connection,moveId,target,reason}=due;this.deps.channel.send(connection,{type:"relocation_due",moveId,target,reason},"event")}ask(fields,connection,signal){if(signal?.aborted)return Promise.resolve(refused("cancelled","the request was cancelled"));let id=`hr_${crypto.randomUUID()}`;return new Promise(resolve56=>{let finish=answer3=>{clearTimeout(timer),signal?.removeEventListener("abort",onAbort),this.pending.delete(id),resolve56(answer3)},onAbort=()=>finish(refused("cancelled","the request was cancelled")),timer=setTimeout(()=>finish(refused("no_answer","the app did not answer in time")),HOST_ANSWER_TIMEOUT_MS);this.pending.set(id,{connection,finish}),signal?.addEventListener("abort",onAbort,{once:!0}),this.deps.channel.send(connection,{type:"host_request",id,...fields},"request")})}};var SOLE_CONNECTION="sole";function relocationChannel(options){let{clientInfo}=options;if(clientInfo===void 0)return{offerer:()=>options.capabilities()?.includes(SESSION_RELOCATION_CAPABILITY)?SOLE_CONNECTION:void 0,current:()=>SOLE_CONNECTION,send:(_connection,record10,kind)=>kind==="event"?options.outputEvent(record10):options.output(record10)};let{relocationConnection,deliverTo}=clientInfo;return{offerer:()=>deliverTo===void 0?void 0:relocationConnection?.(),current:()=>clientInfo.connectionId(),send:(connection,record10)=>deliverTo?.(connection,()=>options.output(record10))}}function answerHostResponse(frame,respond){let reply={id:frame.id,type:"response",command:"host_response"};if(typeof frame.id!="string"||frame.id==="")return{...reply,success:!1,error:"invalid_host_response"};let outcome=respond?.(frame)??"unknown";return outcome==="answered"?{...reply,success:!0}:{...reply,success:!1,error:outcome==="unknown"?"unknown_host_request":outcome}}function isHostResponse(value){return typeof value=="object"&&value!==null&&"type"in value&&value.type==="host_response"}function dialogCall(opts2){return opts2?.toolCallId===void 0?{}:{toolCallId:opts2.toolCallId,...opts2.parentToolCallId===void 0?{}:{parentToolCallId:opts2.parentToolCallId}}}function loadedExtensionName(path16){let synthetic=/^<(?:builtin|inline):([^>]+)>$/.exec(path16);if(synthetic)return synthetic[1];let withoutExtension=basename38(path16,extname6(path16));if(withoutExtension!=="index")return withoutExtension;let parent=dirname69(path16),parentName=basename38(parent);return parentName==="src"||parentName==="dist"?basename38(dirname69(parent)):parentName}function loadedExtensions(session){return session.resourceLoader.getExtensions().extensions.map(extension=>({name:loadedExtensionName(extension.path),path:extension.path,sourceInfo:extension.sourceInfo,enabled:!0}))}function loadedMcpStatus(server){return server.status!==void 0?server.status:server.serverInfo!==null?"connected":server.authStatus==="notLoggedIn"?"needs_auth":"enabled"}function loadedMcpServers(snapshot2){return snapshot2.servers.map(server=>({name:server.name,toolCount:server.tools.length,status:loadedMcpStatus(server),authStatus:server.authStatus,...server.lastError===void 0?{}:{lastError:server.lastError}}))}var MCP_STARTUP_PENDING_DIGEST="mcp-startup-pending";function loadedSurfacesFingerprint(session,extensions,mcpServers){return JSON.stringify({skills:session.resourceLoader.getSkills().skills.map(skill=>({name:skill.name,path:skill.filePath,sourceInfo:skill.sourceInfo,enabled:!skill.disableModelInvocation})),extensions,mcpServers})}function findToolResultMedia(session,toolCallId,contentIndex){let fromContent=content=>{if(!Array.isArray(content))return;let block=content[contentIndex];return block?.type==="image"?block:void 0},matches2=message=>{let candidate=message;return candidate?.role==="toolResult"&&candidate.toolCallId===toolCallId};for(let entry2 of session.sessionManager.getEntries()){if(entry2.type!=="message"||!matches2(entry2.message))continue;let found=fromContent(entry2.message.content);if(found)return found}for(let message of session.messages){if(!matches2(message))continue;let found=fromContent(message.content);if(found)return found}}function createRpcConnectionHandler(runtimeHost,sink,options={}){let clientCapabilities=options.capabilities,unsubscribeSecurityNotices,detachGrantPresentation,grantPresentationAbort=new AbortController,securityBoundByHost=!1,connectionRoles=options.connectionRoles??new ConnectionRoles,currentConnectionId=()=>roleConnection(options.clientInfo?.connectionId()),hasRole=role=>connectionRoles.has(currentConnectionId(),role),routingSessionId=options.sessionId,replacementIssuedHere=!1,session=runtimeHost.session,rpcOwners=new ExtensionOwnerLifetime(options.sessionId===void 0,options.rpcOwner,options.retireRpcBinding),sessionControl,relocation,promptCalls=new Set,turnRequested=!1,unsubscribe,unsubscribeStructured,unsubscribeBackpressure,unsubscribeLoadedSurfaces,unsubscribeExtensionEvents,mcpWireStatus={servers:[]},lastAbortSource,loadedSurfacesDigest,rpcCommandsDigest,suppressLoadedSurfaceEvents=!1,mcpStartupSettledPending=!1,eventOutput=sink.writeRecord?void 0:createRpcEventOutputBuffer(sink.writeRaw,options.eventFlushScheduler),effectContext=()=>({session,by:{connectionId:options.clientInfo?.connectionId()??"local"},...routingSessionId===void 0?{}:{sessionId:routingSessionId}}),tagSessionRecord=value=>routingSessionId===void 0?value:carryRecovery(value,{...value,sessionId:routingSessionId}),output=obj=>{let record10=tagSessionRecord(obj);sink.writeRecord?sink.writeRecord(record10):eventOutput?.writeImmediate(record10)},outputEvent=event=>{let record10=tagSessionRecord(event);sink.writeRecord?sink.writeRecord(record10):eventOutput?.enqueueEvent(record10)},currentLoadedSurfaces=()=>{let extensions=loadedExtensions(session),mcpServers=loadedMcpServers(mcpWireStatus);return{data:{extensions,mcpServers},digest:loadedSurfacesFingerprint(session,extensions,mcpServers)}},recordLoadedSurfaces=emitChange=>{let current=currentLoadedSurfaces(),previous=loadedSurfacesDigest,changed=previous!==void 0&&previous!==current.digest;return loadedSurfacesDigest=current.digest,emitChange&&changed&&!suppressLoadedSurfaceEvents&&emitLoadedSurfacesChanged(previous,current.digest),current},emitLoadedSurfacesChanged=(previous,digest3)=>{options.publishLoadedSurfacesChanged?options.publishLoadedSurfacesChanged(previous,digest3):outputEvent({type:"loaded_surfaces_changed"})},announceMcpStartupSettled=()=>{if(suppressLoadedSurfaceEvents){mcpStartupSettledPending=!0;return}mcpStartupSettledPending=!1,loadedSurfacesDigest=currentLoadedSurfaces().digest,emitLoadedSurfacesChanged(MCP_STARTUP_PENDING_DIGEST,loadedSurfacesDigest)},requestMcpWireStatus=async()=>{let response,request2={sessionId:session.sessionId,respond(snapshot2){response??=snapshot2}};session.resourceLoader.emitExtensionEvent?.(MCP_CONTROL_INVENTORY_REQUEST_EVENT,request2),mcpWireStatus=response===void 0?{servers:[]}:await response},subscribeLoadedSurfaceEvents=()=>{unsubscribeLoadedSurfaces?.(),unsubscribeLoadedSurfaces=session.resourceLoader.onExtensionEvent?.(MCP_CONTROL_INVENTORY_CHANGED_EVENT,data=>{!isMcpControlInventoryChanged(data)||data.sessionId!==session.sessionId||(mcpWireStatus=data.snapshot,data.startupSettled===!0?announceMcpStartupSettled():suppressLoadedSurfaceEvents||recordLoadedSurfaces(!0))})},unsubscribeProviderAccountEvents=subscribeProviderAccountEvents(event=>{if(event.type==="accounts_changed"){outputEvent({type:"auth_accounts_changed",provider:event.provider});return}outputEvent({type:"account_failover",provider:event.provider,from:event.from,to:event.to,reason:event.reason})}),waitForRpcBackpressure=async()=>{eventOutput?.flushEvents(),await sink.waitForBackpressure()},success=(id,command,data)=>data===void 0?{id,type:"response",command,success:!0}:{id,type:"response",command,success:!0,data},error2=(id,command,message,errorCode4,errorData)=>{let details=errorData===void 0&&(command==="edit_user_message"||command==="navigate_tree")?{leafId:session.sessionManager.getLeafId()}:errorData;return{id,type:"response",command,success:!1,error:message,...errorCode4?{errorCode:errorCode4}:{},...details===void 0?{}:{errorData:details}}},uiRequestChanged=change=>{session.refreshLifecycle(),change&&routingSessionId!==void 0&&output(change)},pendingExtensionRequests=new SessionExtensionUiRequests(uiRequestChanged),grantRequests=new Map;sessionDialogRequests.set(session,pendingExtensionRequests);let questions=new ConnectionQuestionBridge(output,uiRequestChanged,()=>options.clientInfo?.connectionId()),secretHandshake=!1,secretOwners=new Map,secretCapable=connection=>connectionRoles.has(connection,INTERACTIVE_USER_CAPABILITY)&&(connection===void 0?secretHandshake&&clientCapabilities?.includes("secret_input_v1")===!0:options.clientInfo?.hasCapability?.(connection,"secret_input_v1")===!0),secretRoute=options.secretInputRoute??{presenter:id=>secretOwners.get(id)?.connection,select:(id,cancel3)=>{let connection=options.clientInfo?.connectionId();if(!secretCapable(connection))return"client_unsupported";secretOwners.set(id,{connection,cancel:cancel3})},accepts:id=>secretOwners.has(id)&&secretOwners.get(id)?.connection===options.clientInfo?.connectionId()&&secretCapable(secretOwners.get(id)?.connection),available:id=>secretOwners.has(id)&&secretCapable(secretOwners.get(id)?.connection),send:(_id,record10)=>output(record10),settled:id=>{let owner=secretOwners.get(id);owner&&(owner.cancel=void 0)},forget:id=>{secretOwners.delete(id)}},secretInputs=new SecretInputRequests(secretRoute,()=>session.admitHumanAnswer()),shutdownRequested=!1,activeLogins=new Map;function createDialogPromise(opts2,defaultValue,request2,parseResponse){if(opts2?.signal?.aborted)return Promise.resolve(defaultValue);let id=crypto2.randomUUID();return new Promise((resolve56,reject)=>{let timeoutId,cleanup=()=>{timeoutId&&clearTimeout(timeoutId),opts2?.signal?.removeEventListener("abort",onAbort),pendingExtensionRequests.delete(id),grantRequests.delete(id)&&options.grantDialogSettled?.(id)},onAbort=()=>{cleanup(),resolve56(defaultValue)};opts2?.signal?.addEventListener("abort",onAbort,{once:!0}),opts2?.timeout&&(timeoutId=setTimeout(()=>{cleanup(),resolve56(defaultValue)},opts2.timeout)),pendingExtensionRequests.set(id,{frame:{type:"extension_ui_request",id,...request2},resolve:response=>{cleanup(),resolve56(parseResponse(response))},reject}),request2.grantSelect===!0&&grantRequests.set(id,options.clientInfo?.connectionId()),output({type:"extension_ui_request",id,...request2})})}let selectGrantDialog=(title,choices,opts2)=>createDialogPromise(opts2,void 0,{method:"select",title,options:choices,timeout:opts2?.timeout,grantSelect:!0},response=>"cancelled"in response&&response.cancelled?void 0:"value"in response?response.value:void 0),createExtensionUIContext=()=>({capabilities:{secretInput:!0},question:(request2,opts2)=>clientCapabilities?.includes(QUESTION_CAPABILITY)?questions.ask(request2,opts2):degradeQuestion(createExtensionUIContext(),request2,opts2),select:(title,options2,opts2)=>createDialogPromise(opts2,void 0,{method:"select",title,options:options2,timeout:opts2?.timeout,...dialogCall(opts2)},r=>"cancelled"in r&&r.cancelled?void 0:"value"in r?r.value:void 0),confirm:(title,message,opts2)=>createDialogPromise(opts2,!1,{method:"confirm",title,message,timeout:opts2?.timeout},r=>"cancelled"in r&&r.cancelled?!1:"confirmed"in r?r.confirmed:!1),input:(title,placeholder,opts2)=>opts2?.secret?secretInputs.input(title,placeholder,opts2):createDialogPromise(opts2,void 0,{method:"input",title,placeholder,timeout:opts2?.timeout,...dialogCall(opts2)},r=>"cancelled"in r&&r.cancelled?void 0:"value"in r?r.value:void 0),notify(message,type2){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"notify",message,notifyType:type2})},onTerminalInput(){return()=>{}},setStatus(key,text4){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setStatus",statusKey:key,statusText:text4})},setSubagentCost(costUsd){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setSubagentCost",costUsd:costUsd!==void 0&&Number.isFinite(costUsd)&&costUsd>=0?costUsd:void 0})},setWorkingMessage(_message){},setWorkingVisible(_visible){},setWorkingIndicator(_options){},setHiddenThinkingLabel(_label){},setWidget(key,content,options2){(content===void 0||Array.isArray(content))&&output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setWidget",widgetKey:key,widgetLines:content,widgetPlacement:options2?.placement,...content!==void 0&&options2?.actions!==void 0&&options2.actions.length>0?{widgetActions:options2.actions.map(({label:label3,command})=>({label:label3,command}))}:{}})},setFooter(_factory){},setHeader(_factory){},setTitle(title){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"setTitle",title})},async custom(){let request2=buildCustomUnsupportedRequest(clientCapabilities,DEFAULT_CUSTOM_EXTENSION_LABEL);request2&&output(request2)},pasteToEditor(text4){this.setEditorText(text4)},setEditorText(text4){output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"set_editor_text",text:text4})},getEditorText(){return""},async editor(title,prefill){let id=crypto2.randomUUID();return new Promise((resolve56,reject)=>{pendingExtensionRequests.set(id,{frame:{type:"extension_ui_request",id,method:"editor",title,prefill},resolve:response=>{"cancelled"in response&&response.cancelled?resolve56(void 0):"value"in response?resolve56(response.value):resolve56(void 0)},reject}),output({type:"extension_ui_request",id,method:"editor",title,prefill})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return theme},getAllThemes(){return[]},getTheme(_name){},setTheme(_theme){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(_expanded){}}),refreshLoadedSurfacesAfter=async(operation,resetMcp)=>{let previousDigest=loadedSurfacesDigest,wasSuppressed=suppressLoadedSurfaceEvents;suppressLoadedSurfaceEvents=!0,resetMcp&&(mcpWireStatus={servers:[]});let commandsChanged;try{await operation(),await requestMcpWireStatus(),loadedSurfacesDigest=currentLoadedSurfaces().digest;let commands=buildRpcCommandsForSession(session);commandsChanged=createCommandsChangedEvent(rpcCommandsDigest,commands),rpcCommandsDigest=rpcCommandListDigest(commands)}finally{suppressLoadedSurfaceEvents=wasSuppressed}!wasSuppressed&&commandsChanged&&outputEvent(commandsChanged),!wasSuppressed&&mcpStartupSettledPending?announceMcpStartupSettled():!wasSuppressed&&previousDigest!==void 0&&previousDigest!==loadedSurfacesDigest&&emitLoadedSurfacesChanged(previousDigest,loadedSurfacesDigest)};runtimeHost.setRebindSession(async()=>{await rebindSession(!0)});let rebindAfterLocalReplacement=async()=>{replacementIssuedHere=!0;try{await rebindSession()}finally{replacementIssuedHere=!1}},refreshGrantPresentation=()=>{if(grantPresentationAbort.abort(),detachGrantPresentation?.(),detachGrantPresentation=void 0,grantPresentationAbort=new AbortController,securityBoundByHost||!clientCapabilities?.includes("grant_select"))return;let signal=grantPresentationAbort.signal;detachGrantPresentation=attachMcpGrantPresentation(session.sessionId,(title,choices,opts2)=>selectGrantDialog(title,choices,{...opts2,signal:opts2?.signal===void 0?signal:AbortSignal.any([opts2.signal,signal])}))},subscribeExtensionEvents=()=>{unsubscribeExtensionEvents=clientCapabilities?.includes(EXTENSION_EVENTS_CAPABILITY)?session.extensionRunner.onRpcEvent(({name,data})=>{outputEvent({type:"extension_event",name,data})}):void 0},replaceClientCapabilities=next=>{let hadEvents=clientCapabilities?.includes(EXTENSION_EVENTS_CAPABILITY)??!1,hadQuestion=clientCapabilities?.includes(QUESTION_CAPABILITY)??!1;clientCapabilities=next,hadQuestion&&!next.includes(QUESTION_CAPABILITY)&&questions.cancelAll(),hadEvents!==next.includes(EXTENSION_EVENTS_CAPABILITY)&&(unsubscribeExtensionEvents?.(),subscribeExtensionEvents())},rebindSession=async(deferRefresh=!1)=>{secretInputs.close(),rpcOwners.retireBinding(),unbindMcpForms?.(),unbindMcpForms=void 0,unsubscribeSecurityNotices?.(),unsubscribeLoadedSurfaces?.(),unsubscribeExtensionEvents?.();let replacedSession=session!==runtimeHost.session;session=runtimeHost.session;let hostedSecurity=options.bindSecurityPresentation?.(session,{...createExtensionUIContext(),select:selectGrantDialog});securityBoundByHost=hostedSecurity!==void 0,refreshGrantPresentation(),unsubscribeSecurityNotices=hostedSecurity??session.securityNotices?.subscribe(snapshot2=>{for(let notice2 of snapshot2.notices)output({type:"extension_ui_request",id:crypto2.randomUUID(),method:"notify",notifyType:"warning",message:notice2.message})}),sessionQuestionBridges.set(session,questions),sessionDialogRequests.set(session,pendingExtensionRequests),sessionControl?.dispose(),sessionControl=new HostSessionControl(session,runtimeHost.launchProfile?.sessionContext?.host_socket,line=>{process.stderr.write(`senpi rpc session ${routingSessionId??"classic"}: ${line}
|
|
2356
2356
|
`)}),session.setControlEndpointHost?.(sessionControl),relocation?.dispose(),relocation=routingSessionId===void 0?void 0:new RpcSessionRelocation({session,pendingPrompts:()=>[...promptCalls],channel:relocationChannel({capabilities:()=>clientCapabilities,clientInfo:options.clientInfo,output,outputEvent})}),session.setRelocationHost?.(relocation),replacedSession&&(lastAbortSource=void 0,(routingSessionId!==void 0||!replacementIssuedHere)&&outputEvent({type:"session_replaced",durableSessionId:session.sessionId,sessionFile:session.sessionFile,cwd:session.sessionManager.getCwd(),sessionName:session.sessionName})),subscribeExtensionEvents(),subscribeLoadedSurfaceEvents(),installSessionSubscriptions();let extensionUi=createExtensionUIContext();unbindMcpForms=await options.bindMcpForms?.(session,extensionUi);let refresh=refreshLoadedSurfacesAfter(()=>session.bindExtensions({uiContext:extensionUi,mode:"rpc",commandContextActions:{waitForIdle:()=>session.agent.waitForIdle(),newSession:async options2=>runtimeHost.newSession(options2),fork:async(entryId,forkOptions)=>({cancelled:(await runtimeHost.fork(entryId,forkOptions)).cancelled}),navigateTree:async(targetId,options2)=>({cancelled:(await session.navigateTree(targetId,{summarize:options2?.summarize,customInstructions:options2?.customInstructions,replaceInstructions:options2?.replaceInstructions,label:options2?.label,expectedLeafId:options2?.expectedLeafId})).cancelled}),editAssistantMessage:async(entryId,text4,options2)=>{let result3=await session.editAssistantMessage(entryId,text4,{summarize:options2?.summarize,customInstructions:options2?.customInstructions,expectedLeafId:options2?.expectedLeafId});return{cancelled:result3.cancelled,unchanged:result3.unchanged,entryId:result3.entryId}},editUserMessage:async(entryId,text4,options2)=>{let result3=await session.editUserMessage(entryId,text4,{summarize:options2?.summarize,customInstructions:options2?.customInstructions,expectedLeafId:options2?.expectedLeafId});return{cancelled:result3.cancelled,unchanged:result3.unchanged,entryId:result3.entryId}},switchSession:async(sessionPath,options2)=>runtimeHost.switchSession(sessionPath,options2),reload:async()=>{await refreshLoadedSurfacesAfter(async()=>{await session.reload()},!1)}},shutdownHandler:()=>{options.shutdownHandler?options.shutdownHandler():shutdownRequested=!0},onError:err=>{output({type:"extension_error",extensionPath:err.extensionPath,event:err.event,error:err.error})}}),!0);function installSessionSubscriptions(){unsubscribe?.(),unsubscribeBackpressure?.(),unsubscribeStructured?.(),unsubscribe=unsubscribeBackpressure=void 0,unsubscribeStructured=sink.writeStructured?subscribeStructuredSessionRecords(session,record10=>sink.writeStructured?.(tagSessionRecord(record10)),cause=>sink.structuredFailed?.(cause)):void 0,unsubscribe=subscribeSessionRecords(session,outputEvent,abortSource=>{lastAbortSource=abortSource}),unsubscribeBackpressure=session.agent.subscribe(async()=>{await waitForRpcBackpressure()})}if(EffectLedger.forSession(session),deferRefresh){refresh.then(()=>session.releaseSettledSessionMemory(),cause=>{outputEvent({type:"rpc_error",error:String(cause)})});return}await refresh,await ClientAdmissions.forSession(session).ready,session.releaseSettledSessionMemory()},startLogin=async provider=>{activeLogins.get(provider)?.abort();let controller=new AbortController,settled2=new AbortController,loginSignal=AbortSignal.any([controller.signal,settled2.signal]);activeLogins.set(provider,controller);let authStorage=session.modelRegistry.authStorage;authStorage.takeReplacement(provider);try{await authStorage.login(provider,{onAuth:info=>{outputEvent({type:"auth_login_url",provider,url:info.url})},onDeviceCode:info=>{outputEvent({type:"auth_login_url",provider,url:info.verificationUri})},...createRpcLoginPromptCallbacks(createExtensionUIContext(),loginSignal),onProgress:message=>{outputEvent({type:"auth_login_progress",provider,text:message})},signal:controller.signal}),session.modelRegistry.refresh(),emitProviderAccountsChanged(provider,"login");let replacement=authStorage.takeReplacement(provider),signedIn=takeClaudeCliLoginOutcome(controller.signal);outputEvent({type:"auth_login_end",provider,success:!0,...replacement,...signedIn})}catch(loginError){let message=loginError instanceof Error?loginError.message:String(loginError);outputEvent({type:"auth_login_end",provider,success:!1,error:message})}finally{settled2.abort(),activeLogins.get(provider)===controller&&activeLogins.delete(provider)}},fastModeContext=()=>({cwd:session.cwd,agentDir:session.agentDir,model:session.model,modelRegistry:session.modelRegistry,serviceTier:session.serviceTier,isProjectTrusted:()=>session.settingsManager.isProjectTrusted(),notify:()=>{},setSessionModel:async model=>session.modelRuntime.hasConfiguredAuth(model.provider)?(await session.setSessionModel(model,{source:"rpc",actor:"set_fast_mode"}),!0):!1,setSessionFastMode:enabled=>session.setSessionFastMode(enabled)}),handleCommand=async(command,requestContext)=>{let id=command.id;switch(command.type){case"get_protocol_info":return{id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities:[...new Set(["multi_session","snapshot_cursor","ui_answer_ledger","session_lifecycle",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,"secret_input_v1",DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,STEER_WHEN_IDLE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,EVAL_CELLS_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,PROVIDER_ACCOUNT_TEST_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,TOOL_BARRIER_CAPABILITY,USER_ACTIVITY_CAPABILITY,RESUME_SESSION_CAPABILITY,ENTRIES_TAIL_CAPABILITY,...options.retryFallbackCommand?[RETRY_FALLBACK_COMMAND_CAPABILITY]:[],...options.toolRuntime?toolRuntimeCapabilities(options.toolRuntime):[],...advertisedCompactCapabilities(options.capabilities??[],!1).filter(capability=>capability!==SESSION_HELD_CAPABILITY&&!isHostOwnedToolRuntimeCapability(capability))])],mode:"classic",...protocolIdentity()}};case"open_session":return error2(id,"open_session","multi_session_disabled");case"prompt":{if(holdAutomaticInput(session,command,hasRole(INTERACTIVE_USER_CAPABILITY)))return success(id,"prompt",{disposition:"handled",heldAsNotice:!0});turnRequested=!0;let admission=handleClientInput(session,command,{output,promptCalls},{interactiveUser:hasRole(INTERACTIVE_USER_CAPABILITY)});promptCalls.add(admission),admission.finally(()=>promptCalls.delete(admission));return}case"append_user_message":{let content=command.content,message=typeof content=="string"?{role:"user",content,timestamp:Date.now()}:{role:"user",content,timestamp:Date.now()};return session.sessionManager.appendMessage(message),session.agent.state.messages=session.sessionManager.buildSessionContext().messages,success(id,"append_user_message")}case"append_session_entry":return session.appendSessionEntry(command.entry),success(id,"append_session_entry");case"continue_from_leaf":{turnRequested=!0;try{return await session.continueFromLeaf(),success(id,"continue_from_leaf")}catch(err){if(err instanceof ContinueFromLeafError)return error2(id,command.type,err.message,err.code);throw err}}case"resume_session":{turnRequested=!0;let{answer:answer3,settled:settled2}=await session.beginResume({expectedSeq:command.expectedSeq,mode:command.mode,message:command.message,effectId:command.effectId});return promptCalls.add(settled2),settled2.then(()=>promptCalls.delete(settled2),err=>{promptCalls.delete(settled2),output({type:"extension_error",extensionPath:"runtime",event:"resume_session",error:err instanceof Error?err.message:String(err)})}),success(id,"resume_session",answer3)}case"send_custom_message":return command.triggerTurn===!0&&(turnRequested=!0),await session.sendCustomMessage({customType:command.customType,content:command.content,display:command.display,details:command.details},{triggerTurn:command.triggerTurn,deliverAs:command.deliverAs}),success(id,"send_custom_message");case"steer":case"follow_up":{if(holdAutomaticInput(session,command,hasRole(INTERACTIVE_USER_CAPABILITY)))return success(id,command.type,{disposition:"handled",heldAsNotice:!0});turnRequested=!0,await handleClientInput(session,command,{output,promptCalls},{interactiveUser:hasRole(INTERACTIVE_USER_CAPABILITY)});return}case"abort":return command.intent==="stop"&&!hasRole(INTERACTIVE_USER_CAPABILITY)?error2(id,"abort","stop_requires_interactive_client: declare interactive_user with set_client_info first"):(secretInputs.cancelAll(),runAbort(effectContext(),command,()=>(command.intent==="stop"?session.stop():session.abort()).catch(cause=>{outputEvent({type:"rpc_error",error:String(cause)})})));case"interrupt":if(command.intent==="stop"&&!hasRole(INTERACTIVE_USER_CAPABILITY))return error2(id,"interrupt","stop_requires_interactive_client: declare interactive_user with set_client_info first");if(command.intent==="stop"){let stopped=await interruptRunningTurn(session,void 0,()=>(ClientAdmissions.forSession(session).noteAbort(effectContext().by),session.stop()));return stopped.interrupted||await session.stop(),success(id,"interrupt",stopped)}return success(id,"interrupt",await interruptRunningTurn(session,command.turnId,()=>(ClientAdmissions.forSession(session).noteAbort(effectContext().by),session.abort())));case"hold_input":{let answer3=runHoldInput(session,command,{interactiveUser:hasRole(INTERACTIVE_USER_CAPABILITY),taskParent:hasRole(TASK_PARENT_CAPABILITY)});return answer3.ok?success(id,"hold_input",answer3.data):error2(id,"hold_input",answer3.error)}case"pause_for_run":{let answer3=await runPauseForRun(session,command,hasRole(TASK_PARENT_CAPABILITY));return answer3.ok?success(id,"pause_for_run",answer3.data):error2(id,"pause_for_run",answer3.error)}case"resume_for_run":{let answer3=await runResumeForRun(session,command,hasRole(TASK_PARENT_CAPABILITY));return answer3.ok?success(id,"resume_for_run",answer3.data):error2(id,"resume_for_run",answer3.error)}case"withdraw_held_input":return hasRole(INTERACTIVE_USER_CAPABILITY)?success(id,"withdraw_held_input",{withdrawn:session.withdrawHeldInput(command.inputId)}):error2(id,"withdraw_held_input","hold_input_requires_interactive_client");case"abort_compaction":return session.abortCompaction(),success(id,"abort_compaction");case"reload":{secretInputs.close();let result3=await session.reload();return success(id,"reload",result3)}case"check_reload_veto":return success(id,"check_reload_veto",await session.checkReloadVeto());case"dequeue_message":case"edit_queued_message":return runQueuedInputChange(effectContext(),command);case"clear_queue":{ClientAdmissions.clearQueuedFor(session);let cleared=session.clearQueue({abortWillFollow:command.abortWillFollow??!1});return await session.whenQueueClearRecorded(),success(id,"clear_queue",{steering:cleared.steering,followUp:cleared.followUp,ordered:[...cleared.ordered]})}case"get_steering_messages":return success(id,"get_steering_messages",{messages:[...session.getSteeringMessages()],ordered:session.getQueuedInputs().filter(input=>input.mode==="steer").map(clientFacingIdentity)});case"get_follow_up_messages":return success(id,"get_follow_up_messages",{messages:[...session.getFollowUpMessages()],ordered:session.getQueuedInputs().filter(input=>input.mode==="followUp").map(clientFacingIdentity)});case"abort_branch_summary":return session.abortBranchSummary(),success(id,"abort_branch_summary");case"wake":{let deliveryIds=Array.isArray(command.delivery_ids)?command.delivery_ids.filter(entry2=>typeof entry2=="string"):void 0,result3=await sessionControl?.wake(deliveryIds)??{};return success(id,"wake",{admitted:result3.admitted??[]})}case"new_session":{let options2=command.parentSession?{parentSession:command.parentSession}:void 0,result3=await runtimeHost.newSession(options2);return routingSessionId===void 0&&!result3.cancelled&&session!==runtimeHost.session&&await rebindAfterLocalReplacement(),success(id,"new_session",result3)}case"set_client_info":{let next=sessionDeclaration(options,command,clientCapabilities,caps=>connectionRoles.declare(currentConnectionId(),caps),replaceClientCapabilities);return next.refusal?error2(id,"set_client_info",next.refusal):(clientCapabilities=next.capabilities,command.capabilities!==void 0&&(secretHandshake=!0,secretRoute.handshake?.(command.capabilities),secretInputs.recheck()),next.grantChanged&&refreshGrantPresentation(),success(id,"set_client_info"))}case"get_snapshot":{let snapshot2=getSnapshot(session,command,{lastAbortSource,enqueue:markerId=>{routingSessionId!==void 0&&output({type:"snapshot_marker",markerId})}});return"error"in snapshot2?error2(id,"get_snapshot",snapshot2.error,RPC_ERROR_INVALID_ARGUMENT):success(id,"get_snapshot",snapshot2.data)}case"get_state":return success(id,"get_state",{...buildRpcSessionState(session,lastAbortSource),answeredUiRequests:[...sessionUiAnswerLedger(session).snapshot(),...secretInputs.answered()]});case"request_self_settle":return success(id,"request_self_settle",session.requestSelfSettle());case"get_effect_status":return runGetEffectStatus(effectContext(),command);case"get_pending_inputs":return success(id,"get_pending_inputs",await session.getPendingInputs(command.knownClientMessageIds));case"set_model":return runSetModel(effectContext(),command);case"set_favorite_models":return session.setFavoriteModels(command.models),success(id,"set_favorite_models");case"set_scoped_models":return session.setScopedModels(command.models),success(id,"set_scoped_models");case"cycle_model":{let result3=await session.cycleModel(command.direction,{origin:{source:"rpc",actor:"cycle_model"}});return result3?success(id,"cycle_model",result3):success(id,"cycle_model",null)}case"get_available_models":return success(id,"get_available_models",await availableModelsData(session));case"set_thinking_level":return runSetThinkingLevel(effectContext(),command);case"cycle_thinking_level":{let level=session.cycleThinkingLevel();return level?success(id,"cycle_thinking_level",{level}):success(id,"cycle_thinking_level",null)}case"get_available_thinking_levels":return success(id,"get_available_thinking_levels",{levels:session.getAvailableThinkingLevels()});case"get_model_thinking_level":{if(typeof command.provider!="string"||typeof command.modelId!="string")return error2(id,"get_model_thinking_level","get_model_thinking_level requires 'provider' and 'modelId'.",RPC_ERROR_INVALID_ARGUMENT);let model=(await session.modelRegistry.getAvailable()).find(m=>m.provider===command.provider&&m.id===command.modelId);return model?success(id,"get_model_thinking_level",session.getThinkingLevelForModel(model)):error2(id,"get_model_thinking_level",`Model not found: ${command.provider}/${command.modelId}`,RPC_ERROR_MODEL_NOT_FOUND)}case"set_fast_mode":{if(typeof command.enabled!="boolean")return error2(id,"set_fast_mode","set_fast_mode requires a boolean 'enabled' field.");let model=session.model;if(!model)return error2(id,"set_fast_mode","No active model.");let result3=await applyFastMode(fastModeContext(),command.enabled);if(!result3.applied)return error2(id,"set_fast_mode",result3.message);let memoryModel=resolveServiceTierMemoryModel(session.modelRegistry,session.model??model);return success(id,"set_fast_mode",{enabled:result3.enabled,serviceTier:result3.recordedTier,provider:memoryModel.provider,modelId:memoryModel.id})}case"get_fast_mode":return success(id,"get_fast_mode",{enabled:session.isFastModeActive(),serviceTier:session.effectiveServiceTier??null});case"set_steering_mode":return session.setSteeringMode(command.mode),success(id,"set_steering_mode");case"set_follow_up_mode":return session.setFollowUpMode(command.mode),success(id,"set_follow_up_mode");case"compact":{let result3=await session.compact(command.customInstructions);return success(id,"compact",result3)}case"set_auto_compaction":return session.setAutoCompactionEnabled(command.enabled),success(id,"set_auto_compaction");case"set_auto_retry":return session.setAutoRetryEnabled(command.enabled),success(id,"set_auto_retry");case"abort_retry":return session.abortRetry(),success(id,"abort_retry");case"set_retry_fallback":{if(!options.retryFallbackCommand)return error2(id,"set_retry_fallback","set_retry_fallback is for a single-session rpc process; a host session takes open_session.retryFallback.");let profileError=sessionRetryFallbackError(command.retryFallback);return profileError!==void 0||command.retryFallback===void 0?error2(id,"set_retry_fallback",profileError??"set_retry_fallback needs retryFallback."):turnRequested||session.isStreaming||session.messages.some(message=>message.role!=="custom")?error2(id,"set_retry_fallback","set_retry_fallback must arrive before the session's first turn."):(runtimeHost.setRetryFallback(command.retryFallback),success(id,"set_retry_fallback"))}case"navigate_tree":{if(command.entryId!==void 0&&command.targetId!==void 0)return error2(id,"navigate_tree","navigate_tree takes either entryId or targetId, not both");if(command.entryId===void 0&&command.targetId===void 0)return error2(id,"navigate_tree","navigate_tree requires entryId or targetId");let targetId=command.entryId??command.targetId;if(typeof targetId!="string"||targetId.length===0)return error2(id,command.type,"navigate_tree requires a non-empty entryId or targetId");if(command.intent!==void 0&&command.intent!=="select"&&command.intent!=="resume")return error2(id,command.type,"navigate_tree intent must be select or resume");try{let result3=await session.navigateTree(targetId,{...command.intent!==void 0?{intent:command.intent}:{},summarize:command.summarize,customInstructions:command.customInstructions,replaceInstructions:command.replaceInstructions,label:command.label,expectedLeafId:command.expectedLeafId}),leafId=session.sessionManager.getLeafId();return command.targetId!==void 0?success(id,command.type,{...result3,leafId}):result3.cancelled?success(id,command.type,{outcome:"cancelled",leafId,...result3.aborted?{aborted:!0}:{}}):success(id,command.type,{outcome:"navigated",leafId,...result3.editorText!==void 0?{editorText:result3.editorText}:{},...result3.summaryEntry?{summaryEntryId:result3.summaryEntry.id}:{}})}catch(err){if(err instanceof AssistantEditError||err instanceof SessionStreamingError)return error2(id,command.type,err.message,err.code);throw err}}case"record_bash_result":return session.recordBashResult(command.command,command.result,{excludeFromContext:command.excludeFromContext}),success(id,"record_bash_result");case"release_tool_barrier":return success(id,"release_tool_barrier",{released:session.releaseToolBarrier(command.barrierId)});case"set_label":return session.sessionManager.appendLabelChange(command.entryId,command.label),success(id,"set_label");case"bash":{routingSessionId!==void 0&&outputEvent({type:"bash_start"});try{let eventResult=await session.extensionRunner.emitUserBash({type:"user_bash",command:command.command,excludeFromContext:command.excludeFromContext??!1,cwd:session.sessionManager.getCwd()});if(eventResult?.result)return session.recordBashResult(command.command,eventResult.result,{excludeFromContext:command.excludeFromContext}),success(id,"bash",eventResult.result);let result3=await session.executeBash(command.command,void 0,{excludeFromContext:command.excludeFromContext,id:command.executionId,operations:eventResult?.operations});return success(id,"bash",result3)}finally{routingSessionId!==void 0&&outputEvent({type:"bash_end"})}}case"abort_bash":return session.abortBash(),success(id,"abort_bash");case"cleanup_bash_output":return await session.cleanupBashOutput(command.path),success(id,"cleanup_bash_output");case"get_session_stats":{let stats=session.getSessionStats();return success(id,"get_session_stats",stats)}case"resolve_path":return success(id,"resolve_path",resolveMessagePath({path:command.path,cwd:session.cwd,projectRoot:messagePathProjectRoot(session.cwd)}));case"memory_report":{let answer3=await answerMemoryReport(session);return answer3.ok?success(id,"memory_report",answer3.data):error2(id,"memory_report",answer3.error)}case"export_html":{let path16=await session.exportToHtml(command.outputPath,{themeName:command.themeName});return success(id,"export_html",{path:path16})}case"export_jsonl":return success(id,"export_jsonl",{path:session.exportToJsonl(command.outputPath)});case"switch_session":{let result3=await runtimeHost.switchSession(command.sessionPath,{cwdOverride:command.cwdOverride});return routingSessionId===void 0&&!result3.cancelled&&session!==runtimeHost.session&&await rebindAfterLocalReplacement(),success(id,"switch_session",result3)}case"fork":{let result3=await runtimeHost.fork(command.entryId,{position:command.position});return routingSessionId===void 0&&!result3.cancelled&&session!==runtimeHost.session&&await rebindAfterLocalReplacement(),success(id,"fork",{text:result3.selectedText,cancelled:result3.cancelled})}case"edit_assistant_message":{if(typeof command.entryId!="string"||command.entryId.length===0||typeof command.text!="string")return error2(id,command.type,"edit_assistant_message requires a non-empty entryId and a text string");try{let result3=await session.editAssistantMessage(command.entryId,command.text,{summarize:command.summarize,customInstructions:command.customInstructions,expectedLeafId:command.expectedLeafId}),leafId=session.sessionManager.getLeafId();if(result3.unchanged)return success(id,command.type,{outcome:"unchanged",leafId});if(result3.cancelled)return success(id,command.type,{outcome:"cancelled",leafId,...result3.aborted?{aborted:!0}:{}});let entry2=result3.entryId?session.sessionManager.getEntry(result3.entryId):void 0;return entry2?.type!=="message"||leafId===null?error2(id,command.type,"Edited assistant entry was not persisted"):success(id,command.type,{outcome:"edited",entry:entry2,leafId,...result3.summaryEntry?{summaryEntryId:result3.summaryEntry.id}:{}})}catch(err){if(err instanceof AssistantEditError||err instanceof SessionStreamingError)return error2(id,command.type,err.message,err.code);throw err}}case"edit_user_message":{if(typeof command.entryId!="string"||command.entryId.length===0||typeof command.text!="string")return error2(id,command.type,"edit_user_message requires a non-empty entryId and a text string");try{let result3=await session.editUserMessage(command.entryId,command.text,{summarize:command.summarize,customInstructions:command.customInstructions,expectedLeafId:command.expectedLeafId}),leafId=session.sessionManager.getLeafId();if(result3.unchanged)return success(id,command.type,{outcome:"unchanged",leafId});if(result3.cancelled)return success(id,command.type,{outcome:"cancelled",leafId,...result3.aborted?{aborted:!0}:{}});let entry2=result3.entryId?session.sessionManager.getEntry(result3.entryId):void 0;return entry2?.type!=="message"||leafId===null?error2(id,command.type,"Edited user entry was not persisted"):success(id,command.type,{outcome:"edited",entry:entry2,leafId,...result3.summaryEntry?{summaryEntryId:result3.summaryEntry.id}:{}})}catch(err){if(err instanceof UserEditError||err instanceof AssistantEditError||err instanceof SessionStreamingError)return error2(id,command.type,err.message,err.code);throw err}}case"clone":{let leafId=session.sessionManager.getLeafId();if(!leafId)return error2(id,"clone","Cannot clone session: no current entry selected");let result3=await runtimeHost.fork(leafId,{position:"at"});return routingSessionId===void 0&&!result3.cancelled&&session!==runtimeHost.session&&await rebindAfterLocalReplacement(),success(id,"clone",{cancelled:result3.cancelled})}case"get_fork_messages":{let messages=session.getUserMessagesForForking();return success(id,"get_fork_messages",{messages})}case"get_entries":return answerGetEntries(session,command);case"get_tree":{let sessionManager=session.sessionManager,tree=sessionManager.getTree(),nodes=[...tree];for(let node of nodes){node.entry=describeUsageLimitEntry(node.entry);for(let child of node.children)nodes.push(child)}return session.releaseFullHistoryView(),success(id,"get_tree",{tree,leafId:sessionManager.getLeafId()})}case"get_last_assistant_text":{let text4=session.getLastAssistantText();return success(id,"get_last_assistant_text",{text:text4})}case"import_jsonl":{let result3=await runtimeHost.importFromJsonl(command.inputPath,command.cwdOverride);return routingSessionId===void 0&&!result3.cancelled&&session!==runtimeHost.session&&await rebindAfterLocalReplacement(),success(id,"import_jsonl",result3)}case"set_session_name":{let name=command.name.trim();return name?(session.setSessionName(name),success(id,"set_session_name")):error2(id,"set_session_name","Session name cannot be empty")}case"record_user_activity":return command.kind!=="draft"?error2(id,"record_user_activity",'record_user_activity: kind must be "draft"',RPC_ERROR_INVALID_ARGUMENT):(session.recordUserActivity("draft"),success(id,"record_user_activity"));case"get_subscription_limits":return success(id,"get_subscription_limits",{accounts:subscriptionLimits.snapshot()});case"get_messages":return success(id,"get_messages",{messages:session.messages.map(message=>message.role==="assistant"?describeUsageLimitMessage(message):message)});case"get_media":{let{toolCallId,contentIndex}=command,content=findToolResultMedia(session,toolCallId,contentIndex);return content?success(id,"get_media",{toolCallId,contentIndex,content}):error2(id,"get_media",RPC_ERROR_MEDIA_NOT_FOUND,RPC_ERROR_MEDIA_NOT_FOUND)}case"get_commands":return success(id,"get_commands",{commands:buildRpcCommandsForSession(session)});case"get_loaded_surfaces":return await requestMcpWireStatus(),success(id,"get_loaded_surfaces",currentLoadedSurfaces().data);case"extension_request":case"eval_cells.list":case"eval_cells.peek":case"eval_cells.stop":{let name=command.type==="extension_request"?command.name.trim():command.type;if(name.length===0)return error2(id,command.type,"Extension RPC request name cannot be empty");try{let data=await session.extensionRunner.requestRpc(name,command.type==="extension_request"?command.data:command,requestContext);return success(id,command.type,data)}catch(cause){if(cause instanceof ExtensionRpcRequestNotFoundError&&(name==="eval_cells.list"||name==="eval_cells.peek"||name==="eval_cells.stop"))return error2(id,command.type,"Eval cell controls are unavailable in this session",RPC_ERROR_EVAL_CELLS_UNAVAILABLE);if(cause instanceof Error&&"code"in cause&&(cause.code===RPC_ERROR_EVAL_CELL_NOT_FOUND||cause.code===RPC_ERROR_INVALID_EVAL_CELL_REQUEST))return error2(id,command.type,cause.message,cause.code);throw cause}}case"get_auth_providers":{let modelRegistry=session.modelRegistry,oauthInfos=buildLoginProviderInfos(modelRegistry,"oauth"),apiKeyInfos=buildLoginProviderInfos(modelRegistry,"api_key"),providers=[...oauthInfos,...apiKeyInfos].map(info=>{let origin=modelRegistry.getProviderOrigin(info.id);return{id:info.id,name:info.name,authType:info.authType,status:authMethodStatus(modelRegistry,info),...storedKeyHint(modelRegistry,info),...origin===void 0?{}:{origin}}});return success(id,"get_auth_providers",{providers})}case"login_start":return startLogin(command.provider),success(id,"login_start");case"login_cancel":return activeLogins.get(command.provider)?.abort(),success(id,"login_cancel");case"login_api_key":{let credential=await apiKeyLoginCredential(session.modelRuntime.getProvider(command.provider),command.key,command.region),replacement=session.modelRegistry.authStorage.set(command.provider,credential);return session.modelRegistry.authStorage.takeReplacement(command.provider),await session.modelRegistry.refresh(),success(id,"login_api_key",replacement)}case"verify_api_key":{let verification=await verifyApiKey({models:session.modelRegistry.getAll(),provider:command.provider,key:command.key,signal:AbortSignal.timeout(15e3)});return success(id,"verify_api_key",verification)}case"logout":{let{notices}=await session.modelRuntime.logoutProvider(command.provider);return session.modelRegistry.authStorage.removeRuntimeApiKey(command.provider),await session.modelRegistry.refresh(),success(id,"logout",notices.length===0?void 0:{notices})}case"get_provider_accounts":{let listing=await listCredentialAccounts(session.modelRegistry.authStorage,command.provider);return success(id,"get_provider_accounts",{accounts:listing.accounts,ordered:listing.ordered})}case"account_pin":return await pinCredentialAccount(session.modelRegistry.authStorage,command.provider,command.name),success(id,"account_pin");case"account_remove":{let{notice:notice2}=await removeCredentialAccount(session.modelRegistry.authStorage,command.provider,command.name);return success(id,"account_remove",notice2===void 0?void 0:{notice:notice2})}case"test_provider_account":try{let check=await testClaudeCliAccount({provider:command.provider,name:command.name,cwd:session.cwd,store:session.modelRegistry.authStorage});return success(id,"test_provider_account",{check})}catch(testError){if(testError instanceof ProviderAccountTestError)return error2(id,"test_provider_account",testError.code);throw testError}case"account_order":{let names=command.names;if(names!==null&&!(Array.isArray(names)&&names.every(name=>typeof name=="string")))throw new Error("account_order names must be an array of account names, or null to clear the order");return await orderCredentialAccounts(session.modelRegistry.authStorage,command.provider,command.names),success(id,"account_order")}default:{let unknownCommand=command;return error2(id,unknownCommand.type,`Unknown command: ${unknownCommand.type}`)}}},handleInputLine=async(line,requestContext)=>{let parsed;try{parsed=JSON.parse(line)}catch{output(error2(void 0,"parse","Failed to parse command: invalid JSON")),await waitForRpcBackpressure();return}let shapeError=rpcCommandShapeError(parsed);if(shapeError){output(error2(void 0,"parse",shapeError)),await waitForRpcBackpressure();return}if(typeof parsed=="object"&&parsed!==null&&"type"in parsed&&parsed.type==="extension_ui_progress"){let progress=parsed;if(secretInputs.has(progress.id)||"secret"in parsed&&parsed.secret===!0){output(refusedExtensionUiResponse(progress.id,"invalid_secret_response"));return}questions.progress(parsed);return}if(isHostResponse(parsed)){output(answerHostResponse(parsed,frame=>relocation?.respond(frame)??"unknown"));return}if(typeof parsed=="object"&&parsed!==null&&"type"in parsed&&parsed.type==="extension_ui_response"){let response=parsed,answered=answeredUiRequestId(response);if(answered!==void 0&&secretInputs.has(answered)||"secret"in response&&response.secret===!0){output(secretInputs.respond(parsed));return}if(!options.workerSecurityBridge&&answered!==void 0&&grantRequests.has(answered)){let sender=options.clientInfo?.connectionId(),capable=sender===void 0?clientCapabilities?.includes("grant_select")===!0:options.clientInfo?.hasCapability?.(sender,"grant_select")===!0;if(grantRequests.get(answered)!==sender||!capable){output(refusedExtensionUiResponse(response.id,"grant_answer_refused"));return}}let reply=settleExtensionUiResponse(response,{questions,dialogs:pendingExtensionRequests,routed:routingSessionId!==void 0,ledger:sessionUiAnswerLedger(session),beforeAnswer:()=>session.admitHumanAnswer()});reply&&output(reply);return}let command=parsed,payloadError=rpcCommandPayloadError(command),messageLengthError=rpcMessageLengthError(command);if(payloadError||messageLengthError){output(error2(command.id,command.type,payloadError??messageLengthError)),await waitForRpcBackpressure();return}try{let response=await handleCommand(command,requestContext);response&&(output(response),await waitForRpcBackpressure())}catch(commandError){let missingCwd=commandError instanceof Error&&commandError.name==="MissingSessionCwdError"&&"issue"in commandError;output(error2(command.id,command.type,commandError instanceof Error?commandError.message:String(commandError),missingCwd?"missing_session_cwd":void 0,missingCwd?commandError.issue:void 0)),await waitForRpcBackpressure()}},stopLimitEvents=options.sessionId===void 0?subscriptionLimits.subscribe(limits=>outputEvent({type:"subscription_limits",...limits})):()=>{},dispose=async(disposeOptions={})=>{unbindMcpForms?.(),grantPresentationAbort.abort(),detachGrantPresentation?.(),unsubscribeSecurityNotices?.(),stopLimitEvents(),sessionControl?.dispose(),sessionControl=void 0,relocation?.dispose(),relocation=void 0,questions.cancelAll(),secretInputs.close(),pendingExtensionRequests.close(),unsubscribeProviderAccountEvents(),unsubscribe?.(),unsubscribeStructured?.(),unsubscribeBackpressure?.(),unsubscribeLoadedSurfaces?.(),unsubscribeExtensionEvents?.(),unsubscribe=void 0,unsubscribeStructured=void 0,unsubscribeBackpressure=void 0,unsubscribeLoadedSurfaces=void 0,unsubscribeExtensionEvents=void 0,options.disposeRuntime!==!1&&await runtimeHost.dispose(disposeOptions)},unbindMcpForms,ready=rebindSession();return{ready,async handleInputLine(line){let requestContext=rpcOwners.capture()?.context;await ready,await handleInputLine(line,requestContext)},pendingPrompts(){return[...promptCalls]},isShutdownRequested(){return shutdownRequested},cancelPendingExtensionUiRequests(){secretInputs.cancelAll(),questions.cancelAll(),pendingExtensionRequests.cancelAll()},connectionDetached(connectionId){for(let[id,owner]of secretOwners)owner.connection===connectionId&&(owner.cancel?.(),secretOwners.delete(id));relocation?.connectionDetached(connectionId)},async dispose(disposeOptions){rpcOwners.dispose(),await ready,await dispose(disposeOptions)}}}function createRpcShutdown(dispose,exit){let pending,code=0;return(exitCode=0,signal)=>(code===0&&(code=exitCode),pending||(pending=(async()=>(await dispose(signal),exit(code)))(),pending))}async function runRpcMode(runtimeHost,toolRuntime){takeOverStdout();let sink={writeRaw:chunk=>{let linearized=chunk.split(`
|
|
2357
2357
|
`).filter(line=>line.length>0).map(line=>{let value=JSON.parse(line);return JSON.stringify(value.type==="message_update"?toJsonEvent(value):value)}).join(`
|
|
2358
2358
|
`);writeRawStdout(linearized.length>0?`${linearized}
|