@iaforged/context-code 2.3.3 → 2.3.6

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 (89) hide show
  1. package/context-bootstrap.js +7 -5
  2. package/dist/src/cli/handlers/auth.js +1 -1
  3. package/dist/src/cli/handlers/modelList.js +1 -1
  4. package/dist/src/commands/agent/agent.js +1 -1
  5. package/dist/src/commands/login/login.js +1 -1
  6. package/dist/src/commands/profile/profile.js +1 -1
  7. package/dist/src/commands/provider/index.js +1 -1
  8. package/dist/src/commands/provider/provider.js +1 -1
  9. package/dist/src/components/BaseTextInput.js +1 -1
  10. package/dist/src/components/LogoV2/AnimatedClawd.js +1 -1
  11. package/dist/src/components/LogoV2/Clawd.js +1 -1
  12. package/dist/src/components/LogoV2/LogoV2.js +1 -1
  13. package/dist/src/components/LogoV2/WelcomeV2.js +1 -1
  14. package/dist/src/components/PromptInput/PromptInputFooterLeftSide.js +1 -1
  15. package/dist/src/components/SessionTokenFooter.js +1 -1
  16. package/dist/src/components/Spinner.js +1 -1
  17. package/dist/src/components/Stats.js +1 -1
  18. package/dist/src/components/TeleportProgress.js +1 -1
  19. package/dist/src/components/TextInput.js +1 -1
  20. package/dist/src/components/design-system/ThemeProvider.js +1 -1
  21. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/AskUserQuestionPermissionRequest.js +1 -1
  22. package/dist/src/core/auth/loginCore.js +1 -1
  23. package/dist/src/core/providers/llmCore.js +1 -1
  24. package/dist/src/core/providers/providerModelCompatibility.js +1 -1
  25. package/dist/src/main.js +1 -1
  26. package/dist/src/query/stopHooks.js +1 -1
  27. package/dist/src/screens/REPL.js +1 -1
  28. package/dist/src/services/PromptSuggestion/promptSuggestion.js +1 -1
  29. package/dist/src/services/analytics/config.js +1 -1
  30. package/dist/src/services/analytics/datadog.js +1 -1
  31. package/dist/src/services/api/openai.js +1 -1
  32. package/dist/src/services/mcp/config.js +1 -1
  33. package/dist/src/services/orchestration/execution/AgentTaskExecutor.js +1 -1
  34. package/dist/src/services/tips/tipRegistry.js +1 -1
  35. package/dist/src/services/toolUseSummary/toolUseSummaryGenerator.js +1 -1
  36. package/dist/src/tools/BriefTool/UI.js +1 -1
  37. package/dist/src/utils/computerControlMcp/mcpServer.js +1 -1
  38. package/dist/src/utils/computerControlMcp/server/.gitattributes +18 -0
  39. package/dist/src/utils/computerControlMcp/server/Dockerfile +25 -0
  40. package/dist/src/utils/computerControlMcp/server/LICENSE +21 -0
  41. package/dist/src/utils/computerControlMcp/server/MANIFEST.in +10 -0
  42. package/dist/src/utils/computerControlMcp/server/README.md +193 -0
  43. package/dist/src/utils/computerControlMcp/server/demonstration.gif +0 -0
  44. package/dist/src/utils/computerControlMcp/server/icon.png +0 -0
  45. package/dist/src/utils/computerControlMcp/server/pyproject.toml +52 -0
  46. package/dist/src/utils/computerControlMcp/server/smithery.yaml +13 -0
  47. package/dist/src/utils/computerControlMcp/server/src/README.md +12 -0
  48. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/FZYTK.TTF +0 -0
  49. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/__init__.py +11 -0
  50. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/__main__.py +21 -0
  51. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/cli.py +128 -0
  52. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/core.py +1008 -0
  53. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/gui.py +126 -0
  54. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/server.py +15 -0
  55. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/test.py +346 -0
  56. package/dist/src/utils/computerControlMcp/server/src/computer_control_mcp/test_image.png +0 -0
  57. package/dist/src/utils/computerControlMcp/server/tests/README.md +22 -0
  58. package/dist/src/utils/computerControlMcp/server/tests/conftest.py +10 -0
  59. package/dist/src/utils/computerControlMcp/server/tests/rapidocr_test.py +21 -0
  60. package/dist/src/utils/computerControlMcp/server/tests/run_cli.py +9 -0
  61. package/dist/src/utils/computerControlMcp/server/tests/run_server.py +15 -0
  62. package/dist/src/utils/computerControlMcp/server/tests/setup.py +16 -0
  63. package/dist/src/utils/computerControlMcp/server/tests/test_computer_control.py +161 -0
  64. package/dist/src/utils/computerControlMcp/server/tests/test_screenshot.py +14 -0
  65. package/dist/src/utils/computerControlMcp/server/tests/test_wgc_env_var.py +42 -0
  66. package/dist/src/utils/computerControlMcp/server/tests/test_wgc_screenshot.py +67 -0
  67. package/dist/src/utils/computerControlMcp/server/uv.lock +4986 -0
  68. package/dist/src/utils/computerControlMcp/setup.js +1 -1
  69. package/dist/src/utils/logoV2Utils.js +1 -1
  70. package/dist/src/utils/model/configs.js +1 -1
  71. package/dist/src/utils/model/model.js +1 -1
  72. package/dist/src/utils/model/modelOptions.js +1 -1
  73. package/dist/src/utils/model/providerBaseUrls.js +1 -1
  74. package/dist/src/utils/model/providerCatalog.js +1 -1
  75. package/dist/src/utils/model/providerModels.js +1 -1
  76. package/dist/src/utils/model/providerProfiles.js +1 -1
  77. package/dist/src/utils/model/providerProfilesDb.js +1 -1
  78. package/dist/src/utils/sembleMcp/setup.js +1 -1
  79. package/dist/src/utils/status.js +1 -1
  80. package/dist/src/utils/theme.js +1 -1
  81. package/dist/src/utils/themes/bootstrap.js +1 -1
  82. package/dist/src/utils/themes/opencodeMapper.js +1 -1
  83. package/dist/webapp/chunk-OJZNEHPP.js +1 -1
  84. package/dist/webapp/chunk-VAB2VXFI.js +1 -1
  85. package/dist/webapp/main-MTQLKGXD.js +1 -1
  86. package/dist/webapp/ngsw-worker.js +1 -1
  87. package/dist/webapp/ngsw.json +1 -1
  88. package/dist/webapp/polyfills-7R4CRVNH.js +1 -1
  89. package/package.json +1 -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 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{SessionTokenFooter as st}from"../components/SessionTokenFooter.js";import{useRemoteSession as nt}from"../hooks/useRemoteSession.js";import{useDirectConnect as rt}from"../hooks/useDirectConnect.js";import{useSSHSession as it}from"../hooks/useSSHSession.js";import{useAssistantHistory as at}from"../hooks/useAssistantHistory.js";import{SkillImprovementSurvey as lt}from"../components/SkillImprovementSurvey.js";import{useSkillImprovementSurvey as ct}from"../hooks/useSkillImprovementSurvey.js";import{useMoreRight as mt}from"../moreright/useMoreRight.js";import{SpinnerWithVerb as ut,BriefIdleStatus as pt}from"../components/Spinner.js";import{getSystemPrompt as dt}from"../constants/prompts.js";import{buildEffectiveSystemPrompt as ft}from"../utils/systemPrompt.js";import{getSystemContext as gt,getUserContext as ht}from"../context.js";import{getMemoryFiles as St}from"../utils/claudemd.js";import{startBackgroundHousekeeping as Ct}from"../utils/backgroundHousekeeping.js";import{getTotalCost as yt,saveCurrentSessionCosts as Tt,resetCostState as vt,getStoredSessionCosts as kt}from"../cost-tracker.js";import{useCostSummary as jt}from"../costHook.js";import{useFpsMetrics as bt}from"../context/fpsMetrics.js";import{useAfterFirstRender as It}from"../hooks/useAfterFirstRender.js";import{useDeferredHookMessages as At}from"../hooks/useDeferredHookMessages.js";import{addToHistory as wt,removeLastFromHistory as Rt,expandPastedTextRefs as Pt,parseReferences as xt}from"../history.js";import{prependModeCharacterToInput as Mt}from"../components/PromptInput/inputModes.js";import{prependToShellHistoryCache as Et}from"../utils/suggestions/shellHistoryCompletion.js";import{useApiKeyVerification as Dt}from"../hooks/useApiKeyVerification.js";import{GlobalKeybindingHandlers as _t}from"../hooks/useGlobalKeybindings.js";import{CommandKeybindingHandlers as Lt}from"../hooks/useCommandKeybindings.js";import{KeybindingSetup as Ot}from"../keybindings/KeybindingProviderSetup.js";import{useShortcutDisplay as Nt}from"../keybindings/useShortcutDisplay.js";import{getShortcutDisplay as Ut}from"../keybindings/shortcutFormat.js";import{CancelRequestHandler as Bt}from"../hooks/useCancelRequest.js";import{useBackgroundTaskNavigation as qt}from"../hooks/useBackgroundTaskNavigation.js";import{useSwarmInitialization as Ht}from"../hooks/useSwarmInitialization.js";import{useTeammateViewAutoExit as $t}from"../hooks/useTeammateViewAutoExit.js";import{errorMessage as Ft}from"../utils/errors.js";import{isHumanTurn as Vt}from"../utils/messagePredicates.js";import{logError as Xt}from"../utils/log.js";const Jt=r("../hooks/useVoiceIntegration.js").useVoiceIntegration,Kt=r("../hooks/useVoiceIntegration.js").VoiceKeybindingHandler,useFrustrationDetection=()=>({state:"closed",handleTranscriptSelect:()=>{}}),useAntOrgWarningNotification=()=>{},Wt=e("COORDINATOR_MODE")?r("../coordinator/coordinatorMode.js").getCoordinatorUserContext:()=>({});import Gt from"../hooks/useCanUseTool.js";import{applyPermissionUpdate as Qt,applyPermissionUpdates as Yt,persistPermissionUpdate as zt}from"../utils/permissions/PermissionUpdate.js";import{buildPermissionUpdates as Zt}from"../components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js";import{stripDangerousPermissionsForAutoMode as eo}from"../utils/permissions/permissionSetup.js";import{getScratchpadDir as to,isScratchpadEnabled as oo}from"../utils/permissions/filesystem.js";import{WEB_FETCH_TOOL_NAME as so}from"../tools/WebFetchTool/prompt.js";import{SLEEP_TOOL_NAME as no}from"../tools/SleepTool/prompt.js";import{clearSpeculativeChecks as ro}from"../tools/BashTool/bashPermissions.js";import{getGlobalConfig as io,saveGlobalConfig as ao,getGlobalConfigWriteCount as lo}from"../utils/config.js";import{hasConsoleBillingAccess as co}from"../utils/billing.js";import{logEvent as mo}from"../services/analytics/index.js";import{getFeatureValue_CACHED_MAY_BE_STALE as uo}from"../services/analytics/growthbook.js";import{textForResubmit as po,handleMessageFromStream as fo,isCompactBoundaryMessage as go,getMessagesAfterCompactBoundary as ho,getContentText as So,createUserMessage as Co,createAssistantMessage as yo,createTurnDurationMessage as To,createAgentsKilledMessage as vo,createApiMetricsMessage as ko,createSystemMessage as jo,createCommandInputMessage as bo,formatCommandInputTags as Io}from"../utils/messages.js";import{generateSessionTitle as Ao}from"../utils/sessionTitle.js";import{BASH_INPUT_TAG as wo,COMMAND_MESSAGE_TAG as Ro,COMMAND_NAME_TAG as Po,LOCAL_COMMAND_STDOUT_TAG as xo}from"../constants/xml.js";import{escapeXml as Mo}from"../utils/xml.js";import{gracefulShutdownSync as Eo}from"../utils/gracefulShutdown.js";import{handlePromptSubmit as Do}from"../utils/handlePromptSubmit.js";import{useQueueProcessor as _o}from"../hooks/useQueueProcessor.js";import{useMailboxBridge as Lo}from"../hooks/useMailboxBridge.js";import{queryCheckpoint as Oo,logQueryProfileReport as No}from"../utils/queryProfiler.js";import{query as Uo}from"../query.js";import{mergeClients as Bo,useMergedClients as qo}from"../hooks/useMergedClients.js";import{getQuerySourceForREPL as Ho}from"../utils/promptCategory.js";import{useMergedTools as $o}from"../hooks/useMergedTools.js";import{mergeAndFilterTools as Fo}from"../utils/toolPool.js";import{useMergedCommands as Vo}from"../hooks/useMergedCommands.js";import{useSkillsChange as Xo}from"../hooks/useSkillsChange.js";import{useManagePlugins as Jo}from"../hooks/useManagePlugins.js";import{Messages as Ko}from"../components/Messages.js";import{TaskListV2 as Wo}from"../components/TaskListV2.js";import{TeammateViewHeader as Go}from"../components/TeammateViewHeader.js";import{useTasksV2WithCollapseEffect as Qo}from"../hooks/useTasksV2.js";import{maybeMarkProjectOnboardingComplete as Yo}from"../projectOnboardingState.js";import{randomUUID as zo}from"crypto";import{processSessionStartHooks as Zo}from"../utils/sessionStart.js";import{executeSessionEndHooks as es,getSessionEndHookTimeoutMs as ts}from"../utils/hooks.js";import{useIdeSelection as os}from"../hooks/useIdeSelection.js";import{getTools as ss,assembleToolPool as ns}from"../tools.js";import{resolveAgentTools as rs}from"../tools/AgentTool/agentToolUtils.js";import{resumeAgentBackground as is}from"../tools/AgentTool/resumeAgent.js";import{useMainLoopModel as as}from"../hooks/useMainLoopModel.js";import{useAppState as ls,useSetAppState as cs,useAppStateStore as ms}from"../state/AppState.js";import{copyPlanForFork as us,copyPlanForResume as ps,getPlanSlug as ds,setPlanSlug as fs}from"../utils/plans.js";import{clearSessionMetadata as gs,resetSessionFilePointer as hs,adoptResumedSessionFile as Ss,removeTranscriptMessage as Cs,restoreSessionMetadata as ys,getCurrentSessionTitle as Ts,isEphemeralToolProgress as vs,isLoggableMessage as ks,saveWorktreeState as js,getAgentTranscript as bs}from"../utils/sessionStorage.js";import{deserializeMessages as Is}from"../utils/conversationRecovery.js";import{extractReadFilesFromMessages as As,extractBashToolsFromMessages as ws}from"../utils/queryHelpers.js";import{resetMicrocompactState as Rs}from"../services/compact/microCompact.js";import{runPostCompactCleanup as Ps}from"../services/compact/postCompactCleanup.js";import{provisionContentReplacementState as xs,reconstructContentReplacementState as Ms}from"../utils/toolResultStorage.js";import{partialCompactConversation as Es}from"../services/compact/compact.js";import{fileHistoryMakeSnapshot as Ds,fileHistoryRewind as _s,copyFileHistoryForResume as Ls,fileHistoryEnabled as Os,fileHistoryHasAnyChanges as Ns}from"../utils/fileHistory.js";import{incrementPromptCount as Us}from"../utils/commitAttribution.js";import{recordAttributionSnapshot as Bs}from"../utils/sessionStorage.js";import{computeStandaloneAgentContext as qs,restoreAgentFromSession as Hs,restoreSessionStateFromLog as $s,restoreWorktreeForResume as Fs,exitRestoredWorktree as Vs}from"../utils/sessionRestore.js";import{isBgSession as Xs,updateSessionName as Js,updateSessionActivity as Ks}from"../utils/concurrentSessions.js";import{isInProcessTeammateTask as Ws}from"../tasks/InProcessTeammateTask/types.js";import{restoreRemoteAgentTasks as Gs}from"../tasks/RemoteAgentTask/RemoteAgentTask.js";import{useInboxPoller as Qs}from"../hooks/useInboxPoller.js";import{usePermissionWhatsAppBridge as Ys}from"../hooks/usePermissionWhatsAppBridge.js";import{useWebappMirror as zs}from"../hooks/useWebappMirror.js";import{useWebappPermissionBridge as Zs}from"../hooks/useWebappPermissionBridge.js";const en=e("PROACTIVE")||e("KAIROS")?r("../proactive/index.js"):null,PROACTIVE_NO_OP_SUBSCRIBE=e=>()=>{},PROACTIVE_FALSE=()=>!1,SUGGEST_BG_PR_NOOP=(e,t)=>!1,tn=((e("PROACTIVE")||e("KAIROS"))&&r("../proactive/useProactive.js").useProactive,e("AGENT_TRIGGERS")?r("../hooks/useScheduledTasks.js").useScheduledTasks:null);import{isAgentSwarmsEnabled as on}from"../utils/agentSwarmsEnabled.js";import{useTaskListWatcher as sn}from"../hooks/useTaskListWatcher.js";import{closeOpenDiffs as nn,getConnectedIdeClient as rn}from"../utils/ide.js";import{useIDEIntegration as an}from"../hooks/useIDEIntegration.js";import ln from"../commands/exit/index.js";import{ExitFlow as cn}from"../components/ExitFlow.js";import{getCurrentWorktreeSession as mn}from"../utils/worktree.js";import{popAllEditable as un,enqueue as pn,getCommandQueue as dn,getCommandQueueLength as fn,removeByFilter as gn}from"../utils/messageQueueManager.js";import{useCommandQueue as hn}from"../hooks/useCommandQueue.js";import{SessionBackgroundHint as Sn}from"../components/SessionBackgroundHint.js";import{startBackgroundSession as Cn}from"../tasks/LocalMainSessionTask.js";import{useSessionBackgrounding as yn}from"../hooks/useSessionBackgrounding.js";import{diagnosticTracker as Tn}from"../services/diagnosticTracking.js";import{handleSpeculationAccept as vn}from"../services/PromptSuggestion/speculation.js";import{IdeOnboardingDialog as kn}from"../components/IdeOnboardingDialog.js";import{EffortCallout as jn,shouldShowEffortCallout as bn}from"../components/EffortCallout.js";import{RemoteCallout as In}from"../components/RemoteCallout.js";import{activityManager as An}from"../utils/activityManager.js";import{createAbortController as wn}from"../utils/abortController.js";import{MCPConnectionManager as Rn}from"../services/mcp/MCPConnectionManager.js";import{useFeedbackSurvey as Pn}from"../components/FeedbackSurvey/useFeedbackSurvey.js";import{useMemorySurvey as xn}from"../components/FeedbackSurvey/useMemorySurvey.js";import{usePostCompactSurvey as Mn}from"../components/FeedbackSurvey/usePostCompactSurvey.js";import{FeedbackSurvey as En}from"../components/FeedbackSurvey/FeedbackSurvey.js";import{useInstallMessages as Dn}from"../hooks/notifs/useInstallMessages.js";import{useAwaySummary as _n}from"../hooks/useAwaySummary.js";import{useChromeExtensionNotification as Ln}from"../hooks/useChromeExtensionNotification.js";import{useOfficialMarketplaceNotification as On}from"../hooks/useOfficialMarketplaceNotification.js";import{usePromptsFromClaudeInChrome as Nn}from"../hooks/usePromptsFromClaudeInChrome.js";import{getTipToShowOnSpinner as Un,recordShownTip as Bn}from"../services/tips/tipScheduler.js";import{checkAndDisableBypassPermissionsIfNeeded as qn,checkAndDisableAutoModeIfNeeded as Hn,useKickOffCheckAndDisableBypassPermissionsIfNeeded as $n,useKickOffCheckAndDisableAutoModeIfNeeded as Fn}from"../utils/permissions/bypassPermissionsKillswitch.js";import{SandboxManager as Vn}from"../utils/sandbox/sandbox-adapter.js";import{SANDBOX_NETWORK_ACCESS_TOOL_NAME as Xn}from"../cli/structuredIO.js";import{useFileHistorySnapshotInit as Jn}from"../hooks/useFileHistorySnapshotInit.js";import{SandboxPermissionRequest as Kn}from"../components/permissions/SandboxPermissionRequest.js";import{SandboxViolationExpandedView as Wn}from"../components/SandboxViolationExpandedView.js";import{useSettingsErrors as Gn}from"../hooks/notifs/useSettingsErrors.js";import{useMcpConnectivityStatus as Qn}from"../hooks/notifs/useMcpConnectivityStatus.js";import{useAutoModeUnavailableNotification as Yn}from"../hooks/notifs/useAutoModeUnavailableNotification.js";import{AUTO_MODE_DESCRIPTION as zn}from"../components/AutoModeOptInDialog.js";import{useLspInitializationNotification as Zn}from"../hooks/notifs/useLspInitializationNotification.js";import{useLspPluginRecommendation as er}from"../hooks/useLspPluginRecommendation.js";import{LspRecommendationMenu as tr}from"../components/LspRecommendation/LspRecommendationMenu.js";import{useClaudeCodeHintRecommendation as or}from"../hooks/useClaudeCodeHintRecommendation.js";import{PluginHintMenu as sr}from"../components/ClaudeCodeHint/PluginHintMenu.js";import{DesktopUpsellStartup as nr,shouldShowDesktopUpsellStartup as rr}from"../components/DesktopUpsell/DesktopUpsellStartup.js";import{usePluginInstallationStatus as ir}from"../hooks/notifs/usePluginInstallationStatus.js";import{usePluginAutoupdateNotification as ar}from"../hooks/notifs/usePluginAutoupdateNotification.js";import{performStartupChecks as lr}from"../utils/plugins/performStartupChecks.js";import{UserTextMessage as cr}from"../components/messages/UserTextMessage.js";import{AwsAuthStatusBox as mr}from"../components/AwsAuthStatusBox.js";import{useRateLimitWarningNotification as ur}from"../hooks/notifs/useRateLimitWarningNotification.js";import{useDeprecationWarningNotification as pr}from"../hooks/notifs/useDeprecationWarningNotification.js";import{useNpmDeprecationNotification as dr}from"../hooks/notifs/useNpmDeprecationNotification.js";import{useIDEStatusIndicator as fr}from"../hooks/notifs/useIDEStatusIndicator.js";import{useModelMigrationNotifications as gr}from"../hooks/notifs/useModelMigrationNotifications.js";import{useCanSwitchToExistingSubscription as hr}from"../hooks/notifs/useCanSwitchToExistingSubscription.js";import{useTeammateLifecycleNotification as Sr}from"../hooks/notifs/useTeammateShutdownNotification.js";import{useFastModeNotification as Cr}from"../hooks/notifs/useFastModeNotification.js";import{AutoRunIssueNotification as yr,shouldAutoRunIssue as Tr,getAutoRunIssueReasonText as vr,getAutoRunCommand as kr}from"../utils/autoRunIssue.js";import{TungstenLiveMonitor as jr}from"../tools/TungstenTool/TungstenLiveMonitor.js";const br=e("WEB_BROWSER_TOOL")?r("../tools/WebBrowserTool/WebBrowserPanel.js"):null;import{IssueFlagBanner as Ir}from"../components/PromptInput/IssueFlagBanner.js";import{useIssueFlagBanner as Ar}from"../hooks/useIssueFlagBanner.js";import{CompanionSprite as wr,CompanionFloatingBubble as Rr,MIN_COLS_FOR_FULL_SPRITE as Pr}from"../buddy/CompanionSprite.js";import{DevBar as xr}from"../components/DevBar.js";import{REMOTE_SAFE_COMMANDS as Mr}from"../commands.js";import{FullscreenLayout as Er,useUnseenDivider as Dr,computeUnseenDivider as _r}from"../components/FullscreenLayout.js";import{isFullscreenEnvEnabled as Lr,maybeGetTmuxMouseHint as Or,isMouseTrackingEnabled as Nr}from"../utils/fullscreen.js";import{AlternateScreen as Ur}from"../ink/components/AlternateScreen.js";import{ScrollKeybindingHandler as Br}from"../components/ScrollKeybindingHandler.js";import{useMessageActions as qr,MessageActionsKeybindings as Hr,MessageActionsBar as $r}from"../components/messageActions.js";import{setClipboard as Fr}from"../ink/termio/osc.js";import{createAttachmentMessage as Vr,getQueuedCommandAttachments as Xr}from"../utils/attachments.js";const Jr=[],Kr={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=Nt("app:toggleTranscript","Global","ctrl+o"),d=Nt("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 Wr=["⠂","⠐"];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?Wr[l]??"✳":"✳"} ${s}`),null}function _temp2(e){return e(_temp)}function _temp(e){return(e+1)%Wr.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:lt=!1,systemPrompt:Nt,appendSystemPrompt:lo,onBeforeQuery:ko,onTurnComplete:sn,disabled:jr=!1,mainThreadAgentDefinition:xr,disableSlashCommands:Wr=!1,taskListId:Gr,remoteSessionConfig:Qr,directConnectConfig:Yr,sshSession:zr,thinkingConfig:Zr}){const ei=!!Qr,ti=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_TERMINAL_TITLE)||ye(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE),[]),oi=N(()=>!1,[]),si=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_VIRTUAL_SCROLL)||ye(process.env.CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL),[]),ni=!!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=${jr}`),()=>Se("[REPL:unmount] REPL unmounting")),[jr]);const[ri,ii]=B(xr),ai=ls(e=>e.toolPermissionContext),li=ls(e=>e.verbose),ci=ls(e=>e.mcp),mi=ls(e=>e.plugins),ui=ls(e=>e.agentDefinitions),pi=ls(e=>e.fileHistory),di=ls(e=>e.initialMessage),fi=hn(),gi=ls(e=>e.spinnerTip),hi="tasks"===ls(e=>e.expandedView),Si=ls(e=>e.pendingWorkerRequest),Ci=ls(e=>e.pendingSandboxRequest),yi=ls(e=>e.teamContext),Ti=ls(e=>e.tasks),vi=ls(e=>e.workerSandboxPermissions),ki=ls(e=>e.elicitation),ji=ls(e=>e.ultraplanPendingChoice),bi=ls(e=>e.ultraplanLaunchPending),Ii=ls(e=>e.viewingAgentTaskId),Ai=cs(),wi=Ii?Ti[Ii]:void 0,Ri=_e(wi)&&wi.retain&&!wi.diskLoaded;O(()=>{if(!Ii||!Ri)return;const e=Ii;bs(he(e)).then(t=>{Ai(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}}}})})},[Ii,Ri,Ai]);const Pi=ms(),xi=W(),Mi=as(),[Ei,Di]=B(n);Xo(ei?void 0:oe(),Di);const _i=L.useSyncExternalStore(en?.subscribeToProactiveChanges??PROACTIVE_NO_OP_SUBSCRIBE,en?.isProactiveActive??PROACTIVE_FALSE),Li=ls(e=>e.isBriefOnly),Oi=N(()=>ss(ai),[ai,_i,Li]);$n(),Fn();const[Ni,Ui]=B(de),Bi=q(e=>{Ui(e)},[Ui]),[qi,Hi]=B("prompt"),[$i,Fi]=B(!1),[Vi,Xi]=B(!1),[Ji,Ki]=B(""),Wi=U(0),Gi=U(void 0),Qi=U(!1),{addNotification:Yi,removeNotification:zi}=F();let Zi=SUGGEST_BG_PR_NOOP;const ea=qo(pe,ci.clients),[ta,oa]=B(void 0),[sa,na]=B(null),[ra,ia]=B(null),[aa,la]=B(!1),[ca,ma]=B(()=>!1),[ua,pa]=B(()=>bn(Mi)),da=ls(e=>e.showRemoteCallout),[fa,ga]=B(()=>rr());gr(),hr(),fr({ideSelection:ta,mcpClients:ea,ideInstallationStatus:ra}),Qn({mcpClients:ea}),Yn(),ir(),ar(),Gn(),ur(Mi),Cr(),pr(Mi),dr(),useAntOrgWarningNotification(),Dn(),Ln(),On(),Zn(),Sr();const{recommendation:ha,handleResponse:Sa}=er(),{recommendation:Ca,handleResponse:ya}=or(),Ta=N(()=>[...Oi,...C],[Oi,C]);Jo({enabled:!ei});const va=Qo();O(()=>{ei||lr(Ai)},[Ai,ei]),Nn(ei?Jr:ea,ai.mode),Ht(Ai,T,{enabled:!ei});const ka=$o(Ta,ci.tools,ai),{tools:ja,allowedAgentTypes:ba}=N(()=>{if(!ri)return{tools:ka,allowedAgentTypes:void 0};const e=rs(ri,ka,!1,!0);return{tools:e.resolvedTools,allowedAgentTypes:e.allowedAgentTypes}},[ri,ka]),Ia=Vo(Ei,mi.commands),Aa=Vo(Ia,ci.commands),wa=N(()=>Wr?[]:Aa,[Wr,Aa]);Ye(ei?Jr:ci.clients),os(ei?Jr:ci.clients,oa);const[Ra,Pa]=B("responding"),xa=U(Ra);xa.current=Ra;const[Ma,Ea]=B([]),[Da,_a]=B(null);O(()=>{if(Da&&!Da.isStreaming&&Da.streamingEndedAt){const e=3e4-(Date.now()-Da.streamingEndedAt);if(e>0){const t=setTimeout(_a,e,null);return()=>clearTimeout(t)}_a(null)}},[Da]);const[La,Oa]=B(null),Na=U(null),Ua=q(e=>{Na.current=e,Oa(e)},[]),Ba=U(()=>{}),qa=U(()=>{}),Ha=U(null),$a=U(null),Fa=U(0),Va=L.useRef(new Ce).current,Xa=L.useSyncExternalStore(Va.subscribe,Va.getSnapshot),[Ja,Ka]=L.useState(Qr?.hasInitialPrompt??!1),Wa=Xa||Ja,[Ga,Qa]=L.useState(void 0),Ya=L.useRef(0),za=L.useRef(!1),Za=L.useRef(0),el=L.useRef(0),tl=L.useRef(null),ol=L.useCallback(()=>{Za.current=Date.now(),el.current=0,tl.current=null},[]),sl=L.useRef(!1);Xa&&!sl.current&&ol(),sl.current=Xa;const nl=L.useCallback(e=>{Ka(e),e&&ol()},[ol]),rl=L.useRef(null),il=L.useRef(void 0),al=L.useRef(void 0),[ll,cl]=L.useState(!1),[ml,ul]=B(null);O(()=>{ml?.notifications&&ml.notifications.forEach(e=>{Yi({key:"auto-updater-notification",text:e,priority:"low"})})},[ml,Yi]),O(()=>{Lr()&&Or().then(e=>{e&&Yi({key:"tmux-mouse-hint",text:e,priority:"low"})})},[]);const[pl,dl]=B(!1);O(()=>{0},[]);const[fl,gl]=B(null),[hl,Sl]=B([]),Cl=q(e=>{Sl(t=>[...t,e])},[]),yl=q(e=>{Sl(t=>0===t.length?[e]:[...t.slice(0,-1),e])},[]),Tl=q(()=>{Sl(e=>e.slice(0,-1))},[]),vl=q(()=>{Sl([])},[]),kl=U(null),jl=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 kl.current={...o,isLocalJSXCommand:!0},void gl(o)}return kl.current?e?.clearLocalJSX?(Se("Clearing local JSX command as requested"),kl.current=null,void gl(null)):void Se("Ignoring setToolJSX update because a local JSX command is active"):e?.clearLocalJSX?(Se("Clearing tool JSX (no local command active)"),void gl(null)):void gl(e)},[]),[bl,Il]=B([]),[Al,wl]=B(null),[Rl,Pl]=B([]),[xl,Ml]=B([]),El=U(new Map),Dl=!1!==ls(e=>e.settings.terminalTitleFromRename)?Ts(se()):void 0,[_l,Ll]=B(),Ol=U((T?.length??0)>0),Nl=ri?.agentType,Ul=Dl??Nl??_l??"Context Code",Bl=bl.length>0||xl.length>0||Si||Ci,ql=!0===fl?.isLocalJSXCommand&&null!=fl?.jsx,Hl=Wa&&!Bl&&!ql;O(()=>{if(Wa&&!Bl&&!ql)return J(),()=>K()},[Wa,Bl,ql]);const $l=Bl||ql?"waiting":Wa?"busy":"idle",Fl="waiting"!==$l?void 0:bl.length>0?`approve ${bl[0].tool.name}`:Si?"worker request":Ci?"sandbox request":ql?"dialog open":"input needed";O(()=>{e("BG_SESSIONS")&&Ks({status:$l,waitingFor:Fl})},[$l,Fl]);const Vl=uo("tengu_terminal_sidebar",!1)&&(io().showStatusInTerminalTab??!1);E(ti||!Vl?null:$l),O(()=>(Ne(Il),()=>Ue()),[Il]);const[Xl,Jl]=B(T??[]),Kl=U(Xl),Wl=U(!1),Gl=q(e=>{const t=Kl.current,o="function"==typeof e?e(Kl.current):e;if(Kl.current=o,o.length<Ya.current)Ya.current=0;else if(o.length>t.length&&za.current){const e=o.length-t.length;(0===t.length||o[0]===t[0]?o.slice(-e):o.slice(0,e)).some(Vt)?za.current=!1:Ya.current=o.length}Jl(o)},[]),Ql=q(e=>{void 0!==e?(Ya.current=Kl.current.length,za.current=!0):za.current=!1,Qa(e)},[]),{dividerIndex:Yl,dividerYRef:zl,onScrollAway:Zl,onRepin:ec,jumpToNew:tc,shiftDivider:oc}=Dr(Xl.length);e("AWAY_SUMMARY")&&_n(Xl,Gl,Wa);const[sc,nc]=B(null),rc=U(null),ic=q(e=>{const t=Kl.current.find(t=>t.uuid===e)?.uuid,o=Kl.current.find(t=>t.uuid.slice(0,24)===e.slice(0,24))?.uuid,s=t??o;s?nc({uuid:s,msgType:"user",expanded:!1}):Yi({key:"timeline-jump-not-found",text:"Message no longer available in active transcript",color:"warning",priority:"medium",timeoutMs:3e3})},[Yi]),ac=N(()=>_r(Xl,Yl),[Yl,Xl.length]),lc=q(()=>{Ha.current?.scrollToBottom(),ec(),nc(null)},[ec,nc]),cc=Xl.at(-1),mc=null!=cc&&Vt(cc);O(()=>{mc&&lc()},[mc,cc,lc]);const{maybeLoadOlder:uc}=e("KAIROS")?at({config:Qr,setMessages:Gl,scrollRef:Ha,onPrepend:oc}):Kr,pc=q((t,o)=>{Fa.current=Date.now(),t?ec():(Zl(o),e("KAIROS")&&uc(o),e("BUDDY")&&Ai(e=>void 0===e.companionReaction?e:{...e,companionReaction:void 0}))},[ec,Zl,uc,Ai]),dc=At(M,Gl),fc=H(Xl),gc=Xl.length-fc.length;gc>0&&Se(`[useDeferredValue] Messages deferred by ${gc} (${fc.length}→${Xl.length})`);const[hc,Sc]=B(null),[Cc,yc]=B(()=>ke()),Tc=U(Cc);Tc.current=Cc;const vc=U(null),kc=q(e=>{Zi(Tc.current,e)||(""===Tc.current&&""!==e&&Date.now()-Fa.current>=3e3&&lc(),Tc.current=e,yc(e),cl(e.trim().length>0))},[cl,lc,Zi]);O(()=>{if(0===Cc.trim().length)return;const e=setTimeout(cl,1500,!1);return()=>clearTimeout(e)},[Cc]);const[jc,bc]=B("prompt"),[Ic,Ac]=B(),wc=q(e=>{const t=new Set(e);Di(e=>e.filter(e=>t.has(e.name)||Mr.has(e)))},[Di]),[Rc,Pc]=B(new Set),xc=U(!1),Mc=nt({config:Qr,setMessages:Gl,setIsLoading:nl,onInit:wc,setToolUseConfirmQueue:Il,tools:Ta,setStreamingToolUses:Ea,setStreamMode:Pa,setInProgressToolUseIDs:Pc}),Ec=rt({config:Yr,setMessages:Gl,setIsLoading:nl,setToolUseConfirmQueue:Il,tools:Ta}),Dc=it({session:zr,setMessages:Gl,setIsLoading:nl,setToolUseConfirmQueue:Il,tools:Ta}),_c=Dc.isRemoteMode?Dc:Ec.isRemoteMode?Ec:Mc,[Lc,Oc]=B({}),[Nc,Uc]=B(0),Bc=U(0),qc=U([]),Hc=q(e=>{const t=Bc.current;if(Bc.current=e(t),Bc.current>t){const e=qc.current;if(e.length>0){const t=e.at(-1);t.lastTokenTime=Date.now(),t.endResponseLength=Bc.current}}},[]),[$c,Fc]=B(null),Vc=!(ls(e=>e.settings.prefersReducedMotion)??!1)&&!G(),Xc=q(e=>{Vc&&Fc(e)},[Vc]),Jc=$c&&Vc&&$c.substring(0,$c.lastIndexOf("\n")+1)||null,[Kc,Wc]=B(0),[Gc,Qc]=B(null),[Yc,zc]=B(null),[Zc,em]=B(null),[tm,om]=B(!1),[sm,nm]=B(void 0),[rm,im]=B(!1),[am,lm]=B(zo()),[cm,mm]=B(null),um=U(Wa),pm=U(!1),dm=U(!1),fm=U(Kc);fm.current=Kc;const[gm]=B(()=>({current:xs(T,ae)})),[hm,Sm]=B(io().hasAcknowledgedCostThreshold),[Cm,ym]=B("INSERT"),[Tm,vm]=B(!1),[km,jm]=B(!1),[bm,Im]=B(!1);O(()=>{ji&&Tm&&vm(!1)},[ji,Tm]);const Am=x(),wm=U(Am);wm.current=Am;const[Rm]=P(),Pm=L.useRef(!1),xm=q(()=>{if(Pm.current)return;Pm.current=!0;const e=Kl.current.slice(Ym.current);for(const t of ws(e))Qm.current.add(t);Ym.current=Kl.current.length,Un({theme:Rm,readFileState:Gm.current,bashTools:Qm.current}).then(async e=>{if(e){const t=await e.content({theme:Rm});Ai(e=>({...e,spinnerTip:t})),Bn(e)}else Ai(e=>void 0===e.spinnerTip?e:{...e,spinnerTip:void 0})})},[Ai,Rm]),Mm=q(()=>{nl(!1),Ql(void 0),Bc.current=0,qc.current=[],Fc(null),Ea([]),Qc(null),zc(null),em(null),xm(),He(),ro()},[xm]),Em=N(()=>De(Ti).some(e=>"running"===e.status),[Ti]);O(()=>{if(!Em&&null!==rl.current){const e=Date.now()-rl.current,t=il.current;rl.current=null,il.current=void 0,Gl(o=>[...o,To(e,t,f(o,ks))])}},[Em,Gl]);const Dm=U(!1);O(()=>{if(e("TRANSCRIPT_CLASSIFIER")){if("auto"!==ai.mode)return void(Dm.current=!1);if(Dm.current)return;if((io().autoPermissionsNotificationCount??0)>=3)return;const e=setTimeout((e,t)=>{e.current=!0,ao(e=>{const t=e.autoPermissionsNotificationCount??0;return t>=3?e:{...e,autoPermissionsNotificationCount:t+1}}),t(e=>[...e,jo(zn,"warning")])},800,Dm,Gl);return()=>clearTimeout(e)}},[ai.mode,Gl]);const _m=U(!1);O(()=>{if(_m.current)return;const e=mn();if(!e?.creationDurationMs||e.usedSparsePaths)return;if(e.creationDurationMs<15e3)return;_m.current=!0;const t=Math.round(e.creationDurationMs/1e3);Gl(e=>[...e,jo(`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")])},[Gl]);const Lm=N(()=>{const e=Xl.findLast(e=>"assistant"===e.type);if("assistant"!==e?.type)return!1;const t=e.message.content.filter(e=>"tool_use"===e.type&&Rc.has(e.id));return t.length>0&&t.every(e=>"tool_use"===e.type&&e.name===no)},[Xl,Rc]),{onBeforeQuery:Om,onTurnComplete:Nm,render:Um}=mt({enabled:oi,setMessages:Gl,inputValue:Cc,setInputValue:kc,setToolJSX:jl}),Bm=(!fl||!0===fl.showSpinner)&&0===bl.length&&0===xl.length&&(Wa||Ga||Em||fn()>0)&&!Si&&!Lm&&(!Jc||Li),qm=bl.length>0||xl.length>0||Rl.length>0||ki.queue.length>0||vi.queue.length>0,Hm=Pn(Xl,Wa,Nc,"session",qm),$m=(ct(Gl),Ar(Xl,Nc)),Fm=N(()=>({...Hm,handleSelect:e=>{ru.current=!1;const t=Hm.handleSelect(e);"bad"===e&&!t&&Tr("feedback_survey_bad")&&(nu("feedback_survey_bad"),ru.current=!0)}}),[Hm]),Vm=Mn(Xl,Wa,qm,{enabled:!ei}),Xm=xn(Xl,Wa,qm,{enabled:!ei}),Jm=useFrustrationDetection(Xl,Wa,qm,"closed"!==Fm.state||"closed"!==Vm.state||"closed"!==Xm.state);an({autoConnectIdeFlag:ve,ideToInstallExtension:sa,setDynamicMcpConfig:Ui,setShowIdeOnboarding:la,setIDEInstallationState:ia}),Jn(ie,pi,e=>Ai(t=>({...t,fileHistory:e})));const Km=q(async(t,o,s)=>{const n=performance.now();try{const i=Is(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());Ai(e=>({...e,agentDefinitions:{...s,allAgents:s.allAgents,activeAgents:o(s.allAgents)}})),i.push(jo(e,"warning"))}}const a=ts();await es("resume",{getAppState:()=>Pi.getState(),setAppState:Ai,signal:AbortSignal.timeout(a),timeoutMs:a});const l=await Zo("resume",{sessionId:t,agentType:ri?.agentType,model:Mi});i.push(...l),"fork"===s?us(o,ge(t)):ps(o,ge(t)),$s(o,Ai),o.fileHistorySnapshots&&Ls(o);const{agentDefinition:c}=Hs(o.agentSetting,xr,ui);ii(c),Ai(e=>({...e,agent:c?.agentType})),Ai(e=>({...e,standaloneAgentContext:qs(o.agentName,o.agentColor)})),Js(o.agentName),eu(i,o.projectPath??te()),Mm(),Ua(null),lm(t);const m=kt(t);Tt(),vt(),ne(ge(t),o.fullPath?g(o.fullPath):null);const{renameRecordingForSession:u}=await import("../utils/asciicast.js");if(await u(),await hs(),gs(),ys(o),Ol.current=!0,Ll(void 0),"fork"!==s)Vs(),Fs(o.worktreeSession),Ss(),Gs({abortController:new AbortController,getAppState:()=>Pi.getState(),setAppState:Ai});else{const e=mn();e&&js(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),gm.current&&"fork"!==s&&(gm.current=Ms(i,o.contentReplacements??[])),Gl(()=>i),jl(null),kc(""),mo("tengu_session_resumed",{entrypoint:s,success:!0,resume_duration_ms:Math.round(performance.now()-n)})}catch(e){throw mo("tengu_session_resumed",{entrypoint:s,success:!1}),e}},[Mm,Ai]),[Wm]=B(()=>Q(z)),Gm=U(Wm),Qm=U(new Set),Ym=U(0),zm=U(new Set),Zm=U(new Set),eu=q((e,t)=>{const o=As(e,t,z);Gm.current=Y(Gm.current,o);for(const t of ws(e))Qm.current.add(t)},[]);O(()=>{T&&T.length>0&&(eu(T,te()),Gs({abortController:new AbortController,getAppState:()=>Pi.getState(),setAppState:Ai}))},[]);const{status:tu,reverify:ou}=Dt(),[su,nu]=B(null),ru=U(!1),[iu,au]=B(null),[lu,cu]=B(!1),mu=!Wa&&rm;const uu=function(){if(lu||iu)return;if(tm)return"message-selector";if(ll)return;if(Rl[0])return"sandbox-permission";const t=!fl||fl.shouldContinueAnimation;return t&&bl[0]?"tool-permission":t&&xl[0]?"prompt":t&&vi.queue[0]?"worker-sandbox-permission":t&&ki.queue[0]?"elicitation":t&&mu?"cost":t&&cm?"idle-return":e("ULTRAPLAN")&&t&&!Wa&&ji?"ultraplan-choice":e("ULTRAPLAN")&&t&&!Wa&&bi?"ultraplan-launch":t&&aa?"ide-onboarding":t&&ua?"effort-callout":t&&da?"remote-callout":t&&ha?"lsp-recommendation":t&&Ca?"plugin-hint":t&&fa?"desktop-upsell":void 0}(),pu=ll&&(Rl[0]||bl[0]||xl[0]||vi.queue[0]||ki.queue[0]||mu);al.current=uu,O(()=>{if(!Wa)return;const e="tool-permission"===uu,t=Date.now();e&&null===tl.current?tl.current=t:e||null===tl.current||(el.current+=t-tl.current,tl.current=null)},[uu,Wa]);const du=U(uu);function onCancel(){if(hl.length>0){const e=hl[hl.length-1];return e?.onClose?.(),void Tl()}if("elicitation"!==uu){if(Se(`[onCancel] focusedInputDialog=${uu} streamMode=${Ra}`),(e("PROACTIVE")||e("KAIROS"))&&en?.pauseProactive(),Va.forceEnd(),dm.current=!1,$c?.trim()&&Gl(e=>[...e,yo({content:$c})]),Mm(),e("TOKEN_BUDGET")&&l(null),"tool-permission"===uu)bl[0]?.onAbort(),Il([]);else if("prompt"===uu){for(const e of xl)e.reject(new Error("Prompt cancelled by user"));Ml([]),Na.current?.abort("user-cancel")}else _c.isRemoteMode?_c.cancelRequest():Na.current?.abort("user-cancel");Ua(null),Nm(Kl.current,!0)}}$(()=>{"tool-permission"===du.current!==("tool-permission"===uu)&&lc(),du.current=uu},[uu,lc]);const fu=q(()=>{const e=un(Cc,0);e&&(kc(e.text),bc("prompt"),e.images.length>0&&Oc(t=>{const o={...t};for(const t of e.images)o[t.id]=t;return o}))},[kc,bc,Cc,Oc]),gu={setToolUseConfirmQueue:Il,onCancel,onAgentsKilled:()=>Gl(e=>[...e,vo()]),isMessageSelectorVisible:tm||!!Tm,screen:qi,abortSignal:La?.signal,popCommandFromQueue:fu,vimMode:Cm,isLocalJSXCommand:fl?.isLocalJSXCommand,isSearchingHistory:km,isHelpOpen:bm,inputMode:jc,inputValue:Cc,streamMode:Ra};O(()=>{yt()>=5&&!rm&&!hm&&(mo("tengu_cost_threshold_reached",{}),Sm(!0),co()&&im(!0))},[Xl,rm,hm]);const hu=q(async t=>{if(on()&&be()){const e=Ie(),o=await Ae(t.host,e);return new Promise(s=>{o?(Re({requestId:e,host:t.host,resolve:s}),Ai(o=>({...o,pendingSandboxRequest:{requestId:e,host:t.host}}))):Pl(e=>[...e,{hostPattern:t,resolvePromise:s}])})}return new Promise(o=>{let s=!1;function resolveOnce(e){s||(s=!0,o(e))}if(Pl(e=>[...e,{hostPattern:t,resolvePromise:resolveOnce}]),e("BRIDGE_MODE")){const e=Pi.getState().replBridgePermissionCallbacks;if(e){const o=zo();e.sendRequest(o,Xn,{host:t.host},zo(),`Allow network connection to ${t.host}?`);const s=e.onResponse(o,e=>{s();const o="allow"===e.behavior;Pl(e=>(e.filter(e=>e.hostPattern.host===t.host).forEach(e=>e.resolvePromise(o)),e.filter(e=>e.hostPattern.host!==t.host)));const n=El.current.get(t.host);if(n){for(const e of n)e();El.current.delete(t.host)}}),cleanup=()=>{s(),e.cancelRequest(o)},n=El.current.get(t.host)??[];n.push(cleanup),El.current.set(t.host,n)}}})},[Ai,Pi]);O(()=>{const e=Vn.getSandboxUnavailableReason();if(e){if(Vn.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 Eo(1,"other");Se(`sandbox disabled: ${e}`,{level:"warn"}),Yi({key:"sandbox-unavailable",jsx:t(s,{children:[o(w,{color:"warning",children:"sandbox disabled"}),o(w,{dimColor:!0,children:" · /sandbox"})]}),priority:"medium"})}},[Yi]),Vn.isSandboxingEnabled()&&Vn.initialize(hu).catch(e=>{process.stderr.write(`\n❌ Sandbox Error: ${Ft(e)}\n`),Eo(1,"other")});const Su=q((e,t)=>{Ai(o=>({...o,toolPermissionContext:{...e,mode:t?.preserveMode?o.toolPermissionContext.mode:e.mode}})),setImmediate(e=>{e(e=>(e.forEach(e=>{e.recheckPermission()}),e))},Il)},[Ai,Il]);O(()=>(Be(Su),()=>qe()),[Su]);const Cu=Gt(Il,Su),yu=q((e,t)=>o=>new Promise((s,n)=>{Ml(r=>[...r,{request:o,title:e,toolInputSummary:t,resolve:s,reject:n}])}),[]),Tu=q((t,o,s,n)=>{const r=Pi.getState(),computeTools=()=>{const e=Pi.getState(),t=ns(e.toolPermissionContext,e.mcp.tools),o=Fo(Ta,t,e.toolPermissionContext.mode);return ri?rs(ri,o,!1,!0).resolvedTools:o};return{abortController:s,options:{commands:wa,tools:computeTools(),debug:i,verbose:r.verbose,mainLoopModel:n,thinkingConfig:!1!==r.thinkingEnabled?Zr:{type:"disabled"},mcpClients:Bo(pe,r.mcp.clients),mcpResources:r.mcp.resources,ideInstallationStatus:ra,isNonInteractiveSession:!1,dynamicMcpConfig:Ni,theme:Rm,agentDefinitions:ba?{...r.agentDefinitions,allowedAgentTypes:ba}:r.agentDefinitions,customSystemPrompt:Nt,appendSystemPrompt:lo,refreshTools:computeTools},getAppState:()=>Pi.getState(),setAppState:Ai,messages:t,setMessages:Gl,updateFileHistoryState(e){Ai(t=>{const o=e(t.fileHistory);return o===t.fileHistory?t:{...t,fileHistory:o}})},updateAttributionState(e){Ai(t=>{const o=e(t.attribution);return o===t.attribution?t:{...t,attribution:o}})},openMessageSelector:()=>{jr||om(!0)},openMessageSelectorAtMessage:e=>{if(jr)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)&&nm(n),om(!0)},jumpToMessage:ic,onChangeAPIKey:ou,readFileState:Gm.current,setToolJSX:jl,addNotification:Yi,appendSystemMessage:e=>Gl(t=>[...t,e]),sendOSNotification:e=>{X(e,xi)},onChangeDynamicMcpConfig:Bi,onInstallIDEExtension:na,nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:Zm.current,dynamicSkillDirTriggers:new Set,discoveredSkillNames:zm.current,setResponseLength:Hc,pushApiMetricsEntry:void 0,setStreamMode:Pa,onCompactProgress:e=>{switch(e.type){case"hooks_start":zc("claudeBlue_FOR_SYSTEM_SPINNER"),em("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),zc(null),em(null)}},setInProgressToolUseIDs:Pc,setHasInterruptibleToolInProgress:e=>{xc.current=e},resume:Km,setConversationId:lm,requestPrompt:e("HOOK_PROMPTS")?yu:void 0,contentReplacementState:gm.current}},[wa,Ta,ri,i,pe,ra,Ni,Rm,ba,Pi,Ai,ou,Yi,Gl,Bi,Km,yu,jr,Nt,lo,lm,ic,Xl]),vu=q(()=>{Na.current?.abort("background");const e=gn(e=>"task-notification"===e.mode);(async()=>{const t=Tu(Kl.current,[],new AbortController,Mi),[o,s,n]=await Promise.all([dt(t.options.tools,Mi,Array.from(ai.additionalWorkingDirectories.keys()),t.options.mcpClients),ht(),gt()]),r=ft({mainThreadAgentDefinition:ri,toolUseContext:t,customSystemPrompt:Nt,defaultSystemPrompt:o,appendSystemPrompt:lo});t.renderedSystemPrompt=r;const i=(await Xr(e).catch(()=>[])).map(Vr),a=new Set;for(const e of Kl.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)));Cn({messages:[...Kl.current,...l],queryParams:{systemPrompt:r,userContext:s,systemContext:n,canUseTool:Cu,toolUseContext:t,querySource:Ho()},description:Ul,setAppState:Ai,agentDefinition:ri})})()},[Mi,ai,ri,Tu,Nt,lo,Cu,Ai]),{handleBackgroundSession:ku}=yn({setMessages:Gl,setIsLoading:nl,resetLoadingState:Mm,setAbortController:Ua,onBackgroundQuery:vu}),ju=q(t=>{fo(t,t=>{go(t)?(Lr()?Gl(e=>[...ho(e,{includeSnipped:!0}),t]):Gl(()=>[t]),lm(zo()),(e("PROACTIVE")||e("KAIROS"))&&en?.setContextBlocked(!1)):"progress"===t.type&&vs(t.data.type)?Gl(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]}):Gl(e=>[...e,t]),(e("PROACTIVE")||e("KAIROS"))&&("assistant"===t.type&&"isApiErrorMessage"in t&&t.isApiErrorMessage?en?.setContextBlocked(!0):"assistant"===t.type&&en?.setContextBlocked(!1))},e=>{Hc(t=>t+e.length)},Pa,Ea,e=>{Gl(t=>t.filter(t=>t!==e)),Cs(e.uuid)},_a,e=>{const t=Date.now(),o=Bc.current;qc.current.push({...e,firstTokenTime:t,lastTokenTime:t,responseLengthBaseline:o,endResponseLength:o})},Xc)},[Gl,Hc,Pa,Ea,_a,Xc]),bu=q(async(t,o,s,n,r,i,a)=>{if(n){const e=Bo(pe,Pi.getState().mcp.clients);Tn.handleQueryStart(e);const t=rn(e);t&&nn(t)}if(Yo(),!(ti||Dl||Nl||Ol.current)){const e=o.find(e=>"user"===e.type&&!e.isMeta),t="user"===e?.type?So(e.message.content):null;!t||t.startsWith(`<${xo}>`)||t.startsWith(`<${Ro}>`)||t.startsWith(`<${Po}>`)||t.startsWith(`<${wo}>`)||(Ol.current=!0,Ao(t,(new AbortController).signal).then(e=>{e?Ll(e):Ol.current=!1},()=>{Ol.current=!1}))}if(Pi.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(go)&&(lm(zo()),(e("PROACTIVE")||e("KAIROS"))&&en?.setContextBlocked(!1)),Mm(),void Ua(null);const l=Tu(t,o,s,i),{tools:c,mcpClients:m}=l.options;if(void 0!==a){const e=l.getAppState;l.getAppState=()=>({...e(),effortValue:a})}Oo("query_context_loading_start");const[,,u,p,d]=await Promise.all([qn(ai,Ai),e("TRANSCRIPT_CLASSIFIER")?Hn(ai,Ai,Pi.getState().fastMode):void 0,dt(c,i,Array.from(ai.additionalWorkingDirectories.keys()),m),ht(),gt()]),f={...p,...Wt(m,oo()?to():void 0),...(e("PROACTIVE")||e("KAIROS"))&&en?.isProactiveActive()&&!wm.current?{terminalFocus:"The terminal is unfocused — the user is not actively watching."}:{}};Oo("query_context_loading_end");const g=ft({mainThreadAgentDefinition:ri,toolUseContext:l,customSystemPrompt:Nt,defaultSystemPrompt:u,appendSystemPrompt:lo});l.renderedSystemPrompt=g,Oo("query_query_start"),le(),ue(),fe();for await(const e of Uo({messages:t,systemPrompt:g,userContext:f,systemContext:d,canUseTool:Cu,toolUseContext:l,querySource:Ho()}))ju(e);e("BUDDY")&&fireCompanionObserver(Kl.current,e=>Ai(t=>t.companionReaction===e?t:{...t,companionReaction:e})),Oo("query_end"),Mm(),No(),await(sn?.(Kl.current))},[pe,Mm,Tu,ai,Ai,Nt,sn,lo,Cu,ri,ju,Dl,ti]),Iu=q(async(t,o,s,n,r,i,a,p)=>{if(on()){const e=Pe(),t=xe();e&&t&&je(e,t,!0)}const g=Va.tryStart();if(null===g)return mo("tengu_concurrent_onquery_detected",{}),void t.filter(e=>"user"===e.type&&!e.isMeta).map(e=>So(e.message.content)).filter(e=>null!==e).forEach((e,t)=>{pn({value:e,mode:"prompt"}),0===t&&mo("tengu_concurrent_onquery_enqueued",{})});try{if(ol(),Gl(e=>[...e,...t]),Bc.current=0,e("TOKEN_BUDGET")){const e=a?d(a):null;l(e??c())}qc.current=[],Ea([]),Fc(null);const m=Kl.current;if(a&&await Om(a,m,t.length),i&&a){if(!await i(a,m))return}await bu(m,t,o,s,n,r,p)}finally{if(Va.end(g)){let t;Wc(Date.now()),dm.current=!1,Mm(),await Nm(Kl.current,o.signal.aborted),Ba.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-el.current;if((s>3e4||void 0!==t)&&!o.signal.aborted&&!_i){De(Pi.getState().tasks).some(e=>"running"===e.status)?(null===rl.current&&(rl.current=Za.current),t&&(il.current=t)):Gl(e=>[...e,To(s,t,f(e,ks))])}Ua(null)}if("user-cancel"===o.signal.reason&&!Va.isActive&&""===Tc.current&&0===fn()&&!Pi.getState().viewingAgentTaskId){const e=Kl.current,t=e.findLast(Ge);if(t){const o=e.lastIndexOf(t);Qe(e,o)&&(Rt(),qa.current(t))}}}},[bu,Ai,Mm,Va,Om,Nm]),Au=U(!1);O(()=>{const t=di;!t||Wa||Au.current||(Au.current=!0,async function(t){if(t.clearContext){const e=t.message.planContent?ds():void 0,{clearConversation:o}=await import("../commands/clear/conversation.js");await o({setMessages:Gl,readFileState:Gm.current,discoveredSkillNames:zm.current,loadedNestedMemoryPaths:Zm.current,getAppState:()=>Pi.getState(),setAppState:Ai,setConversationId:lm}),Ol.current=!1,Ll(void 0),Qm.current.clear(),Ym.current=0,e&&fs(se(),e)}const o=t.message.planContent&&!1;Ai(s=>{let n=t.mode?Yt(s.toolPermissionContext,Zt(t.mode,t.allowedPrompts)):s.toolPermissionContext;return e("TRANSCRIPT_CLASSIFIER")&&"auto"===t.mode&&(n=eo({...n,mode:"auto",prePlanMode:void 0})),{...s,initialMessage:null,toolPermissionContext:n,...o&&{pendingPlanVerification:{plan:t.message.planContent,verificationStarted:!1,verificationCompleted:!1}}}}),Os()&&Ds(e=>{Ai(t=>({...t,fileHistory:e(t.fileHistory)}))},t.message.uuid),await dc();const s=t.message.message.content;if("string"!=typeof s||t.message.planContent){const e=wn();Ua(e),Iu([t.message],e,!0,[],Mi)}else wu(s,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}});setTimeout(e=>{e.current=!1},100,Au)}(t))},[di,Wa,Gl,Ai,Iu,Mi,ja]);const wu=q(async(t,o,s,n)=>{if(lc(),(e("PROACTIVE")||e("KAIROS"))&&en?.resumeProactive(),!s&&t.trim().startsWith("/")){const e=Pt(t,Lc).trim(),s=e.indexOf(" "),r=-1===s?e.slice(1):e.slice(1,s),i=-1===s?"":e.slice(s+1).trim(),a=wa.find(e=>Ke(e)&&(e.name===r||e.aliases?.includes(r)||Je(e)===r));"clear"===a?.name&&Wl.current&&(mo("tengu_idle_return_action",{action:"hint_converted",variant:Wl.current,idleMinutes:Math.round((Date.now()-fm.current)/6e4),messageCount:Kl.current.length,totalInputTokens:p()}),Wl.current=!1);const l=Va.isActive&&(a?.immediate||n?.fromKeybinding);if(a&&l&&"local-jsx"===a.type){t.trim()===Tc.current.trim()&&(kc(""),o.setCursorOffset(0),o.clearBuffer(),Oc({}));const e=xt(t).filter(e=>"text"===Lc[e.id]?.type),s=e.length,r=e.reduce((e,t)=>e+(Lc[t.id]?.content.length??0),0);mo("tengu_paste_text",{pastedTextCount:s,pastedTextBytes:r}),mo("tengu_immediate_command_executed",{commandName:a.name,fromKeybinding:n?.fromKeybinding??!1});return void(async()=>{let e=!1;const t=Tu(Kl.current,[],wn(),Mi),s=await a.load(),n=await s.call((t,s)=>{e=!0,jl({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0});const n=[];t&&"skip"!==s?.display&&(Yi({key:`immediate-${a.name}`,text:t,priority:"immediate"}),Lr()||n.push(bo(Io(Je(a),i)),bo(`<${xo}>${Mo(t)}</${xo}>`))),s?.metaMessages?.length&&n.push(...s.metaMessages.map(e=>Co({content:e,isMeta:!0}))),n.length&&Gl(e=>[...e,...n]),void 0!==Ic&&(kc(Ic.text),o.setCursorOffset(Ic.cursorOffset),Oc(Ic.pastedContents),Ac(void 0))},t,i);n&&!e&&jl({jsx:n,shouldHidePromptInput:!1,isLocalJSXCommand:!0})})()}}if(_c.isRemoteMode&&!t.trim())return;{const e=uo("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&&!io().idleReturnDismissed&&!dm.current&&!s&&!t.trim().startsWith("/")&&fm.current>0&&p()>=r){const s=(Date.now()-fm.current)/6e4;if(s>=n&&"dialog"===e)return mm({input:t,idleMinutes:s}),kc(""),o.setCursorOffset(0),void o.clearBuffer()}}n?.fromKeybinding||(wt({display:s?t:Mt(t,jc),pastedContents:s?{}:Lc}),"bash"===jc&&Et(t.trim()));const r=!s&&t.trim().startsWith("/"),i=!Wa||s||_c.isRemoteMode;if(void 0!==Ic&&!r&&i?(kc(Ic.text),o.setCursorOffset(Ic.cursorOffset),Oc(Ic.pastedContents),Ac(void 0)):i&&(n?.fromKeybinding||(kc(""),o.setCursorOffset(0)),Oc({})),i&&(bc("prompt"),oa(void 0),Uc(e=>e+1),o.clearBuffer(),Pm.current=!1,r||"prompt"!==jc||s||_c.isRemoteMode||(Ql(t),ol()),e("COMMIT_ATTRIBUTION")&&Ai(e=>({...e,attribution:Us(e.attribution,e=>{Bs(e).catch(e=>{Se(`Attribution: Failed to save snapshot: ${e}`)})})}))),s){const{queryRequired:e}=await vn(s.state,s.speculationSessionTimeSavedMs,s.setAppState,t,{setMessages:Gl,readFileState:Gm,cwd:te()});if(e){const e=wn();Ua(e),Iu([],e,!0,[],Mi)}return}if(_c.isRemoteMode&&(!r||"local-jsx"!==wa.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(Lc),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=Co({content:n,imagePasteIds:s});return Gl(e=>[...e,i]),void await _c.sendMessage(r,{uuid:i.uuid})}await dc(),await Do({input:t,helpers:o,queryGuard:Va,isExternalLoading:Ja,mode:jc,commands:wa,onInputChange:kc,setPastedContents:Oc,setToolJSX:jl,getToolUseContext:Tu,messages:Kl.current,mainLoopModel:Mi,pastedContents:Lc,ideSelection:ta,setUserInputOnProcessing:Ql,setAbortController:Ua,abortController:La,onQuery:Iu,setAppState:Ai,querySource:Ho(),onBeforeQuery:ko,canUseTool:Cu,addNotification:Yi,setMessages:Gl,streamMode:xa.current,hasInterruptibleToolInProgress:xc.current,onJumpToMessage:ic}),(r||Wa)&&void 0!==Ic&&(kc(Ic.text),o.setCursorOffset(Ic.cursorOffset),Oc(Ic.pastedContents),Ac(void 0))},[Va,Wa,Ja,jc,wa,kc,bc,Oc,Uc,oa,jl,Tu,Mi,Lc,ta,Ql,Ua,Yi,Iu,Ic,Ac,Ai,ko,Cu,Mc,Gl,dc,lc]),Ru=q(async(e,o,s)=>{_e(o)?(Oe(o.id,Co({content:e}),Ai),"running"===o.status?Le(o.id,e,Ai):is({agentId:o.id,prompt:e,toolUseContext:Tu(Kl.current,[],new AbortController,Mi),canUseTool:Cu}).catch(e=>{Se(`resumeAgentBackground failed: ${Ft(e)}`),Yi({key:`resume-agent-failed-${o.id}`,jsx:t(w,{color:"error",children:["Failed to resume agent: ",Ft(e)]}),priority:"low"})})):Ee(o.id,e,Ai),kc(""),s.setCursorOffset(0),s.clearBuffer()},[Ai,kc,Tu,Cu,Mi,Yi]),Pu=q(()=>{const e=su?kr(su):"/issue";nu(null),wu(e,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(t=>{Se(`Auto-run ${e} failed: ${Ft(t)}`)})},[wu,su]),xu=q(()=>{nu(null)},[]),Mu=q(()=>{wu("/feedback",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(e=>{Se(`Survey feedback request failed: ${e instanceof Error?e.message:String(e)}`)})},[wu]),Eu=U(wu);Eu.current=wu;const Du=q(()=>{Eu.current("/rate-limit-options",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})},[]),_u=q(async()=>{if(cu(!0),e("BG_SESSIONS")&&Xs())return a("tmux",["detach-client"],{stdio:"ignore"}),void cu(!1);if(null!==mn())return void au(o(cn,{showWorktree:!0,onDone:()=>{},onCancel:()=>{au(null),cu(!1)}}));const t=await ln.load(),s=await t.call(()=>{});au(s),null===s&&cu(!1)},[]),Lu=q(()=>{om(e=>!e)},[]),Ou=q(t=>{const o=Kl.current,s=o.lastIndexOf(t);-1!==s&&(mo("tengu_conversation_rewind",{preRewindMessageCount:o.length,postRewindMessageCount:s,messagesRemoved:o.length-s,rewindToMessageIndex:s}),Gl(o.slice(0,s)),lm(zo()),Rs(),e("CONTEXT_COLLAPSE")&&r("../services/contextCollapse/index.js").resetContextCollapse(),Ai(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}})))},[Gl,Ai]),Nu=q(e=>{Ou(e);const t=po(e);if(t&&(kc(t.text),bc(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}}}),Oc(o)}}},[Ou,kc]);qa.current=Nu;const Uu=q(async e=>{setImmediate((e,t)=>e(t),Nu,e)},[Nu]),Bu={copy:e=>{Fr(e).then(e=>{e&&process.stdout.write(e),Yi({key:"selection-copied",text:"copied",color:"success",priority:"immediate",timeoutMs:2e3})})},edit:async e=>{const t=(e=>{const t=e.slice(0,24);return Xl.findIndex(e=>e.uuid.slice(0,24)===t)})(e.uuid),o=t>=0?Xl[t]:void 0;if(!o||!Ge(o))return;const s=!await Ns(pi,o.uuid),n=Qe(Xl,t);s&&n?(onCancel(),Uu(o)):(nm(o),om(!0))}},{enter:qu,handlers:Hu}=qr(sc,nc,rc,Bu);jt(bt()),$e(Xl,Xl.length===T?.length);const{sendBridgeResult:$u}=Fe(Xl,Gl,Na,wa,Mi);Ba.current=$u,Ve(Xl),Xe(Xl),zs(Xl,Wa,onCancel,Da),Zs(bl),It();const Fu=U(!1);O(()=>{fi.length<1?Fu.current=!1:Fu.current||(Fu.current=!0,ao(e=>({...e,promptQueueUseCount:(e.promptQueueUseCount??0)+1})))},[fi.length]);const Vu=q(async e=>{await Do({helpers:{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}},queryGuard:Va,commands:wa,onInputChange:()=>{},setPastedContents:()=>{},setToolJSX:jl,getToolUseContext:Tu,messages:Xl,mainLoopModel:Mi,ideSelection:ta,setUserInputOnProcessing:Ql,setAbortController:Ua,onQuery:Iu,setAppState:Ai,querySource:Ho(),onBeforeQuery:ko,canUseTool:Cu,addNotification:Yi,setMessages:Gl,queuedCommands:e,onJumpToMessage:ic})},[Va,wa,jl,Tu,Xl,Mi,ta,Ql,Cu,Ua,Iu,Yi,Ai,ko,ic]);_o({executeQueuedInput:Vu,hasActiveLocalJsxUI:ql,queryGuard:Va}),O(()=>{An.recordUserActivity(),Z(!0)},[Cc,Nc]),O(()=>{1===Nc&&Ct()},[Nc]),O(()=>{const e=um.current;if(um.current=Wa,!e||Wa)return;if(0===Nc)return;!0===io().taskCompleteNotifEnabled&&X({message:"Respuesta finalizada",notificationType:"task_complete"},xi)},[Wa,Nc,xi]),O(()=>{const e=!Wa&&(bl.length>0||xl.length>0||!!Si||!!Ci),t=pm.current;if(pm.current=e,!e||t)return;!0===io().inputNeededNotifEnabled&&X({message:"Se requiere tu aprobacion o entrada",notificationType:"input_needed"},xi)},[Wa,bl.length,xl.length,Si,Ci,xi]),O(()=>{let e=!1;return(async()=>{const{startHeartbeat:t,stopHeartbeat:o}=await import("../utils/heartbeat.js");e||(t({onStdinStalled:()=>{Yi({key:"heartbeat-stdin-stalled",text:"⚠ stdin parece bloqueado · ejecuta /heartbeat para más info",color:"error",priority:"immediate",timeoutMs:2147483647})},onStdinRecovered:()=>{zi("heartbeat-stdin-stalled")},onGitBashDetected:()=>{Yi({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)}},[Yi,zi]),O(()=>{if(Wa)return;if(0===Nc)return;if(0===Kc)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>=io().messageIdleNotifThresholdMs&&X({message:"Context está esperando tu entrada",notificationType:"idle_prompt"},n)},io().messageIdleNotifThresholdMs,Kc,Wa,fl,al,xi);return()=>clearTimeout(e)},[Wa,fl,Nc,Kc,xi]),O(()=>{if(0===Kc)return;if(Wa)return;const e=uo("tengu_willow_mode","off");if("hint"!==e&&"hint_v2"!==e)return;if(io().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()-Kc),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,mo("tengu_idle_return_action",{action:"hint_shown",variant:i,idleMinutes:Math.round(m),messageCount:r.current.length,totalInputTokens:l})},Math.max(0,r),Kc,Yi,Kl,e,Wl);return()=>{clearTimeout(i),zi("idle-return-hint"),Wl.current=!1}},[Kc,Wa,Yi,zi]);const Xu=q((e,t)=>{if(Va.isActive)return!1;if(dn().some(e=>"prompt"===e.mode||"bash"===e.mode))return!1;const o=wn();Ua(o);const s=Co({content:e,isMeta:!!t?.isMeta||void 0});return Iu([s],o,!0,[],Mi),!0},[Iu,Mi,Pi]),Ju=Jt({setInputValueRaw:yc,inputValueRef:Tc,insertTextRef:vc});if(Qs({enabled:on(),isLoading:Wa,focusedInputDialog:uu,onSubmitMessage:Xu}),Lo({isLoading:Wa,onSubmitMessage:Xu}),Ys(bl),e("AGENT_TRIGGERS")){const e=Pi.getState().kairosEnabled;tn({isLoading:Wa,assistantMode:e,setMessages:Gl})}O(()=>{fi.some(e=>"now"===e.priority)&&Na.current?.abort("interrupt")},[fi]),O(()=>(async function(){ou();const e=await St();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)Gm.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})}(),()=>{Tn.shutdown()}),[]);const{internal_eventEmitter:Ku}=R(),[Wu,Gu]=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=()=>{Gu(e=>e+1)};return Ku?.on("suspend",handleSuspend),Ku?.on("resume",handleResume),()=>{Ku?.off("suspend",handleSuspend),Ku?.off("resume",handleResume)}},[Ku]);const Qu=N(()=>{if(!Wa)return null;const e=Xl.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(Xl.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(Xl,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}`},[Xl,Wa]),Yu=q(()=>{Sc({messagesLength:Xl.length,streamingToolUsesLength:Ma.length})},[Xl.length,Ma.length]),zu=q(()=>{Sc(null)},[]),Zu=Lr()&&!si,ep=U(null),[tp,op]=B(!1),[sp,np]=B(""),[rp,ip]=B(0),[ap,lp]=B(0),cp=q((e,t)=>{ip(e),lp(t)},[]);y((e,t,o)=>{if(t.ctrl||t.meta)return;if("/"===e)return ep.current?.setAnchor(),op(!0),void o.stopImmediatePropagation();const s=e[0];if(("n"===s||"N"===s)&&e===s.repeat(e.length)&&rp>0){const t="n"===s?ep.current?.nextMatch:ep.current?.prevMatch;if(t)for(let o=0;o<e.length;o++)t();o.stopImmediatePropagation()}},{isActive:"transcript"===qi&&Zu&&!tp&&!Vi});const{setQuery:mp,scanElement:up,setPositions:pp}=k(),dp=v().columns,fp=L.useRef(dp);L.useEffect(()=>{fp.current!==dp&&(fp.current=dp,(sp||tp)&&(op(!1),np(""),ip(0),lp(0),ep.current?.disarmSearch(),mp("")))},[dp,sp,tp,mp]),y((e,t,o)=>{if(!t.ctrl&&!t.meta){if("q"===e)return zu(),void o.stopImmediatePropagation();if("["!==e||Vi){if("v"===e){if(o.stopImmediatePropagation(),Qi.current)return;Qi.current=!0;const e=Wi.current,setStatus=t=>{e===Wi.current&&(clearTimeout(Gi.current),Ki(t))};setStatus(`rendering ${fc.length} messages…`),(async()=>{try{const e=Math.max(80,(process.stdout.columns??80)-6),t=(await j(fc,ja,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===Wi.current&&(Gi.current=setTimeout(e=>e(""),4e3,Ki))})()}}else Xi(!0),Fi(!0),o.stopImmediatePropagation()}},{isActive:"transcript"===qi&&Zu&&!tp});const gp="transcript"===qi&&Zu;O(()=>{gp||(np(""),ip(0),lp(0),op(!1),Wi.current++,clearTimeout(Gi.current),Xi(!1),Ki(""))},[gp]),O(()=>{mp(gp?sp:""),gp||pp(null)},[gp,sp,mp,pp]);const hp={screen:qi,setScreen:Hi,showAllInTranscript:$i,setShowAllInTranscript:Fi,messageCount:Xl.length,onEnterTranscript:Yu,onExitTranscript:zu,virtualScrollActive:Zu,searchBarOpen:tp},Sp=hc?fc.slice(0,hc.messagesLength):fc,Cp=hc?Ma.slice(0,hc.streamingToolUsesLength):Ma;if(qt({onOpenBackgroundTasks:ql?void 0:()=>vm(!0)}),$t(),"transcript"===qi){const e=!Lr()||si||Vi?void 0:Ha,n=o(Ko,{messages:Sp,tools:ja,commands:wa,verbose:!0,toolJSX:null,toolUseConfirmQueue:[],inProgressToolUseIDs:Rc,isMessageSelectorVisible:!1,conversationId:am,screen:qi,agentDefinitions:ui,streamingToolUses:Cp,showAllInTranscript:$i,onOpenRateLimitOptions:Du,isLoading:Wa,hidePastThinking:!0,streamingThinking:Da,scrollRef:e,jumpRef:ep,onSearchMatchesChange:cp,scanElement:up,setPositions:pp,disableRenderCap:Vi}),r=fl&&o(A,{flexDirection:"column",width:"100%",children:fl.jsx}),i=t(Ot,{children:[o(AnimatedTerminalTitle,{isAnimating:Hl,title:Ul,disabled:ti,noPrefix:Vl}),o(_t,{...hp}),o(Kt,{voiceHandleKeyEvent:Ju.handleKeyEvent,stripTrailing:Ju.stripTrailing,resetAnchor:Ju.resetAnchor,isActive:!fl?.isLocalJSXCommand}),o(Lt,{onSubmit:wu,isActive:!fl?.isLocalJSXCommand}),e?o(Br,{scrollRef:Ha,isActive:"ultraplan-choice"!==uu,isModal:!tp,onScroll:()=>ep.current?.disarmSearch()}):null,o(Bt,{...gu}),e?o(Er,{scrollRef:Ha,scrollable:t(s,{children:[n,r,o(Wn,{})]}),bottom:tp?o(TranscriptSearchBar,{jumpRef:ep,initialQuery:"",count:rp,current:ap,onClose:e=>{np(rp>0?e:""),op(!1),e||(ip(0),lp(0),ep.current?.setSearchQuery(""))},onCancel:()=>{op(!1),ep.current?.setSearchQuery(""),ep.current?.setSearchQuery(sp),mp(sp)},setHighlight:mp}):o(TranscriptModeFooter,{showAllInTranscript:$i,virtualScroll:!0,status:Ji||void 0,searchBadge:sp&&rp>0?{current:ap,count:rp}:void 0})}):t(s,{children:[n,r,o(Wn,{}),o(TranscriptModeFooter,{showAllInTranscript:$i,virtualScroll:!1,suppressShowAll:Vi,status:Ji||void 0})]})]});return e?o(Ur,{mouseTracking:Nr(),children:i}):i}const yp=Ii?Ti[Ii]:void 0,Tp=yp&&Ws(yp)?yp:void 0,vp=Tp??(yp&&_e(yp)?yp:void 0),kp=Vc||!Wa,jp=vp?vp.messages??[]:kp?Xl:fc,bp=Ga&&!vp&&jp.length<=Ya.current?Ga:void 0,Ip="tool-permission"===uu?o(ze,{onDone:()=>Il(([e,...t])=>t),onReject:fu,toolUseConfirm:bl[0],toolUseContext:Tu(Xl,Xl,La??wn(),Mi),verbose:li,workerBadge:bl[0]?.workerBadge,setStickyFooter:Lr()?wl:void 0},bl[0]?.toolUseID):null,Ap=dp<Pr,wp=!fl?.shouldHidePromptInput&&!uu&&!Tm,Rp=Lr()&&!0===fl?.isLocalJSXCommand,Pp=(hl.length>0?hl[hl.length-1]?.element:null)??(Rp?fl.jsx:null),xp=o(V.Provider,{value:{stack:hl,pushModal:Cl,replaceModal:yl,popModal:Tl,clearModals:vl},children:t(Ot,{children:[o(AnimatedTerminalTitle,{isAnimating:Hl,title:Ul,disabled:ti,noPrefix:Vl}),o(_t,{...hp}),o(Kt,{voiceHandleKeyEvent:Ju.handleKeyEvent,stripTrailing:Ju.stripTrailing,resetAnchor:Ju.resetAnchor,isActive:!fl?.isLocalJSXCommand}),o(Lt,{onSubmit:wu,isActive:!fl?.isLocalJSXCommand}),o(Br,{scrollRef:Ha,isActive:Lr()&&(null!=Pp||!uu||"tool-permission"===uu),onScroll:Pp||Ip||vp?void 0:pc}),e("MESSAGE_ACTIONS")&&Lr()&&!ni?o(Hr,{handlers:Hu,isActive:null!==sc}):null,o(Bt,{...gu}),o(Rn,{dynamicMcpConfig:Ni,isStrictMcpConfig:lt,children:o(Er,{scrollRef:Ha,overlay:Ip,bottomFloat:e("BUDDY")&&wp&&!Ap?o(Rr,{}):void 0,modal:Pp,modalScrollRef:$a,dividerYRef:zl,hidePill:!!vp,hideSticky:!!Tp,newMessageCount:ac?.count??0,onPillClick:()=>{nc(null),tc(Ha.current)},scrollable:t(s,{children:[o(Go,{}),o(Ko,{messages:jp,tools:ja,commands:wa,verbose:li,toolJSX:fl,toolUseConfirmQueue:bl,inProgressToolUseIDs:Tp?Tp.inProgressToolUseIDs??new Set:Rc,isMessageSelectorVisible:tm,conversationId:am,screen:qi,streamingToolUses:Ma,showAllInTranscript:$i,agentDefinitions:ui,onOpenRateLimitOptions:Du,isLoading:Wa,streamingText:Wa&&!vp?Jc:null,isBriefOnly:!vp&&Li,unseenDivider:vp?void 0:ac,scrollRef:Lr()?Ha:void 0,trackStickyPrompt:!!Lr()||void 0,cursor:sc,setCursor:nc,cursorNavRef:rc}),o(mr,{}),!jr&&bp&&!Pp&&o(cr,{param:{text:bp,type:"text"},addMargin:!0,verbose:li}),fl&&!(fl.isLocalJSXCommand&&fl.isImmediate)&&!Rp&&o(A,{flexDirection:"column",width:"100%",children:fl.jsx}),!1,e("WEB_BROWSER_TOOL")?br&&o(br.WebBrowserPanel,{}):null,o(A,{flexGrow:1}),Bm&&o(ut,{mode:Ra,spinnerTip:gi,responseLengthRef:Bc,apiMetricsRef:qc,overrideMessage:Gc,spinnerSuffix:Qu,verbose:li,loadingStartTimeRef:Za,totalPausedMsRef:el,pauseStartTimeRef:tl,overrideColor:Yc,overrideShimmerColor:Zc,hasActiveTools:Rc.size>0,leaderIsIdle:!Wa}),!Bm&&!Wa&&!Ga&&!Em&&Li&&!vp&&o(pt,{}),Lr()&&o(ot,{})]}),bottom:t(A,{flexDirection:e("BUDDY")&&Ap?"column":"row",width:"100%",alignItems:e("BUDDY")&&Ap?void 0:"flex-end",children:[e("BUDDY")&&Ap&&Lr()&&wp?o(wr,{}):null,t(A,{flexDirection:"column",flexGrow:1,children:[Al,fl?.isLocalJSXCommand&&fl.isImmediate&&!Rp&&o(A,{flexDirection:"column",width:"100%",children:fl.jsx}),!Bm&&!fl?.isLocalJSXCommand&&hi&&va&&va.length>0&&o(A,{width:"100%",flexDirection:"column",children:o(Wo,{tasks:va,isStandalone:!0})}),"sandbox-permission"===uu&&o(Kn,{hostPattern:Rl[0].hostPattern,onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=Rl[0];if(!s)return;const n=s.hostPattern.host;if(o){const e={type:"addRules",rules:[{toolName:so,ruleContent:`domain:${n}`}],behavior:t?"allow":"deny",destination:"localSettings"};Ai(t=>({...t,toolPermissionContext:Qt(t.toolPermissionContext,e)})),zt(e),Vn.refreshConfig()}Pl(e=>(e.filter(e=>e.hostPattern.host===n).forEach(e=>e.resolvePromise(t)),e.filter(e=>e.hostPattern.host!==n)));const r=El.current.get(n);if(r){for(const e of r)e();El.current.delete(n)}}},Rl[0].hostPattern.host),"prompt"===uu&&o(et,{title:xl[0].title,toolInputSummary:xl[0].toolInputSummary,request:xl[0].request,onRespond:e=>{const t=xl[0];t&&(t.resolve({prompt_response:t.request.prompt,selected:e}),Ml(([,...e])=>e))},onAbort:()=>{const e=xl[0];e&&(e.reject(new Error("Prompt cancelled by user")),Ml(([,...e])=>e))}},xl[0].request.prompt),Si&&o(Me,{toolName:Si.toolName,description:Si.description}),Ci&&o(Me,{toolName:"Network Access",description:`Waiting for leader to approve network access to ${Ci.host}`}),"worker-sandbox-permission"===uu&&o(Kn,{hostPattern:{host:vi.queue[0].host,port:void 0},onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=vi.queue[0];if(!s)return;const n=s.host;if(we(s.workerName,s.requestId,n,t,yi?.teamName),o&&t){const e={type:"addRules",rules:[{toolName:so,ruleContent:`domain:${n}`}],behavior:"allow",destination:"localSettings"};Ai(t=>({...t,toolPermissionContext:Qt(t.toolPermissionContext,e)})),zt(e),Vn.refreshConfig()}Ai(e=>({...e,workerSandboxPermissions:{...e.workerSandboxPermissions,queue:e.workerSandboxPermissions.queue.slice(1)}}))}},vi.queue[0].requestId),"elicitation"===uu&&o(Ze,{event:ki.queue[0],onResponse:(e,t)=>{const o=ki.queue[0];if(!o)return;o.respond({action:e,content:t});"url"===o.params.mode&&"accept"===e||Ai(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}}))},onWaitingDismiss:e=>{const t=ki.queue[0];Ai(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}})),t?.onWaitingDismiss?.(e)}},ki.queue[0].serverName+":"+String(ki.queue[0].requestId)),"cost"===uu&&o(D,{onDone:()=>{im(!1),Sm(!0),ao(e=>({...e,hasAcknowledgedCostThreshold:!0})),mo("tengu_cost_threshold_acknowledged",{})}}),"idle-return"===uu&&cm&&o(_,{idleMinutes:cm.idleMinutes,totalInputTokens:p(),onDone:async e=>{const t=cm;if(mm(null),mo("tengu_idle_return_action",{action:e,idleMinutes:Math.round(t.idleMinutes),messageCount:Kl.current.length,totalInputTokens:p()}),"dismiss"!==e){if("never"===e&&ao(e=>e.idleReturnDismissed?e:{...e,idleReturnDismissed:!0}),"clear"===e){const{clearConversation:e}=await import("../commands/clear/conversation.js");await e({setMessages:Gl,readFileState:Gm.current,discoveredSkillNames:zm.current,loadedNestedMemoryPaths:Zm.current,getAppState:()=>Pi.getState(),setAppState:Ai,setConversationId:lm}),Ol.current=!1,Ll(void 0),Qm.current.clear(),Ym.current=0}dm.current=!0,Eu.current(t.input,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})}else kc(t.input)}}),"ide-onboarding"===uu&&o(kn,{onDone:()=>la(!1),installationStatus:ra}),!1,!1,"effort-callout"===uu&&o(jn,{model:Mi,onDone:e=>{pa(!1),"dismiss"!==e&&Ai(t=>({...t,effortValue:e}))}}),"remote-callout"===uu&&o(In,{onDone:e=>{Ai(t=>t.showRemoteCallout?{...t,showRemoteCallout:!1,..."enable"===e&&{replBridgeEnabled:!0,replBridgeExplicit:!0,replBridgeOutboundOnly:!1}}:t)}}),iu,"plugin-hint"===uu&&Ca&&o(sr,{pluginName:Ca.pluginName,pluginDescription:Ca.pluginDescription,marketplaceName:Ca.marketplaceName,sourceCommand:Ca.sourceCommand,onResponse:ya}),"lsp-recommendation"===uu&&ha&&o(tr,{pluginName:ha.pluginName,pluginDescription:ha.pluginDescription,fileExtension:ha.fileExtension,onResponse:Sa}),"desktop-upsell"===uu&&o(nr,{onDone:()=>ga(!1)}),e("ULTRAPLAN")?"ultraplan-choice"===uu&&ji&&o(UltraplanChoiceDialog,{plan:ji.plan,sessionId:ji.sessionId,taskId:ji.taskId,setMessages:Gl,readFileState:Gm.current,getAppState:()=>Pi.getState(),setConversationId:lm}):null,e("ULTRAPLAN")?"ultraplan-launch"===uu&&bi&&o(UltraplanLaunchDialog,{onChoice:(e,t)=>{const o=bi.blurb;if(Ai(e=>e.ultraplanLaunchPending?{...e,ultraplanLaunchPending:void 0}:e),"cancel"===e)return;Gl(e=>[...e,bo(Io("ultraplan",o))]);const appendStdout=e=>Gl(t=>[...t,bo(`<${xo}>${Mo(e)}</${xo}>`)]);launchUltraplan({blurb:o,getAppState:()=>Pi.getState(),setAppState:Ai,signal:wn().signal,disconnectedBridge:t?.disconnectedBridge,onSessionReady:e=>{if(!Va.isActive)return void appendStdout(e);const t=Va.subscribe(()=>{Va.isActive||(t(),Pi.getState().ultraplanSessionUrl&&appendStdout(e))})}}).then(appendStdout).catch(Xt)}}):null,Um(),!fl?.shouldHidePromptInput&&!uu&&!lu&&!jr&&!sc&&t(s,{children:[su&&o(yr,{onRun:Pu,onCancel:xu,reason:vr(su)}),"closed"!==Vm.state?o(En,{state:Vm.state,lastResponse:Vm.lastResponse,handleSelect:Vm.handleSelect,inputValue:Cc,setInputValue:kc,onRequestFeedback:Mu}):"closed"!==Xm.state?o(En,{state:Xm.state,lastResponse:Xm.lastResponse,handleSelect:Xm.handleSelect,handleTranscriptSelect:Xm.handleTranscriptSelect,inputValue:Cc,setInputValue:kc,onRequestFeedback:Mu,message:"How well did Claude use its memory? (optional)"}):o(En,{state:Fm.state,lastResponse:Fm.lastResponse,handleSelect:Fm.handleSelect,handleTranscriptSelect:Fm.handleTranscriptSelect,inputValue:Cc,setInputValue:kc,onRequestFeedback:ru.current?void 0:Mu}),"closed"!==Jm.state&&o(En,{state:Jm.state,lastResponse:null,handleSelect:()=>{},handleTranscriptSelect:Jm.handleTranscriptSelect,inputValue:Cc,setInputValue:kc}),!1,$m&&o(Ir,{}),o(tt,{debug:i,ideSelection:ta,hasSuppressedDialogs:!!pu,isLocalJSXCommandActive:ql,getToolUseContext:Tu,toolPermissionContext:ai,setToolPermissionContext:Su,apiKeyStatus:tu,commands:wa,agents:ui.activeAgents,isLoading:Wa,onExit:_u,verbose:li,messages:Xl,onAutoUpdaterResult:ul,autoUpdaterResult:ml,input:Cc,onInputChange:kc,mode:jc,onModeChange:bc,stashedPrompt:Ic,setStashedPrompt:Ac,submitCount:Nc,onShowMessageSelector:Lu,onMessageActionsEnter:e("MESSAGE_ACTIONS")&&Lr()&&!ni?qu:void 0,mcpClients:ea,pastedContents:Lc,setPastedContents:Oc,vimMode:Cm,setVimMode:ym,showBashesDialog:Tm,setShowBashesDialog:vm,onSubmit:wu,onAgentSubmit:Ru,isSearchingHistory:km,setIsSearchingHistory:jm,helpOpen:bm,setHelpOpen:Im,insertTextRef:vc,voiceInterimRange:Ju.interimRange}),o(st,{messages:Xl}),o(Sn,{onBackgroundSession:ku,isLoading:Wa})]}),sc&&o($r,{cursor:sc}),"message-selector"===uu&&o(We,{messages:Xl,preselectedMessage:sm,onPreRestore:onCancel,onRestoreCode:async e=>{await _s(e=>{Ai(t=>({...t,fileHistory:e(t.fileHistory)}))},e.uuid)},onSummarize:async(t,o,s="from")=>{const n=ho(Xl),r=n.indexOf(t);if(-1===r)return void Gl(e=>[...e,jo("That message is no longer in the active context (snipped or pre-compact). Choose a more recent message.","warning")]);const i=wn(),a=Tu(n,[],i,Mi),l=a.getAppState(),c=await dt(a.options.tools,a.options.mainLoopModel,Array.from(l.toolPermissionContext.additionalWorkingDirectories.keys()),a.options.mcpClients),m=ft({mainThreadAgentDefinition:void 0,toolUseContext:a,customSystemPrompt:a.options.customSystemPrompt,defaultSystemPrompt:c,appendSystemPrompt:a.options.appendSystemPrompt}),[u,p]=await Promise.all([ht(),gt()]),d=await Es(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(Lr()&&"from"===s?Gl(e=>{const o=e.findIndex(e=>e.uuid===t.uuid);return[...e.slice(0,-1===o?0:o),...h]}):Gl(h),(e("PROACTIVE")||e("KAIROS"))&&en?.setContextBlocked(!1),lm(zo()),Ps(a.options.querySource),"from"===s){const e=po(t);e&&(kc(e.text),bc(e.mode))}const S=Ut("app:toggleTranscript","Global","ctrl+o");Yi({key:"summarize-ctrl-o-hint",text:`Conversation summarized (${S} for history)`,priority:"medium",timeoutMs:8e3})},onRestoreMessage:Uu,onClose:()=>{om(!1),nm(void 0)}}),!1]}),!e("BUDDY")||Ap&&Lr()||!wp?null:o(wr,{})]})})},Wu)]})});return Lr()?o(Ur,{mouseTracking:Nr(),children:xp}):xp}
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 x,useTerminalFocus as P,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 xe,getAgentName as Pe}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{SessionTokenFooter as st}from"../components/SessionTokenFooter.js";import{useRemoteSession as nt}from"../hooks/useRemoteSession.js";import{useDirectConnect as rt}from"../hooks/useDirectConnect.js";import{useSSHSession as it}from"../hooks/useSSHSession.js";import{useAssistantHistory as at}from"../hooks/useAssistantHistory.js";import{SkillImprovementSurvey as lt}from"../components/SkillImprovementSurvey.js";import{useSkillImprovementSurvey as ct}from"../hooks/useSkillImprovementSurvey.js";import{useMoreRight as mt}from"../moreright/useMoreRight.js";import{SpinnerWithVerb as ut,BriefIdleStatus as pt}from"../components/Spinner.js";import{getSystemPrompt as dt}from"../constants/prompts.js";import{buildEffectiveSystemPrompt as ft}from"../utils/systemPrompt.js";import{getSystemContext as gt,getUserContext as ht}from"../context.js";import{getMemoryFiles as St}from"../utils/claudemd.js";import{startBackgroundHousekeeping as Ct}from"../utils/backgroundHousekeeping.js";import{getTotalCost as yt,saveCurrentSessionCosts as Tt,resetCostState as vt,getStoredSessionCosts as kt}from"../cost-tracker.js";import{useCostSummary as jt}from"../costHook.js";import{useFpsMetrics as bt}from"../context/fpsMetrics.js";import{useAfterFirstRender as It}from"../hooks/useAfterFirstRender.js";import{useDeferredHookMessages as At}from"../hooks/useDeferredHookMessages.js";import{addToHistory as wt,removeLastFromHistory as Rt,expandPastedTextRefs as xt,parseReferences as Pt}from"../history.js";import{prependModeCharacterToInput as Mt}from"../components/PromptInput/inputModes.js";import{prependToShellHistoryCache as Et}from"../utils/suggestions/shellHistoryCompletion.js";import{useApiKeyVerification as Dt}from"../hooks/useApiKeyVerification.js";import{GlobalKeybindingHandlers as _t}from"../hooks/useGlobalKeybindings.js";import{CommandKeybindingHandlers as Lt}from"../hooks/useCommandKeybindings.js";import{KeybindingSetup as Ot}from"../keybindings/KeybindingProviderSetup.js";import{useShortcutDisplay as Nt}from"../keybindings/useShortcutDisplay.js";import{getShortcutDisplay as Ut}from"../keybindings/shortcutFormat.js";import{CancelRequestHandler as Bt}from"../hooks/useCancelRequest.js";import{useBackgroundTaskNavigation as qt}from"../hooks/useBackgroundTaskNavigation.js";import{useSwarmInitialization as Ht}from"../hooks/useSwarmInitialization.js";import{useTeammateViewAutoExit as $t}from"../hooks/useTeammateViewAutoExit.js";import{errorMessage as Ft}from"../utils/errors.js";import{isHumanTurn as Vt}from"../utils/messagePredicates.js";import{logError as Xt}from"../utils/log.js";const Jt=r("../hooks/useVoiceIntegration.js").useVoiceIntegration,Kt=r("../hooks/useVoiceIntegration.js").VoiceKeybindingHandler,useFrustrationDetection=()=>({state:"closed",handleTranscriptSelect:()=>{}}),useAntOrgWarningNotification=()=>{},Wt=e("COORDINATOR_MODE")?r("../coordinator/coordinatorMode.js").getCoordinatorUserContext:()=>({});import Gt from"../hooks/useCanUseTool.js";import{applyPermissionUpdate as Qt,applyPermissionUpdates as Yt,persistPermissionUpdate as zt}from"../utils/permissions/PermissionUpdate.js";import{buildPermissionUpdates as Zt}from"../components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js";import{stripDangerousPermissionsForAutoMode as eo}from"../utils/permissions/permissionSetup.js";import{getScratchpadDir as to,isScratchpadEnabled as oo}from"../utils/permissions/filesystem.js";import{WEB_FETCH_TOOL_NAME as so}from"../tools/WebFetchTool/prompt.js";import{SLEEP_TOOL_NAME as no}from"../tools/SleepTool/prompt.js";import{clearSpeculativeChecks as ro}from"../tools/BashTool/bashPermissions.js";import{getGlobalConfig as io,saveGlobalConfig as ao,getGlobalConfigWriteCount as lo}from"../utils/config.js";import{hasConsoleBillingAccess as co}from"../utils/billing.js";import{logEvent as mo}from"../services/analytics/index.js";import{getFeatureValue_CACHED_MAY_BE_STALE as uo}from"../services/analytics/growthbook.js";import{textForResubmit as po,handleMessageFromStream as fo,isCompactBoundaryMessage as go,getMessagesAfterCompactBoundary as ho,getContentText as So,createUserMessage as Co,createAssistantMessage as yo,createTurnDurationMessage as To,createAgentsKilledMessage as vo,createApiMetricsMessage as ko,createSystemMessage as jo,createCommandInputMessage as bo,formatCommandInputTags as Io}from"../utils/messages.js";import{generateSessionTitle as Ao}from"../utils/sessionTitle.js";import{BASH_INPUT_TAG as wo,COMMAND_MESSAGE_TAG as Ro,COMMAND_NAME_TAG as xo,LOCAL_COMMAND_STDOUT_TAG as Po}from"../constants/xml.js";import{escapeXml as Mo}from"../utils/xml.js";import{gracefulShutdownSync as Eo}from"../utils/gracefulShutdown.js";import{handlePromptSubmit as Do}from"../utils/handlePromptSubmit.js";import{useQueueProcessor as _o}from"../hooks/useQueueProcessor.js";import{useMailboxBridge as Lo}from"../hooks/useMailboxBridge.js";import{queryCheckpoint as Oo,logQueryProfileReport as No}from"../utils/queryProfiler.js";import{query as Uo}from"../query.js";import{mergeClients as Bo,useMergedClients as qo}from"../hooks/useMergedClients.js";import{getQuerySourceForREPL as Ho}from"../utils/promptCategory.js";import{useMergedTools as $o}from"../hooks/useMergedTools.js";import{mergeAndFilterTools as Fo}from"../utils/toolPool.js";import{useMergedCommands as Vo}from"../hooks/useMergedCommands.js";import{useSkillsChange as Xo}from"../hooks/useSkillsChange.js";import{useManagePlugins as Jo}from"../hooks/useManagePlugins.js";import{Messages as Ko}from"../components/Messages.js";import{TaskListV2 as Wo}from"../components/TaskListV2.js";import{TeammateViewHeader as Go}from"../components/TeammateViewHeader.js";import{useTasksV2WithCollapseEffect as Qo}from"../hooks/useTasksV2.js";import{maybeMarkProjectOnboardingComplete as Yo}from"../projectOnboardingState.js";import{randomUUID as zo}from"crypto";import{processSessionStartHooks as Zo}from"../utils/sessionStart.js";import{executeSessionEndHooks as es,getSessionEndHookTimeoutMs as ts}from"../utils/hooks.js";import{useIdeSelection as os}from"../hooks/useIdeSelection.js";import{getTools as ss,assembleToolPool as ns}from"../tools.js";import{resolveAgentTools as rs}from"../tools/AgentTool/agentToolUtils.js";import{resumeAgentBackground as is}from"../tools/AgentTool/resumeAgent.js";import{useMainLoopModel as as}from"../hooks/useMainLoopModel.js";import{useAppState as ls,useSetAppState as cs,useAppStateStore as ms}from"../state/AppState.js";import{copyPlanForFork as us,copyPlanForResume as ps,getPlanSlug as ds,setPlanSlug as fs}from"../utils/plans.js";import{clearSessionMetadata as gs,resetSessionFilePointer as hs,adoptResumedSessionFile as Ss,removeTranscriptMessage as Cs,restoreSessionMetadata as ys,getCurrentSessionTitle as Ts,isEphemeralToolProgress as vs,isLoggableMessage as ks,saveWorktreeState as js,getAgentTranscript as bs}from"../utils/sessionStorage.js";import{deserializeMessages as Is}from"../utils/conversationRecovery.js";import{extractReadFilesFromMessages as As,extractBashToolsFromMessages as ws}from"../utils/queryHelpers.js";import{resetMicrocompactState as Rs}from"../services/compact/microCompact.js";import{runPostCompactCleanup as xs}from"../services/compact/postCompactCleanup.js";import{provisionContentReplacementState as Ps,reconstructContentReplacementState as Ms}from"../utils/toolResultStorage.js";import{partialCompactConversation as Es}from"../services/compact/compact.js";import{fileHistoryMakeSnapshot as Ds,fileHistoryRewind as _s,copyFileHistoryForResume as Ls,fileHistoryEnabled as Os,fileHistoryHasAnyChanges as Ns}from"../utils/fileHistory.js";import{incrementPromptCount as Us}from"../utils/commitAttribution.js";import{recordAttributionSnapshot as Bs}from"../utils/sessionStorage.js";import{computeStandaloneAgentContext as qs,restoreAgentFromSession as Hs,restoreSessionStateFromLog as $s,restoreWorktreeForResume as Fs,exitRestoredWorktree as Vs}from"../utils/sessionRestore.js";import{isBgSession as Xs,updateSessionName as Js,updateSessionActivity as Ks}from"../utils/concurrentSessions.js";import{isInProcessTeammateTask as Ws}from"../tasks/InProcessTeammateTask/types.js";import{restoreRemoteAgentTasks as Gs}from"../tasks/RemoteAgentTask/RemoteAgentTask.js";import{useInboxPoller as Qs}from"../hooks/useInboxPoller.js";import{usePermissionWhatsAppBridge as Ys}from"../hooks/usePermissionWhatsAppBridge.js";import{useWebappMirror as zs}from"../hooks/useWebappMirror.js";import{useWebappPermissionBridge as Zs}from"../hooks/useWebappPermissionBridge.js";const en=e("PROACTIVE")||e("KAIROS")?r("../proactive/index.js"):null,PROACTIVE_NO_OP_SUBSCRIBE=e=>()=>{},PROACTIVE_FALSE=()=>!1,SUGGEST_BG_PR_NOOP=(e,t)=>!1,tn=((e("PROACTIVE")||e("KAIROS"))&&r("../proactive/useProactive.js").useProactive,e("AGENT_TRIGGERS")?r("../hooks/useScheduledTasks.js").useScheduledTasks:null);import{isAgentSwarmsEnabled as on}from"../utils/agentSwarmsEnabled.js";import{useTaskListWatcher as sn}from"../hooks/useTaskListWatcher.js";import{closeOpenDiffs as nn,getConnectedIdeClient as rn}from"../utils/ide.js";import{useIDEIntegration as an}from"../hooks/useIDEIntegration.js";import ln from"../commands/exit/index.js";import{ExitFlow as cn}from"../components/ExitFlow.js";import{getCurrentWorktreeSession as mn}from"../utils/worktree.js";import{popAllEditable as un,enqueue as pn,getCommandQueue as dn,getCommandQueueLength as fn,removeByFilter as gn}from"../utils/messageQueueManager.js";import{useCommandQueue as hn}from"../hooks/useCommandQueue.js";import{SessionBackgroundHint as Sn}from"../components/SessionBackgroundHint.js";import{startBackgroundSession as Cn}from"../tasks/LocalMainSessionTask.js";import{useSessionBackgrounding as yn}from"../hooks/useSessionBackgrounding.js";import{diagnosticTracker as Tn}from"../services/diagnosticTracking.js";import{handleSpeculationAccept as vn}from"../services/PromptSuggestion/speculation.js";import{IdeOnboardingDialog as kn}from"../components/IdeOnboardingDialog.js";import{EffortCallout as jn,shouldShowEffortCallout as bn}from"../components/EffortCallout.js";import{RemoteCallout as In}from"../components/RemoteCallout.js";import{activityManager as An}from"../utils/activityManager.js";import{createAbortController as wn}from"../utils/abortController.js";import{MCPConnectionManager as Rn}from"../services/mcp/MCPConnectionManager.js";import{useFeedbackSurvey as xn}from"../components/FeedbackSurvey/useFeedbackSurvey.js";import{useMemorySurvey as Pn}from"../components/FeedbackSurvey/useMemorySurvey.js";import{usePostCompactSurvey as Mn}from"../components/FeedbackSurvey/usePostCompactSurvey.js";import{FeedbackSurvey as En}from"../components/FeedbackSurvey/FeedbackSurvey.js";import{useInstallMessages as Dn}from"../hooks/notifs/useInstallMessages.js";import{useAwaySummary as _n}from"../hooks/useAwaySummary.js";import{useChromeExtensionNotification as Ln}from"../hooks/useChromeExtensionNotification.js";import{useOfficialMarketplaceNotification as On}from"../hooks/useOfficialMarketplaceNotification.js";import{usePromptsFromClaudeInChrome as Nn}from"../hooks/usePromptsFromClaudeInChrome.js";import{getTipToShowOnSpinner as Un,recordShownTip as Bn}from"../services/tips/tipScheduler.js";import{checkAndDisableBypassPermissionsIfNeeded as qn,checkAndDisableAutoModeIfNeeded as Hn,useKickOffCheckAndDisableBypassPermissionsIfNeeded as $n,useKickOffCheckAndDisableAutoModeIfNeeded as Fn}from"../utils/permissions/bypassPermissionsKillswitch.js";import{SandboxManager as Vn}from"../utils/sandbox/sandbox-adapter.js";import{SANDBOX_NETWORK_ACCESS_TOOL_NAME as Xn}from"../cli/structuredIO.js";import{useFileHistorySnapshotInit as Jn}from"../hooks/useFileHistorySnapshotInit.js";import{SandboxPermissionRequest as Kn}from"../components/permissions/SandboxPermissionRequest.js";import{SandboxViolationExpandedView as Wn}from"../components/SandboxViolationExpandedView.js";import{useSettingsErrors as Gn}from"../hooks/notifs/useSettingsErrors.js";import{useMcpConnectivityStatus as Qn}from"../hooks/notifs/useMcpConnectivityStatus.js";import{useAutoModeUnavailableNotification as Yn}from"../hooks/notifs/useAutoModeUnavailableNotification.js";import{AUTO_MODE_DESCRIPTION as zn}from"../components/AutoModeOptInDialog.js";import{useLspInitializationNotification as Zn}from"../hooks/notifs/useLspInitializationNotification.js";import{useLspPluginRecommendation as er}from"../hooks/useLspPluginRecommendation.js";import{LspRecommendationMenu as tr}from"../components/LspRecommendation/LspRecommendationMenu.js";import{useClaudeCodeHintRecommendation as or}from"../hooks/useClaudeCodeHintRecommendation.js";import{PluginHintMenu as sr}from"../components/ClaudeCodeHint/PluginHintMenu.js";import{DesktopUpsellStartup as nr,shouldShowDesktopUpsellStartup as rr}from"../components/DesktopUpsell/DesktopUpsellStartup.js";import{usePluginInstallationStatus as ir}from"../hooks/notifs/usePluginInstallationStatus.js";import{usePluginAutoupdateNotification as ar}from"../hooks/notifs/usePluginAutoupdateNotification.js";import{performStartupChecks as lr}from"../utils/plugins/performStartupChecks.js";import{UserTextMessage as cr}from"../components/messages/UserTextMessage.js";import{AwsAuthStatusBox as mr}from"../components/AwsAuthStatusBox.js";import{useRateLimitWarningNotification as ur}from"../hooks/notifs/useRateLimitWarningNotification.js";import{useDeprecationWarningNotification as pr}from"../hooks/notifs/useDeprecationWarningNotification.js";import{useNpmDeprecationNotification as dr}from"../hooks/notifs/useNpmDeprecationNotification.js";import{useIDEStatusIndicator as fr}from"../hooks/notifs/useIDEStatusIndicator.js";import{useModelMigrationNotifications as gr}from"../hooks/notifs/useModelMigrationNotifications.js";import{useCanSwitchToExistingSubscription as hr}from"../hooks/notifs/useCanSwitchToExistingSubscription.js";import{useTeammateLifecycleNotification as Sr}from"../hooks/notifs/useTeammateShutdownNotification.js";import{useFastModeNotification as Cr}from"../hooks/notifs/useFastModeNotification.js";import{AutoRunIssueNotification as yr,shouldAutoRunIssue as Tr,getAutoRunIssueReasonText as vr,getAutoRunCommand as kr}from"../utils/autoRunIssue.js";import{TungstenLiveMonitor as jr}from"../tools/TungstenTool/TungstenLiveMonitor.js";const br=e("WEB_BROWSER_TOOL")?r("../tools/WebBrowserTool/WebBrowserPanel.js"):null;import{IssueFlagBanner as Ir}from"../components/PromptInput/IssueFlagBanner.js";import{useIssueFlagBanner as Ar}from"../hooks/useIssueFlagBanner.js";import{CompanionSprite as wr,CompanionFloatingBubble as Rr,MIN_COLS_FOR_FULL_SPRITE as xr}from"../buddy/CompanionSprite.js";import{DevBar as Pr}from"../components/DevBar.js";import{REMOTE_SAFE_COMMANDS as Mr}from"../commands.js";import{FullscreenLayout as Er,useUnseenDivider as Dr,computeUnseenDivider as _r}from"../components/FullscreenLayout.js";import{isFullscreenEnvEnabled as Lr,maybeGetTmuxMouseHint as Or,isMouseTrackingEnabled as Nr}from"../utils/fullscreen.js";import{AlternateScreen as Ur}from"../ink/components/AlternateScreen.js";import{ScrollKeybindingHandler as Br}from"../components/ScrollKeybindingHandler.js";import{useMessageActions as qr,MessageActionsKeybindings as Hr,MessageActionsBar as $r}from"../components/messageActions.js";import{setClipboard as Fr}from"../ink/termio/osc.js";import{createAttachmentMessage as Vr,getQueuedCommandAttachments as Xr}from"../utils/attachments.js";const Jr=[],Kr={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=Nt("app:toggleTranscript","Global","ctrl+o"),d=Nt("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 Wr=["⠂","⠐"];function AnimatedTerminalTitle(e){const t=i(6),{isAnimating:o,title:s,disabled:n,noPrefix:r}=e,a=P(),[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?Wr[l]??"✳":"✳"} ${s}`),null}function _temp2(e){return e(_temp)}function _temp(e){return(e+1)%Wr.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:lt=!1,systemPrompt:Nt,appendSystemPrompt:lo,onBeforeQuery:ko,onTurnComplete:sn,disabled:jr=!1,mainThreadAgentDefinition:Pr,disableSlashCommands:Wr=!1,taskListId:Gr,remoteSessionConfig:Qr,directConnectConfig:Yr,sshSession:zr,thinkingConfig:Zr}){const ei=!!Qr,ti=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_TERMINAL_TITLE)||ye(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE),[]),oi=N(()=>!1,[]),si=N(()=>ye(process.env.CONTEXT_CODE_DISABLE_VIRTUAL_SCROLL)||ye(process.env.CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL),[]),ni=!!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=${jr}`),()=>Se("[REPL:unmount] REPL unmounting")),[jr]);const[ri,ii]=B(Pr),ai=ls(e=>e.toolPermissionContext),li=ls(e=>e.verbose),ci=ls(e=>e.mcp),mi=ls(e=>e.plugins),ui=ls(e=>e.agentDefinitions),pi=ls(e=>e.fileHistory),di=ls(e=>e.initialMessage),fi=hn(),gi=ls(e=>e.spinnerTip),hi="tasks"===ls(e=>e.expandedView),Si=ls(e=>e.pendingWorkerRequest),Ci=ls(e=>e.pendingSandboxRequest),yi=ls(e=>e.teamContext),Ti=ls(e=>e.tasks),vi=ls(e=>e.workerSandboxPermissions),ki=ls(e=>e.elicitation),ji=ls(e=>e.ultraplanPendingChoice),bi=ls(e=>e.ultraplanLaunchPending),Ii=ls(e=>e.viewingAgentTaskId),Ai=cs(),wi=Ii?Ti[Ii]:void 0,Ri=_e(wi)&&wi.retain&&!wi.diskLoaded;O(()=>{if(!Ii||!Ri)return;const e=Ii;bs(he(e)).then(t=>{Ai(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}}}})})},[Ii,Ri,Ai]);const xi=ms(),Pi=W(),Mi=as(),[Ei,Di]=B(n);Xo(ei?void 0:oe(),Di);const _i=L.useSyncExternalStore(en?.subscribeToProactiveChanges??PROACTIVE_NO_OP_SUBSCRIBE,en?.isProactiveActive??PROACTIVE_FALSE),Li=ls(e=>e.isBriefOnly),Oi=N(()=>ss(ai),[ai,_i,Li]);$n(),Fn();const[Ni,Ui]=B(de),Bi=q(e=>{Ui(e)},[Ui]),[qi,Hi]=B("prompt"),[$i,Fi]=B(!1),[Vi,Xi]=B(!1),[Ji,Ki]=B(""),Wi=U(0),Gi=U(void 0),Qi=U(!1),{addNotification:Yi,removeNotification:zi}=F();let Zi=SUGGEST_BG_PR_NOOP;const ea=qo(pe,ci.clients),[ta,oa]=B(void 0),[sa,na]=B(null),[ra,ia]=B(null),[aa,la]=B(!1),[ca,ma]=B(()=>!1),[ua,pa]=B(()=>bn(Mi)),da=ls(e=>e.showRemoteCallout),[fa,ga]=B(()=>rr());gr(),hr(),fr({ideSelection:ta,mcpClients:ea,ideInstallationStatus:ra}),Qn({mcpClients:ea}),Yn(),ir(),ar(),Gn(),ur(Mi),Cr(),pr(Mi),dr(),useAntOrgWarningNotification(),Dn(),Ln(),On(),Zn(),Sr();const{recommendation:ha,handleResponse:Sa}=er(),{recommendation:Ca,handleResponse:ya}=or(),Ta=N(()=>[...Oi,...C],[Oi,C]);Jo({enabled:!ei});const va=Qo();O(()=>{ei||lr(Ai)},[Ai,ei]),Nn(ei?Jr:ea,ai.mode),Ht(Ai,T,{enabled:!ei});const ka=$o(Ta,ci.tools,ai),{tools:ja,allowedAgentTypes:ba}=N(()=>{if(!ri)return{tools:ka,allowedAgentTypes:void 0};const e=rs(ri,ka,!1,!0);return{tools:e.resolvedTools,allowedAgentTypes:e.allowedAgentTypes}},[ri,ka]),Ia=Vo(Ei,mi.commands),Aa=Vo(Ia,ci.commands),wa=N(()=>Wr?[]:Aa,[Wr,Aa]);Ye(ei?Jr:ci.clients),os(ei?Jr:ci.clients,oa);const[Ra,xa]=B("responding"),Pa=U(Ra);Pa.current=Ra;const[Ma,Ea]=B([]),[Da,_a]=B(null);O(()=>{if(Da&&!Da.isStreaming&&Da.streamingEndedAt){const e=3e4-(Date.now()-Da.streamingEndedAt);if(e>0){const t=setTimeout(_a,e,null);return()=>clearTimeout(t)}_a(null)}},[Da]);const[La,Oa]=B(null),Na=U(null),Ua=q(e=>{Na.current=e,Oa(e)},[]),Ba=U(()=>{}),qa=U(()=>{}),Ha=U(null),$a=U(null),Fa=U(0),Va=L.useRef(new Ce).current,Xa=L.useSyncExternalStore(Va.subscribe,Va.getSnapshot),[Ja,Ka]=L.useState(Qr?.hasInitialPrompt??!1),Wa=Xa||Ja,[Ga,Qa]=L.useState(void 0),Ya=L.useRef(0),za=L.useRef(!1),Za=L.useRef(0),el=L.useRef(0),tl=L.useRef(null),ol=L.useCallback(()=>{Za.current=Date.now(),el.current=0,tl.current=null},[]),sl=L.useRef(!1);Xa&&!sl.current&&ol(),sl.current=Xa;const nl=L.useCallback(e=>{Ka(e),e&&ol()},[ol]),rl=L.useRef(null),il=L.useRef(void 0),al=L.useRef(void 0),[ll,cl]=L.useState(!1),[ml,ul]=B(null);O(()=>{ml?.notifications&&ml.notifications.forEach(e=>{Yi({key:"auto-updater-notification",text:e,priority:"low"})})},[ml,Yi]),O(()=>{Lr()&&Or().then(e=>{e&&Yi({key:"tmux-mouse-hint",text:e,priority:"low"})})},[]);const[pl,dl]=B(!1);O(()=>{0},[]);const[fl,gl]=B(null),[hl,Sl]=B([]),Cl=q(e=>{Sl(t=>[...t,e])},[]),yl=q(e=>{Sl(t=>0===t.length?[e]:[...t.slice(0,-1),e])},[]),Tl=q(()=>{Sl(e=>e.slice(0,-1))},[]),vl=q(()=>{Sl([])},[]),kl=U(null),jl=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 kl.current={...o,isLocalJSXCommand:!0},void gl(o)}return kl.current?e?.clearLocalJSX?(Se("Clearing local JSX command as requested"),kl.current=null,void gl(null)):void Se("Ignoring setToolJSX update because a local JSX command is active"):e?.clearLocalJSX?(Se("Clearing tool JSX (no local command active)"),void gl(null)):void gl(e)},[]),[bl,Il]=B([]),[Al,wl]=B(null),[Rl,xl]=B([]),[Pl,Ml]=B([]),El=U(new Map),Dl=!1!==ls(e=>e.settings.terminalTitleFromRename)?Ts(se()):void 0,[_l,Ll]=B(),Ol=U((T?.length??0)>0),Nl=ri?.agentType,Ul=Dl??Nl??_l??"Context Code",Bl=bl.length>0||Pl.length>0||Si||Ci,ql=!0===fl?.isLocalJSXCommand&&null!=fl?.jsx,Hl=Wa&&!Bl&&!ql;O(()=>{if(Wa&&!Bl&&!ql)return J(),()=>K()},[Wa,Bl,ql]);const $l=Bl||ql?"waiting":Wa?"busy":"idle",Fl="waiting"!==$l?void 0:bl.length>0?`approve ${bl[0].tool.name}`:Si?"worker request":Ci?"sandbox request":ql?"dialog open":"input needed";O(()=>{e("BG_SESSIONS")&&Ks({status:$l,waitingFor:Fl})},[$l,Fl]);const Vl=uo("tengu_terminal_sidebar",!1)&&(io().showStatusInTerminalTab??!1);E(ti||!Vl?null:$l),O(()=>(Ne(Il),()=>Ue()),[Il]);const[Xl,Jl]=B(T??[]),Kl=U(Xl),Wl=U(!1),Gl=q(e=>{const t=Kl.current,o="function"==typeof e?e(Kl.current):e;if(Kl.current=o,o.length<Ya.current)Ya.current=0;else if(o.length>t.length&&za.current){const e=o.length-t.length;(0===t.length||o[0]===t[0]?o.slice(-e):o.slice(0,e)).some(Vt)?za.current=!1:Ya.current=o.length}Jl(o)},[]),Ql=q(e=>{void 0!==e?(Ya.current=Kl.current.length,za.current=!0):za.current=!1,Qa(e)},[]),{dividerIndex:Yl,dividerYRef:zl,onScrollAway:Zl,onRepin:ec,jumpToNew:tc,shiftDivider:oc}=Dr(Xl.length);e("AWAY_SUMMARY")&&_n(Xl,Gl,Wa);const[sc,nc]=B(null),rc=U(null),ic=q(e=>{const t=Kl.current.find(t=>t.uuid===e)?.uuid,o=Kl.current.find(t=>t.uuid.slice(0,24)===e.slice(0,24))?.uuid,s=t??o;s?nc({uuid:s,msgType:"user",expanded:!1}):Yi({key:"timeline-jump-not-found",text:"Message no longer available in active transcript",color:"warning",priority:"medium",timeoutMs:3e3})},[Yi]),ac=N(()=>_r(Xl,Yl),[Yl,Xl.length]),lc=q(()=>{Ha.current?.scrollToBottom(),ec(),nc(null)},[ec,nc]),cc=Xl.at(-1),mc=null!=cc&&Vt(cc);O(()=>{mc&&lc()},[mc,cc,lc]);const{maybeLoadOlder:uc}=e("KAIROS")?at({config:Qr,setMessages:Gl,scrollRef:Ha,onPrepend:oc}):Kr,pc=q((t,o)=>{Fa.current=Date.now(),t?ec():(Zl(o),e("KAIROS")&&uc(o),e("BUDDY")&&Ai(e=>void 0===e.companionReaction?e:{...e,companionReaction:void 0}))},[ec,Zl,uc,Ai]),dc=At(M,Gl),fc=H(Xl),gc=Xl.length-fc.length;gc>0&&Se(`[useDeferredValue] Messages deferred by ${gc} (${fc.length}→${Xl.length})`);const[hc,Sc]=B(null),[Cc,yc]=B(()=>ke()),Tc=U(Cc);Tc.current=Cc;const vc=U(null),kc=q(e=>{Zi(Tc.current,e)||(""===Tc.current&&""!==e&&Date.now()-Fa.current>=3e3&&lc(),Tc.current=e,yc(e),cl(e.trim().length>0))},[cl,lc,Zi]);O(()=>{if(0===Cc.trim().length)return;const e=setTimeout(cl,1500,!1);return()=>clearTimeout(e)},[Cc]);const[jc,bc]=B("prompt"),[Ic,Ac]=B(),wc=q(e=>{const t=new Set(e);Di(e=>e.filter(e=>t.has(e.name)||Mr.has(e)))},[Di]),[Rc,xc]=B(new Set),Pc=U(!1),Mc=nt({config:Qr,setMessages:Gl,setIsLoading:nl,onInit:wc,setToolUseConfirmQueue:Il,tools:Ta,setStreamingToolUses:Ea,setStreamMode:xa,setInProgressToolUseIDs:xc}),Ec=rt({config:Yr,setMessages:Gl,setIsLoading:nl,setToolUseConfirmQueue:Il,tools:Ta}),Dc=it({session:zr,setMessages:Gl,setIsLoading:nl,setToolUseConfirmQueue:Il,tools:Ta}),_c=Dc.isRemoteMode?Dc:Ec.isRemoteMode?Ec:Mc,[Lc,Oc]=B({}),[Nc,Uc]=B(0),Bc=U(0),qc=U([]),Hc=q(e=>{const t=Bc.current;if(Bc.current=e(t),Bc.current>t){const e=qc.current;if(e.length>0){const t=e.at(-1);t.lastTokenTime=Date.now(),t.endResponseLength=Bc.current}}},[]),[$c,Fc]=B(null),Vc=!(ls(e=>e.settings.prefersReducedMotion)??!1)&&!G(),Xc=q(e=>{Vc&&Fc(e)},[Vc]),Jc=$c&&Vc&&$c.substring(0,$c.lastIndexOf("\n")+1)||null,[Kc,Wc]=B(0),[Gc,Qc]=B(null),[Yc,zc]=B(null),[Zc,em]=B(null),[tm,om]=B(!1),[sm,nm]=B(void 0),[rm,im]=B(!1),[am,lm]=B(zo()),[cm,mm]=B(null),um=U(Wa),pm=U(!1),dm=U(!1),fm=U(Kc);fm.current=Kc;const[gm]=B(()=>({current:Ps(T,ae)})),[hm,Sm]=B(io().hasAcknowledgedCostThreshold),[Cm,ym]=B("INSERT"),[Tm,vm]=B(!1),[km,jm]=B(!1),[bm,Im]=B(!1);O(()=>{ji&&Tm&&vm(!1)},[ji,Tm]);const Am=P(),wm=U(Am);wm.current=Am;const[Rm]=x(),xm=L.useRef(!1),Pm=q(()=>{if(xm.current)return;xm.current=!0;const e=Kl.current.slice(Ym.current);for(const t of ws(e))Qm.current.add(t);Ym.current=Kl.current.length,Un({theme:Rm,readFileState:Gm.current,bashTools:Qm.current}).then(async e=>{if(e){const t=await e.content({theme:Rm});Ai(e=>({...e,spinnerTip:t})),Bn(e)}else Ai(e=>void 0===e.spinnerTip?e:{...e,spinnerTip:void 0})})},[Ai,Rm]),Mm=q(()=>{nl(!1),Ql(void 0),Bc.current=0,qc.current=[],Fc(null),Ea([]),Qc(null),zc(null),em(null),Pm(),He(),ro()},[Pm]),Em=N(()=>De(Ti).some(e=>"running"===e.status),[Ti]);O(()=>{if(!Em&&null!==rl.current){const e=Date.now()-rl.current,t=il.current;rl.current=null,il.current=void 0,Gl(o=>[...o,To(e,t,f(o,ks))])}},[Em,Gl]);const Dm=U(!1);O(()=>{if(e("TRANSCRIPT_CLASSIFIER")){if("auto"!==ai.mode)return void(Dm.current=!1);if(Dm.current)return;if((io().autoPermissionsNotificationCount??0)>=3)return;const e=setTimeout((e,t)=>{e.current=!0,ao(e=>{const t=e.autoPermissionsNotificationCount??0;return t>=3?e:{...e,autoPermissionsNotificationCount:t+1}}),t(e=>[...e,jo(zn,"warning")])},800,Dm,Gl);return()=>clearTimeout(e)}},[ai.mode,Gl]);const _m=U(!1);O(()=>{if(_m.current)return;const e=mn();if(!e?.creationDurationMs||e.usedSparsePaths)return;if(e.creationDurationMs<15e3)return;_m.current=!0;const t=Math.round(e.creationDurationMs/1e3);Gl(e=>[...e,jo(`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")])},[Gl]);const Lm=N(()=>{const e=Xl.findLast(e=>"assistant"===e.type);if("assistant"!==e?.type)return!1;const t=e.message.content.filter(e=>"tool_use"===e.type&&Rc.has(e.id));return t.length>0&&t.every(e=>"tool_use"===e.type&&e.name===no)},[Xl,Rc]),{onBeforeQuery:Om,onTurnComplete:Nm,render:Um}=mt({enabled:oi,setMessages:Gl,inputValue:Cc,setInputValue:kc,setToolJSX:jl}),Bm=(!fl||!0===fl.showSpinner)&&0===bl.length&&0===Pl.length&&(Wa||Ga||Em||fn()>0)&&!Si&&!Lm&&(!Jc||Li),qm=bl.length>0||Pl.length>0||Rl.length>0||ki.queue.length>0||vi.queue.length>0,Hm=xn(Xl,Wa,Nc,"session",qm),$m=(ct(Gl),Ar(Xl,Nc)),Fm=N(()=>({...Hm,handleSelect:e=>{ru.current=!1;const t=Hm.handleSelect(e);"bad"===e&&!t&&Tr("feedback_survey_bad")&&(nu("feedback_survey_bad"),ru.current=!0)}}),[Hm]),Vm=Mn(Xl,Wa,qm,{enabled:!ei}),Xm=Pn(Xl,Wa,qm,{enabled:!ei}),Jm=useFrustrationDetection(Xl,Wa,qm,"closed"!==Fm.state||"closed"!==Vm.state||"closed"!==Xm.state);an({autoConnectIdeFlag:ve,ideToInstallExtension:sa,setDynamicMcpConfig:Ui,setShowIdeOnboarding:la,setIDEInstallationState:ia}),Jn(ie,pi,e=>Ai(t=>({...t,fileHistory:e})));const Km=q(async(t,o,s)=>{const n=performance.now();try{const i=Is(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());Ai(e=>({...e,agentDefinitions:{...s,allAgents:s.allAgents,activeAgents:o(s.allAgents)}})),i.push(jo(e,"warning"))}}const a=ts();await es("resume",{getAppState:()=>xi.getState(),setAppState:Ai,signal:AbortSignal.timeout(a),timeoutMs:a});const l=await Zo("resume",{sessionId:t,agentType:ri?.agentType,model:Mi});i.push(...l),"fork"===s?us(o,ge(t)):ps(o,ge(t)),$s(o,Ai),o.fileHistorySnapshots&&Ls(o);const{agentDefinition:c}=Hs(o.agentSetting,Pr,ui);ii(c),Ai(e=>({...e,agent:c?.agentType})),Ai(e=>({...e,standaloneAgentContext:qs(o.agentName,o.agentColor)})),Js(o.agentName),eu(i,o.projectPath??te()),Mm(),Ua(null),lm(t);const m=kt(t);Tt(),vt(),ne(ge(t),o.fullPath?g(o.fullPath):null);const{renameRecordingForSession:u}=await import("../utils/asciicast.js");if(await u(),await hs(),gs(),ys(o),Ol.current=!0,Ll(void 0),"fork"!==s)Vs(),Fs(o.worktreeSession),Ss(),Gs({abortController:new AbortController,getAppState:()=>xi.getState(),setAppState:Ai});else{const e=mn();e&&js(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),gm.current&&"fork"!==s&&(gm.current=Ms(i,o.contentReplacements??[])),Gl(()=>i),jl(null),kc(""),mo("tengu_session_resumed",{entrypoint:s,success:!0,resume_duration_ms:Math.round(performance.now()-n)})}catch(e){throw mo("tengu_session_resumed",{entrypoint:s,success:!1}),e}},[Mm,Ai]),[Wm]=B(()=>Q(z)),Gm=U(Wm),Qm=U(new Set),Ym=U(0),zm=U(new Set),Zm=U(new Set),eu=q((e,t)=>{const o=As(e,t,z);Gm.current=Y(Gm.current,o);for(const t of ws(e))Qm.current.add(t)},[]);O(()=>{T&&T.length>0&&(eu(T,te()),Gs({abortController:new AbortController,getAppState:()=>xi.getState(),setAppState:Ai}))},[]);const{status:tu,reverify:ou}=Dt(),[su,nu]=B(null),ru=U(!1),[iu,au]=B(null),[lu,cu]=B(!1),mu=!Wa&&rm;const uu=function(){if(lu||iu)return;if(tm)return"message-selector";if(ll)return;if(Rl[0])return"sandbox-permission";const t=!fl||fl.shouldContinueAnimation;return t&&bl[0]?"tool-permission":t&&Pl[0]?"prompt":t&&vi.queue[0]?"worker-sandbox-permission":t&&ki.queue[0]?"elicitation":t&&mu?"cost":t&&cm?"idle-return":e("ULTRAPLAN")&&t&&!Wa&&ji?"ultraplan-choice":e("ULTRAPLAN")&&t&&!Wa&&bi?"ultraplan-launch":t&&aa?"ide-onboarding":t&&ua?"effort-callout":t&&da?"remote-callout":t&&ha?"lsp-recommendation":t&&Ca?"plugin-hint":t&&fa?"desktop-upsell":void 0}(),pu=ll&&(Rl[0]||bl[0]||Pl[0]||vi.queue[0]||ki.queue[0]||mu);al.current=uu,O(()=>{if(!Wa)return;const e="tool-permission"===uu,t=Date.now();e&&null===tl.current?tl.current=t:e||null===tl.current||(el.current+=t-tl.current,tl.current=null)},[uu,Wa]);const du=U(uu);function onCancel(){if(hl.length>0){const e=hl[hl.length-1];return e?.onClose?.(),void Tl()}if("elicitation"!==uu){if(Se(`[onCancel] focusedInputDialog=${uu} streamMode=${Ra}`),(e("PROACTIVE")||e("KAIROS"))&&en?.pauseProactive(),Va.forceEnd(),dm.current=!1,$c?.trim()&&Gl(e=>[...e,yo({content:$c})]),Mm(),e("TOKEN_BUDGET")&&l(null),"tool-permission"===uu)bl[0]?.onAbort(),Il([]);else if("prompt"===uu){for(const e of Pl)e.reject(new Error("Prompt cancelled by user"));Ml([]),Na.current?.abort("user-cancel")}else _c.isRemoteMode?_c.cancelRequest():Na.current?.abort("user-cancel");Ua(null),Nm(Kl.current,!0)}}$(()=>{"tool-permission"===du.current!==("tool-permission"===uu)&&lc(),du.current=uu},[uu,lc]);const fu=q(()=>{const e=un(Cc,0);e&&(kc(e.text),bc("prompt"),e.images.length>0&&Oc(t=>{const o={...t};for(const t of e.images)o[t.id]=t;return o}))},[kc,bc,Cc,Oc]),gu={setToolUseConfirmQueue:Il,onCancel,onAgentsKilled:()=>Gl(e=>[...e,vo()]),isMessageSelectorVisible:tm||!!Tm,screen:qi,abortSignal:La?.signal,popCommandFromQueue:fu,vimMode:Cm,isLocalJSXCommand:fl?.isLocalJSXCommand,isSearchingHistory:km,isHelpOpen:bm,inputMode:jc,inputValue:Cc,streamMode:Ra};O(()=>{yt()>=5&&!rm&&!hm&&(mo("tengu_cost_threshold_reached",{}),Sm(!0),co()&&im(!0))},[Xl,rm,hm]);const hu=q(async t=>{if(on()&&be()){const e=Ie(),o=await Ae(t.host,e);return new Promise(s=>{o?(Re({requestId:e,host:t.host,resolve:s}),Ai(o=>({...o,pendingSandboxRequest:{requestId:e,host:t.host}}))):xl(e=>[...e,{hostPattern:t,resolvePromise:s}])})}return new Promise(o=>{let s=!1;function resolveOnce(e){s||(s=!0,o(e))}if(xl(e=>[...e,{hostPattern:t,resolvePromise:resolveOnce}]),e("BRIDGE_MODE")){const e=xi.getState().replBridgePermissionCallbacks;if(e){const o=zo();e.sendRequest(o,Xn,{host:t.host},zo(),`Allow network connection to ${t.host}?`);const s=e.onResponse(o,e=>{s();const o="allow"===e.behavior;xl(e=>(e.filter(e=>e.hostPattern.host===t.host).forEach(e=>e.resolvePromise(o)),e.filter(e=>e.hostPattern.host!==t.host)));const n=El.current.get(t.host);if(n){for(const e of n)e();El.current.delete(t.host)}}),cleanup=()=>{s(),e.cancelRequest(o)},n=El.current.get(t.host)??[];n.push(cleanup),El.current.set(t.host,n)}}})},[Ai,xi]);O(()=>{const e=Vn.getSandboxUnavailableReason();if(e){if(Vn.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 Eo(1,"other");Se(`sandbox disabled: ${e}`,{level:"warn"}),Yi({key:"sandbox-unavailable",jsx:t(s,{children:[o(w,{color:"warning",children:"sandbox disabled"}),o(w,{dimColor:!0,children:" · /sandbox"})]}),priority:"medium"})}},[Yi]),Vn.isSandboxingEnabled()&&Vn.initialize(hu).catch(e=>{process.stderr.write(`\n❌ Sandbox Error: ${Ft(e)}\n`),Eo(1,"other")});const Su=q((e,t)=>{Ai(o=>({...o,toolPermissionContext:{...e,mode:t?.preserveMode?o.toolPermissionContext.mode:e.mode}})),setImmediate(e=>{e(e=>(e.forEach(e=>{e.recheckPermission()}),e))},Il)},[Ai,Il]);O(()=>(Be(Su),()=>qe()),[Su]);const Cu=Gt(Il,Su),yu=q((e,t)=>o=>new Promise((s,n)=>{Ml(r=>[...r,{request:o,title:e,toolInputSummary:t,resolve:s,reject:n}])}),[]),Tu=q((t,o,s,n)=>{const r=xi.getState(),computeTools=()=>{const e=xi.getState(),t=ns(e.toolPermissionContext,e.mcp.tools),o=Fo(Ta,t,e.toolPermissionContext.mode);return ri?rs(ri,o,!1,!0).resolvedTools:o};return{abortController:s,options:{commands:wa,tools:computeTools(),debug:i,verbose:r.verbose,mainLoopModel:n,thinkingConfig:!1!==r.thinkingEnabled?Zr:{type:"disabled"},mcpClients:Bo(pe,r.mcp.clients),mcpResources:r.mcp.resources,ideInstallationStatus:ra,isNonInteractiveSession:!1,dynamicMcpConfig:Ni,theme:Rm,agentDefinitions:ba?{...r.agentDefinitions,allowedAgentTypes:ba}:r.agentDefinitions,customSystemPrompt:Nt,appendSystemPrompt:lo,refreshTools:computeTools},getAppState:()=>xi.getState(),setAppState:Ai,messages:t,setMessages:Gl,updateFileHistoryState(e){Ai(t=>{const o=e(t.fileHistory);return o===t.fileHistory?t:{...t,fileHistory:o}})},updateAttributionState(e){Ai(t=>{const o=e(t.attribution);return o===t.attribution?t:{...t,attribution:o}})},openMessageSelector:()=>{jr||om(!0)},openMessageSelectorAtMessage:e=>{if(jr)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)&&nm(n),om(!0)},jumpToMessage:ic,onChangeAPIKey:ou,readFileState:Gm.current,setToolJSX:jl,addNotification:Yi,appendSystemMessage:e=>Gl(t=>[...t,e]),sendOSNotification:e=>{X(e,Pi)},onChangeDynamicMcpConfig:Bi,onInstallIDEExtension:na,nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:Zm.current,dynamicSkillDirTriggers:new Set,discoveredSkillNames:zm.current,setResponseLength:Hc,pushApiMetricsEntry:void 0,setStreamMode:xa,onCompactProgress:e=>{switch(e.type){case"hooks_start":zc("contextBlue_FOR_SYSTEM_SPINNER"),em("contextBlueShimmer_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),zc(null),em(null)}},setInProgressToolUseIDs:xc,setHasInterruptibleToolInProgress:e=>{Pc.current=e},resume:Km,setConversationId:lm,requestPrompt:e("HOOK_PROMPTS")?yu:void 0,contentReplacementState:gm.current}},[wa,Ta,ri,i,pe,ra,Ni,Rm,ba,xi,Ai,ou,Yi,Gl,Bi,Km,yu,jr,Nt,lo,lm,ic,Xl]),vu=q(()=>{Na.current?.abort("background");const e=gn(e=>"task-notification"===e.mode);(async()=>{const t=Tu(Kl.current,[],new AbortController,Mi),[o,s,n]=await Promise.all([dt(t.options.tools,Mi,Array.from(ai.additionalWorkingDirectories.keys()),t.options.mcpClients),ht(),gt()]),r=ft({mainThreadAgentDefinition:ri,toolUseContext:t,customSystemPrompt:Nt,defaultSystemPrompt:o,appendSystemPrompt:lo});t.renderedSystemPrompt=r;const i=(await Xr(e).catch(()=>[])).map(Vr),a=new Set;for(const e of Kl.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)));Cn({messages:[...Kl.current,...l],queryParams:{systemPrompt:r,userContext:s,systemContext:n,canUseTool:Cu,toolUseContext:t,querySource:Ho()},description:Ul,setAppState:Ai,agentDefinition:ri})})()},[Mi,ai,ri,Tu,Nt,lo,Cu,Ai]),{handleBackgroundSession:ku}=yn({setMessages:Gl,setIsLoading:nl,resetLoadingState:Mm,setAbortController:Ua,onBackgroundQuery:vu}),ju=q(t=>{fo(t,t=>{go(t)?(Lr()?Gl(e=>[...ho(e,{includeSnipped:!0}),t]):Gl(()=>[t]),lm(zo()),(e("PROACTIVE")||e("KAIROS"))&&en?.setContextBlocked(!1)):"progress"===t.type&&vs(t.data.type)?Gl(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]}):Gl(e=>[...e,t]),(e("PROACTIVE")||e("KAIROS"))&&("assistant"===t.type&&"isApiErrorMessage"in t&&t.isApiErrorMessage?en?.setContextBlocked(!0):"assistant"===t.type&&en?.setContextBlocked(!1))},e=>{Hc(t=>t+e.length)},xa,Ea,e=>{Gl(t=>t.filter(t=>t!==e)),Cs(e.uuid)},_a,e=>{const t=Date.now(),o=Bc.current;qc.current.push({...e,firstTokenTime:t,lastTokenTime:t,responseLengthBaseline:o,endResponseLength:o})},Xc)},[Gl,Hc,xa,Ea,_a,Xc]),bu=q(async(t,o,s,n,r,i,a)=>{if(n){const e=Bo(pe,xi.getState().mcp.clients);Tn.handleQueryStart(e);const t=rn(e);t&&nn(t)}if(Yo(),!(ti||Dl||Nl||Ol.current)){const e=o.find(e=>"user"===e.type&&!e.isMeta),t="user"===e?.type?So(e.message.content):null;!t||t.startsWith(`<${Po}>`)||t.startsWith(`<${Ro}>`)||t.startsWith(`<${xo}>`)||t.startsWith(`<${wo}>`)||(Ol.current=!0,Ao(t,(new AbortController).signal).then(e=>{e?Ll(e):Ol.current=!1},()=>{Ol.current=!1}))}if(xi.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(go)&&(lm(zo()),(e("PROACTIVE")||e("KAIROS"))&&en?.setContextBlocked(!1)),Mm(),void Ua(null);const l=Tu(t,o,s,i),{tools:c,mcpClients:m}=l.options;if(void 0!==a){const e=l.getAppState;l.getAppState=()=>({...e(),effortValue:a})}Oo("query_context_loading_start");const[,,u,p,d]=await Promise.all([qn(ai,Ai),e("TRANSCRIPT_CLASSIFIER")?Hn(ai,Ai,xi.getState().fastMode):void 0,dt(c,i,Array.from(ai.additionalWorkingDirectories.keys()),m),ht(),gt()]),f={...p,...Wt(m,oo()?to():void 0),...(e("PROACTIVE")||e("KAIROS"))&&en?.isProactiveActive()&&!wm.current?{terminalFocus:"The terminal is unfocused — the user is not actively watching."}:{}};Oo("query_context_loading_end");const g=ft({mainThreadAgentDefinition:ri,toolUseContext:l,customSystemPrompt:Nt,defaultSystemPrompt:u,appendSystemPrompt:lo});l.renderedSystemPrompt=g,Oo("query_query_start"),le(),ue(),fe();for await(const e of Uo({messages:t,systemPrompt:g,userContext:f,systemContext:d,canUseTool:Cu,toolUseContext:l,querySource:Ho()}))ju(e);e("BUDDY")&&fireCompanionObserver(Kl.current,e=>Ai(t=>t.companionReaction===e?t:{...t,companionReaction:e})),Oo("query_end"),Mm(),No(),await(sn?.(Kl.current))},[pe,Mm,Tu,ai,Ai,Nt,sn,lo,Cu,ri,ju,Dl,ti]),Iu=q(async(t,o,s,n,r,i,a,p)=>{if(on()){const e=xe(),t=Pe();e&&t&&je(e,t,!0)}const g=Va.tryStart();if(null===g)return mo("tengu_concurrent_onquery_detected",{}),void t.filter(e=>"user"===e.type&&!e.isMeta).map(e=>So(e.message.content)).filter(e=>null!==e).forEach((e,t)=>{pn({value:e,mode:"prompt"}),0===t&&mo("tengu_concurrent_onquery_enqueued",{})});try{if(ol(),Gl(e=>[...e,...t]),Bc.current=0,e("TOKEN_BUDGET")){const e=a?d(a):null;l(e??c())}qc.current=[],Ea([]),Fc(null);const m=Kl.current;if(a&&await Om(a,m,t.length),i&&a){if(!await i(a,m))return}await bu(m,t,o,s,n,r,p)}finally{if(Va.end(g)){let t;Wc(Date.now()),dm.current=!1,Mm(),await Nm(Kl.current,o.signal.aborted),Ba.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-el.current;if((s>3e4||void 0!==t)&&!o.signal.aborted&&!_i){De(xi.getState().tasks).some(e=>"running"===e.status)?(null===rl.current&&(rl.current=Za.current),t&&(il.current=t)):Gl(e=>[...e,To(s,t,f(e,ks))])}Ua(null)}if("user-cancel"===o.signal.reason&&!Va.isActive&&""===Tc.current&&0===fn()&&!xi.getState().viewingAgentTaskId){const e=Kl.current,t=e.findLast(Ge);if(t){const o=e.lastIndexOf(t);Qe(e,o)&&(Rt(),qa.current(t))}}}},[bu,Ai,Mm,Va,Om,Nm]),Au=U(!1);O(()=>{const t=di;!t||Wa||Au.current||(Au.current=!0,async function(t){if(t.clearContext){const e=t.message.planContent?ds():void 0,{clearConversation:o}=await import("../commands/clear/conversation.js");await o({setMessages:Gl,readFileState:Gm.current,discoveredSkillNames:zm.current,loadedNestedMemoryPaths:Zm.current,getAppState:()=>xi.getState(),setAppState:Ai,setConversationId:lm}),Ol.current=!1,Ll(void 0),Qm.current.clear(),Ym.current=0,e&&fs(se(),e)}const o=t.message.planContent&&!1;Ai(s=>{let n=t.mode?Yt(s.toolPermissionContext,Zt(t.mode,t.allowedPrompts)):s.toolPermissionContext;return e("TRANSCRIPT_CLASSIFIER")&&"auto"===t.mode&&(n=eo({...n,mode:"auto",prePlanMode:void 0})),{...s,initialMessage:null,toolPermissionContext:n,...o&&{pendingPlanVerification:{plan:t.message.planContent,verificationStarted:!1,verificationCompleted:!1}}}}),Os()&&Ds(e=>{Ai(t=>({...t,fileHistory:e(t.fileHistory)}))},t.message.uuid),await dc();const s=t.message.message.content;if("string"!=typeof s||t.message.planContent){const e=wn();Ua(e),Iu([t.message],e,!0,[],Mi)}else wu(s,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}});setTimeout(e=>{e.current=!1},100,Au)}(t))},[di,Wa,Gl,Ai,Iu,Mi,ja]);const wu=q(async(t,o,s,n)=>{if(lc(),(e("PROACTIVE")||e("KAIROS"))&&en?.resumeProactive(),!s&&t.trim().startsWith("/")){const e=xt(t,Lc).trim(),s=e.indexOf(" "),r=-1===s?e.slice(1):e.slice(1,s),i=-1===s?"":e.slice(s+1).trim(),a=wa.find(e=>Ke(e)&&(e.name===r||e.aliases?.includes(r)||Je(e)===r));"clear"===a?.name&&Wl.current&&(mo("tengu_idle_return_action",{action:"hint_converted",variant:Wl.current,idleMinutes:Math.round((Date.now()-fm.current)/6e4),messageCount:Kl.current.length,totalInputTokens:p()}),Wl.current=!1);const l=Va.isActive&&(a?.immediate||n?.fromKeybinding);if(a&&l&&"local-jsx"===a.type){t.trim()===Tc.current.trim()&&(kc(""),o.setCursorOffset(0),o.clearBuffer(),Oc({}));const e=Pt(t).filter(e=>"text"===Lc[e.id]?.type),s=e.length,r=e.reduce((e,t)=>e+(Lc[t.id]?.content.length??0),0);mo("tengu_paste_text",{pastedTextCount:s,pastedTextBytes:r}),mo("tengu_immediate_command_executed",{commandName:a.name,fromKeybinding:n?.fromKeybinding??!1});return void(async()=>{let e=!1;const t=Tu(Kl.current,[],wn(),Mi),s=await a.load(),n=await s.call((t,s)=>{e=!0,jl({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0});const n=[];t&&"skip"!==s?.display&&(Yi({key:`immediate-${a.name}`,text:t,priority:"immediate"}),Lr()||n.push(bo(Io(Je(a),i)),bo(`<${Po}>${Mo(t)}</${Po}>`))),s?.metaMessages?.length&&n.push(...s.metaMessages.map(e=>Co({content:e,isMeta:!0}))),n.length&&Gl(e=>[...e,...n]),void 0!==Ic&&(kc(Ic.text),o.setCursorOffset(Ic.cursorOffset),Oc(Ic.pastedContents),Ac(void 0))},t,i);n&&!e&&jl({jsx:n,shouldHidePromptInput:!1,isLocalJSXCommand:!0})})()}}if(_c.isRemoteMode&&!t.trim())return;{const e=uo("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&&!io().idleReturnDismissed&&!dm.current&&!s&&!t.trim().startsWith("/")&&fm.current>0&&p()>=r){const s=(Date.now()-fm.current)/6e4;if(s>=n&&"dialog"===e)return mm({input:t,idleMinutes:s}),kc(""),o.setCursorOffset(0),void o.clearBuffer()}}n?.fromKeybinding||(wt({display:s?t:Mt(t,jc),pastedContents:s?{}:Lc}),"bash"===jc&&Et(t.trim()));const r=!s&&t.trim().startsWith("/"),i=!Wa||s||_c.isRemoteMode;if(void 0!==Ic&&!r&&i?(kc(Ic.text),o.setCursorOffset(Ic.cursorOffset),Oc(Ic.pastedContents),Ac(void 0)):i&&(n?.fromKeybinding||(kc(""),o.setCursorOffset(0)),Oc({})),i&&(bc("prompt"),oa(void 0),Uc(e=>e+1),o.clearBuffer(),xm.current=!1,r||"prompt"!==jc||s||_c.isRemoteMode||(Ql(t),ol()),e("COMMIT_ATTRIBUTION")&&Ai(e=>({...e,attribution:Us(e.attribution,e=>{Bs(e).catch(e=>{Se(`Attribution: Failed to save snapshot: ${e}`)})})}))),s){const{queryRequired:e}=await vn(s.state,s.speculationSessionTimeSavedMs,s.setAppState,t,{setMessages:Gl,readFileState:Gm,cwd:te()});if(e){const e=wn();Ua(e),Iu([],e,!0,[],Mi)}return}if(_c.isRemoteMode&&(!r||"local-jsx"!==wa.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(Lc),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=Co({content:n,imagePasteIds:s});return Gl(e=>[...e,i]),void await _c.sendMessage(r,{uuid:i.uuid})}await dc(),await Do({input:t,helpers:o,queryGuard:Va,isExternalLoading:Ja,mode:jc,commands:wa,onInputChange:kc,setPastedContents:Oc,setToolJSX:jl,getToolUseContext:Tu,messages:Kl.current,mainLoopModel:Mi,pastedContents:Lc,ideSelection:ta,setUserInputOnProcessing:Ql,setAbortController:Ua,abortController:La,onQuery:Iu,setAppState:Ai,querySource:Ho(),onBeforeQuery:ko,canUseTool:Cu,addNotification:Yi,setMessages:Gl,streamMode:Pa.current,hasInterruptibleToolInProgress:Pc.current,onJumpToMessage:ic}),(r||Wa)&&void 0!==Ic&&(kc(Ic.text),o.setCursorOffset(Ic.cursorOffset),Oc(Ic.pastedContents),Ac(void 0))},[Va,Wa,Ja,jc,wa,kc,bc,Oc,Uc,oa,jl,Tu,Mi,Lc,ta,Ql,Ua,Yi,Iu,Ic,Ac,Ai,ko,Cu,Mc,Gl,dc,lc]),Ru=q(async(e,o,s)=>{_e(o)?(Oe(o.id,Co({content:e}),Ai),"running"===o.status?Le(o.id,e,Ai):is({agentId:o.id,prompt:e,toolUseContext:Tu(Kl.current,[],new AbortController,Mi),canUseTool:Cu}).catch(e=>{Se(`resumeAgentBackground failed: ${Ft(e)}`),Yi({key:`resume-agent-failed-${o.id}`,jsx:t(w,{color:"error",children:["Failed to resume agent: ",Ft(e)]}),priority:"low"})})):Ee(o.id,e,Ai),kc(""),s.setCursorOffset(0),s.clearBuffer()},[Ai,kc,Tu,Cu,Mi,Yi]),xu=q(()=>{const e=su?kr(su):"/issue";nu(null),wu(e,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(t=>{Se(`Auto-run ${e} failed: ${Ft(t)}`)})},[wu,su]),Pu=q(()=>{nu(null)},[]),Mu=q(()=>{wu("/feedback",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}}).catch(e=>{Se(`Survey feedback request failed: ${e instanceof Error?e.message:String(e)}`)})},[wu]),Eu=U(wu);Eu.current=wu;const Du=q(()=>{Eu.current("/rate-limit-options",{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})},[]),_u=q(async()=>{if(cu(!0),e("BG_SESSIONS")&&Xs())return a("tmux",["detach-client"],{stdio:"ignore"}),void cu(!1);if(null!==mn())return void au(o(cn,{showWorktree:!0,onDone:()=>{},onCancel:()=>{au(null),cu(!1)}}));const t=await ln.load(),s=await t.call(()=>{});au(s),null===s&&cu(!1)},[]),Lu=q(()=>{om(e=>!e)},[]),Ou=q(t=>{const o=Kl.current,s=o.lastIndexOf(t);-1!==s&&(mo("tengu_conversation_rewind",{preRewindMessageCount:o.length,postRewindMessageCount:s,messagesRemoved:o.length-s,rewindToMessageIndex:s}),Gl(o.slice(0,s)),lm(zo()),Rs(),e("CONTEXT_COLLAPSE")&&r("../services/contextCollapse/index.js").resetContextCollapse(),Ai(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}})))},[Gl,Ai]),Nu=q(e=>{Ou(e);const t=po(e);if(t&&(kc(t.text),bc(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}}}),Oc(o)}}},[Ou,kc]);qa.current=Nu;const Uu=q(async e=>{setImmediate((e,t)=>e(t),Nu,e)},[Nu]),Bu={copy:e=>{Fr(e).then(e=>{e&&process.stdout.write(e),Yi({key:"selection-copied",text:"copied",color:"success",priority:"immediate",timeoutMs:2e3})})},edit:async e=>{const t=(e=>{const t=e.slice(0,24);return Xl.findIndex(e=>e.uuid.slice(0,24)===t)})(e.uuid),o=t>=0?Xl[t]:void 0;if(!o||!Ge(o))return;const s=!await Ns(pi,o.uuid),n=Qe(Xl,t);s&&n?(onCancel(),Uu(o)):(nm(o),om(!0))}},{enter:qu,handlers:Hu}=qr(sc,nc,rc,Bu);jt(bt()),$e(Xl,Xl.length===T?.length);const{sendBridgeResult:$u}=Fe(Xl,Gl,Na,wa,Mi);Ba.current=$u,Ve(Xl),Xe(Xl),zs(Xl,Wa,onCancel,Da),Zs(bl),It();const Fu=U(!1);O(()=>{fi.length<1?Fu.current=!1:Fu.current||(Fu.current=!0,ao(e=>({...e,promptQueueUseCount:(e.promptQueueUseCount??0)+1})))},[fi.length]);const Vu=q(async e=>{await Do({helpers:{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}},queryGuard:Va,commands:wa,onInputChange:()=>{},setPastedContents:()=>{},setToolJSX:jl,getToolUseContext:Tu,messages:Xl,mainLoopModel:Mi,ideSelection:ta,setUserInputOnProcessing:Ql,setAbortController:Ua,onQuery:Iu,setAppState:Ai,querySource:Ho(),onBeforeQuery:ko,canUseTool:Cu,addNotification:Yi,setMessages:Gl,queuedCommands:e,onJumpToMessage:ic})},[Va,wa,jl,Tu,Xl,Mi,ta,Ql,Cu,Ua,Iu,Yi,Ai,ko,ic]);_o({executeQueuedInput:Vu,hasActiveLocalJsxUI:ql,queryGuard:Va}),O(()=>{An.recordUserActivity(),Z(!0)},[Cc,Nc]),O(()=>{1===Nc&&Ct()},[Nc]),O(()=>{const e=um.current;if(um.current=Wa,!e||Wa)return;if(0===Nc)return;!0===io().taskCompleteNotifEnabled&&X({message:"Respuesta finalizada",notificationType:"task_complete"},Pi)},[Wa,Nc,Pi]),O(()=>{const e=!Wa&&(bl.length>0||Pl.length>0||!!Si||!!Ci),t=pm.current;if(pm.current=e,!e||t)return;!0===io().inputNeededNotifEnabled&&X({message:"Se requiere tu aprobacion o entrada",notificationType:"input_needed"},Pi)},[Wa,bl.length,Pl.length,Si,Ci,Pi]),O(()=>{let e=!1;return(async()=>{const{startHeartbeat:t,stopHeartbeat:o}=await import("../utils/heartbeat.js");e||(t({onStdinStalled:()=>{Yi({key:"heartbeat-stdin-stalled",text:"⚠ stdin parece bloqueado · ejecuta /heartbeat para más info",color:"error",priority:"immediate",timeoutMs:2147483647})},onStdinRecovered:()=>{zi("heartbeat-stdin-stalled")},onGitBashDetected:()=>{Yi({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)}},[Yi,zi]),O(()=>{if(Wa)return;if(0===Nc)return;if(0===Kc)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>=io().messageIdleNotifThresholdMs&&X({message:"Context está esperando tu entrada",notificationType:"idle_prompt"},n)},io().messageIdleNotifThresholdMs,Kc,Wa,fl,al,Pi);return()=>clearTimeout(e)},[Wa,fl,Nc,Kc,Pi]),O(()=>{if(0===Kc)return;if(Wa)return;const e=uo("tengu_willow_mode","off");if("hint"!==e&&"hint_v2"!==e)return;if(io().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()-Kc),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,mo("tengu_idle_return_action",{action:"hint_shown",variant:i,idleMinutes:Math.round(m),messageCount:r.current.length,totalInputTokens:l})},Math.max(0,r),Kc,Yi,Kl,e,Wl);return()=>{clearTimeout(i),zi("idle-return-hint"),Wl.current=!1}},[Kc,Wa,Yi,zi]);const Xu=q((e,t)=>{if(Va.isActive)return!1;if(dn().some(e=>"prompt"===e.mode||"bash"===e.mode))return!1;const o=wn();Ua(o);const s=Co({content:e,isMeta:!!t?.isMeta||void 0});return Iu([s],o,!0,[],Mi),!0},[Iu,Mi,xi]),Ju=Jt({setInputValueRaw:yc,inputValueRef:Tc,insertTextRef:vc});if(Qs({enabled:on(),isLoading:Wa,focusedInputDialog:uu,onSubmitMessage:Xu}),Lo({isLoading:Wa,onSubmitMessage:Xu}),Ys(bl),e("AGENT_TRIGGERS")){const e=xi.getState().kairosEnabled;tn({isLoading:Wa,assistantMode:e,setMessages:Gl})}O(()=>{fi.some(e=>"now"===e.priority)&&Na.current?.abort("interrupt")},[fi]),O(()=>(async function(){ou();const e=await St();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)Gm.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})}(),()=>{Tn.shutdown()}),[]);const{internal_eventEmitter:Ku}=R(),[Wu,Gu]=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=()=>{Gu(e=>e+1)};return Ku?.on("suspend",handleSuspend),Ku?.on("resume",handleResume),()=>{Ku?.off("suspend",handleSuspend),Ku?.off("resume",handleResume)}},[Ku]);const Qu=N(()=>{if(!Wa)return null;const e=Xl.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(Xl.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(Xl,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}`},[Xl,Wa]),Yu=q(()=>{Sc({messagesLength:Xl.length,streamingToolUsesLength:Ma.length})},[Xl.length,Ma.length]),zu=q(()=>{Sc(null)},[]),Zu=Lr()&&!si,ep=U(null),[tp,op]=B(!1),[sp,np]=B(""),[rp,ip]=B(0),[ap,lp]=B(0),cp=q((e,t)=>{ip(e),lp(t)},[]);y((e,t,o)=>{if(t.ctrl||t.meta)return;if("/"===e)return ep.current?.setAnchor(),op(!0),void o.stopImmediatePropagation();const s=e[0];if(("n"===s||"N"===s)&&e===s.repeat(e.length)&&rp>0){const t="n"===s?ep.current?.nextMatch:ep.current?.prevMatch;if(t)for(let o=0;o<e.length;o++)t();o.stopImmediatePropagation()}},{isActive:"transcript"===qi&&Zu&&!tp&&!Vi});const{setQuery:mp,scanElement:up,setPositions:pp}=k(),dp=v().columns,fp=L.useRef(dp);L.useEffect(()=>{fp.current!==dp&&(fp.current=dp,(sp||tp)&&(op(!1),np(""),ip(0),lp(0),ep.current?.disarmSearch(),mp("")))},[dp,sp,tp,mp]),y((e,t,o)=>{if(!t.ctrl&&!t.meta){if("q"===e)return zu(),void o.stopImmediatePropagation();if("["!==e||Vi){if("v"===e){if(o.stopImmediatePropagation(),Qi.current)return;Qi.current=!0;const e=Wi.current,setStatus=t=>{e===Wi.current&&(clearTimeout(Gi.current),Ki(t))};setStatus(`rendering ${fc.length} messages…`),(async()=>{try{const e=Math.max(80,(process.stdout.columns??80)-6),t=(await j(fc,ja,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===Wi.current&&(Gi.current=setTimeout(e=>e(""),4e3,Ki))})()}}else Xi(!0),Fi(!0),o.stopImmediatePropagation()}},{isActive:"transcript"===qi&&Zu&&!tp});const gp="transcript"===qi&&Zu;O(()=>{gp||(np(""),ip(0),lp(0),op(!1),Wi.current++,clearTimeout(Gi.current),Xi(!1),Ki(""))},[gp]),O(()=>{mp(gp?sp:""),gp||pp(null)},[gp,sp,mp,pp]);const hp={screen:qi,setScreen:Hi,showAllInTranscript:$i,setShowAllInTranscript:Fi,messageCount:Xl.length,onEnterTranscript:Yu,onExitTranscript:zu,virtualScrollActive:Zu,searchBarOpen:tp},Sp=hc?fc.slice(0,hc.messagesLength):fc,Cp=hc?Ma.slice(0,hc.streamingToolUsesLength):Ma;if(qt({onOpenBackgroundTasks:ql?void 0:()=>vm(!0)}),$t(),"transcript"===qi){const e=!Lr()||si||Vi?void 0:Ha,n=o(Ko,{messages:Sp,tools:ja,commands:wa,verbose:!0,toolJSX:null,toolUseConfirmQueue:[],inProgressToolUseIDs:Rc,isMessageSelectorVisible:!1,conversationId:am,screen:qi,agentDefinitions:ui,streamingToolUses:Cp,showAllInTranscript:$i,onOpenRateLimitOptions:Du,isLoading:Wa,hidePastThinking:!0,streamingThinking:Da,scrollRef:e,jumpRef:ep,onSearchMatchesChange:cp,scanElement:up,setPositions:pp,disableRenderCap:Vi}),r=fl&&o(A,{flexDirection:"column",width:"100%",children:fl.jsx}),i=t(Ot,{children:[o(AnimatedTerminalTitle,{isAnimating:Hl,title:Ul,disabled:ti,noPrefix:Vl}),o(_t,{...hp}),o(Kt,{voiceHandleKeyEvent:Ju.handleKeyEvent,stripTrailing:Ju.stripTrailing,resetAnchor:Ju.resetAnchor,isActive:!fl?.isLocalJSXCommand}),o(Lt,{onSubmit:wu,isActive:!fl?.isLocalJSXCommand}),e?o(Br,{scrollRef:Ha,isActive:"ultraplan-choice"!==uu,isModal:!tp,onScroll:()=>ep.current?.disarmSearch()}):null,o(Bt,{...gu}),e?o(Er,{scrollRef:Ha,scrollable:t(s,{children:[n,r,o(Wn,{})]}),bottom:tp?o(TranscriptSearchBar,{jumpRef:ep,initialQuery:"",count:rp,current:ap,onClose:e=>{np(rp>0?e:""),op(!1),e||(ip(0),lp(0),ep.current?.setSearchQuery(""))},onCancel:()=>{op(!1),ep.current?.setSearchQuery(""),ep.current?.setSearchQuery(sp),mp(sp)},setHighlight:mp}):o(TranscriptModeFooter,{showAllInTranscript:$i,virtualScroll:!0,status:Ji||void 0,searchBadge:sp&&rp>0?{current:ap,count:rp}:void 0})}):t(s,{children:[n,r,o(Wn,{}),o(TranscriptModeFooter,{showAllInTranscript:$i,virtualScroll:!1,suppressShowAll:Vi,status:Ji||void 0})]})]});return e?o(Ur,{mouseTracking:Nr(),children:i}):i}const yp=Ii?Ti[Ii]:void 0,Tp=yp&&Ws(yp)?yp:void 0,vp=Tp??(yp&&_e(yp)?yp:void 0),kp=Vc||!Wa,jp=vp?vp.messages??[]:kp?Xl:fc,bp=Ga&&!vp&&jp.length<=Ya.current?Ga:void 0,Ip="tool-permission"===uu?o(ze,{onDone:()=>Il(([e,...t])=>t),onReject:fu,toolUseConfirm:bl[0],toolUseContext:Tu(Xl,Xl,La??wn(),Mi),verbose:li,workerBadge:bl[0]?.workerBadge,setStickyFooter:Lr()?wl:void 0},bl[0]?.toolUseID):null,Ap=dp<xr,wp=!fl?.shouldHidePromptInput&&!uu&&!Tm,Rp=Lr()&&!0===fl?.isLocalJSXCommand,xp=(hl.length>0?hl[hl.length-1]?.element:null)??(Rp?fl.jsx:null),Pp=o(V.Provider,{value:{stack:hl,pushModal:Cl,replaceModal:yl,popModal:Tl,clearModals:vl},children:t(Ot,{children:[o(AnimatedTerminalTitle,{isAnimating:Hl,title:Ul,disabled:ti,noPrefix:Vl}),o(_t,{...hp}),o(Kt,{voiceHandleKeyEvent:Ju.handleKeyEvent,stripTrailing:Ju.stripTrailing,resetAnchor:Ju.resetAnchor,isActive:!fl?.isLocalJSXCommand}),o(Lt,{onSubmit:wu,isActive:!fl?.isLocalJSXCommand}),o(Br,{scrollRef:Ha,isActive:Lr()&&(null!=xp||!uu||"tool-permission"===uu),onScroll:xp||Ip||vp?void 0:pc}),e("MESSAGE_ACTIONS")&&Lr()&&!ni?o(Hr,{handlers:Hu,isActive:null!==sc}):null,o(Bt,{...gu}),o(Rn,{dynamicMcpConfig:Ni,isStrictMcpConfig:lt,children:o(Er,{scrollRef:Ha,overlay:Ip,bottomFloat:e("BUDDY")&&wp&&!Ap?o(Rr,{}):void 0,modal:xp,modalScrollRef:$a,dividerYRef:zl,hidePill:!!vp,hideSticky:!!Tp,newMessageCount:ac?.count??0,onPillClick:()=>{nc(null),tc(Ha.current)},scrollable:t(s,{children:[o(Go,{}),o(Ko,{messages:jp,tools:ja,commands:wa,verbose:li,toolJSX:fl,toolUseConfirmQueue:bl,inProgressToolUseIDs:Tp?Tp.inProgressToolUseIDs??new Set:Rc,isMessageSelectorVisible:tm,conversationId:am,screen:qi,streamingToolUses:Ma,showAllInTranscript:$i,agentDefinitions:ui,onOpenRateLimitOptions:Du,isLoading:Wa,streamingText:Wa&&!vp?Jc:null,isBriefOnly:!vp&&Li,unseenDivider:vp?void 0:ac,scrollRef:Lr()?Ha:void 0,trackStickyPrompt:!!Lr()||void 0,cursor:sc,setCursor:nc,cursorNavRef:rc}),o(mr,{}),!jr&&bp&&!xp&&o(cr,{param:{text:bp,type:"text"},addMargin:!0,verbose:li}),fl&&!(fl.isLocalJSXCommand&&fl.isImmediate)&&!Rp&&o(A,{flexDirection:"column",width:"100%",children:fl.jsx}),!1,e("WEB_BROWSER_TOOL")?br&&o(br.WebBrowserPanel,{}):null,o(A,{flexGrow:1}),Bm&&o(ut,{mode:Ra,spinnerTip:gi,responseLengthRef:Bc,apiMetricsRef:qc,overrideMessage:Gc,spinnerSuffix:Qu,verbose:li,loadingStartTimeRef:Za,totalPausedMsRef:el,pauseStartTimeRef:tl,overrideColor:Yc,overrideShimmerColor:Zc,hasActiveTools:Rc.size>0,leaderIsIdle:!Wa}),!Bm&&!Wa&&!Ga&&!Em&&Li&&!vp&&o(pt,{}),Lr()&&o(ot,{})]}),bottom:t(A,{flexDirection:e("BUDDY")&&Ap?"column":"row",width:"100%",alignItems:e("BUDDY")&&Ap?void 0:"flex-end",children:[e("BUDDY")&&Ap&&Lr()&&wp?o(wr,{}):null,t(A,{flexDirection:"column",flexGrow:1,children:[Al,fl?.isLocalJSXCommand&&fl.isImmediate&&!Rp&&o(A,{flexDirection:"column",width:"100%",children:fl.jsx}),!Bm&&!fl?.isLocalJSXCommand&&hi&&va&&va.length>0&&o(A,{width:"100%",flexDirection:"column",children:o(Wo,{tasks:va,isStandalone:!0})}),"sandbox-permission"===uu&&o(Kn,{hostPattern:Rl[0].hostPattern,onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=Rl[0];if(!s)return;const n=s.hostPattern.host;if(o){const e={type:"addRules",rules:[{toolName:so,ruleContent:`domain:${n}`}],behavior:t?"allow":"deny",destination:"localSettings"};Ai(t=>({...t,toolPermissionContext:Qt(t.toolPermissionContext,e)})),zt(e),Vn.refreshConfig()}xl(e=>(e.filter(e=>e.hostPattern.host===n).forEach(e=>e.resolvePromise(t)),e.filter(e=>e.hostPattern.host!==n)));const r=El.current.get(n);if(r){for(const e of r)e();El.current.delete(n)}}},Rl[0].hostPattern.host),"prompt"===uu&&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}),Ml(([,...e])=>e))},onAbort:()=>{const e=Pl[0];e&&(e.reject(new Error("Prompt cancelled by user")),Ml(([,...e])=>e))}},Pl[0].request.prompt),Si&&o(Me,{toolName:Si.toolName,description:Si.description}),Ci&&o(Me,{toolName:"Network Access",description:`Waiting for leader to approve network access to ${Ci.host}`}),"worker-sandbox-permission"===uu&&o(Kn,{hostPattern:{host:vi.queue[0].host,port:void 0},onUserResponse:e=>{const{allow:t,persistToSettings:o}=e,s=vi.queue[0];if(!s)return;const n=s.host;if(we(s.workerName,s.requestId,n,t,yi?.teamName),o&&t){const e={type:"addRules",rules:[{toolName:so,ruleContent:`domain:${n}`}],behavior:"allow",destination:"localSettings"};Ai(t=>({...t,toolPermissionContext:Qt(t.toolPermissionContext,e)})),zt(e),Vn.refreshConfig()}Ai(e=>({...e,workerSandboxPermissions:{...e.workerSandboxPermissions,queue:e.workerSandboxPermissions.queue.slice(1)}}))}},vi.queue[0].requestId),"elicitation"===uu&&o(Ze,{event:ki.queue[0],onResponse:(e,t)=>{const o=ki.queue[0];if(!o)return;o.respond({action:e,content:t});"url"===o.params.mode&&"accept"===e||Ai(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}}))},onWaitingDismiss:e=>{const t=ki.queue[0];Ai(e=>({...e,elicitation:{queue:e.elicitation.queue.slice(1)}})),t?.onWaitingDismiss?.(e)}},ki.queue[0].serverName+":"+String(ki.queue[0].requestId)),"cost"===uu&&o(D,{onDone:()=>{im(!1),Sm(!0),ao(e=>({...e,hasAcknowledgedCostThreshold:!0})),mo("tengu_cost_threshold_acknowledged",{})}}),"idle-return"===uu&&cm&&o(_,{idleMinutes:cm.idleMinutes,totalInputTokens:p(),onDone:async e=>{const t=cm;if(mm(null),mo("tengu_idle_return_action",{action:e,idleMinutes:Math.round(t.idleMinutes),messageCount:Kl.current.length,totalInputTokens:p()}),"dismiss"!==e){if("never"===e&&ao(e=>e.idleReturnDismissed?e:{...e,idleReturnDismissed:!0}),"clear"===e){const{clearConversation:e}=await import("../commands/clear/conversation.js");await e({setMessages:Gl,readFileState:Gm.current,discoveredSkillNames:zm.current,loadedNestedMemoryPaths:Zm.current,getAppState:()=>xi.getState(),setAppState:Ai,setConversationId:lm}),Ol.current=!1,Ll(void 0),Qm.current.clear(),Ym.current=0}dm.current=!0,Eu.current(t.input,{setCursorOffset:()=>{},clearBuffer:()=>{},resetHistory:()=>{}})}else kc(t.input)}}),"ide-onboarding"===uu&&o(kn,{onDone:()=>la(!1),installationStatus:ra}),!1,!1,"effort-callout"===uu&&o(jn,{model:Mi,onDone:e=>{pa(!1),"dismiss"!==e&&Ai(t=>({...t,effortValue:e}))}}),"remote-callout"===uu&&o(In,{onDone:e=>{Ai(t=>t.showRemoteCallout?{...t,showRemoteCallout:!1,..."enable"===e&&{replBridgeEnabled:!0,replBridgeExplicit:!0,replBridgeOutboundOnly:!1}}:t)}}),iu,"plugin-hint"===uu&&Ca&&o(sr,{pluginName:Ca.pluginName,pluginDescription:Ca.pluginDescription,marketplaceName:Ca.marketplaceName,sourceCommand:Ca.sourceCommand,onResponse:ya}),"lsp-recommendation"===uu&&ha&&o(tr,{pluginName:ha.pluginName,pluginDescription:ha.pluginDescription,fileExtension:ha.fileExtension,onResponse:Sa}),"desktop-upsell"===uu&&o(nr,{onDone:()=>ga(!1)}),e("ULTRAPLAN")?"ultraplan-choice"===uu&&ji&&o(UltraplanChoiceDialog,{plan:ji.plan,sessionId:ji.sessionId,taskId:ji.taskId,setMessages:Gl,readFileState:Gm.current,getAppState:()=>xi.getState(),setConversationId:lm}):null,e("ULTRAPLAN")?"ultraplan-launch"===uu&&bi&&o(UltraplanLaunchDialog,{onChoice:(e,t)=>{const o=bi.blurb;if(Ai(e=>e.ultraplanLaunchPending?{...e,ultraplanLaunchPending:void 0}:e),"cancel"===e)return;Gl(e=>[...e,bo(Io("ultraplan",o))]);const appendStdout=e=>Gl(t=>[...t,bo(`<${Po}>${Mo(e)}</${Po}>`)]);launchUltraplan({blurb:o,getAppState:()=>xi.getState(),setAppState:Ai,signal:wn().signal,disconnectedBridge:t?.disconnectedBridge,onSessionReady:e=>{if(!Va.isActive)return void appendStdout(e);const t=Va.subscribe(()=>{Va.isActive||(t(),xi.getState().ultraplanSessionUrl&&appendStdout(e))})}}).then(appendStdout).catch(Xt)}}):null,Um(),!fl?.shouldHidePromptInput&&!uu&&!lu&&!jr&&!sc&&t(s,{children:[su&&o(yr,{onRun:xu,onCancel:Pu,reason:vr(su)}),"closed"!==Vm.state?o(En,{state:Vm.state,lastResponse:Vm.lastResponse,handleSelect:Vm.handleSelect,inputValue:Cc,setInputValue:kc,onRequestFeedback:Mu}):"closed"!==Xm.state?o(En,{state:Xm.state,lastResponse:Xm.lastResponse,handleSelect:Xm.handleSelect,handleTranscriptSelect:Xm.handleTranscriptSelect,inputValue:Cc,setInputValue:kc,onRequestFeedback:Mu,message:"How well did Claude use its memory? (optional)"}):o(En,{state:Fm.state,lastResponse:Fm.lastResponse,handleSelect:Fm.handleSelect,handleTranscriptSelect:Fm.handleTranscriptSelect,inputValue:Cc,setInputValue:kc,onRequestFeedback:ru.current?void 0:Mu}),"closed"!==Jm.state&&o(En,{state:Jm.state,lastResponse:null,handleSelect:()=>{},handleTranscriptSelect:Jm.handleTranscriptSelect,inputValue:Cc,setInputValue:kc}),!1,$m&&o(Ir,{}),o(tt,{debug:i,ideSelection:ta,hasSuppressedDialogs:!!pu,isLocalJSXCommandActive:ql,getToolUseContext:Tu,toolPermissionContext:ai,setToolPermissionContext:Su,apiKeyStatus:tu,commands:wa,agents:ui.activeAgents,isLoading:Wa,onExit:_u,verbose:li,messages:Xl,onAutoUpdaterResult:ul,autoUpdaterResult:ml,input:Cc,onInputChange:kc,mode:jc,onModeChange:bc,stashedPrompt:Ic,setStashedPrompt:Ac,submitCount:Nc,onShowMessageSelector:Lu,onMessageActionsEnter:e("MESSAGE_ACTIONS")&&Lr()&&!ni?qu:void 0,mcpClients:ea,pastedContents:Lc,setPastedContents:Oc,vimMode:Cm,setVimMode:ym,showBashesDialog:Tm,setShowBashesDialog:vm,onSubmit:wu,onAgentSubmit:Ru,isSearchingHistory:km,setIsSearchingHistory:jm,helpOpen:bm,setHelpOpen:Im,insertTextRef:vc,voiceInterimRange:Ju.interimRange}),o(st,{messages:Xl}),o(Sn,{onBackgroundSession:ku,isLoading:Wa})]}),sc&&o($r,{cursor:sc}),"message-selector"===uu&&o(We,{messages:Xl,preselectedMessage:sm,onPreRestore:onCancel,onRestoreCode:async e=>{await _s(e=>{Ai(t=>({...t,fileHistory:e(t.fileHistory)}))},e.uuid)},onSummarize:async(t,o,s="from")=>{const n=ho(Xl),r=n.indexOf(t);if(-1===r)return void Gl(e=>[...e,jo("That message is no longer in the active context (snipped or pre-compact). Choose a more recent message.","warning")]);const i=wn(),a=Tu(n,[],i,Mi),l=a.getAppState(),c=await dt(a.options.tools,a.options.mainLoopModel,Array.from(l.toolPermissionContext.additionalWorkingDirectories.keys()),a.options.mcpClients),m=ft({mainThreadAgentDefinition:void 0,toolUseContext:a,customSystemPrompt:a.options.customSystemPrompt,defaultSystemPrompt:c,appendSystemPrompt:a.options.appendSystemPrompt}),[u,p]=await Promise.all([ht(),gt()]),d=await Es(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(Lr()&&"from"===s?Gl(e=>{const o=e.findIndex(e=>e.uuid===t.uuid);return[...e.slice(0,-1===o?0:o),...h]}):Gl(h),(e("PROACTIVE")||e("KAIROS"))&&en?.setContextBlocked(!1),lm(zo()),xs(a.options.querySource),"from"===s){const e=po(t);e&&(kc(e.text),bc(e.mode))}const S=Ut("app:toggleTranscript","Global","ctrl+o");Yi({key:"summarize-ctrl-o-hint",text:`Conversation summarized (${S} for history)`,priority:"medium",timeoutMs:8e3})},onRestoreMessage:Uu,onClose:()=>{om(!1),nm(void 0)}}),!1]}),!e("BUDDY")||Ap&&Lr()||!wp?null:o(wr,{})]})})},Wu)]})});return Lr()?o(Ur,{mouseTracking:Nr(),children:Pp}):Pp}
@@ -1 +1 @@
1
- import{getIsNonInteractiveSession as e}from"../../bootstrap/state.js";import{isAgentSwarmsEnabled as t}from"../../utils/agentSwarmsEnabled.js";import{count as o}from"../../utils/array.js";import{isEnvDefinedFalsy as s,isEnvTruthy as n}from"../../utils/envUtils.js";import{toError as r}from"../../utils/errors.js";import{createCacheSafeParams as i,runForkedAgent as u}from"../../utils/forkedAgent.js";import{logError as a}from"../../utils/log.js";import{createUserMessage as g,getLastAssistantMessage as p}from"../../utils/messages.js";import{getInitialSettings as l}from"../../utils/settings/settings.js";import{isTeammate as d}from"../../utils/teammate.js";import{getFeatureValue_CACHED_MAY_BE_STALE as c}from"../analytics/growthbook.js";import{logEvent as m}from"../analytics/index.js";import{currentLimits as h}from"../claudeAiLimits.js";import{isSpeculationEnabled as f,startSpeculation as _}from"./speculation.js";let S=null;export function getPromptVariant(){return"user_intent"}export function shouldEnablePromptSuggestion(){const o=process.env.CONTEXT_CODE_ENABLE_PROMPT_SUGGESTION??process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION;if(s(o))return m("tengu_prompt_suggestion_init",{enabled:!1,source:"env"}),!1;if(n(o))return m("tengu_prompt_suggestion_init",{enabled:!0,source:"env"}),!0;if(!c("tengu_chomp_inflection",!1))return m("tengu_prompt_suggestion_init",{enabled:!1,source:"growthbook"}),!1;if(e())return m("tengu_prompt_suggestion_init",{enabled:!1,source:"non_interactive"}),!1;if(t()&&d())return m("tengu_prompt_suggestion_init",{enabled:!1,source:"swarm_teammate"}),!1;const r=!1!==l()?.promptSuggestionEnabled;return m("tengu_prompt_suggestion_init",{enabled:r,source:"setting"}),r}export function abortPromptSuggestion(){S&&(S.abort(),S=null)}export function getSuggestionSuppressReason(e){return e.promptSuggestionEnabled?e.pendingWorkerRequest||e.pendingSandboxRequest?"pending_permission":e.elicitation.queue.length>0?"elicitation_active":"plan"===e.toolPermissionContext.mode?"plan_mode":"external"===process.env.USER_TYPE&&"allowed"!==h.status?"rate_limit":null:"disabled"}export async function tryGenerateSuggestion(e,t,s,n,r){if(e.signal.aborted)return logSuggestionSuppressed("aborted",void 0,void 0,r),null;if(o(t,e=>"assistant"===e.type)<2)return logSuggestionSuppressed("early_conversation",void 0,void 0,r),null;const i=p(t);if(i?.isApiErrorMessage)return logSuggestionSuppressed("last_response_error",void 0,void 0,r),null;const u=getParentCacheSuppressReason(i);if(u)return logSuggestionSuppressed(u,void 0,void 0,r),null;const a=getSuggestionSuppressReason(s());if(a)return logSuggestionSuppressed(a,void 0,void 0,r),null;const g=getPromptVariant(),{suggestion:l,generationRequestId:d}=await generateSuggestion(e,g,n);return e.signal.aborted?(logSuggestionSuppressed("aborted",void 0,void 0,r),null):l?shouldFilterSuggestion(l,g,r)?null:{suggestion:l,promptId:g,generationRequestId:d}:(logSuggestionSuppressed("empty",void 0,g,r),null)}export async function executePromptSuggestion(e){if("repl_main_thread"!==e.querySource)return;S=new AbortController;const t=S,o=i(e);try{const s=await tryGenerateSuggestion(t,e.messages,e.toolUseContext.getAppState,o,"cli");if(!s)return;e.toolUseContext.setAppState(e=>({...e,promptSuggestion:{text:s.suggestion,promptId:s.promptId,shownAt:0,acceptedAt:0,generationRequestId:s.generationRequestId}})),f()&&s.suggestion&&_(s.suggestion,e,e.toolUseContext.setAppState,!1,o)}catch(e){if(e instanceof Error&&("AbortError"===e.name||"APIUserAbortError"===e.name))return void logSuggestionSuppressed("aborted",void 0,void 0,"cli");a(r(e))}finally{S===t&&(S=null)}}const y=1e4;export function getParentCacheSuppressReason(e){if(!e)return null;const t=e.message.usage;return(t.input_tokens??0)+(t.cache_creation_input_tokens??0)+(t.output_tokens??0)>y?"cache_cold":null}const b='[SUGGESTION MODE: Suggest what the user might naturally type next into Context Code.]\n\nFIRST: Look at the user\'s recent messages and original request.\n\nYour job is to predict what THEY would type - not what you think they should do.\n\nTHE TEST: Would they think "I was just about to type that"?\n\nEXAMPLES:\nUser asked "fix the bug and run tests", bug is fixed → "run the tests"\nAfter code written → "try it out"\nClaude offers options → suggest the one the user would likely pick, based on conversation\nClaude asks to continue → "yes" or "go ahead"\nTask complete, obvious follow-up → "commit this" or "push it"\nAfter error or misunderstanding → silence (let them assess/correct)\n\nBe specific: "run the tests" beats "continue".\n\nNEVER SUGGEST:\n- Evaluative ("looks good", "thanks")\n- Questions ("what about...?")\n- Claude-voice ("Let me...", "I\'ll...", "Here\'s...")\n- New ideas they didn\'t ask about\n- Multiple sentences\n\nStay silent if the next step isn\'t obvious from what the user said.\n\nFormat: 2-12 words, match the user\'s style. Or nothing.\n\nReply with ONLY the suggestion, no quotes or explanation.',v={user_intent:b,stated_intent:b};export async function generateSuggestion(e,t,o){const s=v[t],n=await u({promptMessages:[g({content:s})],cacheSafeParams:o,canUseTool:async()=>({behavior:"deny",message:"No tools needed for suggestion",decisionReason:{type:"other",reason:"suggestion only"}}),querySource:"prompt_suggestion",forkLabel:"prompt_suggestion",overrides:{abortController:e},skipTranscript:!0,skipCacheWrite:!0}),r=n.messages.find(e=>"assistant"===e.type),i="assistant"===r?.type?r.requestId??null:null;for(const e of n.messages){if("assistant"!==e.type)continue;const t=e.message.content.find(e=>"text"===e.type);if("text"===t?.type){const e=t.text.trim();if(e)return{suggestion:e,generationRequestId:i}}}return{suggestion:null,generationRequestId:i}}export function shouldFilterSuggestion(e,t,o){if(!e)return logSuggestionSuppressed("empty",void 0,t,o),!0;const s=e.toLowerCase(),n=e.trim().split(/\s+/).length,r=[["done",()=>"done"===s],["meta_text",()=>"nothing found"===s||"nothing found."===s||s.startsWith("nothing to suggest")||s.startsWith("no suggestion")||/\bsilence is\b|\bstay(s|ing)? silent\b/.test(s)||/^\W*silence\W*$/.test(s)],["meta_wrapped",()=>/^\(.*\)$|^\[.*\]$/.test(e)],["error_message",()=>s.startsWith("api error:")||s.startsWith("prompt is too long")||s.startsWith("request timed out")||s.startsWith("invalid api key")||s.startsWith("image was too large")],["prefixed_label",()=>/^\w+:\s/.test(e)],["too_few_words",()=>{if(n>=2)return!1;if(e.startsWith("/"))return!1;return!new Set(["yes","yeah","yep","yea","yup","sure","ok","okay","push","commit","deploy","stop","continue","check","exit","quit","no"]).has(s)}],["too_many_words",()=>n>12],["too_long",()=>e.length>=100],["multiple_sentences",()=>/[.!?]\s+[A-Z]/.test(e)],["has_formatting",()=>/[\n*]|\*\*/.test(e)],["evaluative",()=>/thanks|thank you|looks good|sounds good|that works|that worked|that's all|nice|great|perfect|makes sense|awesome|excellent/.test(s)],["claude_voice",()=>/^(let me|i'll|i've|i'm|i can|i would|i think|i notice|here's|here is|here are|that's|this is|this will|you can|you should|you could|sure,|of course|certainly)/i.test(e)]];for(const[s,n]of r)if(n())return logSuggestionSuppressed(s,e,t,o),!0;return!1}export function logSuggestionOutcome(e,t,o,s,n){const r=Math.round(t.length/(e.length||1)*100)/100,i=t===e,u=Math.max(0,Date.now()-o);m("tengu_prompt_suggestion",{source:"sdk",outcome:i?"accepted":"ignored",prompt_id:s,...n&&{generationRequestId:n},...i&&{timeToAcceptMs:u},...!i&&{timeToIgnoreMs:u},similarity:r,..."ant"===process.env.USER_TYPE&&{suggestion:e,userInput:t}})}export function logSuggestionSuppressed(e,t,o,s){const n=o??getPromptVariant();m("tengu_prompt_suggestion",{...s&&{source:s},outcome:"suppressed",reason:e,prompt_id:n,..."ant"===process.env.USER_TYPE&&t&&{suggestion:t}})}
1
+ import{getIsNonInteractiveSession as t}from"../../bootstrap/state.js";import{isAgentSwarmsEnabled as e}from"../../utils/agentSwarmsEnabled.js";import{count as o}from"../../utils/array.js";import{isEnvDefinedFalsy as s,isEnvTruthy as n}from"../../utils/envUtils.js";import{toError as r}from"../../utils/errors.js";import{createCacheSafeParams as i,runForkedAgent as u}from"../../utils/forkedAgent.js";import{logError as a}from"../../utils/log.js";import{createUserMessage as g,getLastAssistantMessage as l}from"../../utils/messages.js";import{getInitialSettings as p}from"../../utils/settings/settings.js";import{isTeammate as d}from"../../utils/teammate.js";import{getFeatureValue_CACHED_MAY_BE_STALE as c}from"../analytics/growthbook.js";import{logEvent as m}from"../analytics/index.js";import{currentLimits as h}from"../claudeAiLimits.js";import{isSpeculationEnabled as f,startSpeculation as S}from"./speculation.js";let y=null;export function getPromptVariant(){return"user_intent"}export function shouldEnablePromptSuggestion(){return!1}export function abortPromptSuggestion(){y&&(y.abort(),y=null)}export function getSuggestionSuppressReason(t){return t.promptSuggestionEnabled?t.pendingWorkerRequest||t.pendingSandboxRequest?"pending_permission":t.elicitation.queue.length>0?"elicitation_active":"plan"===t.toolPermissionContext.mode?"plan_mode":"external"===process.env.USER_TYPE&&"allowed"!==h.status?"rate_limit":null:"disabled"}export async function tryGenerateSuggestion(t,e,s,n,r){if(t.signal.aborted)return logSuggestionSuppressed("aborted",void 0,void 0,r),null;if(o(e,t=>"assistant"===t.type)<2)return logSuggestionSuppressed("early_conversation",void 0,void 0,r),null;const i=l(e);if(i?.isApiErrorMessage)return logSuggestionSuppressed("last_response_error",void 0,void 0,r),null;const u=getParentCacheSuppressReason(i);if(u)return logSuggestionSuppressed(u,void 0,void 0,r),null;const a=getSuggestionSuppressReason(s());if(a)return logSuggestionSuppressed(a,void 0,void 0,r),null;const g=getPromptVariant(),{suggestion:p,generationRequestId:d}=await generateSuggestion(t,g,n);return t.signal.aborted?(logSuggestionSuppressed("aborted",void 0,void 0,r),null):p?shouldFilterSuggestion(p,g,r)?null:{suggestion:p,promptId:g,generationRequestId:d}:(logSuggestionSuppressed("empty",void 0,g,r),null)}export async function executePromptSuggestion(t){if("repl_main_thread"!==t.querySource)return;y=new AbortController;const e=y,o=i(t);try{const s=await tryGenerateSuggestion(e,t.messages,t.toolUseContext.getAppState,o,"cli");if(!s)return;t.toolUseContext.setAppState(t=>({...t,promptSuggestion:{text:s.suggestion,promptId:s.promptId,shownAt:0,acceptedAt:0,generationRequestId:s.generationRequestId}})),f()&&s.suggestion&&S(s.suggestion,t,t.toolUseContext.setAppState,!1,o)}catch(t){if(t instanceof Error&&("AbortError"===t.name||"APIUserAbortError"===t.name))return void logSuggestionSuppressed("aborted",void 0,void 0,"cli");a(r(t))}finally{y===e&&(y=null)}}const _=1e4;export function getParentCacheSuppressReason(t){if(!t)return null;const e=t.message.usage;return(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.output_tokens??0)>_?"cache_cold":null}const v='[SUGGESTION MODE: Suggest what the user might naturally type next into Context Code.]\n\nFIRST: Look at the user\'s recent messages and original request.\n\nYour job is to predict what THEY would type - not what you think they should do.\n\nTHE TEST: Would they think "I was just about to type that"?\n\nEXAMPLES:\nUser asked "fix the bug and run tests", bug is fixed → "run the tests"\nAfter code written → "try it out"\nClaude offers options → suggest the one the user would likely pick, based on conversation\nClaude asks to continue → "yes" or "go ahead"\nTask complete, obvious follow-up → "commit this" or "push it"\nAfter error or misunderstanding → silence (let them assess/correct)\n\nBe specific: "run the tests" beats "continue".\n\nNEVER SUGGEST:\n- Evaluative ("looks good", "thanks")\n- Questions ("what about...?")\n- Claude-voice ("Let me...", "I\'ll...", "Here\'s...")\n- New ideas they didn\'t ask about\n- Multiple sentences\n\nStay silent if the next step isn\'t obvious from what the user said.\n\nFormat: 2-12 words, match the user\'s style. Or nothing.\n\nReply with ONLY the suggestion, no quotes or explanation.',b={user_intent:v,stated_intent:v};export async function generateSuggestion(t,e,o){const s=b[e],n=await u({promptMessages:[g({content:s})],cacheSafeParams:o,canUseTool:async()=>({behavior:"deny",message:"No tools needed for suggestion",decisionReason:{type:"other",reason:"suggestion only"}}),querySource:"prompt_suggestion",forkLabel:"prompt_suggestion",overrides:{abortController:t},skipTranscript:!0,skipCacheWrite:!0}),r=n.messages.find(t=>"assistant"===t.type),i="assistant"===r?.type?r.requestId??null:null;for(const t of n.messages){if("assistant"!==t.type)continue;const e=t.message.content.find(t=>"text"===t.type);if("text"===e?.type){const t=e.text.trim();if(t)return{suggestion:t,generationRequestId:i}}}return{suggestion:null,generationRequestId:i}}export function shouldFilterSuggestion(t,e,o){if(!t)return logSuggestionSuppressed("empty",void 0,e,o),!0;const s=t.toLowerCase(),n=t.trim().split(/\s+/).length,r=[["done",()=>"done"===s],["meta_text",()=>"nothing found"===s||"nothing found."===s||s.startsWith("nothing to suggest")||s.startsWith("no suggestion")||/\bsilence is\b|\bstay(s|ing)? silent\b/.test(s)||/^\W*silence\W*$/.test(s)],["meta_wrapped",()=>/^\(.*\)$|^\[.*\]$/.test(t)],["error_message",()=>s.startsWith("api error:")||s.startsWith("prompt is too long")||s.startsWith("request timed out")||s.startsWith("invalid api key")||s.startsWith("image was too large")],["prefixed_label",()=>/^\w+:\s/.test(t)],["too_few_words",()=>{if(n>=2)return!1;if(t.startsWith("/"))return!1;return!new Set(["yes","yeah","yep","yea","yup","sure","ok","okay","push","commit","deploy","stop","continue","check","exit","quit","no"]).has(s)}],["too_many_words",()=>n>12],["too_long",()=>t.length>=100],["multiple_sentences",()=>/[.!?]\s+[A-Z]/.test(t)],["has_formatting",()=>/[\n*]|\*\*/.test(t)],["evaluative",()=>/thanks|thank you|looks good|sounds good|that works|that worked|that's all|nice|great|perfect|makes sense|awesome|excellent/.test(s)],["claude_voice",()=>/^(let me|i'll|i've|i'm|i can|i would|i think|i notice|here's|here is|here are|that's|this is|this will|you can|you should|you could|sure,|of course|certainly)/i.test(t)]];for(const[s,n]of r)if(n())return logSuggestionSuppressed(s,t,e,o),!0;return!1}export function logSuggestionOutcome(t,e,o,s,n){const r=Math.round(e.length/(t.length||1)*100)/100,i=e===t,u=Math.max(0,Date.now()-o);m("tengu_prompt_suggestion",{source:"sdk",outcome:i?"accepted":"ignored",prompt_id:s,...n&&{generationRequestId:n},...i&&{timeToAcceptMs:u},...!i&&{timeToIgnoreMs:u},similarity:r,..."ant"===process.env.USER_TYPE&&{suggestion:t,userInput:e}})}export function logSuggestionSuppressed(t,e,o,s){const n=o??getPromptVariant();m("tengu_prompt_suggestion",{...s&&{source:s},outcome:"suppressed",reason:t,prompt_id:n,..."ant"===process.env.USER_TYPE&&e&&{suggestion:e}})}
@@ -1 +1 @@
1
- import{isEnvTruthy as e}from"../../utils/envUtils.js";import{isTelemetryDisabled as s}from"../../utils/privacyLevel.js";export function isAnalyticsDisabled(){return"test"===process.env.NODE_ENV||e(process.env.CLAUDE_CODE_USE_BEDROCK)||e(process.env.CLAUDE_CODE_USE_VERTEX)||e(process.env.CLAUDE_CODE_USE_FOUNDRY)||s()}export function isFeedbackSurveyDisabled(){return"test"===process.env.NODE_ENV||s()}
1
+ export function isAnalyticsDisabled(){return!0}export function isFeedbackSurveyDisabled(){return!0}
@@ -1 +1 @@
1
- import e from"axios";import{createHash as t}from"crypto";import o from"lodash-es/memoize.js";import{getOrCreateUserID as r}from"../../utils/config.js";import{logError as n}from"../../utils/log.js";import{getCanonicalName as s}from"../../utils/model/model.js";import{getAPIProvider as _}from"../../utils/model/providers.js";import{MODEL_COSTS as a}from"../../utils/modelCost.js";import{isAnalyticsDisabled as u}from"./config.js";import{getEventMetadata as i}from"./metadata.js";const c=new Set(["chrome_bridge_connection_succeeded","chrome_bridge_connection_failed","chrome_bridge_disconnected","chrome_bridge_tool_call_completed","chrome_bridge_tool_call_error","chrome_bridge_tool_call_started","chrome_bridge_tool_call_timeout","tengu_api_error","tengu_api_success","tengu_brief_mode_enabled","tengu_brief_mode_toggled","tengu_brief_send","tengu_cancel","tengu_compact_failed","tengu_exit","tengu_flicker","tengu_init","tengu_model_fallback_triggered","tengu_oauth_error","tengu_oauth_success","tengu_oauth_token_refresh_failure","tengu_oauth_token_refresh_success","tengu_oauth_token_refresh_lock_acquiring","tengu_oauth_token_refresh_lock_acquired","tengu_oauth_token_refresh_starting","tengu_oauth_token_refresh_completed","tengu_oauth_token_refresh_lock_releasing","tengu_oauth_token_refresh_lock_released","tengu_query_error","tengu_session_file_read","tengu_started","tengu_tool_use_error","tengu_tool_use_granted_in_prompt_permanent","tengu_tool_use_granted_in_prompt_temporary","tengu_tool_use_rejected_in_prompt","tengu_tool_use_success","tengu_uncaught_exception","tengu_unhandled_rejection","tengu_voice_recording_started","tengu_voice_toggled","tengu_team_mem_sync_pull","tengu_team_mem_sync_push","tengu_team_mem_sync_started","tengu_team_mem_entries_capped"]),l=["arch","clientType","errorType","http_status_range","http_status","kairosActive","model","platform","provider","skillMode","subscriptionType","toolName","userBucket","userType","version","versionBase"];function camelToSnakeCase(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}let d=[],g=null,m=null;async function flushLogs(){if(0===d.length)return;const t=d;d=[];try{await e.post("https://http-intake.logs.us5.datadoghq.com/api/v2/logs",t,{headers:{"Content-Type":"application/json","DD-API-KEY":"pubbbf48e6d78dae54bceaa4acf463299bf"},timeout:5e3})}catch(e){n(e)}}function scheduleFlush(){g||(g=setTimeout(()=>{g=null,flushLogs()},parseInt(process.env.CONTEXT_CODE_DATADOG_FLUSH_INTERVAL_MS||process.env.CLAUDE_CODE_DATADOG_FLUSH_INTERVAL_MS||"",10)||15e3).unref())}export const initializeDatadog=o(async()=>{if(u())return m=!1,!1;try{return m=!0,!0}catch(e){return n(e),m=!1,!1}});export async function shutdownDatadog(){g&&(clearTimeout(g),g=null),await flushLogs()}export async function trackDatadogEvent(e,t){if("production"!==process.env.NODE_ENV)return;if("firstParty"!==_())return;let o=m;if(null===o&&(o=await initializeDatadog()),o&&c.has(e))try{const o=await i({model:t.model,betas:t.betas}),{envContext:r,...n}=o,_={...n,...r,...t,userBucket:p()};if("string"==typeof _.toolName&&_.toolName.startsWith("mcp__")&&(_.toolName="mcp"),"ant"!==process.env.USER_TYPE&&"string"==typeof _.model){const e=s(_.model.replace(/\[1m]$/i,""));_.model=e in a?e:"other"}if("string"==typeof _.version&&(_.version=_.version.replace(/^(\d+\.\d+\.\d+-dev\.\d{8})\.t\d+\.sha[a-f0-9]+$/,"$1")),void 0!==_.status&&null!==_.status){const e=String(_.status);_.http_status=e;const t=e.charAt(0);t>="1"&&t<="5"&&(_.http_status_range=`${t}xx`),delete _.status}const u=_,c={ddsource:"nodejs",ddtags:[`event:${e}`,...l.filter(e=>void 0!==u[e]&&null!==u[e]).map(e=>`${camelToSnakeCase(e)}:${u[e]}`)].join(","),message:e,service:"claude-code",hostname:"claude-code",env:process.env.USER_TYPE};for(const[e,t]of Object.entries(_))null!=t&&(c[camelToSnakeCase(e)]=t);d.push(c),d.length>=100?(g&&(clearTimeout(g),g=null),flushLogs()):scheduleFlush()}catch(e){n(e)}}const p=o(()=>{const e=r(),o=t("sha256").update(e).digest("hex");return parseInt(o.slice(0,8),16)%30});
1
+ import{createHash as e}from"crypto";import t from"lodash-es/memoize.js";import{getOrCreateUserID as o}from"../../utils/config.js";import{logError as r}from"../../utils/log.js";import{getCanonicalName as n}from"../../utils/model/model.js";import{getAPIProvider as _}from"../../utils/model/providers.js";import{MODEL_COSTS as s}from"../../utils/modelCost.js";import{isAnalyticsDisabled as u}from"./config.js";import{getEventMetadata as a}from"./metadata.js";const c=new Set(["chrome_bridge_connection_succeeded","chrome_bridge_connection_failed","chrome_bridge_disconnected","chrome_bridge_tool_call_completed","chrome_bridge_tool_call_error","chrome_bridge_tool_call_started","chrome_bridge_tool_call_timeout","tengu_api_error","tengu_api_success","tengu_brief_mode_enabled","tengu_brief_mode_toggled","tengu_brief_send","tengu_cancel","tengu_compact_failed","tengu_exit","tengu_flicker","tengu_init","tengu_model_fallback_triggered","tengu_oauth_error","tengu_oauth_success","tengu_oauth_token_refresh_failure","tengu_oauth_token_refresh_success","tengu_oauth_token_refresh_lock_acquiring","tengu_oauth_token_refresh_lock_acquired","tengu_oauth_token_refresh_starting","tengu_oauth_token_refresh_completed","tengu_oauth_token_refresh_lock_releasing","tengu_oauth_token_refresh_lock_released","tengu_query_error","tengu_session_file_read","tengu_started","tengu_tool_use_error","tengu_tool_use_granted_in_prompt_permanent","tengu_tool_use_granted_in_prompt_temporary","tengu_tool_use_rejected_in_prompt","tengu_tool_use_success","tengu_uncaught_exception","tengu_unhandled_rejection","tengu_voice_recording_started","tengu_voice_toggled","tengu_team_mem_sync_pull","tengu_team_mem_sync_push","tengu_team_mem_sync_started","tengu_team_mem_entries_capped"]),i=["arch","clientType","errorType","http_status_range","http_status","kairosActive","model","platform","provider","skillMode","subscriptionType","toolName","userBucket","userType","version","versionBase"];function camelToSnakeCase(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}let l=[],d=null,g=null;async function flushLogs(){l=[]}function scheduleFlush(){d||(d=setTimeout(()=>{d=null,flushLogs()},parseInt(process.env.CONTEXT_CODE_DATADOG_FLUSH_INTERVAL_MS||process.env.CLAUDE_CODE_DATADOG_FLUSH_INTERVAL_MS||"",10)||15e3).unref())}export const initializeDatadog=t(async()=>{if(u())return g=!1,!1;try{return g=!0,!0}catch(e){return r(e),g=!1,!1}});export async function shutdownDatadog(){d&&(clearTimeout(d),d=null),await flushLogs()}export async function trackDatadogEvent(e,t){if("production"!==process.env.NODE_ENV)return;if("firstParty"!==_())return;let o=g;if(null===o&&(o=await initializeDatadog()),o&&c.has(e))try{const o=await a({model:t.model,betas:t.betas}),{envContext:r,..._}=o,u={..._,...r,...t,userBucket:m()};if("string"==typeof u.toolName&&u.toolName.startsWith("mcp__")&&(u.toolName="mcp"),"ant"!==process.env.USER_TYPE&&"string"==typeof u.model){const e=n(u.model.replace(/\[1m]$/i,""));u.model=e in s?e:"other"}if("string"==typeof u.version&&(u.version=u.version.replace(/^(\d+\.\d+\.\d+-dev\.\d{8})\.t\d+\.sha[a-f0-9]+$/,"$1")),void 0!==u.status&&null!==u.status){const e=String(u.status);u.http_status=e;const t=e.charAt(0);t>="1"&&t<="5"&&(u.http_status_range=`${t}xx`),delete u.status}const c=u,g={ddsource:"nodejs",ddtags:[`event:${e}`,...i.filter(e=>void 0!==c[e]&&null!==c[e]).map(e=>`${camelToSnakeCase(e)}:${c[e]}`)].join(","),message:e,service:"claude-code",hostname:"claude-code",env:process.env.USER_TYPE};for(const[e,t]of Object.entries(u))null!=t&&(g[camelToSnakeCase(e)]=t);l.push(g),l.length>=100?(d&&(clearTimeout(d),d=null),flushLogs()):scheduleFlush()}catch(e){r(e)}}const m=t(()=>{const t=o(),r=e("sha256").update(t).digest("hex");return parseInt(r.slice(0,8),16)%30});