@iaforged/context-code 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/src/bridge/bridgeMain.js +1 -1
  2. package/dist/src/bridge/types.js +1 -1
  3. package/dist/src/cli/handlers/auth.js +1 -1
  4. package/dist/src/cli/handlers/mcp.js +1 -1
  5. package/dist/src/cli/print.js +1 -1
  6. package/dist/src/commands/copy/copy.js +1 -1
  7. package/dist/src/commands/heartbeat/heartbeat.js +1 -0
  8. package/dist/src/commands/heartbeat/index.js +1 -0
  9. package/dist/src/commands/insights.js +1 -1
  10. package/dist/src/commands/install-github-app/ExistingWorkflowStep.js +1 -1
  11. package/dist/src/commands/install-github-app/InstallAppStep.js +1 -1
  12. package/dist/src/commands/install-github-app/OAuthFlowStep.js +1 -1
  13. package/dist/src/commands/install-github-app/SuccessStep.js +1 -1
  14. package/dist/src/commands/install-github-app/setupGitHubActions.js +1 -1
  15. package/dist/src/commands/login-openai/index.js +1 -1
  16. package/dist/src/commands/mobile/mobile.js +1 -1
  17. package/dist/src/commands/remote-setup/remote-setup.js +1 -1
  18. package/dist/src/commands/swarm-auto/swarmAuto.js +1 -1
  19. package/dist/src/commands/timeline/timeline.js +1 -1
  20. package/dist/src/commands/webapp/webapp.js +1 -1
  21. package/dist/src/commands.js +1 -1
  22. package/dist/src/components/ApproveApiKey.js +1 -1
  23. package/dist/src/components/ChannelDowngradeDialog.js +1 -1
  24. package/dist/src/components/ClaudeCodeHint/PluginHintMenu.js +1 -1
  25. package/dist/src/components/ConsoleOAuthFlow.js +1 -1
  26. package/dist/src/components/CostThresholdDialog.js +1 -1
  27. package/dist/src/components/CtrlOToExpand.js +1 -1
  28. package/dist/src/components/CustomSelect/select.js +1 -1
  29. package/dist/src/components/DesktopHandoff.js +1 -1
  30. package/dist/src/components/DesktopUpsell/DesktopUpsellStartup.js +1 -1
  31. package/dist/src/components/ExportDialog.js +1 -1
  32. package/dist/src/components/Feedback.js +1 -1
  33. package/dist/src/components/FeedbackSurvey/FeedbackSurvey.js +1 -1
  34. package/dist/src/components/FeedbackSurvey/FeedbackSurveyView.js +1 -1
  35. package/dist/src/components/IdeAutoConnectDialog.js +1 -1
  36. package/dist/src/components/IdeOnboardingDialog.js +1 -1
  37. package/dist/src/components/IdleReturnDialog.js +1 -1
  38. package/dist/src/components/InterruptedByUser.js +1 -1
  39. package/dist/src/components/InvalidConfigDialog.js +1 -1
  40. package/dist/src/components/InvalidSettingsDialog.js +1 -1
  41. package/dist/src/components/LanguagePicker.js +1 -1
  42. package/dist/src/components/LogSelector.js +1 -1
  43. package/dist/src/components/LogoV2/ChannelsNotice.js +1 -1
  44. package/dist/src/components/LogoV2/LogoV2.js +1 -1
  45. package/dist/src/components/LogoV2/feedConfigs.js +1 -1
  46. package/dist/src/components/LspRecommendation/LspRecommendationMenu.js +1 -1
  47. package/dist/src/components/MCPServerApprovalDialog.js +1 -1
  48. package/dist/src/components/MCPServerDesktopImportDialog.js +1 -1
  49. package/dist/src/components/ManagedSettingsSecurityDialog/ManagedSettingsSecurityDialog.js +1 -1
  50. package/dist/src/components/MessageSelector.js +1 -1
  51. package/dist/src/components/OutputStylePicker.js +1 -1
  52. package/dist/src/components/PromptInput/PromptInput.js +1 -1
  53. package/dist/src/components/RemoteCallout.js +1 -1
  54. package/dist/src/components/ResumeTask.js +1 -1
  55. package/dist/src/components/Settings/Config.js +1 -1
  56. package/dist/src/components/ShowInIDEPrompt.js +1 -1
  57. package/dist/src/components/Stats.js +1 -1
  58. package/dist/src/components/TagTabs.js +1 -1
  59. package/dist/src/components/TeleportError.js +1 -1
  60. package/dist/src/components/TeleportResumeWrapper.js +1 -1
  61. package/dist/src/components/TextInput.js +1 -1
  62. package/dist/src/components/agents/new-agent-creation/wizard-steps/MethodStep.js +1 -1
  63. package/dist/src/components/design-system/KeyboardShortcutHint.js +1 -1
  64. package/dist/src/components/diff/DiffDetailView.js +1 -1
  65. package/dist/src/components/grove/Grove.js +1 -1
  66. package/dist/src/components/hooks/SelectEventMode.js +1 -1
  67. package/dist/src/components/hooks/SelectHookMode.js +1 -1
  68. package/dist/src/components/hooks/SelectMatcherMode.js +1 -1
  69. package/dist/src/components/hooks/ViewHookMode.js +1 -1
  70. package/dist/src/components/mcp/MCPAgentServerMenu.js +1 -1
  71. package/dist/src/components/mcp/utils/reconnectHelpers.js +1 -1
  72. package/dist/src/components/memory/MemoryFileSelector.js +1 -1
  73. package/dist/src/components/messages/AssistantTextMessage.js +1 -1
  74. package/dist/src/components/messages/PlanApprovalMessage.js +1 -1
  75. package/dist/src/components/messages/ShutdownMessage.js +1 -1
  76. package/dist/src/components/messages/SystemAPIErrorMessage.js +1 -1
  77. package/dist/src/components/messages/UserPlanMessage.js +1 -1
  78. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/PreviewQuestionView.js +1 -1
  79. package/dist/src/components/permissions/ComputerUseApproval/ComputerUseApproval.js +1 -1
  80. package/dist/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.js +1 -1
  81. package/dist/src/components/permissions/FilePermissionDialog/FilePermissionDialog.js +1 -1
  82. package/dist/src/components/permissions/FilePermissionDialog/permissionOptions.js +1 -1
  83. package/dist/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.js +1 -1
  84. package/dist/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +1 -1
  85. package/dist/src/components/permissions/PermissionRequest.js +1 -1
  86. package/dist/src/components/permissions/SedEditPermissionRequest/SedEditPermissionRequest.js +1 -1
  87. package/dist/src/components/permissions/SkillPermissionRequest/SkillPermissionRequest.js +1 -1
  88. package/dist/src/components/permissions/WebFetchPermissionRequest/WebFetchPermissionRequest.js +1 -1
  89. package/dist/src/components/permissions/rules/AddPermissionRules.js +1 -1
  90. package/dist/src/components/permissions/rules/AddWorkspaceDirectory.js +1 -1
  91. package/dist/src/components/permissions/rules/PermissionRuleList.js +1 -1
  92. package/dist/src/components/permissions/rules/RemoveWorkspaceDirectory.js +1 -1
  93. package/dist/src/components/sandbox/SandboxConfigTab.js +1 -1
  94. package/dist/src/components/sandbox/SandboxOverridesTab.js +1 -1
  95. package/dist/src/components/tasks/RemoteSessionDetailDialog.js +1 -1
  96. package/dist/src/constants/outputStyles.js +1 -1
  97. package/dist/src/entrypoints/cli.js +1 -1
  98. package/dist/src/hooks/notifs/useCanSwitchToExistingSubscription.js +1 -1
  99. package/dist/src/main.js +1 -1
  100. package/dist/src/projectOnboardingState.js +1 -1
  101. package/dist/src/screens/REPL.js +1 -1
  102. package/dist/src/server/channelServer.js +1 -0
  103. package/dist/src/server/channelServer.test.js +1 -0
  104. package/dist/src/services/api/errors.js +1 -1
  105. package/dist/src/services/api/filesApi.js +1 -1
  106. package/dist/src/services/api/index.js +1 -1
  107. package/dist/src/services/tips/tipRegistry.js +1 -1
  108. package/dist/src/tasks/RemoteAgentTask/RemoteAgentTask.js +1 -1
  109. package/dist/src/tools/AgentTool/AgentTool.js +1 -1
  110. package/dist/src/tools/ConfigTool/supportedSettings.js +1 -1
  111. package/dist/src/tools/EnterWorktreeTool/EnterWorktreeTool.js +1 -1
  112. package/dist/src/tools/ExitWorktreeTool/ExitWorktreeTool.js +1 -1
  113. package/dist/src/tools/WebFetchTool/WebFetchTool.js +1 -1
  114. package/dist/src/utils/computerUse/cleanup.js +1 -1
  115. package/dist/src/utils/computerUse/wrapper.js +1 -1
  116. package/dist/src/utils/fileHistory.js +1 -1
  117. package/dist/src/utils/heartbeat.js +1 -0
  118. package/dist/src/utils/model/providers.js +1 -1
  119. package/dist/src/utils/permissions/filesystem.js +1 -1
  120. package/dist/src/utils/permissions/permissions.js +1 -1
  121. package/dist/src/utils/processUserInput/processSlashCommand.js +1 -1
  122. package/dist/src/utils/releaseNoteTranslations.js +1 -1
  123. package/dist/src/utils/shell/shellToolUtils.js +1 -1
  124. package/dist/src/utils/sideQuery.js +1 -1
  125. package/dist/src/utils/sshMcp/common.js +1 -0
  126. package/dist/src/utils/sshMcp/setup.js +1 -0
  127. package/dist/src/utils/sshMcp/sshMcpServer.js +1 -0
  128. package/dist/src/utils/sshMcp/sshMcpServer.test.js +1 -0
  129. package/dist/src/utils/teleport.js +1 -1
  130. package/dist/src/webapp/server.js +1 -1
  131. package/dist/sshMcpServer.js +1 -0
  132. package/dist/sshMcpServer.test.js +1 -0
  133. package/dist/webapp/chunk-AMCDNAIG.js +1 -0
  134. package/dist/webapp/{chunk-YUEYJPXQ.js → chunk-NFYBHCXF.js} +1 -1
  135. package/dist/webapp/{chunk-DFKSSBHI.js → chunk-OJZNEHPP.js} +1 -1
  136. package/dist/webapp/chunk-VAB2VXFI.js +1 -0
  137. package/dist/webapp/index.html +2 -2
  138. package/dist/webapp/main-MTQLKGXD.js +1 -0
  139. package/dist/webapp/ngsw.json +14 -14
  140. package/dist/webapp/styles-DIKEDJBH.css +1 -0
  141. package/package.json +2 -1
  142. package/dist/webapp/chunk-4SRNXNLW.js +0 -1
  143. package/dist/webapp/chunk-SIHYW6PA.js +0 -1
  144. package/dist/webapp/main-LBNRQBXX.js +0 -1
  145. package/dist/webapp/styles-FUPULZDX.css +0 -1
@@ -1 +1 @@
1
- import{feature as e}from"../recovery/bunBundleShim.js";import{jsxs as t,jsx as o,Fragment as s}from"react/jsx-runtime";import{createRequire as n}from"module";const r=n(import.meta.url);import{c as i}from"react/compiler-runtime";import{spawnSync as a}from"child_process";import{snapshotOutputTokensForTurn as l,getCurrentTurnTokenBudget as c,getTurnOutputTokens as m,getBudgetContinuationCount as u,getTotalInputTokens as p}from"../bootstrap/state.js";import{parseTokenBudget as d}from"../utils/tokenBudget.js";import{count as f}from"../utils/array.js";import{dirname as g,join as h}from"path";import{tmpdir as S}from"os";import C from"figures";import{useInput as y}from"../ink.js";import{useSearchInput as T}from"../hooks/useSearchInput.js";import{useTerminalSize as v}from"../hooks/useTerminalSize.js";import{useSearchHighlight as k}from"../ink/hooks/use-search-highlight.js";import{renderMessagesToPlainText as j}from"../utils/exportRenderer.js";import{openFileInExternalEditor as b}from"../utils/editor.js";import{writeFile as I}from"fs/promises";import{Box as A,Text as w,useStdin as R,useTheme as P,useTerminalFocus as x,useTerminalTitle as M,useTabStatus as E}from"../ink.js";import{CostThresholdDialog as D}from"../components/CostThresholdDialog.js";import{IdleReturnDialog as _}from"../components/IdleReturnDialog.js";import*as L from"react";import{useEffect as O,useMemo as N,useRef as U,useState as B,useCallback as q,useDeferredValue as H,useLayoutEffect as $}from"react";import{useNotifications as F}from"../context/notifications.js";import{ModalStackContext as V}from"../context/modalStackContext.js";import{sendNotification as X}from"../services/notifier.js";import{startPreventSleep as J,stopPreventSleep as K}from"../services/preventSleep.js";import{useTerminalNotification as W}from"../ink/useTerminalNotification.js";import{hasCursorUpViewportYankBug as Q}from"../ink/terminal.js";import{createFileStateCacheWithSizeLimit as G,mergeFileStateCaches as Y,READ_FILE_STATE_CACHE_SIZE as z}from"../utils/fileStateCache.js";import{updateLastInteractionTime as Z,getLastInteractionTime as ee,getOriginalCwd as te,getProjectRoot as oe,getSessionId as se,switchSession as ne,setCostStateForRestore as re,getTurnHookDurationMs as ie,getTurnHookCount as ae,resetTurnHookDuration as le,getTurnToolDurationMs as ce,getTurnToolCount as me,resetTurnToolDuration as ue,getTurnClassifierDurationMs as pe,getTurnClassifierCount as de,resetTurnClassifierDuration as fe}from"../bootstrap/state.js";import{asSessionId as ge,asAgentId as he}from"../types/ids.js";import{logForDebugging as Se}from"../utils/debug.js";import{QueryGuard as Ce}from"../utils/QueryGuard.js";import{isEnvTruthy as ye}from"../utils/envUtils.js";import{formatTokens as Te,truncateToWidth as ve}from"../utils/format.js";import{consumeEarlyInput as ke}from"../utils/earlyInput.js";import{setMemberActive as je}from"../utils/swarm/teamHelpers.js";import{isSwarmWorker as be,generateSandboxRequestId as Ie,sendSandboxPermissionRequestViaMailbox as Ae,sendSandboxPermissionResponseViaMailbox as we}from"../utils/swarm/permissionSync.js";import{registerSandboxPermissionCallback as Re}from"../hooks/useSwarmPermissionPoller.js";import{getTeamName as Pe,getAgentName as xe}from"../utils/teammate.js";import{WorkerPendingPermission as Me}from"../components/permissions/WorkerPendingPermission.js";import{injectUserMessageToTeammate as Ee,getAllInProcessTeammateTasks as De}from"../tasks/InProcessTeammateTask/InProcessTeammateTask.js";import{isLocalAgentTask as _e,queuePendingMessage as Le,appendMessageToLocalAgent as Oe}from"../tasks/LocalAgentTask/LocalAgentTask.js";import{registerLeaderToolUseConfirmQueue as Ne,unregisterLeaderToolUseConfirmQueue as Ue,registerLeaderSetToolPermissionContext as Be,unregisterLeaderSetToolPermissionContext as qe}from"../utils/swarm/leaderPermissionBridge.js";import{endInteractionSpan as He}from"../utils/telemetry/sessionTracing.js";import{useLogMessages as $e}from"../hooks/useLogMessages.js";import{useReplBridge as Fe}from"../hooks/useReplBridge.js";import{useTelegramMirror as Ve}from"../hooks/useTelegramMirror.js";import{useWhatsAppMirror as Xe}from"../hooks/useWhatsAppMirror.js";import{getCommandName as Je,isCommandEnabled as Ke}from"../commands.js";import{MessageSelector as We,selectableUserMessagesFilter as Qe,messagesAfterAreOnlySynthetic as Ge}from"../components/MessageSelector.js";import{useIdeLogging as Ye}from"../hooks/useIdeLogging.js";import{PermissionRequest as ze}from"../components/permissions/PermissionRequest.js";import{ElicitationDialog as Ze}from"../components/mcp/ElicitationDialog.js";import{PromptDialog as et}from"../components/hooks/PromptDialog.js";import tt from"../components/PromptInput/PromptInput.js";import{PromptInputQueuedCommands as ot}from"../components/PromptInput/PromptInputQueuedCommands.js";import{useRemoteSession as st}from"../hooks/useRemoteSession.js";import{useDirectConnect as nt}from"../hooks/useDirectConnect.js";import{useSSHSession as rt}from"../hooks/useSSHSession.js";import{useAssistantHistory as it}from"../hooks/useAssistantHistory.js";import{SkillImprovementSurvey as at}from"../components/SkillImprovementSurvey.js";import{useSkillImprovementSurvey as lt}from"../hooks/useSkillImprovementSurvey.js";import{useMoreRight as ct}from"../moreright/useMoreRight.js";import{SpinnerWithVerb as mt,BriefIdleStatus as ut}from"../components/Spinner.js";import{getSystemPrompt as pt}from"../constants/prompts.js";import{buildEffectiveSystemPrompt as dt}from"../utils/systemPrompt.js";import{getSystemContext as ft,getUserContext as gt}from"../context.js";import{getMemoryFiles as ht}from"../utils/claudemd.js";import{startBackgroundHousekeeping as St}from"../utils/backgroundHousekeeping.js";import{getTotalCost as Ct,saveCurrentSessionCosts as yt,resetCostState as Tt,getStoredSessionCosts as vt}from"../cost-tracker.js";import{useCostSummary as kt}from"../costHook.js";import{useFpsMetrics as jt}from"../context/fpsMetrics.js";import{useAfterFirstRender as bt}from"../hooks/useAfterFirstRender.js";import{useDeferredHookMessages as It}from"../hooks/useDeferredHookMessages.js";import{addToHistory as At,removeLastFromHistory as wt,expandPastedTextRefs as Rt,parseReferences as Pt}from"../history.js";import{prependModeCharacterToInput as xt}from"../components/PromptInput/inputModes.js";import{prependToShellHistoryCache as Mt}from"../utils/suggestions/shellHistoryCompletion.js";import{useApiKeyVerification as Et}from"../hooks/useApiKeyVerification.js";import{GlobalKeybindingHandlers as Dt}from"../hooks/useGlobalKeybindings.js";import{CommandKeybindingHandlers as _t}from"../hooks/useCommandKeybindings.js";import{KeybindingSetup as Lt}from"../keybindings/KeybindingProviderSetup.js";import{useShortcutDisplay as Ot}from"../keybindings/useShortcutDisplay.js";import{getShortcutDisplay as Nt}from"../keybindings/shortcutFormat.js";import{CancelRequestHandler as Ut}from"../hooks/useCancelRequest.js";import{useBackgroundTaskNavigation as Bt}from"../hooks/useBackgroundTaskNavigation.js";import{useSwarmInitialization as qt}from"../hooks/useSwarmInitialization.js";import{useTeammateViewAutoExit as Ht}from"../hooks/useTeammateViewAutoExit.js";import{errorMessage as $t}from"../utils/errors.js";import{isHumanTurn as Ft}from"../utils/messagePredicates.js";import{logError as Vt}from"../utils/log.js";const Xt=r("../hooks/useVoiceIntegration.js").useVoiceIntegration,Jt=r("../hooks/useVoiceIntegration.js").VoiceKeybindingHandler,useFrustrationDetection=()=>({state:"closed",handleTranscriptSelect:()=>{}}),useAntOrgWarningNotification=()=>{},Kt=e("COORDINATOR_MODE")?r("../coordinator/coordinatorMode.js").getCoordinatorUserContext:()=>({});import Wt from"../hooks/useCanUseTool.js";import{applyPermissionUpdate as Qt,applyPermissionUpdates as Gt,persistPermissionUpdate as Yt}from"../utils/permissions/PermissionUpdate.js";import{buildPermissionUpdates as zt}from"../components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js";import{stripDangerousPermissionsForAutoMode as Zt}from"../utils/permissions/permissionSetup.js";import{getScratchpadDir as eo,isScratchpadEnabled as to}from"../utils/permissions/filesystem.js";import{WEB_FETCH_TOOL_NAME as oo}from"../tools/WebFetchTool/prompt.js";import{SLEEP_TOOL_NAME as so}from"../tools/SleepTool/prompt.js";import{clearSpeculativeChecks as no}from"../tools/BashTool/bashPermissions.js";import{getGlobalConfig as ro,saveGlobalConfig as io,getGlobalConfigWriteCount as ao}from"../utils/config.js";import{hasConsoleBillingAccess as lo}from"../utils/billing.js";import{logEvent as co}from"../services/analytics/index.js";import{getFeatureValue_CACHED_MAY_BE_STALE as mo}from"../services/analytics/growthbook.js";import{textForResubmit as uo,handleMessageFromStream as po,isCompactBoundaryMessage as fo,getMessagesAfterCompactBoundary as go,getContentText as ho,createUserMessage as So,createAssistantMessage as Co,createTurnDurationMessage as yo,createAgentsKilledMessage as To,createApiMetricsMessage as vo,createSystemMessage as ko,createCommandInputMessage as jo,formatCommandInputTags as bo}from"../utils/messages.js";import{generateSessionTitle as Io}from"../utils/sessionTitle.js";import{BASH_INPUT_TAG as Ao,COMMAND_MESSAGE_TAG as wo,COMMAND_NAME_TAG as Ro,LOCAL_COMMAND_STDOUT_TAG as Po}from"../constants/xml.js";import{escapeXml as xo}from"../utils/xml.js";import{gracefulShutdownSync as Mo}from"../utils/gracefulShutdown.js";import{handlePromptSubmit as Eo}from"../utils/handlePromptSubmit.js";import{useQueueProcessor as Do}from"../hooks/useQueueProcessor.js";import{useMailboxBridge as _o}from"../hooks/useMailboxBridge.js";import{queryCheckpoint as Lo,logQueryProfileReport as Oo}from"../utils/queryProfiler.js";import{query as No}from"../query.js";import{mergeClients as Uo,useMergedClients as Bo}from"../hooks/useMergedClients.js";import{getQuerySourceForREPL as qo}from"../utils/promptCategory.js";import{useMergedTools as Ho}from"../hooks/useMergedTools.js";import{mergeAndFilterTools as $o}from"../utils/toolPool.js";import{useMergedCommands as Fo}from"../hooks/useMergedCommands.js";import{useSkillsChange as Vo}from"../hooks/useSkillsChange.js";import{useManagePlugins as Xo}from"../hooks/useManagePlugins.js";import{Messages as Jo}from"../components/Messages.js";import{TaskListV2 as Ko}from"../components/TaskListV2.js";import{TeammateViewHeader as Wo}from"../components/TeammateViewHeader.js";import{useTasksV2WithCollapseEffect as Qo}from"../hooks/useTasksV2.js";import{maybeMarkProjectOnboardingComplete as Go}from"../projectOnboardingState.js";import{randomUUID as Yo}from"crypto";import{processSessionStartHooks as zo}from"../utils/sessionStart.js";import{executeSessionEndHooks as Zo,getSessionEndHookTimeoutMs as es}from"../utils/hooks.js";import{useIdeSelection as ts}from"../hooks/useIdeSelection.js";import{getTools as os,assembleToolPool as ss}from"../tools.js";import{resolveAgentTools as ns}from"../tools/AgentTool/agentToolUtils.js";import{resumeAgentBackground as rs}from"../tools/AgentTool/resumeAgent.js";import{useMainLoopModel as is}from"../hooks/useMainLoopModel.js";import{useAppState as as,useSetAppState as ls,useAppStateStore as cs}from"../state/AppState.js";import{copyPlanForFork as ms,copyPlanForResume as us,getPlanSlug as ps,setPlanSlug as ds}from"../utils/plans.js";import{clearSessionMetadata as fs,resetSessionFilePointer as gs,adoptResumedSessionFile as hs,removeTranscriptMessage as Ss,restoreSessionMetadata as Cs,getCurrentSessionTitle as ys,isEphemeralToolProgress as Ts,isLoggableMessage as vs,saveWorktreeState as ks,getAgentTranscript as js}from"../utils/sessionStorage.js";import{deserializeMessages as bs}from"../utils/conversationRecovery.js";import{extractReadFilesFromMessages as Is,extractBashToolsFromMessages as As}from"../utils/queryHelpers.js";import{resetMicrocompactState as ws}from"../services/compact/microCompact.js";import{runPostCompactCleanup as Rs}from"../services/compact/postCompactCleanup.js";import{provisionContentReplacementState as Ps,reconstructContentReplacementState as xs}from"../utils/toolResultStorage.js";import{partialCompactConversation as Ms}from"../services/compact/compact.js";import{fileHistoryMakeSnapshot as Es,fileHistoryRewind as Ds,copyFileHistoryForResume as _s,fileHistoryEnabled as Ls,fileHistoryHasAnyChanges as Os}from"../utils/fileHistory.js";import{incrementPromptCount as Ns}from"../utils/commitAttribution.js";import{recordAttributionSnapshot as Us}from"../utils/sessionStorage.js";import{computeStandaloneAgentContext as Bs,restoreAgentFromSession as qs,restoreSessionStateFromLog as Hs,restoreWorktreeForResume as $s,exitRestoredWorktree as Fs}from"../utils/sessionRestore.js";import{isBgSession as Vs,updateSessionName as Xs,updateSessionActivity as Js}from"../utils/concurrentSessions.js";import{isInProcessTeammateTask as Ks}from"../tasks/InProcessTeammateTask/types.js";import{restoreRemoteAgentTasks as Ws}from"../tasks/RemoteAgentTask/RemoteAgentTask.js";import{useInboxPoller as Qs}from"../hooks/useInboxPoller.js";import{usePermissionWhatsAppBridge as Gs}from"../hooks/usePermissionWhatsAppBridge.js";import{useWebappMirror as Ys}from"../hooks/useWebappMirror.js";import{useWebappPermissionBridge as zs}from"../hooks/useWebappPermissionBridge.js";const Zs=e("PROACTIVE")||e("KAIROS")?r("../proactive/index.js"):null,PROACTIVE_NO_OP_SUBSCRIBE=e=>()=>{},PROACTIVE_FALSE=()=>!1,SUGGEST_BG_PR_NOOP=(e,t)=>!1,en=((e("PROACTIVE")||e("KAIROS"))&&r("../proactive/useProactive.js").useProactive,e("AGENT_TRIGGERS")?r("../hooks/useScheduledTasks.js").useScheduledTasks:null);import{isAgentSwarmsEnabled as tn}from"../utils/agentSwarmsEnabled.js";import{useTaskListWatcher as on}from"../hooks/useTaskListWatcher.js";import{closeOpenDiffs as sn,getConnectedIdeClient as nn}from"../utils/ide.js";import{useIDEIntegration as rn}from"../hooks/useIDEIntegration.js";import an from"../commands/exit/index.js";import{ExitFlow as ln}from"../components/ExitFlow.js";import{getCurrentWorktreeSession as cn}from"../utils/worktree.js";import{popAllEditable as mn,enqueue as un,getCommandQueue as pn,getCommandQueueLength as dn,removeByFilter as fn}from"../utils/messageQueueManager.js";import{useCommandQueue as gn}from"../hooks/useCommandQueue.js";import{SessionBackgroundHint as hn}from"../components/SessionBackgroundHint.js";import{startBackgroundSession as Sn}from"../tasks/LocalMainSessionTask.js";import{useSessionBackgrounding as Cn}from"../hooks/useSessionBackgrounding.js";import{diagnosticTracker as yn}from"../services/diagnosticTracking.js";import{handleSpeculationAccept as Tn}from"../services/PromptSuggestion/speculation.js";import{IdeOnboardingDialog as vn}from"../components/IdeOnboardingDialog.js";import{EffortCallout as kn,shouldShowEffortCallout as jn}from"../components/EffortCallout.js";import{RemoteCallout as bn}from"../components/RemoteCallout.js";import{activityManager as In}from"../utils/activityManager.js";import{createAbortController as An}from"../utils/abortController.js";import{MCPConnectionManager as wn}from"../services/mcp/MCPConnectionManager.js";import{useFeedbackSurvey as Rn}from"../components/FeedbackSurvey/useFeedbackSurvey.js";import{useMemorySurvey as Pn}from"../components/FeedbackSurvey/useMemorySurvey.js";import{usePostCompactSurvey as xn}from"../components/FeedbackSurvey/usePostCompactSurvey.js";import{FeedbackSurvey as Mn}from"../components/FeedbackSurvey/FeedbackSurvey.js";import{useInstallMessages as En}from"../hooks/notifs/useInstallMessages.js";import{useAwaySummary as Dn}from"../hooks/useAwaySummary.js";import{useChromeExtensionNotification as _n}from"../hooks/useChromeExtensionNotification.js";import{useOfficialMarketplaceNotification as Ln}from"../hooks/useOfficialMarketplaceNotification.js";import{usePromptsFromClaudeInChrome as On}from"../hooks/usePromptsFromClaudeInChrome.js";import{getTipToShowOnSpinner as Nn,recordShownTip as Un}from"../services/tips/tipScheduler.js";import{checkAndDisableBypassPermissionsIfNeeded as Bn,checkAndDisableAutoModeIfNeeded as qn,useKickOffCheckAndDisableBypassPermissionsIfNeeded as Hn,useKickOffCheckAndDisableAutoModeIfNeeded as $n}from"../utils/permissions/bypassPermissionsKillswitch.js";import{SandboxManager as Fn}from"../utils/sandbox/sandbox-adapter.js";import{SANDBOX_NETWORK_ACCESS_TOOL_NAME as Vn}from"../cli/structuredIO.js";import{useFileHistorySnapshotInit as Xn}from"../hooks/useFileHistorySnapshotInit.js";import{SandboxPermissionRequest as Jn}from"../components/permissions/SandboxPermissionRequest.js";import{SandboxViolationExpandedView as Kn}from"../components/SandboxViolationExpandedView.js";import{useSettingsErrors as Wn}from"../hooks/notifs/useSettingsErrors.js";import{useMcpConnectivityStatus as Qn}from"../hooks/notifs/useMcpConnectivityStatus.js";import{useAutoModeUnavailableNotification as Gn}from"../hooks/notifs/useAutoModeUnavailableNotification.js";import{AUTO_MODE_DESCRIPTION as Yn}from"../components/AutoModeOptInDialog.js";import{useLspInitializationNotification as zn}from"../hooks/notifs/useLspInitializationNotification.js";import{useLspPluginRecommendation as Zn}from"../hooks/useLspPluginRecommendation.js";import{LspRecommendationMenu as er}from"../components/LspRecommendation/LspRecommendationMenu.js";import{useClaudeCodeHintRecommendation as tr}from"../hooks/useClaudeCodeHintRecommendation.js";import{PluginHintMenu as or}from"../components/ClaudeCodeHint/PluginHintMenu.js";import{DesktopUpsellStartup as sr,shouldShowDesktopUpsellStartup as nr}from"../components/DesktopUpsell/DesktopUpsellStartup.js";import{usePluginInstallationStatus as rr}from"../hooks/notifs/usePluginInstallationStatus.js";import{usePluginAutoupdateNotification as ir}from"../hooks/notifs/usePluginAutoupdateNotification.js";import{performStartupChecks as ar}from"../utils/plugins/performStartupChecks.js";import{UserTextMessage as lr}from"../components/messages/UserTextMessage.js";import{AwsAuthStatusBox as cr}from"../components/AwsAuthStatusBox.js";import{useRateLimitWarningNotification as mr}from"../hooks/notifs/useRateLimitWarningNotification.js";import{useDeprecationWarningNotification as ur}from"../hooks/notifs/useDeprecationWarningNotification.js";import{useNpmDeprecationNotification as pr}from"../hooks/notifs/useNpmDeprecationNotification.js";import{useIDEStatusIndicator as dr}from"../hooks/notifs/useIDEStatusIndicator.js";import{useModelMigrationNotifications as fr}from"../hooks/notifs/useModelMigrationNotifications.js";import{useCanSwitchToExistingSubscription as gr}from"../hooks/notifs/useCanSwitchToExistingSubscription.js";import{useTeammateLifecycleNotification as hr}from"../hooks/notifs/useTeammateShutdownNotification.js";import{useFastModeNotification as Sr}from"../hooks/notifs/useFastModeNotification.js";import{AutoRunIssueNotification as Cr,shouldAutoRunIssue as yr,getAutoRunIssueReasonText as Tr,getAutoRunCommand as vr}from"../utils/autoRunIssue.js";import{TungstenLiveMonitor as kr}from"../tools/TungstenTool/TungstenLiveMonitor.js";const jr=e("WEB_BROWSER_TOOL")?r("../tools/WebBrowserTool/WebBrowserPanel.js"):null;import{IssueFlagBanner as br}from"../components/PromptInput/IssueFlagBanner.js";import{useIssueFlagBanner as Ir}from"../hooks/useIssueFlagBanner.js";import{CompanionSprite as Ar,CompanionFloatingBubble as wr,MIN_COLS_FOR_FULL_SPRITE as Rr}from"../buddy/CompanionSprite.js";import{DevBar as Pr}from"../components/DevBar.js";import{REMOTE_SAFE_COMMANDS as xr}from"../commands.js";import{FullscreenLayout as Mr,useUnseenDivider as Er,computeUnseenDivider as Dr}from"../components/FullscreenLayout.js";import{isFullscreenEnvEnabled as _r,maybeGetTmuxMouseHint as Lr,isMouseTrackingEnabled as Or}from"../utils/fullscreen.js";import{AlternateScreen as Nr}from"../ink/components/AlternateScreen.js";import{ScrollKeybindingHandler as Ur}from"../components/ScrollKeybindingHandler.js";import{useMessageActions as Br,MessageActionsKeybindings as qr,MessageActionsBar as Hr}from"../components/messageActions.js";import{setClipboard as $r}from"../ink/termio/osc.js";import{createAttachmentMessage as Fr,getQueuedCommandAttachments as Vr}from"../utils/attachments.js";const Xr=[],Jr={maybeLoadOlder:e=>{}};function TranscriptModeFooter(e){const n=i(9),{showAllInTranscript:r,virtualScroll:a,searchBadge:l,suppressShowAll:c,status:m}=e,u=void 0!==c&&c,p=Ot("app:toggleTranscript","Global","ctrl+o"),d=Ot("transcript:toggleShowAll","Transcript","ctrl+e"),f=l?" · n/N para navegar":a?` · ${C.arrowUp}${C.arrowDown} desplazar · inicio/fin extremo`:u?"":` · ${d} para ${r?"contraer":"mostrar todo"}`;let g,h,S;return n[0]!==f||n[1]!==p?(g=t(w,{dimColor:!0,children:["Mostrando transcripción detallada · ",p," para alternar",f]}),n[0]=f,n[1]=p,n[2]=g):g=n[2],n[3]!==l||n[4]!==m?(h=m?t(s,{children:[o(A,{flexGrow:1}),t(w,{children:[m," "]})]}):l?t(s,{children:[o(A,{flexGrow:1}),t(w,{dimColor:!0,children:[l.current,"/",l.count," "]})]}):null,n[3]=l,n[4]=m,n[5]=h):h=n[5],n[6]!==g||n[7]!==h?(S=t(A,{noSelect:!0,alignItems:"center",alignSelf:"center",borderTopDimColor:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,borderStyle:"single",marginTop:1,paddingLeft:2,width:"100%",children:[g,h]}),n[6]=g,n[7]=h,n[8]=S):S=n[8],S}function TranscriptSearchBar({jumpRef:e,count:s,current:n,onClose:r,onCancel:i,setHighlight:a,initialQuery:l}){const{query:c,cursorOffset:m}=T({isActive:!0,initialQuery:l,onExit:()=>r(c),onCancel:i}),[u,p]=L.useState("building");L.useEffect(()=>{let t=!0;const o=e.current?.warmSearchIndex;if(o)return p("building"),o().then(e=>{t&&(e<20?p(null):(p({ms:e}),setTimeout(()=>t&&p(null),2e3)))}),()=>{t=!1};p(null)},[]);const d="building"!==u;O(()=>{d&&(e.current?.setSearchQuery(c),a(c))},[c,d]);const f=m,g=f<c.length?c[f]:" ";return t(A,{borderTopDimColor:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,borderStyle:"single",marginTop:1,paddingLeft:2,width:"100%",noSelect:!0,children:[o(w,{children:"/"}),o(w,{children:c.slice(0,f)}),o(w,{inverse:!0,children:g}),f<c.length&&o(w,{children:c.slice(f+1)}),o(A,{flexGrow:1}),"building"===u?o(w,{dimColor:!0,children:"indexando… "}):u?t(w,{dimColor:!0,children:["indexado en ",u.ms,"ms "]}):0===s&&c?o(w,{color:"error",children:"sin coincidencias "}):s>0?t(w,{dimColor:!0,children:[n,"/",s," "]}):null]})}const Kr=["⠂","⠐"];function AnimatedTerminalTitle(e){const t=i(6),{isAnimating:o,title:s,disabled:n,noPrefix:r}=e,a=x(),[l,c]=B(0);let m,u;t[0]!==n||t[1]!==o||t[2]!==r||t[3]!==a?(m=()=>{if(n||r||!o||!a)return;const e=setInterval(_temp2,960,c);return()=>clearInterval(e)},u=[n,r,o,a],t[0]=n,t[1]=o,t[2]=r,t[3]=a,t[4]=m,t[5]=u):(m=t[4],u=t[5]),O(m,u);return M(n?null:r?s:`${o?Kr[l]??"✳":"✳"} ${s}`),null}function _temp2(e){return e(_temp)}function _temp(e){return(e+1)%Kr.length}export function REPL({commands:n,debug:i,initialTools:C,initialMessages:T,pendingHookMessages:M,initialFileHistorySnapshots:ie,initialContentReplacements:ae,initialAgentName:ce,initialAgentColor:me,mcpClients:pe,dynamicMcpConfig:de,autoConnectIdeFlag:ve,strictMcpConfig:at=!1,systemPrompt:Ot,appendSystemPrompt:ao,onBeforeQuery:vo,onTurnComplete:on,disabled:kr=!1,mainThreadAgentDefinition:Pr,disableSlashCommands:Kr=!1,taskListId:Wr,remoteSessionConfig:Qr,directConnectConfig:Gr,sshSession:Yr,thinkingConfig:zr}){const Zr=!!Qr,ei=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_TERMINAL_TITLE)||ye(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE),[]),ti=N(()=>!1,[]),oi=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_VIRTUAL_SCROLL)||ye(process.env.CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL),[]),si=!!e("MESSAGE_ACTIONS")&&N(()=>ye(process.env.CONTEXT_CODE_DISABLE_MESSAGE_ACTIONS)||ye(process.env.CLAUDE_CODE_DISABLE_MESSAGE_ACTIONS),[]);O(()=>(Se(`[REPL:mount] REPL mounted, disabled=${kr}`),()=>Se("[REPL:unmount] REPL unmounting")),[kr]);const[ni,ri]=B(Pr),ii=as(e=>e.toolPermissionContext),ai=as(e=>e.verbose),li=as(e=>e.mcp),ci=as(e=>e.plugins),mi=as(e=>e.agentDefinitions),ui=as(e=>e.fileHistory),pi=as(e=>e.initialMessage),di=gn(),fi=as(e=>e.spinnerTip),gi="tasks"===as(e=>e.expandedView),hi=as(e=>e.pendingWorkerRequest),Si=as(e=>e.pendingSandboxRequest),Ci=as(e=>e.teamContext),yi=as(e=>e.tasks),Ti=as(e=>e.workerSandboxPermissions),vi=as(e=>e.elicitation),ki=as(e=>e.ultraplanPendingChoice),ji=as(e=>e.ultraplanLaunchPending),bi=as(e=>e.viewingAgentTaskId),Ii=ls(),Ai=bi?yi[bi]:void 0,wi=_e(Ai)&&Ai.retain&&!Ai.diskLoaded;O(()=>{if(!bi||!wi)return;const e=bi;js(he(e)).then(t=>{Ii(o=>{const s=o.tasks[e];if(!_e(s)||s.diskLoaded||!s.retain)return o;const n=s.messages??[],r=new Set(n.map(e=>e.uuid)),i=t?t.messages.filter(e=>!r.has(e.uuid)):[];return{...o,tasks:{...o.tasks,[e]:{...s,messages:[...i,...n],diskLoaded:!0}}}})})},[bi,wi,Ii]);const Ri=cs(),Pi=W(),xi=is(),[Mi,Ei]=B(n);Vo(Zr?void 0:oe(),Ei);const Di=L.useSyncExternalStore(Zs?.subscribeToProactiveChanges??PROACTIVE_NO_OP_SUBSCRIBE,Zs?.isProactiveActive??PROACTIVE_FALSE),_i=as(e=>e.isBriefOnly),Li=N(()=>os(ii),[ii,Di,_i]);Hn(),$n();const[Oi,Ni]=B(de),Ui=q(e=>{Ni(e)},[Ni]),[Bi,qi]=B("prompt"),[Hi,$i]=B(!1),[Fi,Vi]=B(!1),[Xi,Ji]=B(""),Ki=U(0),Wi=U(void 0),Qi=U(!1),{addNotification:Gi,removeNotification:Yi}=F();let zi=SUGGEST_BG_PR_NOOP;const Zi=Bo(pe,li.clients),[ea,ta]=B(void 0),[oa,sa]=B(null),[na,ra]=B(null),[ia,aa]=B(!1),[la,ca]=B(()=>!1),[ma,ua]=B(()=>jn(xi)),pa=as(e=>e.showRemoteCallout),[da,fa]=B(()=>nr());fr(),gr(),dr({ideSelection:ea,mcpClients:Zi,ideInstallationStatus:na}),Qn({mcpClients:Zi}),Gn(),rr(),ir(),Wn(),mr(xi),Sr(),ur(xi),pr(),useAntOrgWarningNotification(),En(),_n(),Ln(),zn(),hr();const{recommendation:ga,handleResponse:ha}=Zn(),{recommendation:Sa,handleResponse:Ca}=tr(),ya=N(()=>[...Li,...C],[Li,C]);Xo({enabled:!Zr});const Ta=Qo();O(()=>{Zr||ar(Ii)},[Ii,Zr]),On(Zr?Xr:Zi,ii.mode),qt(Ii,T,{enabled:!Zr});const va=Ho(ya,li.tools,ii),{tools:ka,allowedAgentTypes:ja}=N(()=>{if(!ni)return{tools:va,allowedAgentTypes:void 0};const e=ns(ni,va,!1,!0);return{tools:e.resolvedTools,allowedAgentTypes:e.allowedAgentTypes}},[ni,va]),ba=Fo(Mi,ci.commands),Ia=Fo(ba,li.commands),Aa=N(()=>Kr?[]:Ia,[Kr,Ia]);Ye(Zr?Xr:li.clients),ts(Zr?Xr:li.clients,ta);const[wa,Ra]=B("responding"),Pa=U(wa);Pa.current=wa;const[xa,Ma]=B([]),[Ea,Da]=B(null);O(()=>{if(Ea&&!Ea.isStreaming&&Ea.streamingEndedAt){const e=3e4-(Date.now()-Ea.streamingEndedAt);if(e>0){const t=setTimeout(Da,e,null);return()=>clearTimeout(t)}Da(null)}},[Ea]);const[_a,La]=B(null),Oa=U(null),Na=q(e=>{Oa.current=e,La(e)},[]),Ua=U(()=>{}),Ba=U(()=>{}),qa=U(null),Ha=U(null),$a=U(0),Fa=L.useRef(new Ce).current,Va=L.useSyncExternalStore(Fa.subscribe,Fa.getSnapshot),[Xa,Ja]=L.useState(Qr?.hasInitialPrompt??!1),Ka=Va||Xa,[Wa,Qa]=L.useState(void 0),Ga=L.useRef(0),Ya=L.useRef(!1),za=L.useRef(0),Za=L.useRef(0),el=L.useRef(null),tl=L.useCallback(()=>{za.current=Date.now(),Za.current=0,el.current=null},[]),ol=L.useRef(!1);Va&&!ol.current&&tl(),ol.current=Va;const sl=L.useCallback(e=>{Ja(e),e&&tl()},[tl]),nl=L.useRef(null),rl=L.useRef(void 0),il=L.useRef(void 0),[al,ll]=L.useState(!1),[cl,ml]=B(null);O(()=>{cl?.notifications&&cl.notifications.forEach(e=>{Gi({key:"auto-updater-notification",text:e,priority:"low"})})},[cl,Gi]),O(()=>{_r()&&Lr().then(e=>{e&&Gi({key:"tmux-mouse-hint",text:e,priority:"low"})})},[]);const[ul,pl]=B(!1);O(()=>{0},[]);const[dl,fl]=B(null),[gl,hl]=B([]),Sl=q(e=>{hl(t=>[...t,e])},[]),Cl=q(e=>{hl(t=>0===t.length?[e]:[...t.slice(0,-1),e])},[]),yl=q(()=>{hl(e=>e.slice(0,-1))},[]),Tl=q(()=>{hl([])},[]),vl=U(null),kl=q(e=>{if(Se(`setToolJSX called with: ${JSON.stringify({hasJsx:!!e?.jsx,shouldHidePromptInput:e?.shouldHidePromptInput,isLocalJSXCommand:e?.isLocalJSXCommand,clearLocalJSX:e?.clearLocalJSX})}`),e?.isLocalJSXCommand){const{clearLocalJSX:t,...o}=e;return vl.current={...o,isLocalJSXCommand:!0},void fl(o)}return vl.current?e?.clearLocalJSX?(Se("Clearing local JSX command as requested"),vl.current=null,void fl(null)):void Se("Ignoring setToolJSX update because a local JSX command is active"):e?.clearLocalJSX?(Se("Clearing tool JSX (no local command active)"),void fl(null)):void fl(e)},[]),[jl,bl]=B([]),[Il,Al]=B(null),[wl,Rl]=B([]),[Pl,xl]=B([]),Ml=U(new Map),El=!1!==as(e=>e.settings.terminalTitleFromRename)?ys(se()):void 0,[Dl,_l]=B(),Ll=U((T?.length??0)>0),Ol=ni?.agentType,Nl=El??Ol??Dl??"Context Code",Ul=jl.length>0||Pl.length>0||hi||Si,Bl=!0===dl?.isLocalJSXCommand&&null!=dl?.jsx,ql=Ka&&!Ul&&!Bl;O(()=>{if(Ka&&!Ul&&!Bl)return J(),()=>K()},[Ka,Ul,Bl]);const Hl=Ul||Bl?"waiting":Ka?"busy":"idle",$l="waiting"!==Hl?void 0:jl.length>0?`approve ${jl[0].tool.name}`:hi?"worker request":Si?"sandbox request":Bl?"dialog open":"input needed";O(()=>{e("BG_SESSIONS")&&Js({status:Hl,waitingFor:$l})},[Hl,$l]);const Fl=mo("tengu_terminal_sidebar",!1)&&(ro().showStatusInTerminalTab??!1);E(ei||!Fl?null:Hl),O(()=>(Ne(bl),()=>Ue()),[bl]);const[Vl,Xl]=B(T??[]),Jl=U(Vl),Kl=U(!1),Wl=q(e=>{const t=Jl.current,o="function"==typeof e?e(Jl.current):e;if(Jl.current=o,o.length<Ga.current)Ga.current=0;else if(o.length>t.length&&Ya.current){const e=o.length-t.length;(0===t.length||o[0]===t[0]?o.slice(-e):o.slice(0,e)).some(Ft)?Ya.current=!1:Ga.current=o.length}Xl(o)},[]),Ql=q(e=>{void 0!==e?(Ga.current=Jl.current.length,Ya.current=!0):Ya.current=!1,Qa(e)},[]),{dividerIndex:Gl,dividerYRef:Yl,onScrollAway:zl,onRepin:Zl,jumpToNew:ec,shiftDivider:tc}=Er(Vl.length);e("AWAY_SUMMARY")&&Dn(Vl,Wl,Ka);const[oc,sc]=B(null),nc=U(null),rc=q(e=>{const t=Jl.current.find(t=>t.uuid===e)?.uuid,o=Jl.current.find(t=>t.uuid.slice(0,24)===e.slice(0,24))?.uuid,s=t??o;s?sc({uuid:s,msgType:"user",expanded:!1}):Gi({key:"timeline-jump-not-found",text:"Message no longer available in active transcript",color:"warning",priority:"medium",timeoutMs:3e3})},[Gi]),ic=N(()=>Dr(Vl,Gl),[Gl,Vl.length]),ac=q(()=>{qa.current?.scrollToBottom(),Zl(),sc(null)},[Zl,sc]),lc=Vl.at(-1),cc=null!=lc&&Ft(lc);O(()=>{cc&&ac()},[cc,lc,ac]);const{maybeLoadOlder:mc}=e("KAIROS")?it({config:Qr,setMessages:Wl,scrollRef:qa,onPrepend:tc}):Jr,uc=q((t,o)=>{$a.current=Date.now(),t?Zl():(zl(o),e("KAIROS")&&mc(o),e("BUDDY")&&Ii(e=>void 0===e.companionReaction?e:{...e,companionReaction:void 0}))},[Zl,zl,mc,Ii]),pc=It(M,Wl),dc=H(Vl),fc=Vl.length-dc.length;fc>0&&Se(`[useDeferredValue] Messages deferred by ${fc} (${dc.length}→${Vl.length})`);const[gc,hc]=B(null),[Sc,Cc]=B(()=>ke()),yc=U(Sc);yc.current=Sc;const Tc=U(null),vc=q(e=>{zi(yc.current,e)||(""===yc.current&&""!==e&&Date.now()-$a.current>=3e3&&ac(),yc.current=e,Cc(e),ll(e.trim().length>0))},[ll,ac,zi]);O(()=>{if(0===Sc.trim().length)return;const e=setTimeout(ll,1500,!1);return()=>clearTimeout(e)},[Sc]);const[kc,jc]=B("prompt"),[bc,Ic]=B(),Ac=q(e=>{const t=new Set(e);Ei(e=>e.filter(e=>t.has(e.name)||xr.has(e)))},[Ei]),[wc,Rc]=B(new Set),Pc=U(!1),xc=st({config:Qr,setMessages:Wl,setIsLoading:sl,onInit:Ac,setToolUseConfirmQueue:bl,tools:ya,setStreamingToolUses:Ma,setStreamMode:Ra,setInProgressToolUseIDs:Rc}),Mc=nt({config:Gr,setMessages:Wl,setIsLoading:sl,setToolUseConfirmQueue:bl,tools:ya}),Ec=rt({session:Yr,setMessages:Wl,setIsLoading:sl,setToolUseConfirmQueue:bl,tools:ya}),Dc=Ec.isRemoteMode?Ec:Mc.isRemoteMode?Mc:xc,[_c,Lc]=B({}),[Oc,Nc]=B(0),Uc=U(0),Bc=U([]),qc=q(e=>{const t=Uc.current;if(Uc.current=e(t),Uc.current>t){const e=Bc.current;if(e.length>0){const t=e.at(-1);t.lastTokenTime=Date.now(),t.endResponseLength=Uc.current}}},[]),[Hc,$c]=B(null),Fc=!(as(e=>e.settings.prefersReducedMotion)??!1)&&!Q(),Vc=q(e=>{Fc&&$c(e)},[Fc]),Xc=Hc&&Fc&&Hc.substring(0,Hc.lastIndexOf("\n")+1)||null,[Jc,Kc]=B(0),[Wc,Qc]=B(null),[Gc,Yc]=B(null),[zc,Zc]=B(null),[em,tm]=B(!1),[om,sm]=B(void 0),[nm,rm]=B(!1),[im,am]=B(Yo()),[lm,cm]=B(null),mm=U(Ka),um=U(!1),pm=U(!1),dm=U(Jc);dm.current=Jc;const[fm]=B(()=>({current:Ps(T,ae)})),[gm,hm]=B(ro().hasAcknowledgedCostThreshold),[Sm,Cm]=B("INSERT"),[ym,Tm]=B(!1),[vm,km]=B(!1),[jm,bm]=B(!1);O(()=>{ki&&ym&&Tm(!1)},[ki,ym]);const Im=x(),Am=U(Im);Am.current=Im;const[wm]=P(),Rm=L.useRef(!1),Pm=q(()=>{if(Rm.current)return;Rm.current=!0;const e=Jl.current.slice(Gm.current);for(const t of As(e))Qm.current.add(t);Gm.current=Jl.current.length,Nn({theme:wm,readFileState:Wm.current,bashTools:Qm.current}).then(async e=>{if(e){const t=await e.content({theme:wm});Ii(e=>({...e,spinnerTip:t})),Un(e)}else Ii(e=>void 0===e.spinnerTip?e:{...e,spinnerTip:void 0})})},[Ii,wm]),xm=q(()=>{sl(!1),Ql(void 0),Uc.current=0,Bc.current=[],$c(null),Ma([]),Qc(null),Yc(null),Zc(null),Pm(),He(),no()},[Pm]),Mm=N(()=>De(yi).some(e=>"running"===e.status),[yi]);O(()=>{if(!Mm&&null!==nl.current){const e=Date.now()-nl.current,t=rl.current;nl.current=null,rl.current=void 0,Wl(o=>[...o,yo(e,t,f(o,vs))])}},[Mm,Wl]);const Em=U(!1);O(()=>{if(e("TRANSCRIPT_CLASSIFIER")){if("auto"!==ii.mode)return void(Em.current=!1);if(Em.current)return;if((ro().autoPermissionsNotificationCount??0)>=3)return;const e=setTimeout((e,t)=>{e.current=!0,io(e=>{const t=e.autoPermissionsNotificationCount??0;return t>=3?e:{...e,autoPermissionsNotificationCount:t+1}}),t(e=>[...e,ko(Yn,"warning")])},800,Em,Wl);return()=>clearTimeout(e)}},[ii.mode,Wl]);const Dm=U(!1);O(()=>{if(Dm.current)return;const e=cn();if(!e?.creationDurationMs||e.usedSparsePaths)return;if(e.creationDurationMs<15e3)return;Dm.current=!0;const t=Math.round(e.creationDurationMs/1e3);Wl(e=>[...e,ko(`Worktree creation took ${t}s. For large repos, set \`worktree.sparsePaths\` in .claude/settings.json to check out only the directories you need — e.g. \`{"worktree": {"sparsePaths": ["src", "packages/foo"]}}\`.`,"info")])},[Wl]);const _m=N(()=>{const e=Vl.findLast(e=>"assistant"===e.type);if("assistant"!==e?.type)return!1;const t=e.message.content.filter(e=>"tool_use"===e.type&&wc.has(e.id));return t.length>0&&t.every(e=>"tool_use"===e.type&&e.name===so)},[Vl,wc]),{onBeforeQuery:Lm,onTurnComplete:Om,render:Nm}=ct({enabled:ti,setMessages:Wl,inputValue:Sc,setInputValue:vc,setToolJSX:kl}),Um=(!dl||!0===dl.showSpinner)&&0===jl.length&&0===Pl.length&&(Ka||Wa||Mm||dn()>0)&&!hi&&!_m&&(!Xc||_i),Bm=jl.length>0||Pl.length>0||wl.length>0||vi.queue.length>0||Ti.queue.length>0,qm=Rn(Vl,Ka,Oc,"session",Bm),Hm=(lt(Wl),Ir(Vl,Oc)),$m=N(()=>({...qm,handleSelect:e=>{nu.current=!1;const t=qm.handleSelect(e);"bad"===e&&!t&&yr("feedback_survey_bad")&&(su("feedback_survey_bad"),nu.current=!0)}}),[qm]),Fm=xn(Vl,Ka,Bm,{enabled:!Zr}),Vm=Pn(Vl,Ka,Bm,{enabled:!Zr}),Xm=useFrustrationDetection(Vl,Ka,Bm,"closed"!==$m.state||"closed"!==Fm.state||"closed"!==Vm.state);rn({autoConnectIdeFlag:ve,ideToInstallExtension:oa,setDynamicMcpConfig:Ni,setShowIdeOnboarding:aa,setIDEInstallationState:ra}),Xn(ie,ui,e=>Ii(t=>({...t,fileHistory:e})));const Jm=q(async(t,o,s)=>{const n=performance.now();try{const i=bs(o.messages);if(e("COORDINATOR_MODE")){const e=r("../coordinator/coordinatorMode.js").matchSessionMode(o.mode);if(e){const{getAgentDefinitionsWithOverrides:t,getActiveAgentsFromList:o}=r("../tools/AgentTool/loadAgentsDir.js");t.cache.clear?.();const s=await t(te());Ii(e=>({...e,agentDefinitions:{...s,allAgents:s.allAgents,activeAgents:o(s.allAgents)}})),i.push(ko(e,"warning"))}}const a=es();await Zo("resume",{getAppState:()=>Ri.getState(),setAppState:Ii,signal:AbortSignal.timeout(a),timeoutMs:a});const l=await zo("resume",{sessionId:t,agentType:ni?.agentType,model:xi});i.push(...l),"fork"===s?ms(o,ge(t)):us(o,ge(t)),Hs(o,Ii),o.fileHistorySnapshots&&_s(o);const{agentDefinition:c}=qs(o.agentSetting,Pr,mi);ri(c),Ii(e=>({...e,agent:c?.agentType})),Ii(e=>({...e,standaloneAgentContext:Bs(o.agentName,o.agentColor)})),Xs(o.agentName),Zm(i,o.projectPath??te()),xm(),Na(null),am(t);const m=vt(t);yt(),Tt(),ne(ge(t),o.fullPath?g(o.fullPath):null);const{renameRecordingForSession:u}=await import("../utils/asciicast.js");if(await u(),await gs(),fs(),Cs(o),Ll.current=!0,_l(void 0),"fork"!==s)Fs(),$s(o.worktreeSession),hs(),Ws({abortController:new AbortController,getAppState:()=>Ri.getState(),setAppState:Ii});else{const e=cn();e&&ks(e)}if(e("COORDINATOR_MODE")){const{saveMode:e}=r("../utils/sessionStorage.js"),{isCoordinatorMode:t}=r("../coordinator/coordinatorMode.js");e(t()?"coordinator":"normal")}m&&re(m),fm.current&&"fork"!==s&&(fm.current=xs(i,o.contentReplacements??[])),Wl(()=>i),kl(null),vc(""),co("tengu_session_resumed",{entrypoint:s,success:!0,resume_duration_ms:Math.round(performance.now()-n)})}catch(e){throw co("tengu_session_resumed",{entrypoint:s,success:!1}),e}},[xm,Ii]),[Km]=B(()=>G(z)),Wm=U(Km),Qm=U(new Set),Gm=U(0),Ym=U(new Set),zm=U(new Set),Zm=q((e,t)=>{const o=Is(e,t,z);Wm.current=Y(Wm.current,o);for(const t of As(e))Qm.current.add(t)},[]);O(()=>{T&&T.length>0&&(Zm(T,te()),Ws({abortController:new AbortController,getAppState:()=>Ri.getState(),setAppState:Ii}))},[]);const{status:eu,reverify:tu}=Et(),[ou,su]=B(null),nu=U(!1),[ru,iu]=B(null),[au,lu]=B(!1),cu=!Ka&&nm;const mu=function(){if(au||ru)return;if(em)return"message-selector";if(al)return;if(wl[0])return"sandbox-permission";const t=!dl||dl.shouldContinueAnimation;return t&&jl[0]?"tool-permission":t&&Pl[0]?"prompt":t&&Ti.queue[0]?"worker-sandbox-permission":t&&vi.queue[0]?"elicitation":t&&cu?"cost":t&&lm?"idle-return":e("ULTRAPLAN")&&t&&!Ka&&ki?"ultraplan-choice":e("ULTRAPLAN")&&t&&!Ka&&ji?"ultraplan-launch":t&&ia?"ide-onboarding":t&&ma?"effort-callout":t&&pa?"remote-callout":t&&ga?"lsp-recommendation":t&&Sa?"plugin-hint":t&&da?"desktop-upsell":void 0}(),uu=al&&(wl[0]||jl[0]||Pl[0]||Ti.queue[0]||vi.queue[0]||cu);il.current=mu,O(()=>{if(!Ka)return;const e="tool-permission"===mu,t=Date.now();e&&null===el.current?el.current=t:e||null===el.current||(Za.current+=t-el.current,el.current=null)},[mu,Ka]);const pu=U(mu);function onCancel(){if(gl.length>0){const e=gl[gl.length-1];return e?.onClose?.(),void yl()}if("elicitation"!==mu){if(Se(`[onCancel] focusedInputDialog=${mu} streamMode=${wa}`),(e("PROACTIVE")||e("KAIROS"))&&Zs?.pauseProactive(),Fa.forceEnd(),pm.current=!1,Hc?.trim()&&Wl(e=>[...e,Co({content:Hc})]),xm(),e("TOKEN_BUDGET")&&l(null),"tool-permission"===mu)jl[0]?.onAbort(),bl([]);else if("prompt"===mu){for(const e of Pl)e.reject(new Error("Prompt cancelled by user"));xl([]),Oa.current?.abort("user-cancel")}else Dc.isRemoteMode?Dc.cancelRequest():Oa.current?.abort("user-cancel");Na(null),Om(Jl.current,!0)}}$(()=>{"tool-permission"===pu.current!==("tool-permission"===mu)&&ac(),pu.current=mu},[mu,ac]);const du=q(()=>{const e=mn(Sc,0);e&&(vc(e.text),jc("prompt"),e.images.length>0&&Lc(t=>{const o={...t};for(const t of e.images)o[t.id]=t;return o}))},[vc,jc,Sc,Lc]),fu={setToolUseConfirmQueue:bl,onCancel,onAgentsKilled:()=>Wl(e=>[...e,To()]),isMessageSelectorVisible:em||!!ym,screen:Bi,abortSignal:_a?.signal,popCommandFromQueue:du,vimMode:Sm,isLocalJSXCommand:dl?.isLocalJSXCommand,isSearchingHistory:vm,isHelpOpen:jm,inputMode:kc,inputValue:Sc,streamMode:wa};O(()=>{Ct()>=5&&!nm&&!gm&&(co("tengu_cost_threshold_reached",{}),hm(!0),lo()&&rm(!0))},[Vl,nm,gm]);const gu=q(async t=>{if(tn()&&be()){const e=Ie(),o=await Ae(t.host,e);return new Promise(s=>{o?(Re({requestId:e,host:t.host,resolve:s}),Ii(o=>({...o,pendingSandboxRequest:{requestId:e,host:t.host}}))):Rl(e=>[...e,{hostPattern:t,resolvePromise:s}])})}return new Promise(o=>{let s=!1;function resolveOnce(e){s||(s=!0,o(e))}if(Rl(e=>[...e,{hostPattern:t,resolvePromise:resolveOnce}]),e("BRIDGE_MODE")){const e=Ri.getState().replBridgePermissionCallbacks;if(e){const o=Yo();e.sendRequest(o,Vn,{host:t.host},Yo(),`Allow network connection to ${t.host}?`);const s=e.onResponse(o,e=>{s();const o="allow"===e.behavior;Rl(e=>(e.filter(e=>e.hostPattern.host===t.host).forEach(e=>e.resolvePromise(o)),e.filter(e=>e.hostPattern.host!==t.host)));const n=Ml.current.get(t.host);if(n){for(const e of n)e();Ml.current.delete(t.host)}}),cleanup=()=>{s(),e.cancelRequest(o)},n=Ml.current.get(t.host)??[];n.push(cleanup),Ml.current.set(t.host,n)}}})},[Ii,Ri]);O(()=>{const e=Fn.getSandboxUnavailableReason();if(e){if(Fn.isSandboxRequired())return process.stderr.write(`\nError: sandbox required but unavailable: ${e}\n sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`),void Mo(1,"other");Se(`sandbox disabled: ${e}`,{level:"warn"}),Gi({key:"sandbox-unavailable",jsx:t(s,{children:[o(w,{color:"warning",children:"sandbox disabled"}),o(w,{dimColor:!0,children:" · /sandbox"})]}),priority:"medium"})}},[Gi]),Fn.isSandboxingEnabled()&&Fn.initialize(gu).catch(e=>{process.stderr.write(`\n❌ Sandbox Error: ${$t(e)}\n`),Mo(1,"other")});const hu=q((e,t)=>{Ii(o=>({...o,toolPermissionContext:{...e,mode:t?.preserveMode?o.toolPermissionContext.mode:e.mode}})),setImmediate(e=>{e(e=>(e.forEach(e=>{e.recheckPermission()}),e))},bl)},[Ii,bl]);O(()=>(Be(hu),()=>qe()),[hu]);const Su=Wt(bl,hu),Cu=q((e,t)=>o=>new Promise((s,n)=>{xl(r=>[...r,{request:o,title:e,toolInputSummary:t,resolve:s,reject:n}])}),[]),yu=q((t,o,s,n)=>{const r=Ri.getState(),computeTools=()=>{const e=Ri.getState(),t=ss(e.toolPermissionContext,e.mcp.tools),o=$o(ya,t,e.toolPermissionContext.mode);return ni?ns(ni,o,!1,!0).resolvedTools:o};return{abortController:s,options:{commands:Aa,tools:computeTools(),debug:i,verbose:r.verbose,mainLoopModel:n,thinkingConfig:!1!==r.thinkingEnabled?zr:{type:"disabled"},mcpClients:Uo(pe,r.mcp.clients),mcpResources:r.mcp.resources,ideInstallationStatus:na,isNonInteractiveSession:!1,dynamicMcpConfig:Oi,theme:wm,agentDefinitions:ja?{...r.agentDefinitions,allowedAgentTypes:ja}:r.agentDefinitions,customSystemPrompt:Ot,appendSystemPrompt:ao,refreshTools:computeTools},getAppState:()=>Ri.getState(),setAppState:Ii,messages:t,setMessages:Wl,updateFileHistoryState(e){Ii(t=>{const o=e(t.fileHistory);return o===t.fileHistory?t:{...t,fileHistory:o}})},updateAttributionState(e){Ii(t=>{const o=e(t.attribution);return o===t.attribution?t:{...t,attribution:o}})},openMessageSelector:()=>{kr||tm(!0)},openMessageSelectorAtMessage:e=>{if(kr)return;const o=t.find(t=>t.uuid===e),s=t.find(t=>t.uuid.slice(0,24)===e.slice(0,24)),n=o??s;n&&Qe(n)&&sm(n),tm(!0)},jumpToMessage:rc,onChangeAPIKey:tu,readFileState:Wm.current,setToolJSX:kl,addNotification:Gi,appendSystemMessage:e=>Wl(t=>[...t,e]),sendOSNotification:e=>{X(e,Pi)},onChangeDynamicMcpConfig:Ui,onInstallIDEExtension:sa,nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:zm.current,dynamicSkillDirTriggers:new Set,discoveredSkillNames:Ym.current,setResponseLength:qc,pushApiMetricsEntry:void 0,setStreamMode:Ra,onCompactProgress:e=>{switch(e.type){case"hooks_start":Yc("claudeBlue_FOR_SYSTEM_SPINNER"),Zc("claudeBlueShimmer_FOR_SYSTEM_SPINNER"),Qc("pre_compact"===e.hookType?"Running PreCompact hooks…":"post_compact"===e.hookType?"Running PostCompact hooks…":"Running SessionStart hooks…");break;case"compact_start":Qc("Compacting conversation");break;case"compact_end":Qc(null),Yc(null),Zc(null)}},setInProgressToolUseIDs:Rc,setHasInterruptibleToolInProgress:e=>{Pc.current=e},resume:Jm,setConversationId:am,requestPrompt:e("HOOK_PROMPTS")?Cu:void 0,contentReplacementState:fm.current}},[Aa,ya,ni,i,pe,na,Oi,wm,ja,Ri,Ii,tu,Gi,Wl,Ui,Jm,Cu,kr,Ot,ao,am,rc,Vl]),Tu=q(()=>{Oa.current?.abort("background");const e=fn(e=>"task-notification"===e.mode);(async()=>{const t=yu(Jl.current,[],new AbortController,xi),[o,s,n]=await Promise.all([pt(t.options.tools,xi,Array.from(ii.additionalWorkingDirectories.keys()),t.options.mcpClients),gt(),ft()]),r=dt({mainThreadAgentDefinition:ni,toolUseContext:t,customSystemPrompt:Ot,defaultSystemPrompt:o,appendSystemPrompt:ao});t.renderedSystemPrompt=r;const i=(await Vr(e).catch(()=>[])).map(Fr),a=new Set;for(const e of Jl.current)"attachment"===e.type&&"queued_command"===e.attachment.type&&"task-notification"===e.attachment.commandMode&&"string"==typeof e.attachment.prompt&&a.add(e.attachment.prompt);const l=i.filter(e=>"queued_command"===e.attachment.type&&("string"!=typeof e.attachment.prompt||!a.has(e.attachment.prompt)));Sn({messages:[...Jl.current,...l],queryParams:{systemPrompt:r,userContext:s,systemContext:n,canUseTool:Su,toolUseContext:t,querySource:qo()},description:Nl,setAppState:Ii,agentDefinition:ni})})()},[xi,ii,ni,yu,Ot,ao,Su,Ii]),{handleBackgroundSession:vu}=Cn({setMessages:Wl,setIsLoading:sl,resetLoadingState:xm,setAbortController:Na,onBackgroundQuery:Tu}),ku=q(t=>{po(t,t=>{fo(t)?(_r()?Wl(e=>[...go(e,{includeSnipped:!0}),t]):Wl(()=>[t]),am(Yo()),(e("PROACTIVE")||e("KAIROS"))&&Zs?.setContextBlocked(!1)):"progress"===t.type&&Ts(t.data.type)?Wl(e=>{const o=e.at(-1);if("progress"===o?.type&&o.parentToolUseID===t.parentToolUseID&&o.data.type===t.data.type){const o=e.slice();return o[o.length-1]=t,o}return[...e,t]}):Wl(e=>[...e,t]),(e("PROACTIVE")||e("KAIROS"))&&("assistant"===t.type&&"isApiErrorMessage"in t&&t.isApiErrorMessage?Zs?.setContextBlocked(!0):"assistant"===t.type&&Zs?.setContextBlocked(!1))},e=>{qc(t=>t+e.length)},Ra,Ma,e=>{Wl(t=>t.filter(t=>t!==e)),Ss(e.uuid)},Da,e=>{const t=Date.now(),o=Uc.current;Bc.current.push({...e,firstTokenTime:t,lastTokenTime:t,responseLengthBaseline:o,endResponseLength:o})},Vc)},[Wl,qc,Ra,Ma,Da,Vc]),ju=q(async(t,o,s,n,r,i,a)=>{if(n){const e=Uo(pe,Ri.getState().mcp.clients);yn.handleQueryStart(e);const t=nn(e);t&&sn(t)}if(Go(),!(ei||El||Ol||Ll.current)){const e=o.find(e=>"user"===e.type&&!e.isMeta),t="user"===e?.type?ho(e.message.content):null;!t||t.startsWith(`<${Po}>`)||t.startsWith(`<${wo}>`)||t.startsWith(`<${Ro}>`)||t.startsWith(`<${Ao}>`)||(Ll.current=!0,Io(t,(new AbortController).signal).then(e=>{e?_l(e):Ll.current=!1},()=>{Ll.current=!1}))}if(Ri.setState(e=>{const t=e.toolPermissionContext.alwaysAllowRules.command;return t===r||t?.length===r.length&&t.every((e,t)=>e===r[t])?e:{...e,toolPermissionContext:{...e.toolPermissionContext,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,command:r}}}}),!n)return o.some(fo)&&(am(Yo()),(e("PROACTIVE")||e("KAIROS"))&&Zs?.setContextBlocked(!1)),xm(),void Na(null);const l=yu(t,o,s,i),{tools:c,mcpClients:m}=l.options;if(void 0!==a){const e=l.getAppState;l.getAppState=()=>({...e(),effortValue:a})}Lo("query_context_loading_start");const[,,u,p,d]=await Promise.all([Bn(ii,Ii),e("TRANSCRIPT_CLASSIFIER")?qn(ii,Ii,Ri.getState().fastMode):void 0,pt(c,i,Array.from(ii.additionalWorkingDirectories.keys()),m),gt(),ft()]),f={...p,...Kt(m,to()?eo():void 0),...(e("PROACTIVE")||e("KAIROS"))&&Zs?.isProactiveActive()&&!Am.current?{terminalFocus:"The terminal is unfocused — the user is not actively watching."}:{}};Lo("query_context_loading_end");const g=dt({mainThreadAgentDefinition:ni,toolUseContext:l,customSystemPrompt:Ot,defaultSystemPrompt:u,appendSystemPrompt:ao});l.renderedSystemPrompt=g,Lo("query_query_start"),le(),ue(),fe();for await(const e of No({messages:t,systemPrompt:g,userContext:f,systemContext:d,canUseTool:Su,toolUseContext:l,querySource:qo()}))ku(e);e("BUDDY")&&fireCompanionObserver(Jl.current,e=>Ii(t=>t.companionReaction===e?t:{...t,companionReaction:e})),Lo("query_end"),xm(),Oo(),await(on?.(Jl.current))},[pe,xm,yu,ii,Ii,Ot,on,ao,Su,ni,ku,El,ei]),bu=q(async(t,o,s,n,r,i,a,p)=>{if(tn()){const e=Pe(),t=xe();e&&t&&je(e,t,!0)}const g=Fa.tryStart();if(null===g)return co("tengu_concurrent_onquery_detected",{}),void t.filter(e=>"user"===e.type&&!e.isMeta).map(e=>ho(e.message.content)).filter(e=>null!==e).forEach((e,t)=>{un({value:e,mode:"prompt"}),0===t&&co("tengu_concurrent_onquery_enqueued",{})});try{if(tl(),Wl(e=>[...e,...t]),Uc.current=0,e("TOKEN_BUDGET")){const e=a?d(a):null;l(e??c())}Bc.current=[],Ma([]),$c(null);const m=Jl.current;if(a&&await Lm(a,m,t.length),i&&a){if(!await i(a,m))return}await ju(m,t,o,s,n,r,p)}finally{if(Fa.end(g)){let t;Kc(Date.now()),pm.current=!1,xm(),await Om(Jl.current,o.signal.aborted),Ua.current(),e("TOKEN_BUDGET")&&(null!==c()&&c()>0&&!o.signal.aborted&&(t={tokens:m(),limit:c(),nudges:u()}),l(null));const s=Date.now()-za.current-Za.current;if((s>3e4||void 0!==t)&&!o.signal.aborted&&!Di){De(Ri.getState().tasks).some(e=>"running"===e.status)?(null===nl.current&&(nl.current=za.current),t&&(rl.current=t)):Wl(e=>[...e,yo(s,t,f(e,vs))])}Na(null)}if("user-cancel"===o.signal.reason&&!Fa.isActive&&""===yc.current&&0===dn()&&!Ri.getState().viewingAgentTaskId){const e=Jl.current,t=e.findLast(Qe);if(t){const o=e.lastIndexOf(t);Ge(e,o)&&(wt(),Ba.current(t))}}}},[ju,Ii,xm,Fa,Lm,Om]),Iu=U(!1);O(()=>{const t=pi;!t||Ka||Iu.current||(Iu.current=!0,async function(t){if(t.clearContext){const e=t.message.planContent?ps():void 0,{clearConversation:o}=await import("../commands/clear/conversation.js");await o({setMessages:Wl,readFileState:Wm.current,discoveredSkillNames:Ym.current,loadedNestedMemoryPaths:zm.current,getAppState:()=>Ri.getState(),setAppState:Ii,setConversationId:am}),Ll.current=!1,_l(void 0),Qm.current.clear(),Gm.current=0,e&&ds(se(),e)}const o=t.message.planContent&&!1;Ii(s=>{let n=t.mode?Gt(s.toolPermissionContext,zt(t.mode,t.allowedPrompts)):s.toolPermissionContext;return e("TRANSCRIPT_CLASSIFIER")&&"auto"===t.mode&&(n=Zt({...n,mode:"auto",prePlanMode:void 0})),{...s,initialMessage:null,toolPermissionContext:n,...o&&{pendingPlanVerification:{plan:t.message.planContent,verificationStarted:!1,verificationCompleted:!1}}}}),Ls()&&Es(e=>{Ii(t=>({...t,fileHistory:e(t.fileHistory)}))},t.message.uuid),await pc();const s=t.message.message.content;if("string"!=typeof s||t.message.planContent){const e=An();Na(e),bu([t.message],e,!0,[],xi)}else Au(s,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}});setTimeout(e=>{e.current=!1},100,Iu)}(t))},[pi,Ka,Wl,Ii,bu,xi,ka]);const Au=q(async(t,o,s,n)=>{if(ac(),(e("PROACTIVE")||e("KAIROS"))&&Zs?.resumeProactive(),!s&&t.trim().startsWith("/")){const e=Rt(t,_c).trim(),s=e.indexOf(" "),r=-1===s?e.slice(1):e.slice(1,s),i=-1===s?"":e.slice(s+1).trim(),a=Aa.find(e=>Ke(e)&&(e.name===r||e.aliases?.includes(r)||Je(e)===r));"clear"===a?.name&&Kl.current&&(co("tengu_idle_return_action",{action:"hint_converted",variant:Kl.current,idleMinutes:Math.round((Date.now()-dm.current)/6e4),messageCount:Jl.current.length,totalInputTokens:p()}),Kl.current=!1);const l=Fa.isActive&&(a?.immediate||n?.fromKeybinding);if(a&&l&&"local-jsx"===a.type){t.trim()===yc.current.trim()&&(vc(""),o.setCursorOffset(0),o.clearBuffer(),Lc({}));const e=Pt(t).filter(e=>"text"===_c[e.id]?.type),s=e.length,r=e.reduce((e,t)=>e+(_c[t.id]?.content.length??0),0);co("tengu_paste_text",{pastedTextCount:s,pastedTextBytes:r}),co("tengu_immediate_command_executed",{commandName:a.name,fromKeybinding:n?.fromKeybinding??!1});return void(async()=>{let e=!1;const t=yu(Jl.current,[],An(),xi),s=await a.load(),n=await s.call((t,s)=>{e=!0,kl({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0});const n=[];t&&"skip"!==s?.display&&(Gi({key:`immediate-${a.name}`,text:t,priority:"immediate"}),_r()||n.push(jo(bo(Je(a),i)),jo(`<${Po}>${xo(t)}</${Po}>`))),s?.metaMessages?.length&&n.push(...s.metaMessages.map(e=>So({content:e,isMeta:!0}))),n.length&&Wl(e=>[...e,...n]),void 0!==bc&&(vc(bc.text),o.setCursorOffset(bc.cursorOffset),Lc(bc.pastedContents),Ic(void 0))},t,i);n&&!e&&kl({jsx:n,shouldHidePromptInput:!1,isLocalJSXCommand:!0})})()}}if(Dc.isRemoteMode&&!t.trim())return;{const e=mo("tengu_willow_mode","off"),n=Number(process.env.CONTEXT_CODE_IDLE_THRESHOLD_MINUTES??process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES??75),r=Number(process.env.CONTEXT_CODE_IDLE_TOKEN_THRESHOLD??process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD??1e5);if("off"!==e&&!ro().idleReturnDismissed&&!pm.current&&!s&&!t.trim().startsWith("/")&&dm.current>0&&p()>=r){const s=(Date.now()-dm.current)/6e4;if(s>=n&&"dialog"===e)return cm({input:t,idleMinutes:s}),vc(""),o.setCursorOffset(0),void o.clearBuffer()}}n?.fromKeybinding||(At({display:s?t:xt(t,kc),pastedContents:s?{}:_c}),"bash"===kc&&Mt(t.trim()));const r=!s&&t.trim().startsWith("/"),i=!Ka||s||Dc.isRemoteMode;if(void 0!==bc&&!r&&i?(vc(bc.text),o.setCursorOffset(bc.cursorOffset),Lc(bc.pastedContents),Ic(void 0)):i&&(n?.fromKeybinding||(vc(""),o.setCursorOffset(0)),Lc({})),i&&(jc("prompt"),ta(void 0),Nc(e=>e+1),o.clearBuffer(),Rm.current=!1,r||"prompt"!==kc||s||Dc.isRemoteMode||(Ql(t),tl()),e("COMMIT_ATTRIBUTION")&&Ii(e=>({...e,attribution:Ns(e.attribution,e=>{Us(e).catch(e=>{Se(`Attribution: Failed to save snapshot: ${e}`)})})}))),s){const{queryRequired:e}=await Tn(s.state,s.speculationSessionTimeSavedMs,s.setAppState,t,{setMessages:Wl,readFileState:Wm,cwd:te()});if(e){const e=An();Na(e),bu([],e,!0,[],xi)}return}if(Dc.isRemoteMode&&(!r||"local-jsx"!==Aa.find(e=>{const o=t.trim().slice(1).split(/\s/)[0];return Ke(e)&&(e.name===o||e.aliases?.includes(o)||Je(e)===o)})?.type)){const e=Object.values(_c),o=e.filter(e=>"image"===e.type),s=o.length>0?o.map(e=>e.id):void 0;let n=t.trim(),r=t.trim();if(e.length>0){const o=[],s=[],i=t.trim();i&&(o.push({type:"text",text:i}),s.push({type:"text",text:i}));for(const t of e)if("image"===t.type){const e={type:"base64",media_type:t.mediaType??"image/png",data:t.content};o.push({type:"image",source:e}),s.push({type:"image",source:e})}else o.push({type:"text",text:t.content}),s.push({type:"text",text:t.content});n=o,r=s}const i=So({content:n,imagePasteIds:s});return Wl(e=>[...e,i]),void await Dc.sendMessage(r,{uuid:i.uuid})}await pc(),await Eo({input:t,helpers:o,queryGuard:Fa,isExternalLoading:Xa,mode:kc,commands:Aa,onInputChange:vc,setPastedContents:Lc,setToolJSX:kl,getToolUseContext:yu,messages:Jl.current,mainLoopModel:xi,pastedContents:_c,ideSelection:ea,setUserInputOnProcessing:Ql,setAbortController:Na,abortController:_a,onQuery:bu,setAppState:Ii,querySource:qo(),onBeforeQuery:vo,canUseTool:Su,addNotification:Gi,setMessages:Wl,streamMode:Pa.current,hasInterruptibleToolInProgress:Pc.current,onJumpToMessage:rc}),(r||Ka)&&void 0!==bc&&(vc(bc.text),o.setCursorOffset(bc.cursorOffset),Lc(bc.pastedContents),Ic(void 0))},[Fa,Ka,Xa,kc,Aa,vc,jc,Lc,Nc,ta,kl,yu,xi,_c,ea,Ql,Na,Gi,bu,bc,Ic,Ii,vo,Su,xc,Wl,pc,ac]),wu=q(async(e,o,s)=>{_e(o)?(Oe(o.id,So({content:e}),Ii),"running"===o.status?Le(o.id,e,Ii):rs({agentId:o.id,prompt:e,toolUseContext:yu(Jl.current,[],new AbortController,xi),canUseTool:Su}).catch(e=>{Se(`resumeAgentBackground failed: ${$t(e)}`),Gi({key:`resume-agent-failed-${o.id}`,jsx:t(w,{color:"error",children:["Failed to resume agent: ",$t(e)]}),priority:"low"})})):Ee(o.id,e,Ii),vc(""),s.setCursorOffset(0),s.clearBuffer()},[Ii,vc,yu,Su,xi,Gi]),Ru=q(()=>{const e=ou?vr(ou):"/issue";su(null),Au(e,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(t=>{Se(`Auto-run ${e} failed: ${$t(t)}`)})},[Au,ou]),Pu=q(()=>{su(null)},[]),xu=q(()=>{Au("/feedback",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(e=>{Se(`Survey feedback request failed: ${e instanceof Error?e.message:String(e)}`)})},[Au]),Mu=U(Au);Mu.current=Au;const Eu=q(()=>{Mu.current("/rate-limit-options",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})},[]),Du=q(async()=>{if(lu(!0),e("BG_SESSIONS")&&Vs())return a("tmux",["detach-client"],{stdio:"ignore"}),void lu(!1);if(null!==cn())return void iu(o(ln,{showWorktree:!0,onDone:()=>{},onCancel:()=>{iu(null),lu(!1)}}));const t=await an.load(),s=await t.call(()=>{});iu(s),null===s&&lu(!1)},[]),_u=q(()=>{tm(e=>!e)},[]),Lu=q(t=>{const o=Jl.current,s=o.lastIndexOf(t);-1!==s&&(co("tengu_conversation_rewind",{preRewindMessageCount:o.length,postRewindMessageCount:s,messagesRemoved:o.length-s,rewindToMessageIndex:s}),Wl(o.slice(0,s)),am(Yo()),ws(),e("CONTEXT_COLLAPSE")&&r("../services/contextCollapse/index.js").resetContextCollapse(),Ii(e=>({...e,toolPermissionContext:t.permissionMode&&e.toolPermissionContext.mode!==t.permissionMode?{...e.toolPermissionContext,mode:t.permissionMode}:e.toolPermissionContext,promptSuggestion:{text:null,promptId:null,shownAt:0,acceptedAt:0,generationRequestId:null}})))},[Wl,Ii]),Ou=q(e=>{Lu(e);const t=uo(e);if(t&&(vc(t.text),jc(t.mode)),Array.isArray(e.message.content)&&e.message.content.some(e=>"image"===e.type)){const t=e.message.content.filter(e=>"image"===e.type);if(t.length>0){const o={};t.forEach((t,s)=>{if("base64"===t.source.type){const n=e.imagePasteIds?.[s]??s+1;o[n]={id:n,type:"image",content:t.source.data,mediaType:t.source.media_type}}}),Lc(o)}}},[Lu,vc]);Ba.current=Ou;const Nu=q(async e=>{setImmediate((e,t)=>e(t),Ou,e)},[Ou]),Uu={copy:e=>{$r(e).then(e=>{e&&process.stdout.write(e),Gi({key:"selection-copied",text:"copied",color:"success",priority:"immediate",timeoutMs:2e3})})},edit:async e=>{const t=(e=>{const t=e.slice(0,24);return Vl.findIndex(e=>e.uuid.slice(0,24)===t)})(e.uuid),o=t>=0?Vl[t]:void 0;if(!o||!Qe(o))return;const s=!await Os(ui,o.uuid),n=Ge(Vl,t);s&&n?(onCancel(),Nu(o)):(sm(o),tm(!0))}},{enter:Bu,handlers:qu}=Br(oc,sc,nc,Uu);kt(jt()),$e(Vl,Vl.length===T?.length);const{sendBridgeResult:Hu}=Fe(Vl,Wl,Oa,Aa,xi);Ua.current=Hu,Ve(Vl),Xe(Vl),Ys(Vl,Ka,onCancel,Ea),zs(jl),bt();const $u=U(!1);O(()=>{di.length<1?$u.current=!1:$u.current||($u.current=!0,io(e=>({...e,promptQueueUseCount:(e.promptQueueUseCount??0)+1})))},[di.length]);const Fu=q(async e=>{await Eo({helpers:{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}},queryGuard:Fa,commands:Aa,onInputChange:()=>{},setPastedContents:()=>{},setToolJSX:kl,getToolUseContext:yu,messages:Vl,mainLoopModel:xi,ideSelection:ea,setUserInputOnProcessing:Ql,setAbortController:Na,onQuery:bu,setAppState:Ii,querySource:qo(),onBeforeQuery:vo,canUseTool:Su,addNotification:Gi,setMessages:Wl,queuedCommands:e,onJumpToMessage:rc})},[Fa,Aa,kl,yu,Vl,xi,ea,Ql,Su,Na,bu,Gi,Ii,vo,rc]);Do({executeQueuedInput:Fu,hasActiveLocalJsxUI:Bl,queryGuard:Fa}),O(()=>{In.recordUserActivity(),Z(!0)},[Sc,Oc]),O(()=>{1===Oc&&St()},[Oc]),O(()=>{const e=mm.current;if(mm.current=Ka,!e||Ka)return;if(0===Oc)return;!0===ro().taskCompleteNotifEnabled&&X({message:"Respuesta finalizada",notificationType:"task_complete"},Pi)},[Ka,Oc,Pi]),O(()=>{const e=!Ka&&(jl.length>0||Pl.length>0||!!hi||!!Si),t=um.current;if(um.current=e,!e||t)return;!0===ro().inputNeededNotifEnabled&&X({message:"Se requiere tu aprobacion o entrada",notificationType:"input_needed"},Pi)},[Ka,jl.length,Pl.length,hi,Si,Pi]),O(()=>{if(Ka)return;if(0===Oc)return;if(0===Jc)return;const e=setTimeout((e,t,o,s,n)=>{if(ee()>e)return;const r=Date.now()-e;!t&&!o&&void 0===s.current&&r>=ro().messageIdleNotifThresholdMs&&X({message:"Claude is waiting for your input",notificationType:"idle_prompt"},n)},ro().messageIdleNotifThresholdMs,Jc,Ka,dl,il,Pi);return()=>clearTimeout(e)},[Ka,dl,Oc,Jc,Pi]),O(()=>{if(0===Jc)return;if(Ka)return;const e=mo("tengu_willow_mode","off");if("hint"!==e&&"hint_v2"!==e)return;if(ro().idleReturnDismissed)return;const n=Number(process.env.CONTEXT_CODE_IDLE_TOKEN_THRESHOLD??process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD??1e5);if(p()<n)return;const r=6e4*Number(process.env.CONTEXT_CODE_IDLE_THRESHOLD_MINUTES??process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES??75)-(Date.now()-Jc),i=setTimeout((e,n,r,i,a)=>{if(0===r.current.length)return;const l=p(),c=Te(l),m=(Date.now()-e)/6e4;n({key:"idle-return-hint",jsx:"hint_v2"===i?t(s,{children:[o(w,{dimColor:!0,children:"new task? "}),o(w,{color:"suggestion",children:"/clear"}),o(w,{dimColor:!0,children:" to save "}),t(w,{color:"suggestion",children:[c," tokens"]})]}):t(w,{color:"warning",children:["new task? /clear to save ",c," tokens"]}),priority:"medium",timeoutMs:2147483647}),a.current=i,co("tengu_idle_return_action",{action:"hint_shown",variant:i,idleMinutes:Math.round(m),messageCount:r.current.length,totalInputTokens:l})},Math.max(0,r),Jc,Gi,Jl,e,Kl);return()=>{clearTimeout(i),Yi("idle-return-hint"),Kl.current=!1}},[Jc,Ka,Gi,Yi]);const Vu=q((e,t)=>{if(Fa.isActive)return!1;if(pn().some(e=>"prompt"===e.mode||"bash"===e.mode))return!1;const o=An();Na(o);const s=So({content:e,isMeta:!!t?.isMeta||void 0});return bu([s],o,!0,[],xi),!0},[bu,xi,Ri]),Xu=Xt({setInputValueRaw:Cc,inputValueRef:yc,insertTextRef:Tc});if(Qs({enabled:tn(),isLoading:Ka,focusedInputDialog:mu,onSubmitMessage:Vu}),_o({isLoading:Ka,onSubmitMessage:Vu}),Gs(jl),e("AGENT_TRIGGERS")){const e=Ri.getState().kairosEnabled;en({isLoading:Ka,assistantMode:e,setMessages:Wl})}O(()=>{di.some(e=>"now"===e.priority)&&Oa.current?.abort("interrupt")},[di]),O(()=>(async function(){tu();const e=await ht();if(e.length>0){const t=e.map(e=>` [${e.type}] ${e.path} (${e.content.length} chars)${e.parent?` (included by ${e.parent})`:""}`).join("\n");Se(`Loaded ${e.length} CLAUDE.md/rules files:\n${t}`)}else Se("No CLAUDE.md/rules files found");for(const t of e)Wm.current.set(t.path,{content:t.contentDiffersFromDisk?t.rawContent??t.content:t.content,timestamp:Date.now(),offset:void 0,limit:void 0,isPartialView:t.contentDiffersFromDisk})}(),()=>{yn.shutdown()}),[]);const{internal_eventEmitter:Ju}=R(),[Ku,Wu]=B(0);O(()=>{const handleSuspend=()=>{process.stdout.write("\nContext Code has been suspended. Run `fg` to bring Context Code back.\nNote: ctrl + z now suspends Context Code, ctrl + _ undoes input.\n")},handleResume=()=>{Wu(e=>e+1)};return Ju?.on("suspend",handleSuspend),Ju?.on("resume",handleResume),()=>{Ju?.off("suspend",handleSuspend),Ju?.off("resume",handleResume)}},[Ju]);const Qu=N(()=>{if(!Ka)return null;const e=Vl.filter(e=>"progress"===e.type&&"hook_progress"===e.data.type&&("Stop"===e.data.hookEvent||"SubagentStop"===e.data.hookEvent));if(0===e.length)return null;const t=e.at(-1)?.toolUseID;if(!t)return null;if(Vl.some(e=>"system"===e.type&&"stop_hook_summary"===e.subtype&&e.toolUseID===t))return null;const o=e.filter(e=>e.toolUseID===t),s=o.length,n=f(Vl,e=>{if("attachment"!==e.type)return!1;const o=e.attachment;return"hookEvent"in o&&("Stop"===o.hookEvent||"SubagentStop"===o.hookEvent)&&"toolUseID"in o&&o.toolUseID===t}),r=o.find(e=>e.data.statusMessage)?.data.statusMessage;if(r)return 1===s?`${r}…`:`${r}… ${n}/${s}`;const i="SubagentStop"===o[0]?.data.hookEvent?"subagent stop":"stop";return 1===s?`running ${i} hook`:`running stop hooks… ${n}/${s}`},[Vl,Ka]),Gu=q(()=>{hc({messagesLength:Vl.length,streamingToolUsesLength:xa.length})},[Vl.length,xa.length]),Yu=q(()=>{hc(null)},[]),zu=_r()&&!oi,Zu=U(null),[ep,tp]=B(!1),[op,sp]=B(""),[np,rp]=B(0),[ip,ap]=B(0),lp=q((e,t)=>{rp(e),ap(t)},[]);y((e,t,o)=>{if(t.ctrl||t.meta)return;if("/"===e)return Zu.current?.setAnchor(),tp(!0),void o.stopImmediatePropagation();const s=e[0];if(("n"===s||"N"===s)&&e===s.repeat(e.length)&&np>0){const t="n"===s?Zu.current?.nextMatch:Zu.current?.prevMatch;if(t)for(let o=0;o<e.length;o++)t();o.stopImmediatePropagation()}},{isActive:"transcript"===Bi&&zu&&!ep&&!Fi});const{setQuery:cp,scanElement:mp,setPositions:up}=k(),pp=v().columns,dp=L.useRef(pp);L.useEffect(()=>{dp.current!==pp&&(dp.current=pp,(op||ep)&&(tp(!1),sp(""),rp(0),ap(0),Zu.current?.disarmSearch(),cp("")))},[pp,op,ep,cp]),y((e,t,o)=>{if(!t.ctrl&&!t.meta){if("q"===e)return Yu(),void o.stopImmediatePropagation();if("["!==e||Fi){if("v"===e){if(o.stopImmediatePropagation(),Qi.current)return;Qi.current=!0;const e=Ki.current,setStatus=t=>{e===Ki.current&&(clearTimeout(Wi.current),Ji(t))};setStatus(`rendering ${dc.length} messages…`),(async()=>{try{const e=Math.max(80,(process.stdout.columns??80)-6),t=(await j(dc,ka,e)).replace(/[ \t]+$/gm,""),o=h(S(),`cc-transcript-${Date.now()}.txt`);await I(o,t);const s=b(o);setStatus(s?`opening ${o}`:`wrote ${o} · no $VISUAL/$EDITOR set`)}catch(e){setStatus(`render failed: ${e instanceof Error?e.message:String(e)}`)}Qi.current=!1,e===Ki.current&&(Wi.current=setTimeout(e=>e(""),4e3,Ji))})()}}else Vi(!0),$i(!0),o.stopImmediatePropagation()}},{isActive:"transcript"===Bi&&zu&&!ep});const fp="transcript"===Bi&&zu;O(()=>{fp||(sp(""),rp(0),ap(0),tp(!1),Ki.current++,clearTimeout(Wi.current),Vi(!1),Ji(""))},[fp]),O(()=>{cp(fp?op:""),fp||up(null)},[fp,op,cp,up]);const gp={screen:Bi,setScreen:qi,showAllInTranscript:Hi,setShowAllInTranscript:$i,messageCount:Vl.length,onEnterTranscript:Gu,onExitTranscript:Yu,virtualScrollActive:zu,searchBarOpen:ep},hp=gc?dc.slice(0,gc.messagesLength):dc,Sp=gc?xa.slice(0,gc.streamingToolUsesLength):xa;if(Bt({onOpenBackgroundTasks:Bl?void 0:()=>Tm(!0)}),Ht(),"transcript"===Bi){const e=!_r()||oi||Fi?void 0:qa,n=o(Jo,{messages:hp,tools:ka,commands:Aa,verbose:!0,toolJSX:null,toolUseConfirmQueue:[],inProgressToolUseIDs:wc,isMessageSelectorVisible:!1,conversationId:im,screen:Bi,agentDefinitions:mi,streamingToolUses:Sp,showAllInTranscript:Hi,onOpenRateLimitOptions:Eu,isLoading:Ka,hidePastThinking:!0,streamingThinking:Ea,scrollRef:e,jumpRef:Zu,onSearchMatchesChange:lp,scanElement:mp,setPositions:up,disableRenderCap:Fi}),r=dl&&o(A,{flexDirection:"column",width:"100%",children:dl.jsx}),i=t(Lt,{children:[o(AnimatedTerminalTitle,{isAnimating:ql,title:Nl,disabled:ei,noPrefix:Fl}),o(Dt,{...gp}),o(Jt,{voiceHandleKeyEvent:Xu.handleKeyEvent,stripTrailing:Xu.stripTrailing,resetAnchor:Xu.resetAnchor,isActive:!dl?.isLocalJSXCommand}),o(_t,{onSubmit:Au,isActive:!dl?.isLocalJSXCommand}),e?o(Ur,{scrollRef:qa,isActive:"ultraplan-choice"!==mu,isModal:!ep,onScroll:()=>Zu.current?.disarmSearch()}):null,o(Ut,{...fu}),e?o(Mr,{scrollRef:qa,scrollable:t(s,{children:[n,r,o(Kn,{})]}),bottom:ep?o(TranscriptSearchBar,{jumpRef:Zu,initialQuery:"",count:np,current:ip,onClose:e=>{sp(np>0?e:""),tp(!1),e||(rp(0),ap(0),Zu.current?.setSearchQuery(""))},onCancel:()=>{tp(!1),Zu.current?.setSearchQuery(""),Zu.current?.setSearchQuery(op),cp(op)},setHighlight:cp}):o(TranscriptModeFooter,{showAllInTranscript:Hi,virtualScroll:!0,status:Xi||void 0,searchBadge:op&&np>0?{current:ip,count:np}:void 0})}):t(s,{children:[n,r,o(Kn,{}),o(TranscriptModeFooter,{showAllInTranscript:Hi,virtualScroll:!1,suppressShowAll:Fi,status:Xi||void 0})]})]});return e?o(Nr,{mouseTracking:Or(),children:i}):i}const Cp=bi?yi[bi]:void 0,yp=Cp&&Ks(Cp)?Cp:void 0,Tp=yp??(Cp&&_e(Cp)?Cp:void 0),vp=Fc||!Ka,kp=Tp?Tp.messages??[]:vp?Vl:dc,jp=Wa&&!Tp&&kp.length<=Ga.current?Wa:void 0,bp="tool-permission"===mu?o(ze,{onDone:()=>bl(([e,...t])=>t),onReject:du,toolUseConfirm:jl[0],toolUseContext:yu(Vl,Vl,_a??An(),xi),verbose:ai,workerBadge:jl[0]?.workerBadge,setStickyFooter:_r()?Al:void 0},jl[0]?.toolUseID):null,Ip=pp<Rr,Ap=!dl?.shouldHidePromptInput&&!mu&&!ym,wp=_r()&&!0===dl?.isLocalJSXCommand,Rp=(gl.length>0?gl[gl.length-1]?.element:null)??(wp?dl.jsx:null),Pp=o(V.Provider,{value:{stack:gl,pushModal:Sl,replaceModal:Cl,popModal:yl,clearModals:Tl},children:t(Lt,{children:[o(AnimatedTerminalTitle,{isAnimating:ql,title:Nl,disabled:ei,noPrefix:Fl}),o(Dt,{...gp}),o(Jt,{voiceHandleKeyEvent:Xu.handleKeyEvent,stripTrailing:Xu.stripTrailing,resetAnchor:Xu.resetAnchor,isActive:!dl?.isLocalJSXCommand}),o(_t,{onSubmit:Au,isActive:!dl?.isLocalJSXCommand}),o(Ur,{scrollRef:qa,isActive:_r()&&(null!=Rp||!mu||"tool-permission"===mu),onScroll:Rp||bp||Tp?void 0:uc}),e("MESSAGE_ACTIONS")&&_r()&&!si?o(qr,{handlers:qu,isActive:null!==oc}):null,o(Ut,{...fu}),o(wn,{dynamicMcpConfig:Oi,isStrictMcpConfig:at,children:o(Mr,{scrollRef:qa,overlay:bp,bottomFloat:e("BUDDY")&&Ap&&!Ip?o(wr,{}):void 0,modal:Rp,modalScrollRef:Ha,dividerYRef:Yl,hidePill:!!Tp,hideSticky:!!yp,newMessageCount:ic?.count??0,onPillClick:()=>{sc(null),ec(qa.current)},scrollable:t(s,{children:[o(Wo,{}),o(Jo,{messages:kp,tools:ka,commands:Aa,verbose:ai,toolJSX:dl,toolUseConfirmQueue:jl,inProgressToolUseIDs:yp?yp.inProgressToolUseIDs??new Set:wc,isMessageSelectorVisible:em,conversationId:im,screen:Bi,streamingToolUses:xa,showAllInTranscript:Hi,agentDefinitions:mi,onOpenRateLimitOptions:Eu,isLoading:Ka,streamingText:Ka&&!Tp?Xc:null,isBriefOnly:!Tp&&_i,unseenDivider:Tp?void 0:ic,scrollRef:_r()?qa:void 0,trackStickyPrompt:!!_r()||void 0,cursor:oc,setCursor:sc,cursorNavRef:nc}),o(cr,{}),!kr&&jp&&!Rp&&o(lr,{param:{text:jp,type:"text"},addMargin:!0,verbose:ai}),dl&&!(dl.isLocalJSXCommand&&dl.isImmediate)&&!wp&&o(A,{flexDirection:"column",width:"100%",children:dl.jsx}),!1,e("WEB_BROWSER_TOOL")?jr&&o(jr.WebBrowserPanel,{}):null,o(A,{flexGrow:1}),Um&&o(mt,{mode:wa,spinnerTip:fi,responseLengthRef:Uc,apiMetricsRef:Bc,overrideMessage:Wc,spinnerSuffix:Qu,verbose:ai,loadingStartTimeRef:za,totalPausedMsRef:Za,pauseStartTimeRef:el,overrideColor:Gc,overrideShimmerColor:zc,hasActiveTools:wc.size>0,leaderIsIdle:!Ka}),!Um&&!Ka&&!Wa&&!Mm&&_i&&!Tp&&o(ut,{}),_r()&&o(ot,{})]}),bottom:t(A,{flexDirection:e("BUDDY")&&Ip?"column":"row",width:"100%",alignItems:e("BUDDY")&&Ip?void 0:"flex-end",children:[e("BUDDY")&&Ip&&_r()&&Ap?o(Ar,{}):null,t(A,{flexDirection:"column",flexGrow:1,children:[Il,dl?.isLocalJSXCommand&&dl.isImmediate&&!wp&&o(A,{flexDirection:"column",width:"100%",children:dl.jsx}),!Um&&!dl?.isLocalJSXCommand&&gi&&Ta&&Ta.length>0&&o(A,{width:"100%",flexDirection:"column",children:o(Ko,{tasks:Ta,isStandalone:!0})}),"sandbox-permission"===mu&&o(Jn,{hostPattern:wl[0].hostPattern,onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=wl[0];if(!s)return;const n=s.hostPattern.host;if(o){const e={type:"addRules",rules:[{toolName:oo,ruleContent:`domain:${n}`}],behavior:t?"allow":"deny",destination:"localSettings"};Ii(t=>({...t,toolPermissionContext:Qt(t.toolPermissionContext,e)})),Yt(e),Fn.refreshConfig()}Rl(e=>(e.filter(e=>e.hostPattern.host===n).forEach(e=>e.resolvePromise(t)),e.filter(e=>e.hostPattern.host!==n)));const r=Ml.current.get(n);if(r){for(const e of r)e();Ml.current.delete(n)}}},wl[0].hostPattern.host),"prompt"===mu&&o(et,{title:Pl[0].title,toolInputSummary:Pl[0].toolInputSummary,request:Pl[0].request,onRespond:e=>{const t=Pl[0];t&&(t.resolve({prompt_response:t.request.prompt,selected:e}),xl(([,...e])=>e))},onAbort:()=>{const e=Pl[0];e&&(e.reject(new Error("Prompt cancelled by user")),xl(([,...e])=>e))}},Pl[0].request.prompt),hi&&o(Me,{toolName:hi.toolName,description:hi.description}),Si&&o(Me,{toolName:"Network Access",description:`Waiting for leader to approve network access to ${Si.host}`}),"worker-sandbox-permission"===mu&&o(Jn,{hostPattern:{host:Ti.queue[0].host,port:void 0},onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=Ti.queue[0];if(!s)return;const n=s.host;if(we(s.workerName,s.requestId,n,t,Ci?.teamName),o&&t){const e={type:"addRules",rules:[{toolName:oo,ruleContent:`domain:${n}`}],behavior:"allow",destination:"localSettings"};Ii(t=>({...t,toolPermissionContext:Qt(t.toolPermissionContext,e)})),Yt(e),Fn.refreshConfig()}Ii(e=>({...e,workerSandboxPermissions:{...e.workerSandboxPermissions,queue:e.workerSandboxPermissions.queue.slice(1)}}))}},Ti.queue[0].requestId),"elicitation"===mu&&o(Ze,{event:vi.queue[0],onResponse:(e,t)=>{const o=vi.queue[0];if(!o)return;o.respond({action:e,content:t});"url"===o.params.mode&&"accept"===e||Ii(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}}))},onWaitingDismiss:e=>{const t=vi.queue[0];Ii(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}})),t?.onWaitingDismiss?.(e)}},vi.queue[0].serverName+":"+String(vi.queue[0].requestId)),"cost"===mu&&o(D,{onDone:()=>{rm(!1),hm(!0),io(e=>({...e,hasAcknowledgedCostThreshold:!0})),co("tengu_cost_threshold_acknowledged",{})}}),"idle-return"===mu&&lm&&o(_,{idleMinutes:lm.idleMinutes,totalInputTokens:p(),onDone:async e=>{const t=lm;if(cm(null),co("tengu_idle_return_action",{action:e,idleMinutes:Math.round(t.idleMinutes),messageCount:Jl.current.length,totalInputTokens:p()}),"dismiss"!==e){if("never"===e&&io(e=>e.idleReturnDismissed?e:{...e,idleReturnDismissed:!0}),"clear"===e){const{clearConversation:e}=await import("../commands/clear/conversation.js");await e({setMessages:Wl,readFileState:Wm.current,discoveredSkillNames:Ym.current,loadedNestedMemoryPaths:zm.current,getAppState:()=>Ri.getState(),setAppState:Ii,setConversationId:am}),Ll.current=!1,_l(void 0),Qm.current.clear(),Gm.current=0}pm.current=!0,Mu.current(t.input,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})}else vc(t.input)}}),"ide-onboarding"===mu&&o(vn,{onDone:()=>aa(!1),installationStatus:na}),!1,!1,"effort-callout"===mu&&o(kn,{model:xi,onDone:e=>{ua(!1),"dismiss"!==e&&Ii(t=>({...t,effortValue:e}))}}),"remote-callout"===mu&&o(bn,{onDone:e=>{Ii(t=>t.showRemoteCallout?{...t,showRemoteCallout:!1,..."enable"===e&&{replBridgeEnabled:!0,replBridgeExplicit:!0,replBridgeOutboundOnly:!1}}:t)}}),ru,"plugin-hint"===mu&&Sa&&o(or,{pluginName:Sa.pluginName,pluginDescription:Sa.pluginDescription,marketplaceName:Sa.marketplaceName,sourceCommand:Sa.sourceCommand,onResponse:Ca}),"lsp-recommendation"===mu&&ga&&o(er,{pluginName:ga.pluginName,pluginDescription:ga.pluginDescription,fileExtension:ga.fileExtension,onResponse:ha}),"desktop-upsell"===mu&&o(sr,{onDone:()=>fa(!1)}),e("ULTRAPLAN")?"ultraplan-choice"===mu&&ki&&o(UltraplanChoiceDialog,{plan:ki.plan,sessionId:ki.sessionId,taskId:ki.taskId,setMessages:Wl,readFileState:Wm.current,getAppState:()=>Ri.getState(),setConversationId:am}):null,e("ULTRAPLAN")?"ultraplan-launch"===mu&&ji&&o(UltraplanLaunchDialog,{onChoice:(e,t)=>{const o=ji.blurb;if(Ii(e=>e.ultraplanLaunchPending?{...e,ultraplanLaunchPending:void 0}:e),"cancel"===e)return;Wl(e=>[...e,jo(bo("ultraplan",o))]);const appendStdout=e=>Wl(t=>[...t,jo(`<${Po}>${xo(e)}</${Po}>`)]);launchUltraplan({blurb:o,getAppState:()=>Ri.getState(),setAppState:Ii,signal:An().signal,disconnectedBridge:t?.disconnectedBridge,onSessionReady:e=>{if(!Fa.isActive)return void appendStdout(e);const t=Fa.subscribe(()=>{Fa.isActive||(t(),Ri.getState().ultraplanSessionUrl&&appendStdout(e))})}}).then(appendStdout).catch(Vt)}}):null,Nm(),!dl?.shouldHidePromptInput&&!mu&&!au&&!kr&&!oc&&t(s,{children:[ou&&o(Cr,{onRun:Ru,onCancel:Pu,reason:Tr(ou)}),"closed"!==Fm.state?o(Mn,{state:Fm.state,lastResponse:Fm.lastResponse,handleSelect:Fm.handleSelect,inputValue:Sc,setInputValue:vc,onRequestFeedback:xu}):"closed"!==Vm.state?o(Mn,{state:Vm.state,lastResponse:Vm.lastResponse,handleSelect:Vm.handleSelect,handleTranscriptSelect:Vm.handleTranscriptSelect,inputValue:Sc,setInputValue:vc,onRequestFeedback:xu,message:"How well did Claude use its memory? (optional)"}):o(Mn,{state:$m.state,lastResponse:$m.lastResponse,handleSelect:$m.handleSelect,handleTranscriptSelect:$m.handleTranscriptSelect,inputValue:Sc,setInputValue:vc,onRequestFeedback:nu.current?void 0:xu}),"closed"!==Xm.state&&o(Mn,{state:Xm.state,lastResponse:null,handleSelect:()=>{},handleTranscriptSelect:Xm.handleTranscriptSelect,inputValue:Sc,setInputValue:vc}),!1,Hm&&o(br,{}),o(tt,{debug:i,ideSelection:ea,hasSuppressedDialogs:!!uu,isLocalJSXCommandActive:Bl,getToolUseContext:yu,toolPermissionContext:ii,setToolPermissionContext:hu,apiKeyStatus:eu,commands:Aa,agents:mi.activeAgents,isLoading:Ka,onExit:Du,verbose:ai,messages:Vl,onAutoUpdaterResult:ml,autoUpdaterResult:cl,input:Sc,onInputChange:vc,mode:kc,onModeChange:jc,stashedPrompt:bc,setStashedPrompt:Ic,submitCount:Oc,onShowMessageSelector:_u,onMessageActionsEnter:e("MESSAGE_ACTIONS")&&_r()&&!si?Bu:void 0,mcpClients:Zi,pastedContents:_c,setPastedContents:Lc,vimMode:Sm,setVimMode:Cm,showBashesDialog:ym,setShowBashesDialog:Tm,onSubmit:Au,onAgentSubmit:wu,isSearchingHistory:vm,setIsSearchingHistory:km,helpOpen:jm,setHelpOpen:bm,insertTextRef:Tc,voiceInterimRange:Xu.interimRange}),o(hn,{onBackgroundSession:vu,isLoading:Ka})]}),oc&&o(Hr,{cursor:oc}),"message-selector"===mu&&o(We,{messages:Vl,preselectedMessage:om,onPreRestore:onCancel,onRestoreCode:async e=>{await Ds(e=>{Ii(t=>({...t,fileHistory:e(t.fileHistory)}))},e.uuid)},onSummarize:async(t,o,s="from")=>{const n=go(Vl),r=n.indexOf(t);if(-1===r)return void Wl(e=>[...e,ko("That message is no longer in the active context (snipped or pre-compact). Choose a more recent message.","warning")]);const i=An(),a=yu(n,[],i,xi),l=a.getAppState(),c=await pt(a.options.tools,a.options.mainLoopModel,Array.from(l.toolPermissionContext.additionalWorkingDirectories.keys()),a.options.mcpClients),m=dt({mainThreadAgentDefinition:void 0,toolUseContext:a,customSystemPrompt:a.options.customSystemPrompt,defaultSystemPrompt:c,appendSystemPrompt:a.options.appendSystemPrompt}),[u,p]=await Promise.all([gt(),ft()]),d=await Ms(n,r,a,{systemPrompt:m,userContext:u,systemContext:p,toolUseContext:a,forkContextMessages:n},o,s),f=d.messagesToKeep??[],g="up_to"===s?[...d.summaryMessages,...f]:[...f,...d.summaryMessages],h=[d.boundaryMarker,...g,...d.attachments,...d.hookResults];if(_r()&&"from"===s?Wl(e=>{const o=e.findIndex(e=>e.uuid===t.uuid);return[...e.slice(0,-1===o?0:o),...h]}):Wl(h),(e("PROACTIVE")||e("KAIROS"))&&Zs?.setContextBlocked(!1),am(Yo()),Rs(a.options.querySource),"from"===s){const e=uo(t);e&&(vc(e.text),jc(e.mode))}const S=Nt("app:toggleTranscript","Global","ctrl+o");Gi({key:"summarize-ctrl-o-hint",text:`Conversation summarized (${S} for history)`,priority:"medium",timeoutMs:8e3})},onRestoreMessage:Nu,onClose:()=>{tm(!1),sm(void 0)}}),!1]}),!e("BUDDY")||Ip&&_r()||!Ap?null:o(Ar,{})]})})},Ku)]})});return _r()?o(Nr,{mouseTracking:Or(),children:Pp}):Pp}
1
+ import{feature as e}from"../recovery/bunBundleShim.js";import{jsxs as t,jsx as o,Fragment as s}from"react/jsx-runtime";import{createRequire as n}from"module";const r=n(import.meta.url);import{c as i}from"react/compiler-runtime";import{spawnSync as a}from"child_process";import{snapshotOutputTokensForTurn as l,getCurrentTurnTokenBudget as c,getTurnOutputTokens as m,getBudgetContinuationCount as u,getTotalInputTokens as p}from"../bootstrap/state.js";import{parseTokenBudget as d}from"../utils/tokenBudget.js";import{count as f}from"../utils/array.js";import{dirname as g,join as h}from"path";import{tmpdir as S}from"os";import C from"figures";import{useInput as y}from"../ink.js";import{useSearchInput as T}from"../hooks/useSearchInput.js";import{useTerminalSize as v}from"../hooks/useTerminalSize.js";import{useSearchHighlight as k}from"../ink/hooks/use-search-highlight.js";import{renderMessagesToPlainText as j}from"../utils/exportRenderer.js";import{openFileInExternalEditor as b}from"../utils/editor.js";import{writeFile as I}from"fs/promises";import{Box as A,Text as w,useStdin as R,useTheme as P,useTerminalFocus as x,useTerminalTitle as M,useTabStatus as E}from"../ink.js";import{CostThresholdDialog as D}from"../components/CostThresholdDialog.js";import{IdleReturnDialog as _}from"../components/IdleReturnDialog.js";import*as L from"react";import{useEffect as O,useMemo as N,useRef as U,useState as B,useCallback as q,useDeferredValue as H,useLayoutEffect as $}from"react";import{useNotifications as F}from"../context/notifications.js";import{ModalStackContext as V}from"../context/modalStackContext.js";import{sendNotification as X}from"../services/notifier.js";import{startPreventSleep as J,stopPreventSleep as K}from"../services/preventSleep.js";import{useTerminalNotification as W}from"../ink/useTerminalNotification.js";import{hasCursorUpViewportYankBug as G}from"../ink/terminal.js";import{createFileStateCacheWithSizeLimit as Q,mergeFileStateCaches as Y,READ_FILE_STATE_CACHE_SIZE as z}from"../utils/fileStateCache.js";import{updateLastInteractionTime as Z,getLastInteractionTime as ee,getOriginalCwd as te,getProjectRoot as oe,getSessionId as se,switchSession as ne,setCostStateForRestore as re,getTurnHookDurationMs as ie,getTurnHookCount as ae,resetTurnHookDuration as le,getTurnToolDurationMs as ce,getTurnToolCount as me,resetTurnToolDuration as ue,getTurnClassifierDurationMs as pe,getTurnClassifierCount as de,resetTurnClassifierDuration as fe}from"../bootstrap/state.js";import{asSessionId as ge,asAgentId as he}from"../types/ids.js";import{logForDebugging as Se}from"../utils/debug.js";import{QueryGuard as Ce}from"../utils/QueryGuard.js";import{isEnvTruthy as ye}from"../utils/envUtils.js";import{formatTokens as Te,truncateToWidth as ve}from"../utils/format.js";import{consumeEarlyInput as ke}from"../utils/earlyInput.js";import{setMemberActive as je}from"../utils/swarm/teamHelpers.js";import{isSwarmWorker as be,generateSandboxRequestId as Ie,sendSandboxPermissionRequestViaMailbox as Ae,sendSandboxPermissionResponseViaMailbox as we}from"../utils/swarm/permissionSync.js";import{registerSandboxPermissionCallback as Re}from"../hooks/useSwarmPermissionPoller.js";import{getTeamName as Pe,getAgentName as xe}from"../utils/teammate.js";import{WorkerPendingPermission as Me}from"../components/permissions/WorkerPendingPermission.js";import{injectUserMessageToTeammate as Ee,getAllInProcessTeammateTasks as De}from"../tasks/InProcessTeammateTask/InProcessTeammateTask.js";import{isLocalAgentTask as _e,queuePendingMessage as Le,appendMessageToLocalAgent as Oe}from"../tasks/LocalAgentTask/LocalAgentTask.js";import{registerLeaderToolUseConfirmQueue as Ne,unregisterLeaderToolUseConfirmQueue as Ue,registerLeaderSetToolPermissionContext as Be,unregisterLeaderSetToolPermissionContext as qe}from"../utils/swarm/leaderPermissionBridge.js";import{endInteractionSpan as He}from"../utils/telemetry/sessionTracing.js";import{useLogMessages as $e}from"../hooks/useLogMessages.js";import{useReplBridge as Fe}from"../hooks/useReplBridge.js";import{useTelegramMirror as Ve}from"../hooks/useTelegramMirror.js";import{useWhatsAppMirror as Xe}from"../hooks/useWhatsAppMirror.js";import{getCommandName as Je,isCommandEnabled as Ke}from"../commands.js";import{MessageSelector as We,selectableUserMessagesFilter as Ge,messagesAfterAreOnlySynthetic as Qe}from"../components/MessageSelector.js";import{useIdeLogging as Ye}from"../hooks/useIdeLogging.js";import{PermissionRequest as ze}from"../components/permissions/PermissionRequest.js";import{ElicitationDialog as Ze}from"../components/mcp/ElicitationDialog.js";import{PromptDialog as et}from"../components/hooks/PromptDialog.js";import tt from"../components/PromptInput/PromptInput.js";import{PromptInputQueuedCommands as ot}from"../components/PromptInput/PromptInputQueuedCommands.js";import{useRemoteSession as st}from"../hooks/useRemoteSession.js";import{useDirectConnect as nt}from"../hooks/useDirectConnect.js";import{useSSHSession as rt}from"../hooks/useSSHSession.js";import{useAssistantHistory as it}from"../hooks/useAssistantHistory.js";import{SkillImprovementSurvey as at}from"../components/SkillImprovementSurvey.js";import{useSkillImprovementSurvey as lt}from"../hooks/useSkillImprovementSurvey.js";import{useMoreRight as ct}from"../moreright/useMoreRight.js";import{SpinnerWithVerb as mt,BriefIdleStatus as ut}from"../components/Spinner.js";import{getSystemPrompt as pt}from"../constants/prompts.js";import{buildEffectiveSystemPrompt as dt}from"../utils/systemPrompt.js";import{getSystemContext as ft,getUserContext as gt}from"../context.js";import{getMemoryFiles as ht}from"../utils/claudemd.js";import{startBackgroundHousekeeping as St}from"../utils/backgroundHousekeeping.js";import{getTotalCost as Ct,saveCurrentSessionCosts as yt,resetCostState as Tt,getStoredSessionCosts as vt}from"../cost-tracker.js";import{useCostSummary as kt}from"../costHook.js";import{useFpsMetrics as jt}from"../context/fpsMetrics.js";import{useAfterFirstRender as bt}from"../hooks/useAfterFirstRender.js";import{useDeferredHookMessages as It}from"../hooks/useDeferredHookMessages.js";import{addToHistory as At,removeLastFromHistory as wt,expandPastedTextRefs as Rt,parseReferences as Pt}from"../history.js";import{prependModeCharacterToInput as xt}from"../components/PromptInput/inputModes.js";import{prependToShellHistoryCache as Mt}from"../utils/suggestions/shellHistoryCompletion.js";import{useApiKeyVerification as Et}from"../hooks/useApiKeyVerification.js";import{GlobalKeybindingHandlers as Dt}from"../hooks/useGlobalKeybindings.js";import{CommandKeybindingHandlers as _t}from"../hooks/useCommandKeybindings.js";import{KeybindingSetup as Lt}from"../keybindings/KeybindingProviderSetup.js";import{useShortcutDisplay as Ot}from"../keybindings/useShortcutDisplay.js";import{getShortcutDisplay as Nt}from"../keybindings/shortcutFormat.js";import{CancelRequestHandler as Ut}from"../hooks/useCancelRequest.js";import{useBackgroundTaskNavigation as Bt}from"../hooks/useBackgroundTaskNavigation.js";import{useSwarmInitialization as qt}from"../hooks/useSwarmInitialization.js";import{useTeammateViewAutoExit as Ht}from"../hooks/useTeammateViewAutoExit.js";import{errorMessage as $t}from"../utils/errors.js";import{isHumanTurn as Ft}from"../utils/messagePredicates.js";import{logError as Vt}from"../utils/log.js";const Xt=r("../hooks/useVoiceIntegration.js").useVoiceIntegration,Jt=r("../hooks/useVoiceIntegration.js").VoiceKeybindingHandler,useFrustrationDetection=()=>({state:"closed",handleTranscriptSelect:()=>{}}),useAntOrgWarningNotification=()=>{},Kt=e("COORDINATOR_MODE")?r("../coordinator/coordinatorMode.js").getCoordinatorUserContext:()=>({});import Wt from"../hooks/useCanUseTool.js";import{applyPermissionUpdate as Gt,applyPermissionUpdates as Qt,persistPermissionUpdate as Yt}from"../utils/permissions/PermissionUpdate.js";import{buildPermissionUpdates as zt}from"../components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js";import{stripDangerousPermissionsForAutoMode as Zt}from"../utils/permissions/permissionSetup.js";import{getScratchpadDir as eo,isScratchpadEnabled as to}from"../utils/permissions/filesystem.js";import{WEB_FETCH_TOOL_NAME as oo}from"../tools/WebFetchTool/prompt.js";import{SLEEP_TOOL_NAME as so}from"../tools/SleepTool/prompt.js";import{clearSpeculativeChecks as no}from"../tools/BashTool/bashPermissions.js";import{getGlobalConfig as ro,saveGlobalConfig as io,getGlobalConfigWriteCount as ao}from"../utils/config.js";import{hasConsoleBillingAccess as lo}from"../utils/billing.js";import{logEvent as co}from"../services/analytics/index.js";import{getFeatureValue_CACHED_MAY_BE_STALE as mo}from"../services/analytics/growthbook.js";import{textForResubmit as uo,handleMessageFromStream as po,isCompactBoundaryMessage as fo,getMessagesAfterCompactBoundary as go,getContentText as ho,createUserMessage as So,createAssistantMessage as Co,createTurnDurationMessage as yo,createAgentsKilledMessage as To,createApiMetricsMessage as vo,createSystemMessage as ko,createCommandInputMessage as jo,formatCommandInputTags as bo}from"../utils/messages.js";import{generateSessionTitle as Io}from"../utils/sessionTitle.js";import{BASH_INPUT_TAG as Ao,COMMAND_MESSAGE_TAG as wo,COMMAND_NAME_TAG as Ro,LOCAL_COMMAND_STDOUT_TAG as Po}from"../constants/xml.js";import{escapeXml as xo}from"../utils/xml.js";import{gracefulShutdownSync as Mo}from"../utils/gracefulShutdown.js";import{handlePromptSubmit as Eo}from"../utils/handlePromptSubmit.js";import{useQueueProcessor as Do}from"../hooks/useQueueProcessor.js";import{useMailboxBridge as _o}from"../hooks/useMailboxBridge.js";import{queryCheckpoint as Lo,logQueryProfileReport as Oo}from"../utils/queryProfiler.js";import{query as No}from"../query.js";import{mergeClients as Uo,useMergedClients as Bo}from"../hooks/useMergedClients.js";import{getQuerySourceForREPL as qo}from"../utils/promptCategory.js";import{useMergedTools as Ho}from"../hooks/useMergedTools.js";import{mergeAndFilterTools as $o}from"../utils/toolPool.js";import{useMergedCommands as Fo}from"../hooks/useMergedCommands.js";import{useSkillsChange as Vo}from"../hooks/useSkillsChange.js";import{useManagePlugins as Xo}from"../hooks/useManagePlugins.js";import{Messages as Jo}from"../components/Messages.js";import{TaskListV2 as Ko}from"../components/TaskListV2.js";import{TeammateViewHeader as Wo}from"../components/TeammateViewHeader.js";import{useTasksV2WithCollapseEffect as Go}from"../hooks/useTasksV2.js";import{maybeMarkProjectOnboardingComplete as Qo}from"../projectOnboardingState.js";import{randomUUID as Yo}from"crypto";import{processSessionStartHooks as zo}from"../utils/sessionStart.js";import{executeSessionEndHooks as Zo,getSessionEndHookTimeoutMs as es}from"../utils/hooks.js";import{useIdeSelection as ts}from"../hooks/useIdeSelection.js";import{getTools as os,assembleToolPool as ss}from"../tools.js";import{resolveAgentTools as ns}from"../tools/AgentTool/agentToolUtils.js";import{resumeAgentBackground as rs}from"../tools/AgentTool/resumeAgent.js";import{useMainLoopModel as is}from"../hooks/useMainLoopModel.js";import{useAppState as as,useSetAppState as ls,useAppStateStore as cs}from"../state/AppState.js";import{copyPlanForFork as ms,copyPlanForResume as us,getPlanSlug as ps,setPlanSlug as ds}from"../utils/plans.js";import{clearSessionMetadata as fs,resetSessionFilePointer as gs,adoptResumedSessionFile as hs,removeTranscriptMessage as Ss,restoreSessionMetadata as Cs,getCurrentSessionTitle as ys,isEphemeralToolProgress as Ts,isLoggableMessage as vs,saveWorktreeState as ks,getAgentTranscript as js}from"../utils/sessionStorage.js";import{deserializeMessages as bs}from"../utils/conversationRecovery.js";import{extractReadFilesFromMessages as Is,extractBashToolsFromMessages as As}from"../utils/queryHelpers.js";import{resetMicrocompactState as ws}from"../services/compact/microCompact.js";import{runPostCompactCleanup as Rs}from"../services/compact/postCompactCleanup.js";import{provisionContentReplacementState as Ps,reconstructContentReplacementState as xs}from"../utils/toolResultStorage.js";import{partialCompactConversation as Ms}from"../services/compact/compact.js";import{fileHistoryMakeSnapshot as Es,fileHistoryRewind as Ds,copyFileHistoryForResume as _s,fileHistoryEnabled as Ls,fileHistoryHasAnyChanges as Os}from"../utils/fileHistory.js";import{incrementPromptCount as Ns}from"../utils/commitAttribution.js";import{recordAttributionSnapshot as Us}from"../utils/sessionStorage.js";import{computeStandaloneAgentContext as Bs,restoreAgentFromSession as qs,restoreSessionStateFromLog as Hs,restoreWorktreeForResume as $s,exitRestoredWorktree as Fs}from"../utils/sessionRestore.js";import{isBgSession as Vs,updateSessionName as Xs,updateSessionActivity as Js}from"../utils/concurrentSessions.js";import{isInProcessTeammateTask as Ks}from"../tasks/InProcessTeammateTask/types.js";import{restoreRemoteAgentTasks as Ws}from"../tasks/RemoteAgentTask/RemoteAgentTask.js";import{useInboxPoller as Gs}from"../hooks/useInboxPoller.js";import{usePermissionWhatsAppBridge as Qs}from"../hooks/usePermissionWhatsAppBridge.js";import{useWebappMirror as Ys}from"../hooks/useWebappMirror.js";import{useWebappPermissionBridge as zs}from"../hooks/useWebappPermissionBridge.js";const Zs=e("PROACTIVE")||e("KAIROS")?r("../proactive/index.js"):null,PROACTIVE_NO_OP_SUBSCRIBE=e=>()=>{},PROACTIVE_FALSE=()=>!1,SUGGEST_BG_PR_NOOP=(e,t)=>!1,en=((e("PROACTIVE")||e("KAIROS"))&&r("../proactive/useProactive.js").useProactive,e("AGENT_TRIGGERS")?r("../hooks/useScheduledTasks.js").useScheduledTasks:null);import{isAgentSwarmsEnabled as tn}from"../utils/agentSwarmsEnabled.js";import{useTaskListWatcher as on}from"../hooks/useTaskListWatcher.js";import{closeOpenDiffs as sn,getConnectedIdeClient as nn}from"../utils/ide.js";import{useIDEIntegration as rn}from"../hooks/useIDEIntegration.js";import an from"../commands/exit/index.js";import{ExitFlow as ln}from"../components/ExitFlow.js";import{getCurrentWorktreeSession as cn}from"../utils/worktree.js";import{popAllEditable as mn,enqueue as un,getCommandQueue as pn,getCommandQueueLength as dn,removeByFilter as fn}from"../utils/messageQueueManager.js";import{useCommandQueue as gn}from"../hooks/useCommandQueue.js";import{SessionBackgroundHint as hn}from"../components/SessionBackgroundHint.js";import{startBackgroundSession as Sn}from"../tasks/LocalMainSessionTask.js";import{useSessionBackgrounding as Cn}from"../hooks/useSessionBackgrounding.js";import{diagnosticTracker as yn}from"../services/diagnosticTracking.js";import{handleSpeculationAccept as Tn}from"../services/PromptSuggestion/speculation.js";import{IdeOnboardingDialog as vn}from"../components/IdeOnboardingDialog.js";import{EffortCallout as kn,shouldShowEffortCallout as jn}from"../components/EffortCallout.js";import{RemoteCallout as bn}from"../components/RemoteCallout.js";import{activityManager as In}from"../utils/activityManager.js";import{createAbortController as An}from"../utils/abortController.js";import{MCPConnectionManager as wn}from"../services/mcp/MCPConnectionManager.js";import{useFeedbackSurvey as Rn}from"../components/FeedbackSurvey/useFeedbackSurvey.js";import{useMemorySurvey as Pn}from"../components/FeedbackSurvey/useMemorySurvey.js";import{usePostCompactSurvey as xn}from"../components/FeedbackSurvey/usePostCompactSurvey.js";import{FeedbackSurvey as Mn}from"../components/FeedbackSurvey/FeedbackSurvey.js";import{useInstallMessages as En}from"../hooks/notifs/useInstallMessages.js";import{useAwaySummary as Dn}from"../hooks/useAwaySummary.js";import{useChromeExtensionNotification as _n}from"../hooks/useChromeExtensionNotification.js";import{useOfficialMarketplaceNotification as Ln}from"../hooks/useOfficialMarketplaceNotification.js";import{usePromptsFromClaudeInChrome as On}from"../hooks/usePromptsFromClaudeInChrome.js";import{getTipToShowOnSpinner as Nn,recordShownTip as Un}from"../services/tips/tipScheduler.js";import{checkAndDisableBypassPermissionsIfNeeded as Bn,checkAndDisableAutoModeIfNeeded as qn,useKickOffCheckAndDisableBypassPermissionsIfNeeded as Hn,useKickOffCheckAndDisableAutoModeIfNeeded as $n}from"../utils/permissions/bypassPermissionsKillswitch.js";import{SandboxManager as Fn}from"../utils/sandbox/sandbox-adapter.js";import{SANDBOX_NETWORK_ACCESS_TOOL_NAME as Vn}from"../cli/structuredIO.js";import{useFileHistorySnapshotInit as Xn}from"../hooks/useFileHistorySnapshotInit.js";import{SandboxPermissionRequest as Jn}from"../components/permissions/SandboxPermissionRequest.js";import{SandboxViolationExpandedView as Kn}from"../components/SandboxViolationExpandedView.js";import{useSettingsErrors as Wn}from"../hooks/notifs/useSettingsErrors.js";import{useMcpConnectivityStatus as Gn}from"../hooks/notifs/useMcpConnectivityStatus.js";import{useAutoModeUnavailableNotification as Qn}from"../hooks/notifs/useAutoModeUnavailableNotification.js";import{AUTO_MODE_DESCRIPTION as Yn}from"../components/AutoModeOptInDialog.js";import{useLspInitializationNotification as zn}from"../hooks/notifs/useLspInitializationNotification.js";import{useLspPluginRecommendation as Zn}from"../hooks/useLspPluginRecommendation.js";import{LspRecommendationMenu as er}from"../components/LspRecommendation/LspRecommendationMenu.js";import{useClaudeCodeHintRecommendation as tr}from"../hooks/useClaudeCodeHintRecommendation.js";import{PluginHintMenu as or}from"../components/ClaudeCodeHint/PluginHintMenu.js";import{DesktopUpsellStartup as sr,shouldShowDesktopUpsellStartup as nr}from"../components/DesktopUpsell/DesktopUpsellStartup.js";import{usePluginInstallationStatus as rr}from"../hooks/notifs/usePluginInstallationStatus.js";import{usePluginAutoupdateNotification as ir}from"../hooks/notifs/usePluginAutoupdateNotification.js";import{performStartupChecks as ar}from"../utils/plugins/performStartupChecks.js";import{UserTextMessage as lr}from"../components/messages/UserTextMessage.js";import{AwsAuthStatusBox as cr}from"../components/AwsAuthStatusBox.js";import{useRateLimitWarningNotification as mr}from"../hooks/notifs/useRateLimitWarningNotification.js";import{useDeprecationWarningNotification as ur}from"../hooks/notifs/useDeprecationWarningNotification.js";import{useNpmDeprecationNotification as pr}from"../hooks/notifs/useNpmDeprecationNotification.js";import{useIDEStatusIndicator as dr}from"../hooks/notifs/useIDEStatusIndicator.js";import{useModelMigrationNotifications as fr}from"../hooks/notifs/useModelMigrationNotifications.js";import{useCanSwitchToExistingSubscription as gr}from"../hooks/notifs/useCanSwitchToExistingSubscription.js";import{useTeammateLifecycleNotification as hr}from"../hooks/notifs/useTeammateShutdownNotification.js";import{useFastModeNotification as Sr}from"../hooks/notifs/useFastModeNotification.js";import{AutoRunIssueNotification as Cr,shouldAutoRunIssue as yr,getAutoRunIssueReasonText as Tr,getAutoRunCommand as vr}from"../utils/autoRunIssue.js";import{TungstenLiveMonitor as kr}from"../tools/TungstenTool/TungstenLiveMonitor.js";const jr=e("WEB_BROWSER_TOOL")?r("../tools/WebBrowserTool/WebBrowserPanel.js"):null;import{IssueFlagBanner as br}from"../components/PromptInput/IssueFlagBanner.js";import{useIssueFlagBanner as Ir}from"../hooks/useIssueFlagBanner.js";import{CompanionSprite as Ar,CompanionFloatingBubble as wr,MIN_COLS_FOR_FULL_SPRITE as Rr}from"../buddy/CompanionSprite.js";import{DevBar as Pr}from"../components/DevBar.js";import{REMOTE_SAFE_COMMANDS as xr}from"../commands.js";import{FullscreenLayout as Mr,useUnseenDivider as Er,computeUnseenDivider as Dr}from"../components/FullscreenLayout.js";import{isFullscreenEnvEnabled as _r,maybeGetTmuxMouseHint as Lr,isMouseTrackingEnabled as Or}from"../utils/fullscreen.js";import{AlternateScreen as Nr}from"../ink/components/AlternateScreen.js";import{ScrollKeybindingHandler as Ur}from"../components/ScrollKeybindingHandler.js";import{useMessageActions as Br,MessageActionsKeybindings as qr,MessageActionsBar as Hr}from"../components/messageActions.js";import{setClipboard as $r}from"../ink/termio/osc.js";import{createAttachmentMessage as Fr,getQueuedCommandAttachments as Vr}from"../utils/attachments.js";const Xr=[],Jr={maybeLoadOlder:e=>{}};function TranscriptModeFooter(e){const n=i(9),{showAllInTranscript:r,virtualScroll:a,searchBadge:l,suppressShowAll:c,status:m}=e,u=void 0!==c&&c,p=Ot("app:toggleTranscript","Global","ctrl+o"),d=Ot("transcript:toggleShowAll","Transcript","ctrl+e"),f=l?" · n/N para navegar":a?` · ${C.arrowUp}${C.arrowDown} desplazar · inicio/fin extremo`:u?"":` · ${d} para ${r?"contraer":"mostrar todo"}`;let g,h,S;return n[0]!==f||n[1]!==p?(g=t(w,{dimColor:!0,children:["Mostrando transcripción detallada · ",p," para alternar",f]}),n[0]=f,n[1]=p,n[2]=g):g=n[2],n[3]!==l||n[4]!==m?(h=m?t(s,{children:[o(A,{flexGrow:1}),t(w,{children:[m," "]})]}):l?t(s,{children:[o(A,{flexGrow:1}),t(w,{dimColor:!0,children:[l.current,"/",l.count," "]})]}):null,n[3]=l,n[4]=m,n[5]=h):h=n[5],n[6]!==g||n[7]!==h?(S=t(A,{noSelect:!0,alignItems:"center",alignSelf:"center",borderTopDimColor:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,borderStyle:"single",marginTop:1,paddingLeft:2,width:"100%",children:[g,h]}),n[6]=g,n[7]=h,n[8]=S):S=n[8],S}function TranscriptSearchBar({jumpRef:e,count:s,current:n,onClose:r,onCancel:i,setHighlight:a,initialQuery:l}){const{query:c,cursorOffset:m}=T({isActive:!0,initialQuery:l,onExit:()=>r(c),onCancel:i}),[u,p]=L.useState("building");L.useEffect(()=>{let t=!0;const o=e.current?.warmSearchIndex;if(o)return p("building"),o().then(e=>{t&&(e<20?p(null):(p({ms:e}),setTimeout(()=>t&&p(null),2e3)))}),()=>{t=!1};p(null)},[]);const d="building"!==u;O(()=>{d&&(e.current?.setSearchQuery(c),a(c))},[c,d]);const f=m,g=f<c.length?c[f]:" ";return t(A,{borderTopDimColor:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,borderStyle:"single",marginTop:1,paddingLeft:2,width:"100%",noSelect:!0,children:[o(w,{children:"/"}),o(w,{children:c.slice(0,f)}),o(w,{inverse:!0,children:g}),f<c.length&&o(w,{children:c.slice(f+1)}),o(A,{flexGrow:1}),"building"===u?o(w,{dimColor:!0,children:"indexando… "}):u?t(w,{dimColor:!0,children:["indexado en ",u.ms,"ms "]}):0===s&&c?o(w,{color:"error",children:"sin coincidencias "}):s>0?t(w,{dimColor:!0,children:[n,"/",s," "]}):null]})}const Kr=["⠂","⠐"];function AnimatedTerminalTitle(e){const t=i(6),{isAnimating:o,title:s,disabled:n,noPrefix:r}=e,a=x(),[l,c]=B(0);let m,u;t[0]!==n||t[1]!==o||t[2]!==r||t[3]!==a?(m=()=>{if(n||r||!o||!a)return;const e=setInterval(_temp2,960,c);return()=>clearInterval(e)},u=[n,r,o,a],t[0]=n,t[1]=o,t[2]=r,t[3]=a,t[4]=m,t[5]=u):(m=t[4],u=t[5]),O(m,u);return M(n?null:r?s:`${o?Kr[l]??"✳":"✳"} ${s}`),null}function _temp2(e){return e(_temp)}function _temp(e){return(e+1)%Kr.length}export function REPL({commands:n,debug:i,initialTools:C,initialMessages:T,pendingHookMessages:M,initialFileHistorySnapshots:ie,initialContentReplacements:ae,initialAgentName:ce,initialAgentColor:me,mcpClients:pe,dynamicMcpConfig:de,autoConnectIdeFlag:ve,strictMcpConfig:at=!1,systemPrompt:Ot,appendSystemPrompt:ao,onBeforeQuery:vo,onTurnComplete:on,disabled:kr=!1,mainThreadAgentDefinition:Pr,disableSlashCommands:Kr=!1,taskListId:Wr,remoteSessionConfig:Gr,directConnectConfig:Qr,sshSession:Yr,thinkingConfig:zr}){const Zr=!!Gr,ei=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_TERMINAL_TITLE)||ye(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE),[]),ti=N(()=>!1,[]),oi=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_VIRTUAL_SCROLL)||ye(process.env.CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL),[]),si=!!e("MESSAGE_ACTIONS")&&N(()=>ye(process.env.CONTEXT_CODE_DISABLE_MESSAGE_ACTIONS)||ye(process.env.CLAUDE_CODE_DISABLE_MESSAGE_ACTIONS),[]);O(()=>(Se(`[REPL:mount] REPL mounted, disabled=${kr}`),()=>Se("[REPL:unmount] REPL unmounting")),[kr]);const[ni,ri]=B(Pr),ii=as(e=>e.toolPermissionContext),ai=as(e=>e.verbose),li=as(e=>e.mcp),ci=as(e=>e.plugins),mi=as(e=>e.agentDefinitions),ui=as(e=>e.fileHistory),pi=as(e=>e.initialMessage),di=gn(),fi=as(e=>e.spinnerTip),gi="tasks"===as(e=>e.expandedView),hi=as(e=>e.pendingWorkerRequest),Si=as(e=>e.pendingSandboxRequest),Ci=as(e=>e.teamContext),yi=as(e=>e.tasks),Ti=as(e=>e.workerSandboxPermissions),vi=as(e=>e.elicitation),ki=as(e=>e.ultraplanPendingChoice),ji=as(e=>e.ultraplanLaunchPending),bi=as(e=>e.viewingAgentTaskId),Ii=ls(),Ai=bi?yi[bi]:void 0,wi=_e(Ai)&&Ai.retain&&!Ai.diskLoaded;O(()=>{if(!bi||!wi)return;const e=bi;js(he(e)).then(t=>{Ii(o=>{const s=o.tasks[e];if(!_e(s)||s.diskLoaded||!s.retain)return o;const n=s.messages??[],r=new Set(n.map(e=>e.uuid)),i=t?t.messages.filter(e=>!r.has(e.uuid)):[];return{...o,tasks:{...o.tasks,[e]:{...s,messages:[...i,...n],diskLoaded:!0}}}})})},[bi,wi,Ii]);const Ri=cs(),Pi=W(),xi=is(),[Mi,Ei]=B(n);Vo(Zr?void 0:oe(),Ei);const Di=L.useSyncExternalStore(Zs?.subscribeToProactiveChanges??PROACTIVE_NO_OP_SUBSCRIBE,Zs?.isProactiveActive??PROACTIVE_FALSE),_i=as(e=>e.isBriefOnly),Li=N(()=>os(ii),[ii,Di,_i]);Hn(),$n();const[Oi,Ni]=B(de),Ui=q(e=>{Ni(e)},[Ni]),[Bi,qi]=B("prompt"),[Hi,$i]=B(!1),[Fi,Vi]=B(!1),[Xi,Ji]=B(""),Ki=U(0),Wi=U(void 0),Gi=U(!1),{addNotification:Qi,removeNotification:Yi}=F();let zi=SUGGEST_BG_PR_NOOP;const Zi=Bo(pe,li.clients),[ea,ta]=B(void 0),[oa,sa]=B(null),[na,ra]=B(null),[ia,aa]=B(!1),[la,ca]=B(()=>!1),[ma,ua]=B(()=>jn(xi)),pa=as(e=>e.showRemoteCallout),[da,fa]=B(()=>nr());fr(),gr(),dr({ideSelection:ea,mcpClients:Zi,ideInstallationStatus:na}),Gn({mcpClients:Zi}),Qn(),rr(),ir(),Wn(),mr(xi),Sr(),ur(xi),pr(),useAntOrgWarningNotification(),En(),_n(),Ln(),zn(),hr();const{recommendation:ga,handleResponse:ha}=Zn(),{recommendation:Sa,handleResponse:Ca}=tr(),ya=N(()=>[...Li,...C],[Li,C]);Xo({enabled:!Zr});const Ta=Go();O(()=>{Zr||ar(Ii)},[Ii,Zr]),On(Zr?Xr:Zi,ii.mode),qt(Ii,T,{enabled:!Zr});const va=Ho(ya,li.tools,ii),{tools:ka,allowedAgentTypes:ja}=N(()=>{if(!ni)return{tools:va,allowedAgentTypes:void 0};const e=ns(ni,va,!1,!0);return{tools:e.resolvedTools,allowedAgentTypes:e.allowedAgentTypes}},[ni,va]),ba=Fo(Mi,ci.commands),Ia=Fo(ba,li.commands),Aa=N(()=>Kr?[]:Ia,[Kr,Ia]);Ye(Zr?Xr:li.clients),ts(Zr?Xr:li.clients,ta);const[wa,Ra]=B("responding"),Pa=U(wa);Pa.current=wa;const[xa,Ma]=B([]),[Ea,Da]=B(null);O(()=>{if(Ea&&!Ea.isStreaming&&Ea.streamingEndedAt){const e=3e4-(Date.now()-Ea.streamingEndedAt);if(e>0){const t=setTimeout(Da,e,null);return()=>clearTimeout(t)}Da(null)}},[Ea]);const[_a,La]=B(null),Oa=U(null),Na=q(e=>{Oa.current=e,La(e)},[]),Ua=U(()=>{}),Ba=U(()=>{}),qa=U(null),Ha=U(null),$a=U(0),Fa=L.useRef(new Ce).current,Va=L.useSyncExternalStore(Fa.subscribe,Fa.getSnapshot),[Xa,Ja]=L.useState(Gr?.hasInitialPrompt??!1),Ka=Va||Xa,[Wa,Ga]=L.useState(void 0),Qa=L.useRef(0),Ya=L.useRef(!1),za=L.useRef(0),Za=L.useRef(0),el=L.useRef(null),tl=L.useCallback(()=>{za.current=Date.now(),Za.current=0,el.current=null},[]),ol=L.useRef(!1);Va&&!ol.current&&tl(),ol.current=Va;const sl=L.useCallback(e=>{Ja(e),e&&tl()},[tl]),nl=L.useRef(null),rl=L.useRef(void 0),il=L.useRef(void 0),[al,ll]=L.useState(!1),[cl,ml]=B(null);O(()=>{cl?.notifications&&cl.notifications.forEach(e=>{Qi({key:"auto-updater-notification",text:e,priority:"low"})})},[cl,Qi]),O(()=>{_r()&&Lr().then(e=>{e&&Qi({key:"tmux-mouse-hint",text:e,priority:"low"})})},[]);const[ul,pl]=B(!1);O(()=>{0},[]);const[dl,fl]=B(null),[gl,hl]=B([]),Sl=q(e=>{hl(t=>[...t,e])},[]),Cl=q(e=>{hl(t=>0===t.length?[e]:[...t.slice(0,-1),e])},[]),yl=q(()=>{hl(e=>e.slice(0,-1))},[]),Tl=q(()=>{hl([])},[]),vl=U(null),kl=q(e=>{if(Se(`setToolJSX called with: ${JSON.stringify({hasJsx:!!e?.jsx,shouldHidePromptInput:e?.shouldHidePromptInput,isLocalJSXCommand:e?.isLocalJSXCommand,clearLocalJSX:e?.clearLocalJSX})}`),e?.isLocalJSXCommand){const{clearLocalJSX:t,...o}=e;return vl.current={...o,isLocalJSXCommand:!0},void fl(o)}return vl.current?e?.clearLocalJSX?(Se("Clearing local JSX command as requested"),vl.current=null,void fl(null)):void Se("Ignoring setToolJSX update because a local JSX command is active"):e?.clearLocalJSX?(Se("Clearing tool JSX (no local command active)"),void fl(null)):void fl(e)},[]),[jl,bl]=B([]),[Il,Al]=B(null),[wl,Rl]=B([]),[Pl,xl]=B([]),Ml=U(new Map),El=!1!==as(e=>e.settings.terminalTitleFromRename)?ys(se()):void 0,[Dl,_l]=B(),Ll=U((T?.length??0)>0),Ol=ni?.agentType,Nl=El??Ol??Dl??"Context Code",Ul=jl.length>0||Pl.length>0||hi||Si,Bl=!0===dl?.isLocalJSXCommand&&null!=dl?.jsx,ql=Ka&&!Ul&&!Bl;O(()=>{if(Ka&&!Ul&&!Bl)return J(),()=>K()},[Ka,Ul,Bl]);const Hl=Ul||Bl?"waiting":Ka?"busy":"idle",$l="waiting"!==Hl?void 0:jl.length>0?`approve ${jl[0].tool.name}`:hi?"worker request":Si?"sandbox request":Bl?"dialog open":"input needed";O(()=>{e("BG_SESSIONS")&&Js({status:Hl,waitingFor:$l})},[Hl,$l]);const Fl=mo("tengu_terminal_sidebar",!1)&&(ro().showStatusInTerminalTab??!1);E(ei||!Fl?null:Hl),O(()=>(Ne(bl),()=>Ue()),[bl]);const[Vl,Xl]=B(T??[]),Jl=U(Vl),Kl=U(!1),Wl=q(e=>{const t=Jl.current,o="function"==typeof e?e(Jl.current):e;if(Jl.current=o,o.length<Qa.current)Qa.current=0;else if(o.length>t.length&&Ya.current){const e=o.length-t.length;(0===t.length||o[0]===t[0]?o.slice(-e):o.slice(0,e)).some(Ft)?Ya.current=!1:Qa.current=o.length}Xl(o)},[]),Gl=q(e=>{void 0!==e?(Qa.current=Jl.current.length,Ya.current=!0):Ya.current=!1,Ga(e)},[]),{dividerIndex:Ql,dividerYRef:Yl,onScrollAway:zl,onRepin:Zl,jumpToNew:ec,shiftDivider:tc}=Er(Vl.length);e("AWAY_SUMMARY")&&Dn(Vl,Wl,Ka);const[oc,sc]=B(null),nc=U(null),rc=q(e=>{const t=Jl.current.find(t=>t.uuid===e)?.uuid,o=Jl.current.find(t=>t.uuid.slice(0,24)===e.slice(0,24))?.uuid,s=t??o;s?sc({uuid:s,msgType:"user",expanded:!1}):Qi({key:"timeline-jump-not-found",text:"Message no longer available in active transcript",color:"warning",priority:"medium",timeoutMs:3e3})},[Qi]),ic=N(()=>Dr(Vl,Ql),[Ql,Vl.length]),ac=q(()=>{qa.current?.scrollToBottom(),Zl(),sc(null)},[Zl,sc]),lc=Vl.at(-1),cc=null!=lc&&Ft(lc);O(()=>{cc&&ac()},[cc,lc,ac]);const{maybeLoadOlder:mc}=e("KAIROS")?it({config:Gr,setMessages:Wl,scrollRef:qa,onPrepend:tc}):Jr,uc=q((t,o)=>{$a.current=Date.now(),t?Zl():(zl(o),e("KAIROS")&&mc(o),e("BUDDY")&&Ii(e=>void 0===e.companionReaction?e:{...e,companionReaction:void 0}))},[Zl,zl,mc,Ii]),pc=It(M,Wl),dc=H(Vl),fc=Vl.length-dc.length;fc>0&&Se(`[useDeferredValue] Messages deferred by ${fc} (${dc.length}→${Vl.length})`);const[gc,hc]=B(null),[Sc,Cc]=B(()=>ke()),yc=U(Sc);yc.current=Sc;const Tc=U(null),vc=q(e=>{zi(yc.current,e)||(""===yc.current&&""!==e&&Date.now()-$a.current>=3e3&&ac(),yc.current=e,Cc(e),ll(e.trim().length>0))},[ll,ac,zi]);O(()=>{if(0===Sc.trim().length)return;const e=setTimeout(ll,1500,!1);return()=>clearTimeout(e)},[Sc]);const[kc,jc]=B("prompt"),[bc,Ic]=B(),Ac=q(e=>{const t=new Set(e);Ei(e=>e.filter(e=>t.has(e.name)||xr.has(e)))},[Ei]),[wc,Rc]=B(new Set),Pc=U(!1),xc=st({config:Gr,setMessages:Wl,setIsLoading:sl,onInit:Ac,setToolUseConfirmQueue:bl,tools:ya,setStreamingToolUses:Ma,setStreamMode:Ra,setInProgressToolUseIDs:Rc}),Mc=nt({config:Qr,setMessages:Wl,setIsLoading:sl,setToolUseConfirmQueue:bl,tools:ya}),Ec=rt({session:Yr,setMessages:Wl,setIsLoading:sl,setToolUseConfirmQueue:bl,tools:ya}),Dc=Ec.isRemoteMode?Ec:Mc.isRemoteMode?Mc:xc,[_c,Lc]=B({}),[Oc,Nc]=B(0),Uc=U(0),Bc=U([]),qc=q(e=>{const t=Uc.current;if(Uc.current=e(t),Uc.current>t){const e=Bc.current;if(e.length>0){const t=e.at(-1);t.lastTokenTime=Date.now(),t.endResponseLength=Uc.current}}},[]),[Hc,$c]=B(null),Fc=!(as(e=>e.settings.prefersReducedMotion)??!1)&&!G(),Vc=q(e=>{Fc&&$c(e)},[Fc]),Xc=Hc&&Fc&&Hc.substring(0,Hc.lastIndexOf("\n")+1)||null,[Jc,Kc]=B(0),[Wc,Gc]=B(null),[Qc,Yc]=B(null),[zc,Zc]=B(null),[em,tm]=B(!1),[om,sm]=B(void 0),[nm,rm]=B(!1),[im,am]=B(Yo()),[lm,cm]=B(null),mm=U(Ka),um=U(!1),pm=U(!1),dm=U(Jc);dm.current=Jc;const[fm]=B(()=>({current:Ps(T,ae)})),[gm,hm]=B(ro().hasAcknowledgedCostThreshold),[Sm,Cm]=B("INSERT"),[ym,Tm]=B(!1),[vm,km]=B(!1),[jm,bm]=B(!1);O(()=>{ki&&ym&&Tm(!1)},[ki,ym]);const Im=x(),Am=U(Im);Am.current=Im;const[wm]=P(),Rm=L.useRef(!1),Pm=q(()=>{if(Rm.current)return;Rm.current=!0;const e=Jl.current.slice(Qm.current);for(const t of As(e))Gm.current.add(t);Qm.current=Jl.current.length,Nn({theme:wm,readFileState:Wm.current,bashTools:Gm.current}).then(async e=>{if(e){const t=await e.content({theme:wm});Ii(e=>({...e,spinnerTip:t})),Un(e)}else Ii(e=>void 0===e.spinnerTip?e:{...e,spinnerTip:void 0})})},[Ii,wm]),xm=q(()=>{sl(!1),Gl(void 0),Uc.current=0,Bc.current=[],$c(null),Ma([]),Gc(null),Yc(null),Zc(null),Pm(),He(),no()},[Pm]),Mm=N(()=>De(yi).some(e=>"running"===e.status),[yi]);O(()=>{if(!Mm&&null!==nl.current){const e=Date.now()-nl.current,t=rl.current;nl.current=null,rl.current=void 0,Wl(o=>[...o,yo(e,t,f(o,vs))])}},[Mm,Wl]);const Em=U(!1);O(()=>{if(e("TRANSCRIPT_CLASSIFIER")){if("auto"!==ii.mode)return void(Em.current=!1);if(Em.current)return;if((ro().autoPermissionsNotificationCount??0)>=3)return;const e=setTimeout((e,t)=>{e.current=!0,io(e=>{const t=e.autoPermissionsNotificationCount??0;return t>=3?e:{...e,autoPermissionsNotificationCount:t+1}}),t(e=>[...e,ko(Yn,"warning")])},800,Em,Wl);return()=>clearTimeout(e)}},[ii.mode,Wl]);const Dm=U(!1);O(()=>{if(Dm.current)return;const e=cn();if(!e?.creationDurationMs||e.usedSparsePaths)return;if(e.creationDurationMs<15e3)return;Dm.current=!0;const t=Math.round(e.creationDurationMs/1e3);Wl(e=>[...e,ko(`Worktree creation took ${t}s. For large repos, set \`worktree.sparsePaths\` in .claude/settings.json to check out only the directories you need — e.g. \`{"worktree": {"sparsePaths": ["src", "packages/foo"]}}\`.`,"info")])},[Wl]);const _m=N(()=>{const e=Vl.findLast(e=>"assistant"===e.type);if("assistant"!==e?.type)return!1;const t=e.message.content.filter(e=>"tool_use"===e.type&&wc.has(e.id));return t.length>0&&t.every(e=>"tool_use"===e.type&&e.name===so)},[Vl,wc]),{onBeforeQuery:Lm,onTurnComplete:Om,render:Nm}=ct({enabled:ti,setMessages:Wl,inputValue:Sc,setInputValue:vc,setToolJSX:kl}),Um=(!dl||!0===dl.showSpinner)&&0===jl.length&&0===Pl.length&&(Ka||Wa||Mm||dn()>0)&&!hi&&!_m&&(!Xc||_i),Bm=jl.length>0||Pl.length>0||wl.length>0||vi.queue.length>0||Ti.queue.length>0,qm=Rn(Vl,Ka,Oc,"session",Bm),Hm=(lt(Wl),Ir(Vl,Oc)),$m=N(()=>({...qm,handleSelect:e=>{nu.current=!1;const t=qm.handleSelect(e);"bad"===e&&!t&&yr("feedback_survey_bad")&&(su("feedback_survey_bad"),nu.current=!0)}}),[qm]),Fm=xn(Vl,Ka,Bm,{enabled:!Zr}),Vm=Pn(Vl,Ka,Bm,{enabled:!Zr}),Xm=useFrustrationDetection(Vl,Ka,Bm,"closed"!==$m.state||"closed"!==Fm.state||"closed"!==Vm.state);rn({autoConnectIdeFlag:ve,ideToInstallExtension:oa,setDynamicMcpConfig:Ni,setShowIdeOnboarding:aa,setIDEInstallationState:ra}),Xn(ie,ui,e=>Ii(t=>({...t,fileHistory:e})));const Jm=q(async(t,o,s)=>{const n=performance.now();try{const i=bs(o.messages);if(e("COORDINATOR_MODE")){const e=r("../coordinator/coordinatorMode.js").matchSessionMode(o.mode);if(e){const{getAgentDefinitionsWithOverrides:t,getActiveAgentsFromList:o}=r("../tools/AgentTool/loadAgentsDir.js");t.cache.clear?.();const s=await t(te());Ii(e=>({...e,agentDefinitions:{...s,allAgents:s.allAgents,activeAgents:o(s.allAgents)}})),i.push(ko(e,"warning"))}}const a=es();await Zo("resume",{getAppState:()=>Ri.getState(),setAppState:Ii,signal:AbortSignal.timeout(a),timeoutMs:a});const l=await zo("resume",{sessionId:t,agentType:ni?.agentType,model:xi});i.push(...l),"fork"===s?ms(o,ge(t)):us(o,ge(t)),Hs(o,Ii),o.fileHistorySnapshots&&_s(o);const{agentDefinition:c}=qs(o.agentSetting,Pr,mi);ri(c),Ii(e=>({...e,agent:c?.agentType})),Ii(e=>({...e,standaloneAgentContext:Bs(o.agentName,o.agentColor)})),Xs(o.agentName),Zm(i,o.projectPath??te()),xm(),Na(null),am(t);const m=vt(t);yt(),Tt(),ne(ge(t),o.fullPath?g(o.fullPath):null);const{renameRecordingForSession:u}=await import("../utils/asciicast.js");if(await u(),await gs(),fs(),Cs(o),Ll.current=!0,_l(void 0),"fork"!==s)Fs(),$s(o.worktreeSession),hs(),Ws({abortController:new AbortController,getAppState:()=>Ri.getState(),setAppState:Ii});else{const e=cn();e&&ks(e)}if(e("COORDINATOR_MODE")){const{saveMode:e}=r("../utils/sessionStorage.js"),{isCoordinatorMode:t}=r("../coordinator/coordinatorMode.js");e(t()?"coordinator":"normal")}m&&re(m),fm.current&&"fork"!==s&&(fm.current=xs(i,o.contentReplacements??[])),Wl(()=>i),kl(null),vc(""),co("tengu_session_resumed",{entrypoint:s,success:!0,resume_duration_ms:Math.round(performance.now()-n)})}catch(e){throw co("tengu_session_resumed",{entrypoint:s,success:!1}),e}},[xm,Ii]),[Km]=B(()=>Q(z)),Wm=U(Km),Gm=U(new Set),Qm=U(0),Ym=U(new Set),zm=U(new Set),Zm=q((e,t)=>{const o=Is(e,t,z);Wm.current=Y(Wm.current,o);for(const t of As(e))Gm.current.add(t)},[]);O(()=>{T&&T.length>0&&(Zm(T,te()),Ws({abortController:new AbortController,getAppState:()=>Ri.getState(),setAppState:Ii}))},[]);const{status:eu,reverify:tu}=Et(),[ou,su]=B(null),nu=U(!1),[ru,iu]=B(null),[au,lu]=B(!1),cu=!Ka&&nm;const mu=function(){if(au||ru)return;if(em)return"message-selector";if(al)return;if(wl[0])return"sandbox-permission";const t=!dl||dl.shouldContinueAnimation;return t&&jl[0]?"tool-permission":t&&Pl[0]?"prompt":t&&Ti.queue[0]?"worker-sandbox-permission":t&&vi.queue[0]?"elicitation":t&&cu?"cost":t&&lm?"idle-return":e("ULTRAPLAN")&&t&&!Ka&&ki?"ultraplan-choice":e("ULTRAPLAN")&&t&&!Ka&&ji?"ultraplan-launch":t&&ia?"ide-onboarding":t&&ma?"effort-callout":t&&pa?"remote-callout":t&&ga?"lsp-recommendation":t&&Sa?"plugin-hint":t&&da?"desktop-upsell":void 0}(),uu=al&&(wl[0]||jl[0]||Pl[0]||Ti.queue[0]||vi.queue[0]||cu);il.current=mu,O(()=>{if(!Ka)return;const e="tool-permission"===mu,t=Date.now();e&&null===el.current?el.current=t:e||null===el.current||(Za.current+=t-el.current,el.current=null)},[mu,Ka]);const pu=U(mu);function onCancel(){if(gl.length>0){const e=gl[gl.length-1];return e?.onClose?.(),void yl()}if("elicitation"!==mu){if(Se(`[onCancel] focusedInputDialog=${mu} streamMode=${wa}`),(e("PROACTIVE")||e("KAIROS"))&&Zs?.pauseProactive(),Fa.forceEnd(),pm.current=!1,Hc?.trim()&&Wl(e=>[...e,Co({content:Hc})]),xm(),e("TOKEN_BUDGET")&&l(null),"tool-permission"===mu)jl[0]?.onAbort(),bl([]);else if("prompt"===mu){for(const e of Pl)e.reject(new Error("Prompt cancelled by user"));xl([]),Oa.current?.abort("user-cancel")}else Dc.isRemoteMode?Dc.cancelRequest():Oa.current?.abort("user-cancel");Na(null),Om(Jl.current,!0)}}$(()=>{"tool-permission"===pu.current!==("tool-permission"===mu)&&ac(),pu.current=mu},[mu,ac]);const du=q(()=>{const e=mn(Sc,0);e&&(vc(e.text),jc("prompt"),e.images.length>0&&Lc(t=>{const o={...t};for(const t of e.images)o[t.id]=t;return o}))},[vc,jc,Sc,Lc]),fu={setToolUseConfirmQueue:bl,onCancel,onAgentsKilled:()=>Wl(e=>[...e,To()]),isMessageSelectorVisible:em||!!ym,screen:Bi,abortSignal:_a?.signal,popCommandFromQueue:du,vimMode:Sm,isLocalJSXCommand:dl?.isLocalJSXCommand,isSearchingHistory:vm,isHelpOpen:jm,inputMode:kc,inputValue:Sc,streamMode:wa};O(()=>{Ct()>=5&&!nm&&!gm&&(co("tengu_cost_threshold_reached",{}),hm(!0),lo()&&rm(!0))},[Vl,nm,gm]);const gu=q(async t=>{if(tn()&&be()){const e=Ie(),o=await Ae(t.host,e);return new Promise(s=>{o?(Re({requestId:e,host:t.host,resolve:s}),Ii(o=>({...o,pendingSandboxRequest:{requestId:e,host:t.host}}))):Rl(e=>[...e,{hostPattern:t,resolvePromise:s}])})}return new Promise(o=>{let s=!1;function resolveOnce(e){s||(s=!0,o(e))}if(Rl(e=>[...e,{hostPattern:t,resolvePromise:resolveOnce}]),e("BRIDGE_MODE")){const e=Ri.getState().replBridgePermissionCallbacks;if(e){const o=Yo();e.sendRequest(o,Vn,{host:t.host},Yo(),`Allow network connection to ${t.host}?`);const s=e.onResponse(o,e=>{s();const o="allow"===e.behavior;Rl(e=>(e.filter(e=>e.hostPattern.host===t.host).forEach(e=>e.resolvePromise(o)),e.filter(e=>e.hostPattern.host!==t.host)));const n=Ml.current.get(t.host);if(n){for(const e of n)e();Ml.current.delete(t.host)}}),cleanup=()=>{s(),e.cancelRequest(o)},n=Ml.current.get(t.host)??[];n.push(cleanup),Ml.current.set(t.host,n)}}})},[Ii,Ri]);O(()=>{const e=Fn.getSandboxUnavailableReason();if(e){if(Fn.isSandboxRequired())return process.stderr.write(`\nError: sandbox required but unavailable: ${e}\n sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`),void Mo(1,"other");Se(`sandbox disabled: ${e}`,{level:"warn"}),Qi({key:"sandbox-unavailable",jsx:t(s,{children:[o(w,{color:"warning",children:"sandbox disabled"}),o(w,{dimColor:!0,children:" · /sandbox"})]}),priority:"medium"})}},[Qi]),Fn.isSandboxingEnabled()&&Fn.initialize(gu).catch(e=>{process.stderr.write(`\n❌ Sandbox Error: ${$t(e)}\n`),Mo(1,"other")});const hu=q((e,t)=>{Ii(o=>({...o,toolPermissionContext:{...e,mode:t?.preserveMode?o.toolPermissionContext.mode:e.mode}})),setImmediate(e=>{e(e=>(e.forEach(e=>{e.recheckPermission()}),e))},bl)},[Ii,bl]);O(()=>(Be(hu),()=>qe()),[hu]);const Su=Wt(bl,hu),Cu=q((e,t)=>o=>new Promise((s,n)=>{xl(r=>[...r,{request:o,title:e,toolInputSummary:t,resolve:s,reject:n}])}),[]),yu=q((t,o,s,n)=>{const r=Ri.getState(),computeTools=()=>{const e=Ri.getState(),t=ss(e.toolPermissionContext,e.mcp.tools),o=$o(ya,t,e.toolPermissionContext.mode);return ni?ns(ni,o,!1,!0).resolvedTools:o};return{abortController:s,options:{commands:Aa,tools:computeTools(),debug:i,verbose:r.verbose,mainLoopModel:n,thinkingConfig:!1!==r.thinkingEnabled?zr:{type:"disabled"},mcpClients:Uo(pe,r.mcp.clients),mcpResources:r.mcp.resources,ideInstallationStatus:na,isNonInteractiveSession:!1,dynamicMcpConfig:Oi,theme:wm,agentDefinitions:ja?{...r.agentDefinitions,allowedAgentTypes:ja}:r.agentDefinitions,customSystemPrompt:Ot,appendSystemPrompt:ao,refreshTools:computeTools},getAppState:()=>Ri.getState(),setAppState:Ii,messages:t,setMessages:Wl,updateFileHistoryState(e){Ii(t=>{const o=e(t.fileHistory);return o===t.fileHistory?t:{...t,fileHistory:o}})},updateAttributionState(e){Ii(t=>{const o=e(t.attribution);return o===t.attribution?t:{...t,attribution:o}})},openMessageSelector:()=>{kr||tm(!0)},openMessageSelectorAtMessage:e=>{if(kr)return;const o=t.find(t=>t.uuid===e),s=t.find(t=>t.uuid.slice(0,24)===e.slice(0,24)),n=o??s;n&&Ge(n)&&sm(n),tm(!0)},jumpToMessage:rc,onChangeAPIKey:tu,readFileState:Wm.current,setToolJSX:kl,addNotification:Qi,appendSystemMessage:e=>Wl(t=>[...t,e]),sendOSNotification:e=>{X(e,Pi)},onChangeDynamicMcpConfig:Ui,onInstallIDEExtension:sa,nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:zm.current,dynamicSkillDirTriggers:new Set,discoveredSkillNames:Ym.current,setResponseLength:qc,pushApiMetricsEntry:void 0,setStreamMode:Ra,onCompactProgress:e=>{switch(e.type){case"hooks_start":Yc("claudeBlue_FOR_SYSTEM_SPINNER"),Zc("claudeBlueShimmer_FOR_SYSTEM_SPINNER"),Gc("pre_compact"===e.hookType?"Running PreCompact hooks…":"post_compact"===e.hookType?"Running PostCompact hooks…":"Running SessionStart hooks…");break;case"compact_start":Gc("Compacting conversation");break;case"compact_end":Gc(null),Yc(null),Zc(null)}},setInProgressToolUseIDs:Rc,setHasInterruptibleToolInProgress:e=>{Pc.current=e},resume:Jm,setConversationId:am,requestPrompt:e("HOOK_PROMPTS")?Cu:void 0,contentReplacementState:fm.current}},[Aa,ya,ni,i,pe,na,Oi,wm,ja,Ri,Ii,tu,Qi,Wl,Ui,Jm,Cu,kr,Ot,ao,am,rc,Vl]),Tu=q(()=>{Oa.current?.abort("background");const e=fn(e=>"task-notification"===e.mode);(async()=>{const t=yu(Jl.current,[],new AbortController,xi),[o,s,n]=await Promise.all([pt(t.options.tools,xi,Array.from(ii.additionalWorkingDirectories.keys()),t.options.mcpClients),gt(),ft()]),r=dt({mainThreadAgentDefinition:ni,toolUseContext:t,customSystemPrompt:Ot,defaultSystemPrompt:o,appendSystemPrompt:ao});t.renderedSystemPrompt=r;const i=(await Vr(e).catch(()=>[])).map(Fr),a=new Set;for(const e of Jl.current)"attachment"===e.type&&"queued_command"===e.attachment.type&&"task-notification"===e.attachment.commandMode&&"string"==typeof e.attachment.prompt&&a.add(e.attachment.prompt);const l=i.filter(e=>"queued_command"===e.attachment.type&&("string"!=typeof e.attachment.prompt||!a.has(e.attachment.prompt)));Sn({messages:[...Jl.current,...l],queryParams:{systemPrompt:r,userContext:s,systemContext:n,canUseTool:Su,toolUseContext:t,querySource:qo()},description:Nl,setAppState:Ii,agentDefinition:ni})})()},[xi,ii,ni,yu,Ot,ao,Su,Ii]),{handleBackgroundSession:vu}=Cn({setMessages:Wl,setIsLoading:sl,resetLoadingState:xm,setAbortController:Na,onBackgroundQuery:Tu}),ku=q(t=>{po(t,t=>{fo(t)?(_r()?Wl(e=>[...go(e,{includeSnipped:!0}),t]):Wl(()=>[t]),am(Yo()),(e("PROACTIVE")||e("KAIROS"))&&Zs?.setContextBlocked(!1)):"progress"===t.type&&Ts(t.data.type)?Wl(e=>{const o=e.at(-1);if("progress"===o?.type&&o.parentToolUseID===t.parentToolUseID&&o.data.type===t.data.type){const o=e.slice();return o[o.length-1]=t,o}return[...e,t]}):Wl(e=>[...e,t]),(e("PROACTIVE")||e("KAIROS"))&&("assistant"===t.type&&"isApiErrorMessage"in t&&t.isApiErrorMessage?Zs?.setContextBlocked(!0):"assistant"===t.type&&Zs?.setContextBlocked(!1))},e=>{qc(t=>t+e.length)},Ra,Ma,e=>{Wl(t=>t.filter(t=>t!==e)),Ss(e.uuid)},Da,e=>{const t=Date.now(),o=Uc.current;Bc.current.push({...e,firstTokenTime:t,lastTokenTime:t,responseLengthBaseline:o,endResponseLength:o})},Vc)},[Wl,qc,Ra,Ma,Da,Vc]),ju=q(async(t,o,s,n,r,i,a)=>{if(n){const e=Uo(pe,Ri.getState().mcp.clients);yn.handleQueryStart(e);const t=nn(e);t&&sn(t)}if(Qo(),!(ei||El||Ol||Ll.current)){const e=o.find(e=>"user"===e.type&&!e.isMeta),t="user"===e?.type?ho(e.message.content):null;!t||t.startsWith(`<${Po}>`)||t.startsWith(`<${wo}>`)||t.startsWith(`<${Ro}>`)||t.startsWith(`<${Ao}>`)||(Ll.current=!0,Io(t,(new AbortController).signal).then(e=>{e?_l(e):Ll.current=!1},()=>{Ll.current=!1}))}if(Ri.setState(e=>{const t=e.toolPermissionContext.alwaysAllowRules.command;return t===r||t?.length===r.length&&t.every((e,t)=>e===r[t])?e:{...e,toolPermissionContext:{...e.toolPermissionContext,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,command:r}}}}),!n)return o.some(fo)&&(am(Yo()),(e("PROACTIVE")||e("KAIROS"))&&Zs?.setContextBlocked(!1)),xm(),void Na(null);const l=yu(t,o,s,i),{tools:c,mcpClients:m}=l.options;if(void 0!==a){const e=l.getAppState;l.getAppState=()=>({...e(),effortValue:a})}Lo("query_context_loading_start");const[,,u,p,d]=await Promise.all([Bn(ii,Ii),e("TRANSCRIPT_CLASSIFIER")?qn(ii,Ii,Ri.getState().fastMode):void 0,pt(c,i,Array.from(ii.additionalWorkingDirectories.keys()),m),gt(),ft()]),f={...p,...Kt(m,to()?eo():void 0),...(e("PROACTIVE")||e("KAIROS"))&&Zs?.isProactiveActive()&&!Am.current?{terminalFocus:"The terminal is unfocused — the user is not actively watching."}:{}};Lo("query_context_loading_end");const g=dt({mainThreadAgentDefinition:ni,toolUseContext:l,customSystemPrompt:Ot,defaultSystemPrompt:u,appendSystemPrompt:ao});l.renderedSystemPrompt=g,Lo("query_query_start"),le(),ue(),fe();for await(const e of No({messages:t,systemPrompt:g,userContext:f,systemContext:d,canUseTool:Su,toolUseContext:l,querySource:qo()}))ku(e);e("BUDDY")&&fireCompanionObserver(Jl.current,e=>Ii(t=>t.companionReaction===e?t:{...t,companionReaction:e})),Lo("query_end"),xm(),Oo(),await(on?.(Jl.current))},[pe,xm,yu,ii,Ii,Ot,on,ao,Su,ni,ku,El,ei]),bu=q(async(t,o,s,n,r,i,a,p)=>{if(tn()){const e=Pe(),t=xe();e&&t&&je(e,t,!0)}const g=Fa.tryStart();if(null===g)return co("tengu_concurrent_onquery_detected",{}),void t.filter(e=>"user"===e.type&&!e.isMeta).map(e=>ho(e.message.content)).filter(e=>null!==e).forEach((e,t)=>{un({value:e,mode:"prompt"}),0===t&&co("tengu_concurrent_onquery_enqueued",{})});try{if(tl(),Wl(e=>[...e,...t]),Uc.current=0,e("TOKEN_BUDGET")){const e=a?d(a):null;l(e??c())}Bc.current=[],Ma([]),$c(null);const m=Jl.current;if(a&&await Lm(a,m,t.length),i&&a){if(!await i(a,m))return}await ju(m,t,o,s,n,r,p)}finally{if(Fa.end(g)){let t;Kc(Date.now()),pm.current=!1,xm(),await Om(Jl.current,o.signal.aborted),Ua.current(),e("TOKEN_BUDGET")&&(null!==c()&&c()>0&&!o.signal.aborted&&(t={tokens:m(),limit:c(),nudges:u()}),l(null));const s=Date.now()-za.current-Za.current;if((s>3e4||void 0!==t)&&!o.signal.aborted&&!Di){De(Ri.getState().tasks).some(e=>"running"===e.status)?(null===nl.current&&(nl.current=za.current),t&&(rl.current=t)):Wl(e=>[...e,yo(s,t,f(e,vs))])}Na(null)}if("user-cancel"===o.signal.reason&&!Fa.isActive&&""===yc.current&&0===dn()&&!Ri.getState().viewingAgentTaskId){const e=Jl.current,t=e.findLast(Ge);if(t){const o=e.lastIndexOf(t);Qe(e,o)&&(wt(),Ba.current(t))}}}},[ju,Ii,xm,Fa,Lm,Om]),Iu=U(!1);O(()=>{const t=pi;!t||Ka||Iu.current||(Iu.current=!0,async function(t){if(t.clearContext){const e=t.message.planContent?ps():void 0,{clearConversation:o}=await import("../commands/clear/conversation.js");await o({setMessages:Wl,readFileState:Wm.current,discoveredSkillNames:Ym.current,loadedNestedMemoryPaths:zm.current,getAppState:()=>Ri.getState(),setAppState:Ii,setConversationId:am}),Ll.current=!1,_l(void 0),Gm.current.clear(),Qm.current=0,e&&ds(se(),e)}const o=t.message.planContent&&!1;Ii(s=>{let n=t.mode?Qt(s.toolPermissionContext,zt(t.mode,t.allowedPrompts)):s.toolPermissionContext;return e("TRANSCRIPT_CLASSIFIER")&&"auto"===t.mode&&(n=Zt({...n,mode:"auto",prePlanMode:void 0})),{...s,initialMessage:null,toolPermissionContext:n,...o&&{pendingPlanVerification:{plan:t.message.planContent,verificationStarted:!1,verificationCompleted:!1}}}}),Ls()&&Es(e=>{Ii(t=>({...t,fileHistory:e(t.fileHistory)}))},t.message.uuid),await pc();const s=t.message.message.content;if("string"!=typeof s||t.message.planContent){const e=An();Na(e),bu([t.message],e,!0,[],xi)}else Au(s,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}});setTimeout(e=>{e.current=!1},100,Iu)}(t))},[pi,Ka,Wl,Ii,bu,xi,ka]);const Au=q(async(t,o,s,n)=>{if(ac(),(e("PROACTIVE")||e("KAIROS"))&&Zs?.resumeProactive(),!s&&t.trim().startsWith("/")){const e=Rt(t,_c).trim(),s=e.indexOf(" "),r=-1===s?e.slice(1):e.slice(1,s),i=-1===s?"":e.slice(s+1).trim(),a=Aa.find(e=>Ke(e)&&(e.name===r||e.aliases?.includes(r)||Je(e)===r));"clear"===a?.name&&Kl.current&&(co("tengu_idle_return_action",{action:"hint_converted",variant:Kl.current,idleMinutes:Math.round((Date.now()-dm.current)/6e4),messageCount:Jl.current.length,totalInputTokens:p()}),Kl.current=!1);const l=Fa.isActive&&(a?.immediate||n?.fromKeybinding);if(a&&l&&"local-jsx"===a.type){t.trim()===yc.current.trim()&&(vc(""),o.setCursorOffset(0),o.clearBuffer(),Lc({}));const e=Pt(t).filter(e=>"text"===_c[e.id]?.type),s=e.length,r=e.reduce((e,t)=>e+(_c[t.id]?.content.length??0),0);co("tengu_paste_text",{pastedTextCount:s,pastedTextBytes:r}),co("tengu_immediate_command_executed",{commandName:a.name,fromKeybinding:n?.fromKeybinding??!1});return void(async()=>{let e=!1;const t=yu(Jl.current,[],An(),xi),s=await a.load(),n=await s.call((t,s)=>{e=!0,kl({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0});const n=[];t&&"skip"!==s?.display&&(Qi({key:`immediate-${a.name}`,text:t,priority:"immediate"}),_r()||n.push(jo(bo(Je(a),i)),jo(`<${Po}>${xo(t)}</${Po}>`))),s?.metaMessages?.length&&n.push(...s.metaMessages.map(e=>So({content:e,isMeta:!0}))),n.length&&Wl(e=>[...e,...n]),void 0!==bc&&(vc(bc.text),o.setCursorOffset(bc.cursorOffset),Lc(bc.pastedContents),Ic(void 0))},t,i);n&&!e&&kl({jsx:n,shouldHidePromptInput:!1,isLocalJSXCommand:!0})})()}}if(Dc.isRemoteMode&&!t.trim())return;{const e=mo("tengu_willow_mode","off"),n=Number(process.env.CONTEXT_CODE_IDLE_THRESHOLD_MINUTES??process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES??75),r=Number(process.env.CONTEXT_CODE_IDLE_TOKEN_THRESHOLD??process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD??1e5);if("off"!==e&&!ro().idleReturnDismissed&&!pm.current&&!s&&!t.trim().startsWith("/")&&dm.current>0&&p()>=r){const s=(Date.now()-dm.current)/6e4;if(s>=n&&"dialog"===e)return cm({input:t,idleMinutes:s}),vc(""),o.setCursorOffset(0),void o.clearBuffer()}}n?.fromKeybinding||(At({display:s?t:xt(t,kc),pastedContents:s?{}:_c}),"bash"===kc&&Mt(t.trim()));const r=!s&&t.trim().startsWith("/"),i=!Ka||s||Dc.isRemoteMode;if(void 0!==bc&&!r&&i?(vc(bc.text),o.setCursorOffset(bc.cursorOffset),Lc(bc.pastedContents),Ic(void 0)):i&&(n?.fromKeybinding||(vc(""),o.setCursorOffset(0)),Lc({})),i&&(jc("prompt"),ta(void 0),Nc(e=>e+1),o.clearBuffer(),Rm.current=!1,r||"prompt"!==kc||s||Dc.isRemoteMode||(Gl(t),tl()),e("COMMIT_ATTRIBUTION")&&Ii(e=>({...e,attribution:Ns(e.attribution,e=>{Us(e).catch(e=>{Se(`Attribution: Failed to save snapshot: ${e}`)})})}))),s){const{queryRequired:e}=await Tn(s.state,s.speculationSessionTimeSavedMs,s.setAppState,t,{setMessages:Wl,readFileState:Wm,cwd:te()});if(e){const e=An();Na(e),bu([],e,!0,[],xi)}return}if(Dc.isRemoteMode&&(!r||"local-jsx"!==Aa.find(e=>{const o=t.trim().slice(1).split(/\s/)[0];return Ke(e)&&(e.name===o||e.aliases?.includes(o)||Je(e)===o)})?.type)){const e=Object.values(_c),o=e.filter(e=>"image"===e.type),s=o.length>0?o.map(e=>e.id):void 0;let n=t.trim(),r=t.trim();if(e.length>0){const o=[],s=[],i=t.trim();i&&(o.push({type:"text",text:i}),s.push({type:"text",text:i}));for(const t of e)if("image"===t.type){const e={type:"base64",media_type:t.mediaType??"image/png",data:t.content};o.push({type:"image",source:e}),s.push({type:"image",source:e})}else o.push({type:"text",text:t.content}),s.push({type:"text",text:t.content});n=o,r=s}const i=So({content:n,imagePasteIds:s});return Wl(e=>[...e,i]),void await Dc.sendMessage(r,{uuid:i.uuid})}await pc(),await Eo({input:t,helpers:o,queryGuard:Fa,isExternalLoading:Xa,mode:kc,commands:Aa,onInputChange:vc,setPastedContents:Lc,setToolJSX:kl,getToolUseContext:yu,messages:Jl.current,mainLoopModel:xi,pastedContents:_c,ideSelection:ea,setUserInputOnProcessing:Gl,setAbortController:Na,abortController:_a,onQuery:bu,setAppState:Ii,querySource:qo(),onBeforeQuery:vo,canUseTool:Su,addNotification:Qi,setMessages:Wl,streamMode:Pa.current,hasInterruptibleToolInProgress:Pc.current,onJumpToMessage:rc}),(r||Ka)&&void 0!==bc&&(vc(bc.text),o.setCursorOffset(bc.cursorOffset),Lc(bc.pastedContents),Ic(void 0))},[Fa,Ka,Xa,kc,Aa,vc,jc,Lc,Nc,ta,kl,yu,xi,_c,ea,Gl,Na,Qi,bu,bc,Ic,Ii,vo,Su,xc,Wl,pc,ac]),wu=q(async(e,o,s)=>{_e(o)?(Oe(o.id,So({content:e}),Ii),"running"===o.status?Le(o.id,e,Ii):rs({agentId:o.id,prompt:e,toolUseContext:yu(Jl.current,[],new AbortController,xi),canUseTool:Su}).catch(e=>{Se(`resumeAgentBackground failed: ${$t(e)}`),Qi({key:`resume-agent-failed-${o.id}`,jsx:t(w,{color:"error",children:["Failed to resume agent: ",$t(e)]}),priority:"low"})})):Ee(o.id,e,Ii),vc(""),s.setCursorOffset(0),s.clearBuffer()},[Ii,vc,yu,Su,xi,Qi]),Ru=q(()=>{const e=ou?vr(ou):"/issue";su(null),Au(e,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(t=>{Se(`Auto-run ${e} failed: ${$t(t)}`)})},[Au,ou]),Pu=q(()=>{su(null)},[]),xu=q(()=>{Au("/feedback",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(e=>{Se(`Survey feedback request failed: ${e instanceof Error?e.message:String(e)}`)})},[Au]),Mu=U(Au);Mu.current=Au;const Eu=q(()=>{Mu.current("/rate-limit-options",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})},[]),Du=q(async()=>{if(lu(!0),e("BG_SESSIONS")&&Vs())return a("tmux",["detach-client"],{stdio:"ignore"}),void lu(!1);if(null!==cn())return void iu(o(ln,{showWorktree:!0,onDone:()=>{},onCancel:()=>{iu(null),lu(!1)}}));const t=await an.load(),s=await t.call(()=>{});iu(s),null===s&&lu(!1)},[]),_u=q(()=>{tm(e=>!e)},[]),Lu=q(t=>{const o=Jl.current,s=o.lastIndexOf(t);-1!==s&&(co("tengu_conversation_rewind",{preRewindMessageCount:o.length,postRewindMessageCount:s,messagesRemoved:o.length-s,rewindToMessageIndex:s}),Wl(o.slice(0,s)),am(Yo()),ws(),e("CONTEXT_COLLAPSE")&&r("../services/contextCollapse/index.js").resetContextCollapse(),Ii(e=>({...e,toolPermissionContext:t.permissionMode&&e.toolPermissionContext.mode!==t.permissionMode?{...e.toolPermissionContext,mode:t.permissionMode}:e.toolPermissionContext,promptSuggestion:{text:null,promptId:null,shownAt:0,acceptedAt:0,generationRequestId:null}})))},[Wl,Ii]),Ou=q(e=>{Lu(e);const t=uo(e);if(t&&(vc(t.text),jc(t.mode)),Array.isArray(e.message.content)&&e.message.content.some(e=>"image"===e.type)){const t=e.message.content.filter(e=>"image"===e.type);if(t.length>0){const o={};t.forEach((t,s)=>{if("base64"===t.source.type){const n=e.imagePasteIds?.[s]??s+1;o[n]={id:n,type:"image",content:t.source.data,mediaType:t.source.media_type}}}),Lc(o)}}},[Lu,vc]);Ba.current=Ou;const Nu=q(async e=>{setImmediate((e,t)=>e(t),Ou,e)},[Ou]),Uu={copy:e=>{$r(e).then(e=>{e&&process.stdout.write(e),Qi({key:"selection-copied",text:"copied",color:"success",priority:"immediate",timeoutMs:2e3})})},edit:async e=>{const t=(e=>{const t=e.slice(0,24);return Vl.findIndex(e=>e.uuid.slice(0,24)===t)})(e.uuid),o=t>=0?Vl[t]:void 0;if(!o||!Ge(o))return;const s=!await Os(ui,o.uuid),n=Qe(Vl,t);s&&n?(onCancel(),Nu(o)):(sm(o),tm(!0))}},{enter:Bu,handlers:qu}=Br(oc,sc,nc,Uu);kt(jt()),$e(Vl,Vl.length===T?.length);const{sendBridgeResult:Hu}=Fe(Vl,Wl,Oa,Aa,xi);Ua.current=Hu,Ve(Vl),Xe(Vl),Ys(Vl,Ka,onCancel,Ea),zs(jl),bt();const $u=U(!1);O(()=>{di.length<1?$u.current=!1:$u.current||($u.current=!0,io(e=>({...e,promptQueueUseCount:(e.promptQueueUseCount??0)+1})))},[di.length]);const Fu=q(async e=>{await Eo({helpers:{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}},queryGuard:Fa,commands:Aa,onInputChange:()=>{},setPastedContents:()=>{},setToolJSX:kl,getToolUseContext:yu,messages:Vl,mainLoopModel:xi,ideSelection:ea,setUserInputOnProcessing:Gl,setAbortController:Na,onQuery:bu,setAppState:Ii,querySource:qo(),onBeforeQuery:vo,canUseTool:Su,addNotification:Qi,setMessages:Wl,queuedCommands:e,onJumpToMessage:rc})},[Fa,Aa,kl,yu,Vl,xi,ea,Gl,Su,Na,bu,Qi,Ii,vo,rc]);Do({executeQueuedInput:Fu,hasActiveLocalJsxUI:Bl,queryGuard:Fa}),O(()=>{In.recordUserActivity(),Z(!0)},[Sc,Oc]),O(()=>{1===Oc&&St()},[Oc]),O(()=>{const e=mm.current;if(mm.current=Ka,!e||Ka)return;if(0===Oc)return;!0===ro().taskCompleteNotifEnabled&&X({message:"Respuesta finalizada",notificationType:"task_complete"},Pi)},[Ka,Oc,Pi]),O(()=>{const e=!Ka&&(jl.length>0||Pl.length>0||!!hi||!!Si),t=um.current;if(um.current=e,!e||t)return;!0===ro().inputNeededNotifEnabled&&X({message:"Se requiere tu aprobacion o entrada",notificationType:"input_needed"},Pi)},[Ka,jl.length,Pl.length,hi,Si,Pi]),O(()=>{let e=!1;return(async()=>{const{startHeartbeat:t,stopHeartbeat:o}=await import("../utils/heartbeat.js");e||(t({onStdinStalled:()=>{Qi({key:"heartbeat-stdin-stalled",text:"⚠ stdin parece bloqueado · ejecuta /heartbeat para más info",color:"error",priority:"immediate",timeoutMs:2147483647})},onStdinRecovered:()=>{Yi("heartbeat-stdin-stalled")},onGitBashDetected:()=>{Qi({key:"heartbeat-gitbash-tip",text:"Tip: en Git Bash añade `export MSYS=enable_pcon` a ~/.bashrc para evitar cuelgues. Ver /heartbeat",color:"suggestion",priority:"low",timeoutMs:3e4})}}),globalThis.__contextHeartbeatStop=o)})(),()=>{e=!0;const t=globalThis.__contextHeartbeatStop;t&&(t(),delete globalThis.__contextHeartbeatStop)}},[Qi,Yi]),O(()=>{if(Ka)return;if(0===Oc)return;if(0===Jc)return;const e=setTimeout((e,t,o,s,n)=>{if(ee()>e)return;const r=Date.now()-e;!t&&!o&&void 0===s.current&&r>=ro().messageIdleNotifThresholdMs&&X({message:"Context está esperando tu entrada",notificationType:"idle_prompt"},n)},ro().messageIdleNotifThresholdMs,Jc,Ka,dl,il,Pi);return()=>clearTimeout(e)},[Ka,dl,Oc,Jc,Pi]),O(()=>{if(0===Jc)return;if(Ka)return;const e=mo("tengu_willow_mode","off");if("hint"!==e&&"hint_v2"!==e)return;if(ro().idleReturnDismissed)return;const n=Number(process.env.CONTEXT_CODE_IDLE_TOKEN_THRESHOLD??process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD??1e5);if(p()<n)return;const r=6e4*Number(process.env.CONTEXT_CODE_IDLE_THRESHOLD_MINUTES??process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES??75)-(Date.now()-Jc),i=setTimeout((e,n,r,i,a)=>{if(0===r.current.length)return;const l=p(),c=Te(l),m=(Date.now()-e)/6e4;n({key:"idle-return-hint",jsx:"hint_v2"===i?t(s,{children:[o(w,{dimColor:!0,children:"new task? "}),o(w,{color:"suggestion",children:"/clear"}),o(w,{dimColor:!0,children:" to save "}),t(w,{color:"suggestion",children:[c," tokens"]})]}):t(w,{color:"warning",children:["new task? /clear to save ",c," tokens"]}),priority:"medium",timeoutMs:2147483647}),a.current=i,co("tengu_idle_return_action",{action:"hint_shown",variant:i,idleMinutes:Math.round(m),messageCount:r.current.length,totalInputTokens:l})},Math.max(0,r),Jc,Qi,Jl,e,Kl);return()=>{clearTimeout(i),Yi("idle-return-hint"),Kl.current=!1}},[Jc,Ka,Qi,Yi]);const Vu=q((e,t)=>{if(Fa.isActive)return!1;if(pn().some(e=>"prompt"===e.mode||"bash"===e.mode))return!1;const o=An();Na(o);const s=So({content:e,isMeta:!!t?.isMeta||void 0});return bu([s],o,!0,[],xi),!0},[bu,xi,Ri]),Xu=Xt({setInputValueRaw:Cc,inputValueRef:yc,insertTextRef:Tc});if(Gs({enabled:tn(),isLoading:Ka,focusedInputDialog:mu,onSubmitMessage:Vu}),_o({isLoading:Ka,onSubmitMessage:Vu}),Qs(jl),e("AGENT_TRIGGERS")){const e=Ri.getState().kairosEnabled;en({isLoading:Ka,assistantMode:e,setMessages:Wl})}O(()=>{di.some(e=>"now"===e.priority)&&Oa.current?.abort("interrupt")},[di]),O(()=>(async function(){tu();const e=await ht();if(e.length>0){const t=e.map(e=>` [${e.type}] ${e.path} (${e.content.length} chars)${e.parent?` (included by ${e.parent})`:""}`).join("\n");Se(`Loaded ${e.length} CLAUDE.md/rules files:\n${t}`)}else Se("No CLAUDE.md/rules files found");for(const t of e)Wm.current.set(t.path,{content:t.contentDiffersFromDisk?t.rawContent??t.content:t.content,timestamp:Date.now(),offset:void 0,limit:void 0,isPartialView:t.contentDiffersFromDisk})}(),()=>{yn.shutdown()}),[]);const{internal_eventEmitter:Ju}=R(),[Ku,Wu]=B(0);O(()=>{const handleSuspend=()=>{process.stdout.write("\nContext Code has been suspended. Run `fg` to bring Context Code back.\nNote: ctrl + z now suspends Context Code, ctrl + _ undoes input.\n")},handleResume=()=>{Wu(e=>e+1)};return Ju?.on("suspend",handleSuspend),Ju?.on("resume",handleResume),()=>{Ju?.off("suspend",handleSuspend),Ju?.off("resume",handleResume)}},[Ju]);const Gu=N(()=>{if(!Ka)return null;const e=Vl.filter(e=>"progress"===e.type&&"hook_progress"===e.data.type&&("Stop"===e.data.hookEvent||"SubagentStop"===e.data.hookEvent));if(0===e.length)return null;const t=e.at(-1)?.toolUseID;if(!t)return null;if(Vl.some(e=>"system"===e.type&&"stop_hook_summary"===e.subtype&&e.toolUseID===t))return null;const o=e.filter(e=>e.toolUseID===t),s=o.length,n=f(Vl,e=>{if("attachment"!==e.type)return!1;const o=e.attachment;return"hookEvent"in o&&("Stop"===o.hookEvent||"SubagentStop"===o.hookEvent)&&"toolUseID"in o&&o.toolUseID===t}),r=o.find(e=>e.data.statusMessage)?.data.statusMessage;if(r)return 1===s?`${r}…`:`${r}… ${n}/${s}`;const i="SubagentStop"===o[0]?.data.hookEvent?"subagent stop":"stop";return 1===s?`running ${i} hook`:`running stop hooks… ${n}/${s}`},[Vl,Ka]),Qu=q(()=>{hc({messagesLength:Vl.length,streamingToolUsesLength:xa.length})},[Vl.length,xa.length]),Yu=q(()=>{hc(null)},[]),zu=_r()&&!oi,Zu=U(null),[ep,tp]=B(!1),[op,sp]=B(""),[np,rp]=B(0),[ip,ap]=B(0),lp=q((e,t)=>{rp(e),ap(t)},[]);y((e,t,o)=>{if(t.ctrl||t.meta)return;if("/"===e)return Zu.current?.setAnchor(),tp(!0),void o.stopImmediatePropagation();const s=e[0];if(("n"===s||"N"===s)&&e===s.repeat(e.length)&&np>0){const t="n"===s?Zu.current?.nextMatch:Zu.current?.prevMatch;if(t)for(let o=0;o<e.length;o++)t();o.stopImmediatePropagation()}},{isActive:"transcript"===Bi&&zu&&!ep&&!Fi});const{setQuery:cp,scanElement:mp,setPositions:up}=k(),pp=v().columns,dp=L.useRef(pp);L.useEffect(()=>{dp.current!==pp&&(dp.current=pp,(op||ep)&&(tp(!1),sp(""),rp(0),ap(0),Zu.current?.disarmSearch(),cp("")))},[pp,op,ep,cp]),y((e,t,o)=>{if(!t.ctrl&&!t.meta){if("q"===e)return Yu(),void o.stopImmediatePropagation();if("["!==e||Fi){if("v"===e){if(o.stopImmediatePropagation(),Gi.current)return;Gi.current=!0;const e=Ki.current,setStatus=t=>{e===Ki.current&&(clearTimeout(Wi.current),Ji(t))};setStatus(`rendering ${dc.length} messages…`),(async()=>{try{const e=Math.max(80,(process.stdout.columns??80)-6),t=(await j(dc,ka,e)).replace(/[ \t]+$/gm,""),o=h(S(),`cc-transcript-${Date.now()}.txt`);await I(o,t);const s=b(o);setStatus(s?`opening ${o}`:`wrote ${o} · no $VISUAL/$EDITOR set`)}catch(e){setStatus(`render failed: ${e instanceof Error?e.message:String(e)}`)}Gi.current=!1,e===Ki.current&&(Wi.current=setTimeout(e=>e(""),4e3,Ji))})()}}else Vi(!0),$i(!0),o.stopImmediatePropagation()}},{isActive:"transcript"===Bi&&zu&&!ep});const fp="transcript"===Bi&&zu;O(()=>{fp||(sp(""),rp(0),ap(0),tp(!1),Ki.current++,clearTimeout(Wi.current),Vi(!1),Ji(""))},[fp]),O(()=>{cp(fp?op:""),fp||up(null)},[fp,op,cp,up]);const gp={screen:Bi,setScreen:qi,showAllInTranscript:Hi,setShowAllInTranscript:$i,messageCount:Vl.length,onEnterTranscript:Qu,onExitTranscript:Yu,virtualScrollActive:zu,searchBarOpen:ep},hp=gc?dc.slice(0,gc.messagesLength):dc,Sp=gc?xa.slice(0,gc.streamingToolUsesLength):xa;if(Bt({onOpenBackgroundTasks:Bl?void 0:()=>Tm(!0)}),Ht(),"transcript"===Bi){const e=!_r()||oi||Fi?void 0:qa,n=o(Jo,{messages:hp,tools:ka,commands:Aa,verbose:!0,toolJSX:null,toolUseConfirmQueue:[],inProgressToolUseIDs:wc,isMessageSelectorVisible:!1,conversationId:im,screen:Bi,agentDefinitions:mi,streamingToolUses:Sp,showAllInTranscript:Hi,onOpenRateLimitOptions:Eu,isLoading:Ka,hidePastThinking:!0,streamingThinking:Ea,scrollRef:e,jumpRef:Zu,onSearchMatchesChange:lp,scanElement:mp,setPositions:up,disableRenderCap:Fi}),r=dl&&o(A,{flexDirection:"column",width:"100%",children:dl.jsx}),i=t(Lt,{children:[o(AnimatedTerminalTitle,{isAnimating:ql,title:Nl,disabled:ei,noPrefix:Fl}),o(Dt,{...gp}),o(Jt,{voiceHandleKeyEvent:Xu.handleKeyEvent,stripTrailing:Xu.stripTrailing,resetAnchor:Xu.resetAnchor,isActive:!dl?.isLocalJSXCommand}),o(_t,{onSubmit:Au,isActive:!dl?.isLocalJSXCommand}),e?o(Ur,{scrollRef:qa,isActive:"ultraplan-choice"!==mu,isModal:!ep,onScroll:()=>Zu.current?.disarmSearch()}):null,o(Ut,{...fu}),e?o(Mr,{scrollRef:qa,scrollable:t(s,{children:[n,r,o(Kn,{})]}),bottom:ep?o(TranscriptSearchBar,{jumpRef:Zu,initialQuery:"",count:np,current:ip,onClose:e=>{sp(np>0?e:""),tp(!1),e||(rp(0),ap(0),Zu.current?.setSearchQuery(""))},onCancel:()=>{tp(!1),Zu.current?.setSearchQuery(""),Zu.current?.setSearchQuery(op),cp(op)},setHighlight:cp}):o(TranscriptModeFooter,{showAllInTranscript:Hi,virtualScroll:!0,status:Xi||void 0,searchBadge:op&&np>0?{current:ip,count:np}:void 0})}):t(s,{children:[n,r,o(Kn,{}),o(TranscriptModeFooter,{showAllInTranscript:Hi,virtualScroll:!1,suppressShowAll:Fi,status:Xi||void 0})]})]});return e?o(Nr,{mouseTracking:Or(),children:i}):i}const Cp=bi?yi[bi]:void 0,yp=Cp&&Ks(Cp)?Cp:void 0,Tp=yp??(Cp&&_e(Cp)?Cp:void 0),vp=Fc||!Ka,kp=Tp?Tp.messages??[]:vp?Vl:dc,jp=Wa&&!Tp&&kp.length<=Qa.current?Wa:void 0,bp="tool-permission"===mu?o(ze,{onDone:()=>bl(([e,...t])=>t),onReject:du,toolUseConfirm:jl[0],toolUseContext:yu(Vl,Vl,_a??An(),xi),verbose:ai,workerBadge:jl[0]?.workerBadge,setStickyFooter:_r()?Al:void 0},jl[0]?.toolUseID):null,Ip=pp<Rr,Ap=!dl?.shouldHidePromptInput&&!mu&&!ym,wp=_r()&&!0===dl?.isLocalJSXCommand,Rp=(gl.length>0?gl[gl.length-1]?.element:null)??(wp?dl.jsx:null),Pp=o(V.Provider,{value:{stack:gl,pushModal:Sl,replaceModal:Cl,popModal:yl,clearModals:Tl},children:t(Lt,{children:[o(AnimatedTerminalTitle,{isAnimating:ql,title:Nl,disabled:ei,noPrefix:Fl}),o(Dt,{...gp}),o(Jt,{voiceHandleKeyEvent:Xu.handleKeyEvent,stripTrailing:Xu.stripTrailing,resetAnchor:Xu.resetAnchor,isActive:!dl?.isLocalJSXCommand}),o(_t,{onSubmit:Au,isActive:!dl?.isLocalJSXCommand}),o(Ur,{scrollRef:qa,isActive:_r()&&(null!=Rp||!mu||"tool-permission"===mu),onScroll:Rp||bp||Tp?void 0:uc}),e("MESSAGE_ACTIONS")&&_r()&&!si?o(qr,{handlers:qu,isActive:null!==oc}):null,o(Ut,{...fu}),o(wn,{dynamicMcpConfig:Oi,isStrictMcpConfig:at,children:o(Mr,{scrollRef:qa,overlay:bp,bottomFloat:e("BUDDY")&&Ap&&!Ip?o(wr,{}):void 0,modal:Rp,modalScrollRef:Ha,dividerYRef:Yl,hidePill:!!Tp,hideSticky:!!yp,newMessageCount:ic?.count??0,onPillClick:()=>{sc(null),ec(qa.current)},scrollable:t(s,{children:[o(Wo,{}),o(Jo,{messages:kp,tools:ka,commands:Aa,verbose:ai,toolJSX:dl,toolUseConfirmQueue:jl,inProgressToolUseIDs:yp?yp.inProgressToolUseIDs??new Set:wc,isMessageSelectorVisible:em,conversationId:im,screen:Bi,streamingToolUses:xa,showAllInTranscript:Hi,agentDefinitions:mi,onOpenRateLimitOptions:Eu,isLoading:Ka,streamingText:Ka&&!Tp?Xc:null,isBriefOnly:!Tp&&_i,unseenDivider:Tp?void 0:ic,scrollRef:_r()?qa:void 0,trackStickyPrompt:!!_r()||void 0,cursor:oc,setCursor:sc,cursorNavRef:nc}),o(cr,{}),!kr&&jp&&!Rp&&o(lr,{param:{text:jp,type:"text"},addMargin:!0,verbose:ai}),dl&&!(dl.isLocalJSXCommand&&dl.isImmediate)&&!wp&&o(A,{flexDirection:"column",width:"100%",children:dl.jsx}),!1,e("WEB_BROWSER_TOOL")?jr&&o(jr.WebBrowserPanel,{}):null,o(A,{flexGrow:1}),Um&&o(mt,{mode:wa,spinnerTip:fi,responseLengthRef:Uc,apiMetricsRef:Bc,overrideMessage:Wc,spinnerSuffix:Gu,verbose:ai,loadingStartTimeRef:za,totalPausedMsRef:Za,pauseStartTimeRef:el,overrideColor:Qc,overrideShimmerColor:zc,hasActiveTools:wc.size>0,leaderIsIdle:!Ka}),!Um&&!Ka&&!Wa&&!Mm&&_i&&!Tp&&o(ut,{}),_r()&&o(ot,{})]}),bottom:t(A,{flexDirection:e("BUDDY")&&Ip?"column":"row",width:"100%",alignItems:e("BUDDY")&&Ip?void 0:"flex-end",children:[e("BUDDY")&&Ip&&_r()&&Ap?o(Ar,{}):null,t(A,{flexDirection:"column",flexGrow:1,children:[Il,dl?.isLocalJSXCommand&&dl.isImmediate&&!wp&&o(A,{flexDirection:"column",width:"100%",children:dl.jsx}),!Um&&!dl?.isLocalJSXCommand&&gi&&Ta&&Ta.length>0&&o(A,{width:"100%",flexDirection:"column",children:o(Ko,{tasks:Ta,isStandalone:!0})}),"sandbox-permission"===mu&&o(Jn,{hostPattern:wl[0].hostPattern,onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=wl[0];if(!s)return;const n=s.hostPattern.host;if(o){const e={type:"addRules",rules:[{toolName:oo,ruleContent:`domain:${n}`}],behavior:t?"allow":"deny",destination:"localSettings"};Ii(t=>({...t,toolPermissionContext:Gt(t.toolPermissionContext,e)})),Yt(e),Fn.refreshConfig()}Rl(e=>(e.filter(e=>e.hostPattern.host===n).forEach(e=>e.resolvePromise(t)),e.filter(e=>e.hostPattern.host!==n)));const r=Ml.current.get(n);if(r){for(const e of r)e();Ml.current.delete(n)}}},wl[0].hostPattern.host),"prompt"===mu&&o(et,{title:Pl[0].title,toolInputSummary:Pl[0].toolInputSummary,request:Pl[0].request,onRespond:e=>{const t=Pl[0];t&&(t.resolve({prompt_response:t.request.prompt,selected:e}),xl(([,...e])=>e))},onAbort:()=>{const e=Pl[0];e&&(e.reject(new Error("Prompt cancelled by user")),xl(([,...e])=>e))}},Pl[0].request.prompt),hi&&o(Me,{toolName:hi.toolName,description:hi.description}),Si&&o(Me,{toolName:"Network Access",description:`Waiting for leader to approve network access to ${Si.host}`}),"worker-sandbox-permission"===mu&&o(Jn,{hostPattern:{host:Ti.queue[0].host,port:void 0},onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=Ti.queue[0];if(!s)return;const n=s.host;if(we(s.workerName,s.requestId,n,t,Ci?.teamName),o&&t){const e={type:"addRules",rules:[{toolName:oo,ruleContent:`domain:${n}`}],behavior:"allow",destination:"localSettings"};Ii(t=>({...t,toolPermissionContext:Gt(t.toolPermissionContext,e)})),Yt(e),Fn.refreshConfig()}Ii(e=>({...e,workerSandboxPermissions:{...e.workerSandboxPermissions,queue:e.workerSandboxPermissions.queue.slice(1)}}))}},Ti.queue[0].requestId),"elicitation"===mu&&o(Ze,{event:vi.queue[0],onResponse:(e,t)=>{const o=vi.queue[0];if(!o)return;o.respond({action:e,content:t});"url"===o.params.mode&&"accept"===e||Ii(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}}))},onWaitingDismiss:e=>{const t=vi.queue[0];Ii(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}})),t?.onWaitingDismiss?.(e)}},vi.queue[0].serverName+":"+String(vi.queue[0].requestId)),"cost"===mu&&o(D,{onDone:()=>{rm(!1),hm(!0),io(e=>({...e,hasAcknowledgedCostThreshold:!0})),co("tengu_cost_threshold_acknowledged",{})}}),"idle-return"===mu&&lm&&o(_,{idleMinutes:lm.idleMinutes,totalInputTokens:p(),onDone:async e=>{const t=lm;if(cm(null),co("tengu_idle_return_action",{action:e,idleMinutes:Math.round(t.idleMinutes),messageCount:Jl.current.length,totalInputTokens:p()}),"dismiss"!==e){if("never"===e&&io(e=>e.idleReturnDismissed?e:{...e,idleReturnDismissed:!0}),"clear"===e){const{clearConversation:e}=await import("../commands/clear/conversation.js");await e({setMessages:Wl,readFileState:Wm.current,discoveredSkillNames:Ym.current,loadedNestedMemoryPaths:zm.current,getAppState:()=>Ri.getState(),setAppState:Ii,setConversationId:am}),Ll.current=!1,_l(void 0),Gm.current.clear(),Qm.current=0}pm.current=!0,Mu.current(t.input,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})}else vc(t.input)}}),"ide-onboarding"===mu&&o(vn,{onDone:()=>aa(!1),installationStatus:na}),!1,!1,"effort-callout"===mu&&o(kn,{model:xi,onDone:e=>{ua(!1),"dismiss"!==e&&Ii(t=>({...t,effortValue:e}))}}),"remote-callout"===mu&&o(bn,{onDone:e=>{Ii(t=>t.showRemoteCallout?{...t,showRemoteCallout:!1,..."enable"===e&&{replBridgeEnabled:!0,replBridgeExplicit:!0,replBridgeOutboundOnly:!1}}:t)}}),ru,"plugin-hint"===mu&&Sa&&o(or,{pluginName:Sa.pluginName,pluginDescription:Sa.pluginDescription,marketplaceName:Sa.marketplaceName,sourceCommand:Sa.sourceCommand,onResponse:Ca}),"lsp-recommendation"===mu&&ga&&o(er,{pluginName:ga.pluginName,pluginDescription:ga.pluginDescription,fileExtension:ga.fileExtension,onResponse:ha}),"desktop-upsell"===mu&&o(sr,{onDone:()=>fa(!1)}),e("ULTRAPLAN")?"ultraplan-choice"===mu&&ki&&o(UltraplanChoiceDialog,{plan:ki.plan,sessionId:ki.sessionId,taskId:ki.taskId,setMessages:Wl,readFileState:Wm.current,getAppState:()=>Ri.getState(),setConversationId:am}):null,e("ULTRAPLAN")?"ultraplan-launch"===mu&&ji&&o(UltraplanLaunchDialog,{onChoice:(e,t)=>{const o=ji.blurb;if(Ii(e=>e.ultraplanLaunchPending?{...e,ultraplanLaunchPending:void 0}:e),"cancel"===e)return;Wl(e=>[...e,jo(bo("ultraplan",o))]);const appendStdout=e=>Wl(t=>[...t,jo(`<${Po}>${xo(e)}</${Po}>`)]);launchUltraplan({blurb:o,getAppState:()=>Ri.getState(),setAppState:Ii,signal:An().signal,disconnectedBridge:t?.disconnectedBridge,onSessionReady:e=>{if(!Fa.isActive)return void appendStdout(e);const t=Fa.subscribe(()=>{Fa.isActive||(t(),Ri.getState().ultraplanSessionUrl&&appendStdout(e))})}}).then(appendStdout).catch(Vt)}}):null,Nm(),!dl?.shouldHidePromptInput&&!mu&&!au&&!kr&&!oc&&t(s,{children:[ou&&o(Cr,{onRun:Ru,onCancel:Pu,reason:Tr(ou)}),"closed"!==Fm.state?o(Mn,{state:Fm.state,lastResponse:Fm.lastResponse,handleSelect:Fm.handleSelect,inputValue:Sc,setInputValue:vc,onRequestFeedback:xu}):"closed"!==Vm.state?o(Mn,{state:Vm.state,lastResponse:Vm.lastResponse,handleSelect:Vm.handleSelect,handleTranscriptSelect:Vm.handleTranscriptSelect,inputValue:Sc,setInputValue:vc,onRequestFeedback:xu,message:"How well did Claude use its memory? (optional)"}):o(Mn,{state:$m.state,lastResponse:$m.lastResponse,handleSelect:$m.handleSelect,handleTranscriptSelect:$m.handleTranscriptSelect,inputValue:Sc,setInputValue:vc,onRequestFeedback:nu.current?void 0:xu}),"closed"!==Xm.state&&o(Mn,{state:Xm.state,lastResponse:null,handleSelect:()=>{},handleTranscriptSelect:Xm.handleTranscriptSelect,inputValue:Sc,setInputValue:vc}),!1,Hm&&o(br,{}),o(tt,{debug:i,ideSelection:ea,hasSuppressedDialogs:!!uu,isLocalJSXCommandActive:Bl,getToolUseContext:yu,toolPermissionContext:ii,setToolPermissionContext:hu,apiKeyStatus:eu,commands:Aa,agents:mi.activeAgents,isLoading:Ka,onExit:Du,verbose:ai,messages:Vl,onAutoUpdaterResult:ml,autoUpdaterResult:cl,input:Sc,onInputChange:vc,mode:kc,onModeChange:jc,stashedPrompt:bc,setStashedPrompt:Ic,submitCount:Oc,onShowMessageSelector:_u,onMessageActionsEnter:e("MESSAGE_ACTIONS")&&_r()&&!si?Bu:void 0,mcpClients:Zi,pastedContents:_c,setPastedContents:Lc,vimMode:Sm,setVimMode:Cm,showBashesDialog:ym,setShowBashesDialog:Tm,onSubmit:Au,onAgentSubmit:wu,isSearchingHistory:vm,setIsSearchingHistory:km,helpOpen:jm,setHelpOpen:bm,insertTextRef:Tc,voiceInterimRange:Xu.interimRange}),o(hn,{onBackgroundSession:vu,isLoading:Ka})]}),oc&&o(Hr,{cursor:oc}),"message-selector"===mu&&o(We,{messages:Vl,preselectedMessage:om,onPreRestore:onCancel,onRestoreCode:async e=>{await Ds(e=>{Ii(t=>({...t,fileHistory:e(t.fileHistory)}))},e.uuid)},onSummarize:async(t,o,s="from")=>{const n=go(Vl),r=n.indexOf(t);if(-1===r)return void Wl(e=>[...e,ko("That message is no longer in the active context (snipped or pre-compact). Choose a more recent message.","warning")]);const i=An(),a=yu(n,[],i,xi),l=a.getAppState(),c=await pt(a.options.tools,a.options.mainLoopModel,Array.from(l.toolPermissionContext.additionalWorkingDirectories.keys()),a.options.mcpClients),m=dt({mainThreadAgentDefinition:void 0,toolUseContext:a,customSystemPrompt:a.options.customSystemPrompt,defaultSystemPrompt:c,appendSystemPrompt:a.options.appendSystemPrompt}),[u,p]=await Promise.all([gt(),ft()]),d=await Ms(n,r,a,{systemPrompt:m,userContext:u,systemContext:p,toolUseContext:a,forkContextMessages:n},o,s),f=d.messagesToKeep??[],g="up_to"===s?[...d.summaryMessages,...f]:[...f,...d.summaryMessages],h=[d.boundaryMarker,...g,...d.attachments,...d.hookResults];if(_r()&&"from"===s?Wl(e=>{const o=e.findIndex(e=>e.uuid===t.uuid);return[...e.slice(0,-1===o?0:o),...h]}):Wl(h),(e("PROACTIVE")||e("KAIROS"))&&Zs?.setContextBlocked(!1),am(Yo()),Rs(a.options.querySource),"from"===s){const e=uo(t);e&&(vc(e.text),jc(e.mode))}const S=Nt("app:toggleTranscript","Global","ctrl+o");Qi({key:"summarize-ctrl-o-hint",text:`Conversation summarized (${S} for history)`,priority:"medium",timeoutMs:8e3})},onRestoreMessage:Nu,onClose:()=>{tm(!1),sm(void 0)}}),!1]}),!e("BUDDY")||Ip&&_r()||!Ap?null:o(Ar,{})]})})},Ku)]})});return _r()?o(Nr,{mouseTracking:Or(),children:Pp}):Pp}
@@ -0,0 +1 @@
1
+ import{createInterface as e}from"node:readline";import{WebSocketServer as t}from"ws";import{QueryEngine as s}from"../QueryEngine.js";import{getTools as o}from"../tools.js";import{getCommands as a}from"../commands.js";import{getSessionId as r}from"../bootstrap/state.js";import{createStore as n}from"../state/store.js";import{getDefaultAppState as i}from"../state/AppStateStore.js";import{cloneFileStateCache as l}from"../utils/fileStateCache.js";import{createAbortController as c}from"../utils/abortController.js";import*as d from"../webapp/server.js";class Deferred{promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}let h=null;export function getActiveHeadlessServer(){return h}export class HeadlessChannelServer{engine=null;wsServer=null;activeWsClients=new Set;activeToolResolver=null;abortController=null;currentCwd=process.cwd();constructor(){h=this}async start(s={}){if(e({input:process.stdin,output:process.stdout,terminal:!1}).on("line",e=>{this.handleInputLine(e.trim())}),s.useWs){const e=s.port||9878;this.wsServer=new t({port:e,host:"127.0.0.1"}),this.wsServer.on("connection",e=>{this.activeWsClients.add(e),this.sendToChannel({type:"channel_connected",message:"Conexión establecida con el canal Headles WebSocket."},e),e.on("message",e=>{this.handleInputLine(e.toString().trim())}),e.on("close",()=>{this.activeWsClients.delete(e)})}),console.error(`[Headless Channel Server] WebSocket escuchando en ws://127.0.0.1:${e}`)}console.error("[Headless Channel Server] Inicializado en stdio (JSONLines). Esperando start_session...")}async handleInputLine(e){if(e)try{const t=JSON.parse(e);switch(t.type){case"start_session":await this.handleStartSession(t);break;case"submit_prompt":await this.handleSubmitPrompt(t);break;case"approve_tool":this.handleApproveTool(t);break;case"reject_tool":this.handleRejectTool(t);break;case"abort":this.handleAbort();break;default:this.sendError(`Tipo de comando desconocido: ${t.type}`)}}catch(e){this.sendError(`Error al procesar línea JSON: ${e.message}`)}}async handleStartSession(e){const t=e.cwd||process.cwd();this.currentCwd=t;try{const d=n(i()),h=d.getState(),p=o(h.toolPermissionContext),m=await a(t);this.abortController=c(),this.engine=new s({cwd:t,tools:p,commands:m,mcpClients:h.mcp.clients.map(e=>e.config),agents:[],canUseTool:this.makeInteractiveCanUseTool(),getAppState:()=>d.getState(),setAppState:e=>d.setState(e),readFileCache:l(h.readFileCache),abortController:this.abortController,userSpecifiedModel:e.options?.model}),this.sendToChannel({type:"session_created",session_id:r(),status:"idle",cwd:t})}catch(e){this.sendError(`Fallo al inicializar sesión Headless: ${e.message}`)}}makeInteractiveCanUseTool(){return async(e,t,s,o,a,r)=>{this.activeToolResolver&&this.activeToolResolver.reject(new Error("Turno interrumpido por nueva solicitud de herramienta.")),this.activeToolResolver=new Deferred,this.sendToChannel({type:"tool_call",tool_use_id:a,tool_name:e.name,arguments:t,description:e.description}),d.broadcastPermission({id:a,toolName:e.name,arguments:t,description:e.description});try{return await this.activeToolResolver.promise}finally{this.activeToolResolver=null}}}async handleSubmitPrompt(e){const t=e.text;t?await this.handleSubmitPromptDirect(t,e.uuid):this.sendError('El campo "text" es requerido para enviar un prompt.')}async handleSubmitPromptDirect(e,t){if(this.engine||await this.handleStartSession({cwd:this.currentCwd}),this.engine){this.abortController&&!this.abortController.signal.aborted||(this.abortController=c());try{this.sendToChannel({type:"status_change",status:"thinking"});const s=this.engine.submitMessage(e,{uuid:t});for await(const e of s)this.sendToChannel(e),this.broadcastHeadlessMessageToWebapp(e)}catch(e){this.sendToChannel({type:"session_ended",is_error:!0,error:e.message}),d.broadcastStatus(!1),d.broadcastThinking("",!1)}}else this.sendError("No se pudo inicializar la sesión del motor headless.")}handleApproveTool(e){this.activeToolResolver?(this.activeToolResolver.resolve({behavior:"allow"}),this.sendToChannel({type:"tool_approved",tool_use_id:e.tool_use_id}),d.broadcastPermissionResolved(e.tool_use_id,"approved","webapp")):this.sendError("No hay ninguna confirmación de herramienta pendiente.")}handleRejectTool(e){this.activeToolResolver?(this.activeToolResolver.resolve({behavior:"deny"}),this.sendToChannel({type:"tool_rejected",tool_use_id:e.tool_use_id}),d.broadcastPermissionResolved(e.tool_use_id,"rejected","webapp")):this.sendError("No hay ninguna confirmación de herramienta pendiente.")}handleAbort(){this.abortController?(this.abortController.abort(),this.sendToChannel({type:"aborted",message:"Inferencia cancelada por el cliente."}),d.broadcastStatus(!1),d.broadcastThinking("",!1)):this.sendError("No hay ninguna tarea activa para cancelar.")}broadcastHeadlessMessageToWebapp(e){"assistant"===e.type&&e.message&&"string"==typeof e.message.content&&d.broadcastMessage("assistant",e.message.content),"user"===e.type&&e.message&&"string"==typeof e.message.content&&d.broadcastMessage("user",e.message.content),"status"===e.type&&("thinking"===e.status?(d.broadcastThinking("Pensando...",!0),d.broadcastStatus(!0)):"done"===e.status&&(d.broadcastStatus(!1),d.broadcastThinking("",!1))),"result"===e.type&&(d.broadcastStatus(!1),d.broadcastThinking("",!1),e.result&&d.broadcastMessage("assistant",e.result))}sendToChannel(e,t){const s=JSON.stringify(e);if(process.stdout.write(s+"\n"),t)t.readyState===WebSocket.OPEN&&t.send(s);else for(const e of this.activeWsClients)e.readyState===WebSocket.OPEN&&e.send(s)}sendError(e){this.sendToChannel({type:"channel_error",message:e})}}export async function runHeadlessChannelServer(e={}){const t=new HeadlessChannelServer;await t.start(e)}
@@ -0,0 +1 @@
1
+ import e from"node:assert";import{HeadlessChannelServer as o}from"./channelServer.js";console.log("🧪 Iniciando pruebas unitarias de HeadlessChannelServer..."),async function(){try{const t=new o;e.strictEqual(typeof t.start,"function","El método start debe ser una función"),e.strictEqual(typeof t.handleSubmitPromptDirect,"function","El método handleSubmitPromptDirect debe ser una función"),console.log("✅ Test 1 aprobado: HeadlessChannelServer instanciado correctamente.");const n=process.stdout.write,a=[];process.stdout.write=e=>(a.push(e.toString()),!0);try{await t.handleInputLine('{"type": "unknown_action"}'),e.ok(a.length>0,"Debe emitir al menos un evento en la salida estándar");const o=JSON.parse(a[0].trim());e.strictEqual(o.type,"channel_error","Debe emitir un channel_error ante acciones desconocidas"),console.log("✅ Test 2 aprobado: Control de excepciones del protocolo JSONLines validado con éxito.")}finally{process.stdout.write=n}console.log("🔒 Verificando flujo diferido de aprobación de herramientas..."),e.strictEqual(typeof t.handleApproveTool,"function","handleApproveTool debe estar expuesto"),e.strictEqual(typeof t.handleRejectTool,"function","handleRejectTool debe estar expuesto"),e.strictEqual(typeof t.handleAbort,"function","handleAbort debe estar expuesto"),console.log("✅ Test 3 aprobado: El ciclo de promesas de seguridad diferida está correctamente expuesto."),console.log("\n🎉 ¡Todas las pruebas unitarias de Headless pasaron con éxito impecable! 🎉"),process.exit(0)}catch(e){console.error("❌ Fallo en las pruebas unitarias de Headless:",e.message),process.exit(1)}}();
@@ -1 +1 @@
1
- import{MACRO as e}from"../../recovery/bunBundleShim.js";import{APIConnectionError as t,APIConnectionTimeoutError as o,APIError as r}from"@anthropic-ai/sdk/index.js";import{AFK_MODE_BETA_HEADER as s}from"../../constants/betas.js";import{getAnthropicApiKeyWithSource as n,getClaudeAIOAuthTokens as i,getOauthAccountInfo as a,isClaudeAISubscriber as u}from"../../utils/auth.js";import{createAssistantAPIErrorMessage as c,NO_RESPONSE_REQUESTED as l}from"../../utils/messages.js";import{getDefaultMainLoopModelSetting as d,isNonCustomOpusModel as g}from"../../utils/model/model.js";import{getModelStrings as m}from"../../utils/model/modelStrings.js";import{getAPIProvider as f}from"../../utils/model/providers.js";import{getIsNonInteractiveSession as _}from"../../bootstrap/state.js";import{API_PDF_MAX_PAGES as p,PDF_TARGET_RAW_SIZE as E}from"../../constants/apiLimits.js";import{isEnvTruthy as h}from"../../utils/envUtils.js";import{formatFileSize as A}from"../../utils/format.js";import{ImageResizeError as R}from"../../utils/imageResizer.js";import{ImageSizeError as y}from"../../utils/imageValidation.js";import{logEvent as v}from"../analytics/index.js";import{getRateLimitErrorMessage as P}from"../claudeAiLimits.js";import{shouldProcessRateLimits as O}from"../rateLimitMocking.js";import{extractConnectionErrorDetails as x,formatAPIError as T}from"./errorUtils.js";export const API_ERROR_MESSAGE_PREFIX="API Error";export function startsWithApiErrorPrefix(e){return e.startsWith("API Error")||e.startsWith("Please run /login · API Error")}export const PROMPT_TOO_LONG_ERROR_MESSAGE="Prompt is too long";export function isPromptTooLongMessage(e){if(!e.isApiErrorMessage)return!1;const t=e.message.content;return!!Array.isArray(t)&&t.some(e=>"text"===e.type&&e.text.startsWith("Prompt is too long"))}export function parsePromptTooLongTokenCounts(e){const t=e.match(/prompt is too long[^0-9]*(\d+)\s*tokens?\s*>\s*(\d+)/i);return{actualTokens:t?parseInt(t[1],10):void 0,limitTokens:t?parseInt(t[2],10):void 0}}export function getPromptTooLongTokenGap(e){if(!isPromptTooLongMessage(e)||!e.errorDetails)return;const{actualTokens:t,limitTokens:o}=parsePromptTooLongTokenCounts(e.errorDetails);if(void 0===t||void 0===o)return;const r=t-o;return r>0?r:void 0}export function isMediaSizeError(e){return e.includes("image exceeds")&&e.includes("maximum")||e.includes("image dimensions exceed")&&e.includes("many-image")||/maximum of \d+ PDF pages/.test(e)}export function isMediaSizeErrorMessage(e){return!0===e.isApiErrorMessage&&void 0!==e.errorDetails&&isMediaSizeError(e.errorDetails)}export const CREDIT_BALANCE_TOO_LOW_ERROR_MESSAGE="Credit balance is too low";export const INVALID_API_KEY_ERROR_MESSAGE="No has iniciado sesion · Ejecuta /login";export const INVALID_API_KEY_ERROR_MESSAGE_EXTERNAL="Invalid API key · Fix external API key";export const ORG_DISABLED_ERROR_MESSAGE_ENV_KEY_WITH_OAUTH="Your ANTHROPIC_API_KEY belongs to a disabled organization · Unset the environment variable to use your subscription instead";export const ORG_DISABLED_ERROR_MESSAGE_ENV_KEY="Your ANTHROPIC_API_KEY belongs to a disabled organization · Update or unset the environment variable";export const TOKEN_REVOKED_ERROR_MESSAGE="OAuth token revoked · Please run /login";export const CCR_AUTH_ERROR_MESSAGE="Authentication error · This may be a temporary network issue, please try again";export const REPEATED_529_ERROR_MESSAGE="Repeated 529 Overloaded errors";export const CUSTOM_OFF_SWITCH_MESSAGE="Opus is experiencing high load, please use /model to switch to Sonnet";export const API_TIMEOUT_ERROR_MESSAGE="Request timed out";export function getPdfTooLargeErrorMessage(){const e=`max ${p} pages, ${A(E)}`;return _()?`PDF too large (${e}). Try reading the file a different way (e.g., extract text with pdftotext).`:`PDF too large (${e}). Double press esc to go back and try again, or use pdftotext to convert to text first.`}export function getPdfPasswordProtectedErrorMessage(){return _()?"PDF is password protected. Try using a CLI tool to extract or convert the PDF.":"PDF is password protected. Please double press esc to edit your message and try again."}export function getPdfInvalidErrorMessage(){return _()?"The PDF file was not valid. Try converting it to text first (e.g., pdftotext).":"The PDF file was not valid. Double press esc to go back and try again with a different file."}export function getImageTooLargeErrorMessage(){return _()?"Image was too large. Try resizing the image or using a different approach.":"Image was too large. Double press esc to go back and try again with a smaller image."}export function getRequestTooLargeErrorMessage(){const e=`max ${A(E)}`;return _()?`Request too large (${e}). Try with a smaller file.`:`Request too large (${e}). Double press esc to go back and try with a smaller file.`}export const OAUTH_ORG_NOT_ALLOWED_ERROR_MESSAGE="Your account does not have access to Context Code. Please run /login.";export function getTokenRevokedErrorMessage(){return _()?"Your account does not have access to Claude. Please login again or contact your administrator.":TOKEN_REVOKED_ERROR_MESSAGE}export function getOauthOrgNotAllowedErrorMessage(){return _()?"Your organization does not have access to Claude. Please login again or contact your administrator.":OAUTH_ORG_NOT_ALLOWED_ERROR_MESSAGE}function isCCRMode(){return h(process.env.CONTEXT_CODE_REMOTE)||h(process.env.CLAUDE_CODE_REMOTE)}export function isValidAPIMessage(e){return"object"==typeof e&&null!==e&&"content"in e&&"model"in e&&"usage"in e&&Array.isArray(e.content)&&"string"==typeof e.model&&"object"==typeof e.usage}export function extractUnknownErrorFormat(e){if(e&&"object"==typeof e)return e.Output?.__type?e.Output.__type:void 0}export function getAssistantMessageFromError(m,p,E){if(m instanceof o||m instanceof t&&m.message.toLowerCase().includes("timeout"))return c({content:"Request timed out",error:"unknown"});if(m instanceof y||m instanceof R)return c({content:getImageTooLargeErrorMessage()});if(m instanceof Error&&m.message.includes(CUSTOM_OFF_SWITCH_MESSAGE))return c({content:CUSTOM_OFF_SWITCH_MESSAGE,error:"rate_limit"});if(m instanceof r&&429===m.status&&O(u())){const e=m.headers?.get?.("anthropic-ratelimit-unified-representative-claim"),t=m.headers?.get?.("anthropic-ratelimit-unified-overage-status");if(e||t){const o={status:"rejected",unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},r=m.headers?.get?.("anthropic-ratelimit-unified-reset");r&&(o.resetsAt=Number(r)),e&&(o.rateLimitType=e),t&&(o.overageStatus=t);const s=m.headers?.get?.("anthropic-ratelimit-unified-overage-reset");s&&(o.overageResetsAt=Number(s));const n=m.headers?.get?.("anthropic-ratelimit-unified-overage-disabled-reason");n&&(o.overageDisabledReason=n);const i=P(o,p);return c(i?{content:i,error:"rate_limit"}:{content:l,error:"rate_limit"})}if(m.message.includes("Extra usage is required for long context")){const e=_()?"enable extra usage at claude.ai/settings/usage, or use --model to switch to standard context":"run /extra-usage to enable, or /model to switch to standard context";return c({content:`API Error: Extra usage is required for 1M context · ${e}`,error:"rate_limit"})}const o=m.message.replace(/^429\s+/,""),r=o.match(/"message"\s*:\s*"([^"]*)"/)?.[1];return c({content:`API Error: Request rejected (429) · ${r||o||"this may be a temporary capacity issue — check status.anthropic.com"}`,error:"rate_limit"})}if(m instanceof Error&&m.message.toLowerCase().includes("prompt is too long"))return c({content:"Prompt is too long",error:"invalid_request",errorDetails:m.message});if(m instanceof Error&&/maximum of \d+ PDF pages/.test(m.message))return c({content:getPdfTooLargeErrorMessage(),error:"invalid_request",errorDetails:m.message});if(m instanceof Error&&m.message.includes("The PDF specified is password protected"))return c({content:getPdfPasswordProtectedErrorMessage(),error:"invalid_request"});if(m instanceof Error&&m.message.includes("The PDF specified was not valid"))return c({content:getPdfInvalidErrorMessage(),error:"invalid_request"});if(m instanceof r&&400===m.status&&m.message.includes("image exceeds")&&m.message.includes("maximum"))return c({content:getImageTooLargeErrorMessage(),errorDetails:m.message});if(m instanceof r&&400===m.status&&m.message.includes("image dimensions exceed")&&m.message.includes("many-image"))return c({content:_()?"An image in the conversation exceeds the dimension limit for many-image requests (2000px). Start a new session with fewer images.":"An image in the conversation exceeds the dimension limit for many-image requests (2000px). Run /compact to remove old images from context, or start a new session.",error:"invalid_request",errorDetails:m.message});if(s&&m instanceof r&&400===m.status&&m.message.includes(s)&&m.message.includes("anthropic-beta"))return c({content:"Auto mode is unavailable for your plan",error:"invalid_request"});if(m instanceof r&&413===m.status)return c({content:getRequestTooLargeErrorMessage(),error:"invalid_request"});if(m instanceof r&&400===m.status&&m.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after")){if(E?.messages&&E?.messagesForAPI){const e=m.message.match(/toolu_[a-zA-Z0-9]+/),t=e?e[0]:null;t&&function(e,t,o){try{let r=-1;for(let t=0;t<o.length;t++){const s=o[t];if(!s)continue;const n=s.message.content;if(Array.isArray(n))for(const o of n)if("tool_use"===o.type&&"id"in o&&o.id===e){r=t;break}if(-1!==r)break}let s=-1;for(let o=0;o<t.length;o++){const r=t[o];if(r){if("assistant"===r.type&&"message"in r){const t=r.message.content;if(Array.isArray(t))for(const r of t)if("tool_use"===r.type&&"id"in r&&r.id===e){s=o;break}}if(-1!==s)break}}const n=[];for(let e=r+1;e<o.length;e++){const t=o[e];if(!t)continue;const r=t.message.content;if(Array.isArray(r))for(const e of r){const o=t.message.role;"tool_use"===e.type&&"id"in e?n.push(`${o}:tool_use:${e.id}`):"tool_result"===e.type&&"tool_use_id"in e?n.push(`${o}:tool_result:${e.tool_use_id}`):"text"===e.type?n.push(`${o}:text`):"thinking"===e.type?n.push(`${o}:thinking`):"image"===e.type?n.push(`${o}:image`):n.push(`${o}:${e.type}`)}else"string"==typeof r&&n.push(`${t.message.role}:string_content`)}const i=[];for(let e=s+1;e<t.length;e++){const o=t[e];if(o)switch(o.type){case"user":case"assistant":if("message"in o){const e=o.message.content;if(Array.isArray(e))for(const t of e){const e=o.message.role;"tool_use"===t.type&&"id"in t?i.push(`${e}:tool_use:${t.id}`):"tool_result"===t.type&&"tool_use_id"in t?i.push(`${e}:tool_result:${t.tool_use_id}`):"text"===t.type?i.push(`${e}:text`):"thinking"===t.type?i.push(`${e}:thinking`):"image"===t.type?i.push(`${e}:image`):i.push(`${e}:${t.type}`)}else"string"==typeof e&&i.push(`${o.message.role}:string_content`)}break;case"attachment":"attachment"in o&&i.push(`attachment:${o.attachment.type}`);break;case"system":"subtype"in o&&i.push(`system:${o.subtype}`);break;case"progress":"progress"in o&&o.progress&&"object"==typeof o.progress&&"type"in o.progress?i.push(`progress:${o.progress.type??"unknown"}`):i.push("progress:unknown")}}v("tengu_tool_use_tool_result_mismatch_error",{toolUseId:e,normalizedSequence:n.join(", "),preNormalizedSequence:i.join(", "),normalizedMessageCount:o.length,originalMessageCount:t.length,normalizedToolUseIndex:r,originalToolUseIndex:s})}catch(e){}}(t,E.messages,E.messagesForAPI)}if("ant"===process.env.USER_TYPE){const t=`API Error: 400 ${m.message}\n\nRun /share and post the JSON file to ${e.FEEDBACK_CHANNEL}.`,o=_()?"":" Then, use /rewind to recover the conversation.";return c({content:t+o,error:"invalid_request"})}{const e="API Error: 400 due to tool use concurrency issues.",t=_()?"":" Run /rewind to recover the conversation.";return c({content:e+t,error:"invalid_request"})}}if(m instanceof r&&400===m.status&&m.message.includes("unexpected `tool_use_id` found in `tool_result`")&&v("tengu_unexpected_tool_result",{}),m instanceof r&&400===m.status&&m.message.includes("`tool_use` ids must be unique")){v("tengu_duplicate_tool_use_id",{});const e=_()?"":" Run /rewind to recover the conversation.";return c({content:`API Error: 400 duplicate tool_use ID in conversation history.${e}`,error:"invalid_request",errorDetails:m.message})}if(u()&&m instanceof r&&400===m.status&&m.message.toLowerCase().includes("invalid model name")&&(g(p)||"opus"===p))return c({content:"Claude Opus is not available with the Claude Pro plan. If you have updated your subscription plan recently, run /logout and /login for the plan to take effect.",error:"invalid_request"});if("ant"===process.env.USER_TYPE&&!process.env.ANTHROPIC_MODEL&&m instanceof Error&&m.message.toLowerCase().includes("invalid model name")){const t=a()?.organizationUuid,o=`[ANT-ONLY] Your org isn't gated into the \`${p}\` model. Either run \`claude\` with \`ANTHROPIC_MODEL=${d()}\``,r=t?`${o} or share your orgId (${t}) in ${e.FEEDBACK_CHANNEL} for help getting access.`:`${o} or reach out in ${e.FEEDBACK_CHANNEL} for help getting access.`;return c({content:r,error:"invalid_request"})}if(m instanceof Error&&m.message.includes("Your credit balance is too low"))return c({content:"Credit balance is too low",error:"billing_error"});if(m instanceof r&&400===m.status&&m.message.toLowerCase().includes("organization has been disabled")){const{source:e}=n();if("ANTHROPIC_API_KEY"===e&&process.env.ANTHROPIC_API_KEY&&!u()){const e=null!=i()?.accessToken;return c({error:"invalid_request",content:e?ORG_DISABLED_ERROR_MESSAGE_ENV_KEY_WITH_OAUTH:ORG_DISABLED_ERROR_MESSAGE_ENV_KEY})}}if(m instanceof Error&&m.message.toLowerCase().includes("x-api-key")){if(isCCRMode())return c({error:"authentication_failed",content:CCR_AUTH_ERROR_MESSAGE});const{source:e}=n();return c({error:"authentication_failed",content:"ANTHROPIC_API_KEY"===e||"apiKeyHelper"===e?INVALID_API_KEY_ERROR_MESSAGE_EXTERNAL:INVALID_API_KEY_ERROR_MESSAGE})}if(m instanceof r&&403===m.status&&m.message.includes("OAuth token has been revoked"))return c({error:"authentication_failed",content:getTokenRevokedErrorMessage()});if(m instanceof r&&(401===m.status||403===m.status)&&m.message.includes("OAuth authentication is currently not allowed for this organization"))return c({error:"authentication_failed",content:getOauthOrgNotAllowedErrorMessage()});if(m instanceof r&&(401===m.status||403===m.status))return isCCRMode()?c({error:"authentication_failed",content:CCR_AUTH_ERROR_MESSAGE}):c({error:"authentication_failed",content:_()?`Failed to authenticate. API Error: ${m.message}`:`Please run /login · API Error: ${m.message}`});if((h(process.env.CONTEXT_CODE_USE_BEDROCK)||h(process.env.CLAUDE_CODE_USE_BEDROCK))&&m instanceof Error&&m.message.toLowerCase().includes("model id")){const e=_()?"--model":"/model",t=get3PModelFallbackSuggestion(p);return c({content:t?`API Error (${p}): ${m.message}. Try ${e} to switch to ${t}.`:`API Error (${p}): ${m.message}. Run ${e} to pick a different model.`,error:"invalid_request"})}if(m instanceof r&&404===m.status){const e=_()?"--model":"/model",t=get3PModelFallbackSuggestion(p);return c({content:t?`The model ${p} is not available on your ${f()} deployment. Try ${e} to switch to ${t}, or ask your admin to enable this model.`:`There's an issue with the selected model (${p}). It may not exist or you may not have access to it. Run ${e} to pick a different model.`,error:"invalid_request"})}return m instanceof t?c({content:`API Error: ${T(m)}`,error:"unknown"}):m instanceof Error?c({content:`API Error: ${m.message}`,error:"unknown"}):c({content:"API Error",error:"unknown"})}function get3PModelFallbackSuggestion(e){if("firstParty"===f())return;if("string"!=typeof e||0===e.trim().length)return;const t=e.toLowerCase();return t.includes("opus-4-7")||t.includes("opus_4_7")?m().opus46:t.includes("opus-4-6")||t.includes("opus_4_6")?m().opus41:t.includes("sonnet-4-6")||t.includes("sonnet_4_6")?m().sonnet45:t.includes("sonnet-4-5")||t.includes("sonnet_4_5")?m().sonnet40:void 0}export function classifyAPIError(e){if(e instanceof Error&&"Request was aborted."===e.message)return"aborted";if(e instanceof o||e instanceof t&&e.message.toLowerCase().includes("timeout"))return"api_timeout";if(e instanceof Error&&e.message.includes(REPEATED_529_ERROR_MESSAGE))return"repeated_529";if(e instanceof Error&&e.message.includes(CUSTOM_OFF_SWITCH_MESSAGE))return"capacity_off_switch";if(e instanceof r&&429===e.status)return"rate_limit";if(e instanceof r&&(529===e.status||e.message?.includes('"type":"overloaded_error"')))return"server_overload";if(e instanceof Error&&e.message.toLowerCase().includes("Prompt is too long".toLowerCase()))return"prompt_too_long";if(e instanceof Error&&/maximum of \d+ PDF pages/.test(e.message))return"pdf_too_large";if(e instanceof Error&&e.message.includes("The PDF specified is password protected"))return"pdf_password_protected";if(e instanceof r&&400===e.status&&e.message.includes("image exceeds")&&e.message.includes("maximum"))return"image_too_large";if(e instanceof r&&400===e.status&&e.message.includes("image dimensions exceed")&&e.message.includes("many-image"))return"image_too_large";if(e instanceof r&&400===e.status&&e.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after"))return"tool_use_mismatch";if(e instanceof r&&400===e.status&&e.message.includes("unexpected `tool_use_id` found in `tool_result`"))return"unexpected_tool_result";if(e instanceof r&&400===e.status&&e.message.includes("`tool_use` ids must be unique"))return"duplicate_tool_use_id";if(e instanceof r&&400===e.status&&e.message.toLowerCase().includes("invalid model name"))return"invalid_model";if(e instanceof Error&&e.message.toLowerCase().includes("Credit balance is too low".toLowerCase()))return"credit_balance_low";if(e instanceof Error&&e.message.toLowerCase().includes("x-api-key"))return"invalid_api_key";if(e instanceof r&&403===e.status&&e.message.includes("OAuth token has been revoked"))return"token_revoked";if(e instanceof r&&(401===e.status||403===e.status)&&e.message.includes("OAuth authentication is currently not allowed for this organization"))return"oauth_org_not_allowed";if(e instanceof r&&(401===e.status||403===e.status))return"auth_error";if((h(process.env.CONTEXT_CODE_USE_BEDROCK)||h(process.env.CLAUDE_CODE_USE_BEDROCK))&&e instanceof Error&&e.message.toLowerCase().includes("model id"))return"bedrock_model_access";if(e instanceof r){const t=e.status;if(t>=500)return"server_error";if(t>=400)return"client_error"}if(e instanceof t){const t=x(e);return t?.isSSLError?"ssl_cert_error":"connection_error"}return"unknown"}export function categorizeRetryableAPIError(e){return 529===e.status||e.message?.includes('"type":"overloaded_error"')||429===e.status?"rate_limit":401===e.status||403===e.status?"authentication_failed":void 0!==e.status&&e.status>=408?"server_error":"unknown"}export function getErrorMessageIfRefusal(e,t){if("refusal"!==e)return;v("tengu_refusal_api_response",{});const o=_()?"API Error: Context Code is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Try rephrasing the request or attempting a different approach.":"API Error: Context Code is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Please double press esc to edit your last message or start a new session for Context Code to assist with a different task.";return c({content:o+("claude-sonnet-4-20250514"!==t?" If you are seeing this refusal repeatedly, try running /model claude-sonnet-4-20250514 to switch models.":""),error:"invalid_request"})}
1
+ import{MACRO as e}from"../../recovery/bunBundleShim.js";import{APIConnectionError as t,APIConnectionTimeoutError as o,APIError as r}from"@anthropic-ai/sdk/index.js";import{AFK_MODE_BETA_HEADER as s}from"../../constants/betas.js";import{getAnthropicApiKeyWithSource as n,getClaudeAIOAuthTokens as i,getOauthAccountInfo as a,isClaudeAISubscriber as u}from"../../utils/auth.js";import{createAssistantAPIErrorMessage as c,NO_RESPONSE_REQUESTED as l}from"../../utils/messages.js";import{getDefaultMainLoopModelSetting as d,isNonCustomOpusModel as g}from"../../utils/model/model.js";import{getModelStrings as m}from"../../utils/model/modelStrings.js";import{getAPIProvider as f}from"../../utils/model/providers.js";import{getIsNonInteractiveSession as _}from"../../bootstrap/state.js";import{API_PDF_MAX_PAGES as p,PDF_TARGET_RAW_SIZE as E}from"../../constants/apiLimits.js";import{isEnvTruthy as h}from"../../utils/envUtils.js";import{formatFileSize as A}from"../../utils/format.js";import{ImageResizeError as R}from"../../utils/imageResizer.js";import{ImageSizeError as y}from"../../utils/imageValidation.js";import{logEvent as v}from"../analytics/index.js";import{getRateLimitErrorMessage as P}from"../claudeAiLimits.js";import{shouldProcessRateLimits as O}from"../rateLimitMocking.js";import{extractConnectionErrorDetails as x,formatAPIError as T}from"./errorUtils.js";export const API_ERROR_MESSAGE_PREFIX="API Error";export function startsWithApiErrorPrefix(e){return e.startsWith("API Error")||e.startsWith("Please run /login · API Error")}export const PROMPT_TOO_LONG_ERROR_MESSAGE="Prompt is too long";export function isPromptTooLongMessage(e){if(!e.isApiErrorMessage)return!1;const t=e.message.content;return!!Array.isArray(t)&&t.some(e=>"text"===e.type&&e.text.startsWith("Prompt is too long"))}export function parsePromptTooLongTokenCounts(e){const t=e.match(/prompt is too long[^0-9]*(\d+)\s*tokens?\s*>\s*(\d+)/i);return{actualTokens:t?parseInt(t[1],10):void 0,limitTokens:t?parseInt(t[2],10):void 0}}export function getPromptTooLongTokenGap(e){if(!isPromptTooLongMessage(e)||!e.errorDetails)return;const{actualTokens:t,limitTokens:o}=parsePromptTooLongTokenCounts(e.errorDetails);if(void 0===t||void 0===o)return;const r=t-o;return r>0?r:void 0}export function isMediaSizeError(e){return e.includes("image exceeds")&&e.includes("maximum")||e.includes("image dimensions exceed")&&e.includes("many-image")||/maximum of \d+ PDF pages/.test(e)}export function isMediaSizeErrorMessage(e){return!0===e.isApiErrorMessage&&void 0!==e.errorDetails&&isMediaSizeError(e.errorDetails)}export const CREDIT_BALANCE_TOO_LOW_ERROR_MESSAGE="Credit balance is too low";export const INVALID_API_KEY_ERROR_MESSAGE="No has iniciado sesion · Ejecuta /login";export const INVALID_API_KEY_ERROR_MESSAGE_EXTERNAL="Invalid API key · Fix external API key";export const ORG_DISABLED_ERROR_MESSAGE_ENV_KEY_WITH_OAUTH="Your ANTHROPIC_API_KEY belongs to a disabled organization · Unset the environment variable to use your subscription instead";export const ORG_DISABLED_ERROR_MESSAGE_ENV_KEY="Your ANTHROPIC_API_KEY belongs to a disabled organization · Update or unset the environment variable";export const TOKEN_REVOKED_ERROR_MESSAGE="OAuth token revoked · Please run /login";export const CCR_AUTH_ERROR_MESSAGE="Authentication error · This may be a temporary network issue, please try again";export const REPEATED_529_ERROR_MESSAGE="Repeated 529 Overloaded errors";export const CUSTOM_OFF_SWITCH_MESSAGE="Opus is experiencing high load, please use /model to switch to Sonnet";export const API_TIMEOUT_ERROR_MESSAGE="Request timed out";export function getPdfTooLargeErrorMessage(){const e=`max ${p} pages, ${A(E)}`;return _()?`PDF too large (${e}). Try reading the file a different way (e.g., extract text with pdftotext).`:`PDF too large (${e}). Double press esc to go back and try again, or use pdftotext to convert to text first.`}export function getPdfPasswordProtectedErrorMessage(){return _()?"PDF is password protected. Try using a CLI tool to extract or convert the PDF.":"PDF is password protected. Please double press esc to edit your message and try again."}export function getPdfInvalidErrorMessage(){return _()?"The PDF file was not valid. Try converting it to text first (e.g., pdftotext).":"The PDF file was not valid. Double press esc to go back and try again with a different file."}export function getImageTooLargeErrorMessage(){return _()?"Image was too large. Try resizing the image or using a different approach.":"Image was too large. Double press esc to go back and try again with a smaller image."}export function getRequestTooLargeErrorMessage(){const e=`max ${A(E)}`;return _()?`Request too large (${e}). Try with a smaller file.`:`Request too large (${e}). Double press esc to go back and try with a smaller file.`}export const OAUTH_ORG_NOT_ALLOWED_ERROR_MESSAGE="Your account does not have access to Context Code. Please run /login.";export function getTokenRevokedErrorMessage(){return _()?"Your account does not have access to Claude. Please login again or contact your administrator.":TOKEN_REVOKED_ERROR_MESSAGE}export function getOauthOrgNotAllowedErrorMessage(){return _()?"Your organization does not have access to Claude. Please login again or contact your administrator.":OAUTH_ORG_NOT_ALLOWED_ERROR_MESSAGE}function isCCRMode(){return h(process.env.CONTEXT_CODE_REMOTE)||h(process.env.CLAUDE_CODE_REMOTE)}export function isValidAPIMessage(e){return"object"==typeof e&&null!==e&&"content"in e&&"model"in e&&"usage"in e&&Array.isArray(e.content)&&"string"==typeof e.model&&"object"==typeof e.usage}export function extractUnknownErrorFormat(e){if(e&&"object"==typeof e)return e.Output?.__type?e.Output.__type:void 0}export function getAssistantMessageFromError(m,p,E){if(m instanceof o||m instanceof t&&m.message.toLowerCase().includes("timeout"))return c({content:"Request timed out",error:"unknown"});if(m instanceof y||m instanceof R)return c({content:getImageTooLargeErrorMessage()});if(m instanceof Error&&m.message.includes(CUSTOM_OFF_SWITCH_MESSAGE))return c({content:CUSTOM_OFF_SWITCH_MESSAGE,error:"rate_limit"});if(m instanceof r&&429===m.status&&O(u())){const e=m.headers?.get?.("anthropic-ratelimit-unified-representative-claim"),t=m.headers?.get?.("anthropic-ratelimit-unified-overage-status");if(e||t){const o={status:"rejected",unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},r=m.headers?.get?.("anthropic-ratelimit-unified-reset");r&&(o.resetsAt=Number(r)),e&&(o.rateLimitType=e),t&&(o.overageStatus=t);const s=m.headers?.get?.("anthropic-ratelimit-unified-overage-reset");s&&(o.overageResetsAt=Number(s));const n=m.headers?.get?.("anthropic-ratelimit-unified-overage-disabled-reason");n&&(o.overageDisabledReason=n);const i=P(o,p);return c(i?{content:i,error:"rate_limit"}:{content:l,error:"rate_limit"})}if(m.message.includes("Extra usage is required for long context")){const e=_()?"enable extra usage at claude.ai/settings/usage, or use --model to switch to standard context":"run /extra-usage to enable, or /model to switch to standard context";return c({content:`API Error: Extra usage is required for 1M context · ${e}`,error:"rate_limit"})}const o=m.message.replace(/^429\s+/,""),r=o.match(/"message"\s*:\s*"([^"]*)"/)?.[1];return c({content:`API Error: Request rejected (429) · ${r||o||"this may be a temporary capacity issue — check status.anthropic.com"}`,error:"rate_limit"})}if(m instanceof Error&&m.message.toLowerCase().includes("prompt is too long"))return c({content:"Prompt is too long",error:"invalid_request",errorDetails:m.message});if(m instanceof Error&&/maximum of \d+ PDF pages/.test(m.message))return c({content:getPdfTooLargeErrorMessage(),error:"invalid_request",errorDetails:m.message});if(m instanceof Error&&m.message.includes("The PDF specified is password protected"))return c({content:getPdfPasswordProtectedErrorMessage(),error:"invalid_request"});if(m instanceof Error&&m.message.includes("The PDF specified was not valid"))return c({content:getPdfInvalidErrorMessage(),error:"invalid_request"});if(m instanceof r&&400===m.status&&m.message.includes("image exceeds")&&m.message.includes("maximum"))return c({content:getImageTooLargeErrorMessage(),errorDetails:m.message});if(m instanceof r&&400===m.status&&m.message.includes("image dimensions exceed")&&m.message.includes("many-image"))return c({content:_()?"An image in the conversation exceeds the dimension limit for many-image requests (2000px). Start a new session with fewer images.":"An image in the conversation exceeds the dimension limit for many-image requests (2000px). Run /compact to remove old images from context, or start a new session.",error:"invalid_request",errorDetails:m.message});if(s&&m instanceof r&&400===m.status&&m.message.includes(s)&&m.message.includes("anthropic-beta"))return c({content:"Auto mode is unavailable for your plan",error:"invalid_request"});if(m instanceof r&&413===m.status)return c({content:getRequestTooLargeErrorMessage(),error:"invalid_request"});if(m instanceof r&&400===m.status&&m.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after")){if(E?.messages&&E?.messagesForAPI){const e=m.message.match(/toolu_[a-zA-Z0-9]+/),t=e?e[0]:null;t&&function(e,t,o){try{let r=-1;for(let t=0;t<o.length;t++){const s=o[t];if(!s)continue;const n=s.message.content;if(Array.isArray(n))for(const o of n)if("tool_use"===o.type&&"id"in o&&o.id===e){r=t;break}if(-1!==r)break}let s=-1;for(let o=0;o<t.length;o++){const r=t[o];if(r){if("assistant"===r.type&&"message"in r){const t=r.message.content;if(Array.isArray(t))for(const r of t)if("tool_use"===r.type&&"id"in r&&r.id===e){s=o;break}}if(-1!==s)break}}const n=[];for(let e=r+1;e<o.length;e++){const t=o[e];if(!t)continue;const r=t.message.content;if(Array.isArray(r))for(const e of r){const o=t.message.role;"tool_use"===e.type&&"id"in e?n.push(`${o}:tool_use:${e.id}`):"tool_result"===e.type&&"tool_use_id"in e?n.push(`${o}:tool_result:${e.tool_use_id}`):"text"===e.type?n.push(`${o}:text`):"thinking"===e.type?n.push(`${o}:thinking`):"image"===e.type?n.push(`${o}:image`):n.push(`${o}:${e.type}`)}else"string"==typeof r&&n.push(`${t.message.role}:string_content`)}const i=[];for(let e=s+1;e<t.length;e++){const o=t[e];if(o)switch(o.type){case"user":case"assistant":if("message"in o){const e=o.message.content;if(Array.isArray(e))for(const t of e){const e=o.message.role;"tool_use"===t.type&&"id"in t?i.push(`${e}:tool_use:${t.id}`):"tool_result"===t.type&&"tool_use_id"in t?i.push(`${e}:tool_result:${t.tool_use_id}`):"text"===t.type?i.push(`${e}:text`):"thinking"===t.type?i.push(`${e}:thinking`):"image"===t.type?i.push(`${e}:image`):i.push(`${e}:${t.type}`)}else"string"==typeof e&&i.push(`${o.message.role}:string_content`)}break;case"attachment":"attachment"in o&&i.push(`attachment:${o.attachment.type}`);break;case"system":"subtype"in o&&i.push(`system:${o.subtype}`);break;case"progress":"progress"in o&&o.progress&&"object"==typeof o.progress&&"type"in o.progress?i.push(`progress:${o.progress.type??"unknown"}`):i.push("progress:unknown")}}v("tengu_tool_use_tool_result_mismatch_error",{toolUseId:e,normalizedSequence:n.join(", "),preNormalizedSequence:i.join(", "),normalizedMessageCount:o.length,originalMessageCount:t.length,normalizedToolUseIndex:r,originalToolUseIndex:s})}catch(e){}}(t,E.messages,E.messagesForAPI)}if("ant"===process.env.USER_TYPE){const t=`API Error: 400 ${m.message}\n\nRun /share and post the JSON file to ${e.FEEDBACK_CHANNEL}.`,o=_()?"":" Then, use /rewind to recover the conversation.";return c({content:t+o,error:"invalid_request"})}{const e="API Error: 400 due to tool use concurrency issues.",t=_()?"":" Run /rewind to recover the conversation.";return c({content:e+t,error:"invalid_request"})}}if(m instanceof r&&400===m.status&&m.message.includes("unexpected `tool_use_id` found in `tool_result`")&&v("tengu_unexpected_tool_result",{}),m instanceof r&&400===m.status&&m.message.includes("`tool_use` ids must be unique")){v("tengu_duplicate_tool_use_id",{});const e=_()?"":" Run /rewind to recover the conversation.";return c({content:`API Error: 400 duplicate tool_use ID in conversation history.${e}`,error:"invalid_request",errorDetails:m.message})}if(u()&&m instanceof r&&400===m.status&&m.message.toLowerCase().includes("invalid model name")&&(g(p)||"opus"===p))return c({content:"Opus no está disponible con el plan Context Pro. Si actualizaste tu plan de suscripción recientemente, ejecuta /logout y /login para que el plan se active.",error:"invalid_request"});if("ant"===process.env.USER_TYPE&&!process.env.ANTHROPIC_MODEL&&m instanceof Error&&m.message.toLowerCase().includes("invalid model name")){const t=a()?.organizationUuid,o=`[ANT-ONLY] Your org isn't gated into the \`${p}\` model. Either run \`claude\` with \`ANTHROPIC_MODEL=${d()}\``,r=t?`${o} or share your orgId (${t}) in ${e.FEEDBACK_CHANNEL} for help getting access.`:`${o} or reach out in ${e.FEEDBACK_CHANNEL} for help getting access.`;return c({content:r,error:"invalid_request"})}if(m instanceof Error&&m.message.includes("Your credit balance is too low"))return c({content:"Credit balance is too low",error:"billing_error"});if(m instanceof r&&400===m.status&&m.message.toLowerCase().includes("organization has been disabled")){const{source:e}=n();if("ANTHROPIC_API_KEY"===e&&process.env.ANTHROPIC_API_KEY&&!u()){const e=null!=i()?.accessToken;return c({error:"invalid_request",content:e?ORG_DISABLED_ERROR_MESSAGE_ENV_KEY_WITH_OAUTH:ORG_DISABLED_ERROR_MESSAGE_ENV_KEY})}}if(m instanceof Error&&m.message.toLowerCase().includes("x-api-key")){if(isCCRMode())return c({error:"authentication_failed",content:CCR_AUTH_ERROR_MESSAGE});const{source:e}=n();return c({error:"authentication_failed",content:"ANTHROPIC_API_KEY"===e||"apiKeyHelper"===e?INVALID_API_KEY_ERROR_MESSAGE_EXTERNAL:INVALID_API_KEY_ERROR_MESSAGE})}if(m instanceof r&&403===m.status&&m.message.includes("OAuth token has been revoked"))return c({error:"authentication_failed",content:getTokenRevokedErrorMessage()});if(m instanceof r&&(401===m.status||403===m.status)&&m.message.includes("OAuth authentication is currently not allowed for this organization"))return c({error:"authentication_failed",content:getOauthOrgNotAllowedErrorMessage()});if(m instanceof r&&(401===m.status||403===m.status))return isCCRMode()?c({error:"authentication_failed",content:CCR_AUTH_ERROR_MESSAGE}):c({error:"authentication_failed",content:_()?`Failed to authenticate. API Error: ${m.message}`:`Please run /login · API Error: ${m.message}`});if((h(process.env.CONTEXT_CODE_USE_BEDROCK)||h(process.env.CLAUDE_CODE_USE_BEDROCK))&&m instanceof Error&&m.message.toLowerCase().includes("model id")){const e=_()?"--model":"/model",t=get3PModelFallbackSuggestion(p);return c({content:t?`API Error (${p}): ${m.message}. Try ${e} to switch to ${t}.`:`API Error (${p}): ${m.message}. Run ${e} to pick a different model.`,error:"invalid_request"})}if(m instanceof r&&404===m.status){const e=_()?"--model":"/model",t=get3PModelFallbackSuggestion(p);return c({content:t?`The model ${p} is not available on your ${f()} deployment. Try ${e} to switch to ${t}, or ask your admin to enable this model.`:`There's an issue with the selected model (${p}). It may not exist or you may not have access to it. Run ${e} to pick a different model.`,error:"invalid_request"})}return m instanceof t?c({content:`API Error: ${T(m)}`,error:"unknown"}):m instanceof Error?c({content:`API Error: ${m.message}`,error:"unknown"}):c({content:"API Error",error:"unknown"})}function get3PModelFallbackSuggestion(e){if("firstParty"===f())return;if("string"!=typeof e||0===e.trim().length)return;const t=e.toLowerCase();return t.includes("opus-4-7")||t.includes("opus_4_7")?m().opus46:t.includes("opus-4-6")||t.includes("opus_4_6")?m().opus41:t.includes("sonnet-4-6")||t.includes("sonnet_4_6")?m().sonnet45:t.includes("sonnet-4-5")||t.includes("sonnet_4_5")?m().sonnet40:void 0}export function classifyAPIError(e){if(e instanceof Error&&"Request was aborted."===e.message)return"aborted";if(e instanceof o||e instanceof t&&e.message.toLowerCase().includes("timeout"))return"api_timeout";if(e instanceof Error&&e.message.includes(REPEATED_529_ERROR_MESSAGE))return"repeated_529";if(e instanceof Error&&e.message.includes(CUSTOM_OFF_SWITCH_MESSAGE))return"capacity_off_switch";if(e instanceof r&&429===e.status)return"rate_limit";if(e instanceof r&&(529===e.status||e.message?.includes('"type":"overloaded_error"')))return"server_overload";if(e instanceof Error&&e.message.toLowerCase().includes("Prompt is too long".toLowerCase()))return"prompt_too_long";if(e instanceof Error&&/maximum of \d+ PDF pages/.test(e.message))return"pdf_too_large";if(e instanceof Error&&e.message.includes("The PDF specified is password protected"))return"pdf_password_protected";if(e instanceof r&&400===e.status&&e.message.includes("image exceeds")&&e.message.includes("maximum"))return"image_too_large";if(e instanceof r&&400===e.status&&e.message.includes("image dimensions exceed")&&e.message.includes("many-image"))return"image_too_large";if(e instanceof r&&400===e.status&&e.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after"))return"tool_use_mismatch";if(e instanceof r&&400===e.status&&e.message.includes("unexpected `tool_use_id` found in `tool_result`"))return"unexpected_tool_result";if(e instanceof r&&400===e.status&&e.message.includes("`tool_use` ids must be unique"))return"duplicate_tool_use_id";if(e instanceof r&&400===e.status&&e.message.toLowerCase().includes("invalid model name"))return"invalid_model";if(e instanceof Error&&e.message.toLowerCase().includes("Credit balance is too low".toLowerCase()))return"credit_balance_low";if(e instanceof Error&&e.message.toLowerCase().includes("x-api-key"))return"invalid_api_key";if(e instanceof r&&403===e.status&&e.message.includes("OAuth token has been revoked"))return"token_revoked";if(e instanceof r&&(401===e.status||403===e.status)&&e.message.includes("OAuth authentication is currently not allowed for this organization"))return"oauth_org_not_allowed";if(e instanceof r&&(401===e.status||403===e.status))return"auth_error";if((h(process.env.CONTEXT_CODE_USE_BEDROCK)||h(process.env.CLAUDE_CODE_USE_BEDROCK))&&e instanceof Error&&e.message.toLowerCase().includes("model id"))return"bedrock_model_access";if(e instanceof r){const t=e.status;if(t>=500)return"server_error";if(t>=400)return"client_error"}if(e instanceof t){const t=x(e);return t?.isSSLError?"ssl_cert_error":"connection_error"}return"unknown"}export function categorizeRetryableAPIError(e){return 529===e.status||e.message?.includes('"type":"overloaded_error"')||429===e.status?"rate_limit":401===e.status||403===e.status?"authentication_failed":void 0!==e.status&&e.status>=408?"server_error":"unknown"}export function getErrorMessageIfRefusal(e,t){if("refusal"!==e)return;v("tengu_refusal_api_response",{});const o=_()?"API Error: Context Code is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Try rephrasing the request or attempting a different approach.":"API Error: Context Code is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Please double press esc to edit your last message or start a new session for Context Code to assist with a different task.";return c({content:o+("claude-sonnet-4-20250514"!==t?" If you are seeing this refusal repeatedly, try running /model claude-sonnet-4-20250514 to switch models.":""),error:"invalid_request"})}
@@ -1 +1 @@
1
- import e from"axios";import{randomUUID as t}from"crypto";import*as r from"fs/promises";import*as o from"path";import{count as a}from"../../utils/array.js";import{getCwd as i}from"../../utils/cwd.js";import{logForDebugging as n}from"../../utils/debug.js";import{errorMessage as s}from"../../utils/errors.js";import{logError as l}from"../../utils/log.js";import{sleep as f}from"../../utils/sleep.js";import{logEvent as u}from"../analytics/index.js";const d="files-api-2025-04-14,oauth-2025-04-20",c="2023-06-01";function getDefaultApiBaseUrl(){return process.env.ANTHROPIC_BASE_URL||process.env.CONTEXT_CODE_API_BASE_URL||process.env.CLAUDE_CODE_API_BASE_URL||"https://api.anthropic.com"}function logDebugError(e){n(`[files-api] ${e}`,{level:"error"})}function logDebug(e){n(`[files-api] ${e}`)}const p=524288e3;async function retryWithBackoff(e,t){let r="";for(let o=1;o<=3;o++){const a=await t(o);if(a.done)return a.value;if(r=a.error||`${e} failed`,logDebug(`${e} attempt ${o}/3 failed: ${r}`),o<3){const t=500*Math.pow(2,o-1);logDebug(`Retrying ${e} in ${t}ms...`),await f(t)}}throw new Error(`${r} after 3 attempts`)}export async function downloadFile(t,r){const o=`${r.baseUrl||getDefaultApiBaseUrl()}/v1/files/${t}/content`,a={Authorization:`Bearer ${r.oauthToken}`,"anthropic-version":c,"anthropic-beta":d};return logDebug(`Downloading file ${t} from ${o}`),retryWithBackoff(`Download file ${t}`,async()=>{try{const r=await e.get(o,{headers:a,responseType:"arraybuffer",timeout:6e4,validateStatus:e=>e<500});if(200===r.status)return logDebug(`Downloaded file ${t} (${r.data.length} bytes)`),{done:!0,value:Buffer.from(r.data)};if(404===r.status)throw new Error(`File not found: ${t}`);if(401===r.status)throw new Error("Authentication failed: invalid or missing API key");if(403===r.status)throw new Error(`Access denied to file: ${t}`);return{done:!1,error:`status ${r.status}`}}catch(t){if(!e.isAxiosError(t))throw t;return{done:!1,error:t.message}}})}export function buildDownloadPath(e,t,r){const a=o.normalize(r);if(a.startsWith(".."))return logDebugError(`Invalid file path: ${r}. Path must not traverse above workspace`),null;const i=o.join(e,t,"uploads"),n=[o.join(e,t,"uploads")+o.sep,o.sep+"uploads"+o.sep].find(e=>a.startsWith(e)),s=n?a.slice(n.length):a;return o.join(i,s)}export async function downloadAndSaveFile(e,t){const{fileId:a,relativePath:n}=e,f=buildDownloadPath(i(),t.sessionId,n);if(!f)return{fileId:a,path:"",success:!1,error:`Invalid file path: ${n}`};try{const e=await downloadFile(a,t),i=o.dirname(f);return await r.mkdir(i,{recursive:!0}),await r.writeFile(f,e),logDebug(`Saved file ${a} to ${f} (${e.length} bytes)`),{fileId:a,path:f,success:!0,bytesWritten:e.length}}catch(e){return logDebugError(`Failed to download file ${a}: ${s(e)}`),e instanceof Error&&l(e),{fileId:a,path:f,success:!1,error:s(e)}}}async function parallelWithLimit(e,t,r){const o=new Array(e.length);let a=0;async function worker(){for(;a<e.length;){const r=a++,i=e[r];void 0!==i&&(o[r]=await t(i,r))}}const i=[],n=Math.min(r,e.length);for(let e=0;e<n;e++)i.push(worker());return await Promise.all(i),o}export async function downloadSessionFiles(e,t,r=5){if(0===e.length)return[];logDebug(`Downloading ${e.length} file(s) for session ${t.sessionId}`);const o=Date.now(),i=await parallelWithLimit(e,e=>downloadAndSaveFile(e,t),r),n=Date.now()-o;return logDebug(`Downloaded ${a(i,e=>e.success)}/${e.length} file(s) in ${n}ms`),i}export async function uploadFile(a,i,n,l){const f=`${n.baseUrl||getDefaultApiBaseUrl()}/v1/files`,h={Authorization:`Bearer ${n.oauthToken}`,"anthropic-version":c,"anthropic-beta":d};let g;logDebug(`Uploading file ${a} as ${i}`);try{g=await r.readFile(a)}catch(e){return u("tengu_file_upload_failed",{error_type:"file_read"}),{path:i,error:s(e),success:!1}}const m=g.length;if(m>p)return u("tengu_file_upload_failed",{error_type:"file_too_large"}),{path:i,error:`File exceeds maximum size of 524288000 bytes (actual: ${m})`,success:!1};const w=`----FormBoundary${t()}`,$=o.basename(i),_=[];_.push(Buffer.from(`--${w}\r\nContent-Disposition: form-data; name="file"; filename="${$}"\r\nContent-Type: application/octet-stream\r\n\r\n`)),_.push(g),_.push(Buffer.from("\r\n")),_.push(Buffer.from(`--${w}\r\nContent-Disposition: form-data; name="purpose"\r\n\r\nuser_data\r\n`)),_.push(Buffer.from(`--${w}--\r\n`));const b=Buffer.concat(_);try{return await retryWithBackoff(`Upload file ${i}`,async()=>{try{const t=await e.post(f,b,{headers:{...h,"Content-Type":`multipart/form-data; boundary=${w}`,"Content-Length":b.length.toString()},timeout:12e4,signal:l?.signal,validateStatus:e=>e<500});if(200===t.status||201===t.status){const e=t.data?.id;return e?(logDebug(`Uploaded file ${a} -> ${e} (${m} bytes)`),{done:!0,value:{path:i,fileId:e,size:m,success:!0}}):{done:!1,error:"Upload succeeded but no file ID returned"}}if(401===t.status)throw u("tengu_file_upload_failed",{error_type:"auth"}),new UploadNonRetriableError("Authentication failed: invalid or missing API key");if(403===t.status)throw u("tengu_file_upload_failed",{error_type:"forbidden"}),new UploadNonRetriableError("Access denied for upload");if(413===t.status)throw u("tengu_file_upload_failed",{error_type:"size"}),new UploadNonRetriableError("File too large for upload");return{done:!1,error:`status ${t.status}`}}catch(t){if(t instanceof UploadNonRetriableError)throw t;if(e.isCancel(t))throw new UploadNonRetriableError("Upload canceled");if(e.isAxiosError(t))return{done:!1,error:t.message};throw t}})}catch(e){return e instanceof UploadNonRetriableError?{path:i,error:e.message,success:!1}:(u("tengu_file_upload_failed",{error_type:"network"}),{path:i,error:s(e),success:!1})}}class UploadNonRetriableError extends Error{constructor(e){super(e),this.name="UploadNonRetriableError"}}export async function uploadSessionFiles(e,t,r=5){if(0===e.length)return[];logDebug(`Uploading ${e.length} file(s) for session ${t.sessionId}`);const o=Date.now(),i=await parallelWithLimit(e,e=>uploadFile(e.path,e.relativePath,t),r),n=Date.now()-o;return logDebug(`Uploaded ${a(i,e=>e.success)}/${e.length} file(s) in ${n}ms`),i}export async function listFilesCreatedAfter(t,r){const o=r.baseUrl||getDefaultApiBaseUrl(),a={Authorization:`Bearer ${r.oauthToken}`,"anthropic-version":c,"anthropic-beta":d};logDebug(`Listing files created after ${t}`);const i=[];let n;for(;;){const r={after_created_at:t};n&&(r.after_id=n);const s=await retryWithBackoff(`List files after ${t}`,async()=>{try{const t=await e.get(`${o}/v1/files`,{headers:a,params:r,timeout:6e4,validateStatus:e=>e<500});if(200===t.status)return{done:!0,value:t.data};if(401===t.status)throw u("tengu_file_list_failed",{error_type:"auth"}),new Error("Authentication failed: invalid or missing API key");if(403===t.status)throw u("tengu_file_list_failed",{error_type:"forbidden"}),new Error("Access denied to list files");return{done:!1,error:`status ${t.status}`}}catch(t){if(!e.isAxiosError(t))throw t;return u("tengu_file_list_failed",{error_type:"network"}),{done:!1,error:t.message}}}),l=s.data||[];for(const e of l)i.push({filename:e.filename,fileId:e.id,size:e.size_bytes});if(!s.has_more)break;const f=l.at(-1);if(!f?.id)break;n=f.id}return logDebug(`Listed ${i.length} files created after ${t}`),i}export function parseFileSpecs(e){const t=[],r=e.flatMap(e=>e.split(" ").filter(Boolean));for(const e of r){const r=e.indexOf(":");if(-1===r)continue;const o=e.substring(0,r),a=e.substring(r+1);o&&a?t.push({fileId:o,relativePath:a}):logDebugError(`Invalid file spec: ${e}. Both file_id and path are required`)}return t}
1
+ import e from"axios";import{randomUUID as t}from"crypto";import*as r from"fs/promises";import*as o from"path";import{count as a}from"../../utils/array.js";import{getCwd as i}from"../../utils/cwd.js";import{logForDebugging as n}from"../../utils/debug.js";import{errorMessage as s}from"../../utils/errors.js";import{logError as l}from"../../utils/log.js";import{sleep as f}from"../../utils/sleep.js";import{logEvent as u}from"../analytics/index.js";const d="files-api-2025-04-14,oauth-2025-04-20",c="2023-06-01";function getDefaultApiBaseUrl(){return process.env.ANTHROPIC_BASE_URL||process.env.CONTEXT_CODE_API_BASE_URL||process.env.CLAUDE_CODE_API_BASE_URL||"https://api.anthropic.com"}function logDebugError(e){n(`[files-api] ${e}`,{level:"error"})}function logDebug(e){n(`[files-api] ${e}`)}const p=524288e3;async function retryWithBackoff(e,t){let r="";for(let o=1;o<=3;o++){const a=await t(o);if(a.done)return a.value;if(r=a.error||`${e} failed`,logDebug(`${e} attempt ${o}/3 failed: ${r}`),o<3){const t=500*Math.pow(2,o-1);logDebug(`Retrying ${e} in ${t}ms...`),await f(t)}}throw new Error(`${r} after 3 attempts`)}export async function downloadFile(t,r){const o=`${r.baseUrl||getDefaultApiBaseUrl()}/v1/files/${t}/content`,a={Authorization:`Bearer ${r.oauthToken}`,"anthropic-version":c,"anthropic-beta":d};return logDebug(`Downloading file ${t} from ${o}`),retryWithBackoff(`Download file ${t}`,async()=>{try{const r=await e.get(o,{headers:a,responseType:"arraybuffer",timeout:6e4,validateStatus:e=>e<500});if(200===r.status)return logDebug(`Downloaded file ${t} (${r.data.length} bytes)`),{done:!0,value:Buffer.from(r.data)};if(404===r.status)throw new Error(`File not found: ${t}`);if(401===r.status)throw new Error("Autenticación fallida: API key inválida o faltante");if(403===r.status)throw new Error(`Access denied to file: ${t}`);return{done:!1,error:`status ${r.status}`}}catch(t){if(!e.isAxiosError(t))throw t;return{done:!1,error:t.message}}})}export function buildDownloadPath(e,t,r){const a=o.normalize(r);if(a.startsWith(".."))return logDebugError(`Invalid file path: ${r}. Path must not traverse above workspace`),null;const i=o.join(e,t,"uploads"),n=[o.join(e,t,"uploads")+o.sep,o.sep+"uploads"+o.sep].find(e=>a.startsWith(e)),s=n?a.slice(n.length):a;return o.join(i,s)}export async function downloadAndSaveFile(e,t){const{fileId:a,relativePath:n}=e,f=buildDownloadPath(i(),t.sessionId,n);if(!f)return{fileId:a,path:"",success:!1,error:`Invalid file path: ${n}`};try{const e=await downloadFile(a,t),i=o.dirname(f);return await r.mkdir(i,{recursive:!0}),await r.writeFile(f,e),logDebug(`Saved file ${a} to ${f} (${e.length} bytes)`),{fileId:a,path:f,success:!0,bytesWritten:e.length}}catch(e){return logDebugError(`Failed to download file ${a}: ${s(e)}`),e instanceof Error&&l(e),{fileId:a,path:f,success:!1,error:s(e)}}}async function parallelWithLimit(e,t,r){const o=new Array(e.length);let a=0;async function worker(){for(;a<e.length;){const r=a++,i=e[r];void 0!==i&&(o[r]=await t(i,r))}}const i=[],n=Math.min(r,e.length);for(let e=0;e<n;e++)i.push(worker());return await Promise.all(i),o}export async function downloadSessionFiles(e,t,r=5){if(0===e.length)return[];logDebug(`Downloading ${e.length} file(s) for session ${t.sessionId}`);const o=Date.now(),i=await parallelWithLimit(e,e=>downloadAndSaveFile(e,t),r),n=Date.now()-o;return logDebug(`Downloaded ${a(i,e=>e.success)}/${e.length} file(s) in ${n}ms`),i}export async function uploadFile(a,i,n,l){const f=`${n.baseUrl||getDefaultApiBaseUrl()}/v1/files`,h={Authorization:`Bearer ${n.oauthToken}`,"anthropic-version":c,"anthropic-beta":d};let g;logDebug(`Uploading file ${a} as ${i}`);try{g=await r.readFile(a)}catch(e){return u("tengu_file_upload_failed",{error_type:"file_read"}),{path:i,error:s(e),success:!1}}const m=g.length;if(m>p)return u("tengu_file_upload_failed",{error_type:"file_too_large"}),{path:i,error:`File exceeds maximum size of 524288000 bytes (actual: ${m})`,success:!1};const w=`----FormBoundary${t()}`,$=o.basename(i),_=[];_.push(Buffer.from(`--${w}\r\nContent-Disposition: form-data; name="file"; filename="${$}"\r\nContent-Type: application/octet-stream\r\n\r\n`)),_.push(g),_.push(Buffer.from("\r\n")),_.push(Buffer.from(`--${w}\r\nContent-Disposition: form-data; name="purpose"\r\n\r\nuser_data\r\n`)),_.push(Buffer.from(`--${w}--\r\n`));const b=Buffer.concat(_);try{return await retryWithBackoff(`Upload file ${i}`,async()=>{try{const t=await e.post(f,b,{headers:{...h,"Content-Type":`multipart/form-data; boundary=${w}`,"Content-Length":b.length.toString()},timeout:12e4,signal:l?.signal,validateStatus:e=>e<500});if(200===t.status||201===t.status){const e=t.data?.id;return e?(logDebug(`Uploaded file ${a} -> ${e} (${m} bytes)`),{done:!0,value:{path:i,fileId:e,size:m,success:!0}}):{done:!1,error:"Upload succeeded but no file ID returned"}}if(401===t.status)throw u("tengu_file_upload_failed",{error_type:"auth"}),new UploadNonRetriableError("Authentication failed: invalid or missing API key");if(403===t.status)throw u("tengu_file_upload_failed",{error_type:"forbidden"}),new UploadNonRetriableError("Access denied for upload");if(413===t.status)throw u("tengu_file_upload_failed",{error_type:"size"}),new UploadNonRetriableError("File too large for upload");return{done:!1,error:`status ${t.status}`}}catch(t){if(t instanceof UploadNonRetriableError)throw t;if(e.isCancel(t))throw new UploadNonRetriableError("Upload canceled");if(e.isAxiosError(t))return{done:!1,error:t.message};throw t}})}catch(e){return e instanceof UploadNonRetriableError?{path:i,error:e.message,success:!1}:(u("tengu_file_upload_failed",{error_type:"network"}),{path:i,error:s(e),success:!1})}}class UploadNonRetriableError extends Error{constructor(e){super(e),this.name="UploadNonRetriableError"}}export async function uploadSessionFiles(e,t,r=5){if(0===e.length)return[];logDebug(`Uploading ${e.length} file(s) for session ${t.sessionId}`);const o=Date.now(),i=await parallelWithLimit(e,e=>uploadFile(e.path,e.relativePath,t),r),n=Date.now()-o;return logDebug(`Uploaded ${a(i,e=>e.success)}/${e.length} file(s) in ${n}ms`),i}export async function listFilesCreatedAfter(t,r){const o=r.baseUrl||getDefaultApiBaseUrl(),a={Authorization:`Bearer ${r.oauthToken}`,"anthropic-version":c,"anthropic-beta":d};logDebug(`Listing files created after ${t}`);const i=[];let n;for(;;){const r={after_created_at:t};n&&(r.after_id=n);const s=await retryWithBackoff(`List files after ${t}`,async()=>{try{const t=await e.get(`${o}/v1/files`,{headers:a,params:r,timeout:6e4,validateStatus:e=>e<500});if(200===t.status)return{done:!0,value:t.data};if(401===t.status)throw u("tengu_file_list_failed",{error_type:"auth"}),new Error("Autenticación fallida: API key inválida o faltante");if(403===t.status)throw u("tengu_file_list_failed",{error_type:"forbidden"}),new Error("Acceso denegado para listar archivos");return{done:!1,error:`status ${t.status}`}}catch(t){if(!e.isAxiosError(t))throw t;return u("tengu_file_list_failed",{error_type:"network"}),{done:!1,error:t.message}}}),l=s.data||[];for(const e of l)i.push({filename:e.filename,fileId:e.id,size:e.size_bytes});if(!s.has_more)break;const f=l.at(-1);if(!f?.id)break;n=f.id}return logDebug(`Listed ${i.length} files created after ${t}`),i}export function parseFileSpecs(e){const t=[],r=e.flatMap(e=>e.split(" ").filter(Boolean));for(const e of r){const r=e.indexOf(":");if(-1===r)continue;const o=e.substring(0,r),a=e.substring(r+1);o&&a?t.push({fileId:o,relativePath:a}):logDebugError(`Invalid file spec: ${e}. Both file_id and path are required`)}return t}