From 4f12899ee1366696661f2c96f25013cc28e64e20 Mon Sep 17 00:00:00 2001 From: "C.z" <1911176376@qq.com> Date: Thu, 23 Apr 2026 16:49:56 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=B3=A8=E9=87=8A=E4=B8=AD=E6=96=87=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- comment_counts.txt | 693 + comment_matches.txt | 37172 +++++ docs/README.md | 100 + docs/architecture-design.md | 259 + docs/bridge-remote-control.md | 308 + docs/command-tool-task-system.md | 332 + docs/request-lifecycle.md | 289 + docs/runtime-startup.md | 246 + docs/services-layer.md | 294 + docs/source-code-reading-guide.md | 222 + docs/state-and-data-flow.md | 288 + package.json | 1 + real_comment_counts.json | 2774 + real_comment_extract.json | 109200 +++++++++++++++ services_tools_comments.json | 870 + services_tools_comments_after.txt | 276 + src/QueryEngine.ts | 320 +- src/Task.ts | 24 +- src/assistant/sessionHistory.ts | 14 +- src/bridge/bridgeApi.ts | 90 +- src/bridge/bridgeConfig.ts | 29 +- src/bridge/bridgeDebug.ts | 57 +- src/bridge/bridgeEnabled.ts | 140 +- src/bridge/bridgeMain.ts | 942 +- src/bridge/bridgeMessaging.ts | 148 +- src/bridge/bridgePermissionCallbacks.ts | 10 +- src/bridge/bridgePointer.ts | 97 +- src/bridge/bridgeStatusUtil.ts | 50 +- src/bridge/bridgeUI.ts | 107 +- src/bridge/capacityWake.ts | 24 +- src/bridge/codeSessionApi.ts | 24 +- src/bridge/createSession.ts | 63 +- src/bridge/debugUtils.ts | 24 +- src/bridge/envLessBridgeConfig.ts | 103 +- src/bridge/flushGate.ts | 41 +- src/bridge/inboundAttachments.ts | 58 +- src/bridge/initReplBridge.ts | 309 +- src/bridge/jwtUtils.ts | 83 +- src/bridge/pollConfig.ts | 57 +- src/bridge/pollConfigDefaults.ts | 69 +- src/bridge/remoteBridgeCore.ts | 375 +- src/bridge/replBridge.ts | 252 +- src/bridge/replBridgeHandle.ts | 22 +- src/bridge/replBridgeTransport.ts | 226 +- src/bridge/sessionRunner.ts | 105 +- src/bridge/trustedDevice.ts | 85 +- src/bridge/types.ts | 143 +- src/bridge/workSecret.ts | 60 +- src/buddy/CompanionSprite.tsx | 64 +- src/buddy/companion.ts | 38 +- src/buddy/prompt.ts | 2 +- src/buddy/sprites.ts | 14 +- src/buddy/types.ts | 12 +- src/buddy/useBuddyNotification.tsx | 10 +- src/cli/exit.ts | 26 +- src/cli/ndjsonSafeStringify.ts | 30 +- src/cli/transports/WorkerStateUploader.ts | 47 +- src/cli/transports/transportUtils.ts | 6 +- src/cli/update.ts | 46 +- src/commands/add-dir/add-dir.tsx | 16 +- src/commands/add-dir/validation.ts | 16 +- src/commands/branch/branch.ts | 68 +- src/commands/branch/index.ts | 2 +- src/commands/bridge-kick.ts | 4 +- src/commands/bridge/bridge.tsx | 10 +- src/commands/brief.ts | 51 +- src/commands/clear/caches.ts | 71 +- src/commands/clear/conversation.ts | 86 +- src/commands/color/color.ts | 12 +- src/commands/commit-push-pr.ts | 8 +- src/commands/compact/compact.ts | 54 +- src/commands/copy/copy.tsx | 10 +- src/commands/cost/index.ts | 6 +- src/commands/effort/effort.tsx | 10 +- src/commands/exit/exit.tsx | 6 +- src/commands/fast/fast.tsx | 8 +- src/commands/feedback/feedback.tsx | 2 +- src/commands/passes/passes.tsx | 2 +- src/commands/plan/plan.tsx | 8 +- src/commands/reload-plugins/index.ts | 6 +- src/commands/reload-plugins/reload-plugins.ts | 33 +- src/commands/review.ts | 10 +- src/commands/rewind/rewind.ts | 2 +- src/commands/sandbox-toggle/index.ts | 4 +- .../sandbox-toggle/sandbox-toggle.tsx | 26 +- src/commands/security-review.ts | 6 +- src/commands/thinkback-play/index.ts | 4 +- src/commands/thinkback-play/thinkback-play.ts | 2 +- src/commands/upgrade/upgrade.tsx | 2 +- src/commands/voice/voice.ts | 26 +- src/components/ValidationErrorsList.tsx | 18 +- src/components/VirtualMessageList.tsx | 543 +- src/context.ts | 32 +- src/cost-tracker.ts | 22 +- src/dialogLaunchers.tsx | 46 +- src/entrypoints/agentSdkTypes.ts | 30 +- src/entrypoints/init.ts | 135 +- src/entrypoints/mcp.ts | 20 +- src/entrypoints/sandboxTypes.ts | 16 +- src/entrypoints/sdk/coreTypes.ts | 22 +- src/entrypoints/sdk/runtimeTypes.ts | 2 +- src/entrypoints/sdk/toolTypes.ts | 2 +- src/history.ts | 122 +- src/hooks/useVimInput.ts | 50 +- src/hooks/useVirtualScroll.ts | 642 +- src/ink.ts | 4 +- src/ink/Ansi.tsx | 10 +- src/ink/bidi.ts | 52 +- src/ink/clearTerminal.ts | 24 +- src/ink/colorize.ts | 73 +- src/ink/components/AlternateScreen.tsx | 29 +- src/ink/components/ClockContext.tsx | 18 +- .../components/CursorDeclarationContext.ts | 19 +- src/ink/components/RawAnsi.tsx | 27 +- src/ink/components/TerminalFocusContext.tsx | 6 +- src/ink/constants.ts | 2 +- src/ink/dom.ts | 87 +- src/ink/events/click-event.ts | 28 +- src/ink/events/emitter.ts | 11 +- src/ink/events/input-event.ts | 115 +- src/ink/events/keyboard-event.ts | 24 +- src/ink/events/terminal-event.ts | 16 +- src/ink/events/terminal-focus-event.ts | 8 +- src/ink/focus.ts | 32 +- src/ink/frame.ts | 52 +- src/ink/hit-test.ts | 46 +- src/ink/hooks/use-animation-frame.ts | 23 +- src/ink/hooks/use-declared-cursor.ts | 57 +- src/ink/hooks/use-input.ts | 41 +- src/ink/hooks/use-search-highlight.ts | 30 +- src/ink/hooks/use-selection.ts | 49 +- src/ink/hooks/use-tab-status.ts | 19 +- src/ink/hooks/use-terminal-viewport.ts | 55 +- src/ink/instances.ts | 8 +- src/ink/measure-text.ts | 10 +- src/ink/node-cache.ts | 23 +- src/ink/optimizer.ts | 42 +- src/ink/render-border.ts | 12 +- src/ink/root.ts | 44 +- src/ink/stringWidth.ts | 80 +- src/ink/supports-hyperlinks.ts | 18 +- src/ink/tabstops.ts | 4 +- src/ink/termio/ansi.ts | 16 +- src/ink/termio/csi.ts | 148 +- src/ink/termio/dec.ts | 22 +- src/ink/termio/esc.ts | 26 +- src/ink/termio/osc.ts | 228 +- src/ink/termio/parser.ts | 55 +- src/ink/termio/tokenize.ts | 98 +- src/ink/termio/types.ts | 62 +- src/interactiveHelpers.tsx | 157 +- src/memdir/findRelevantMemories.ts | 32 +- src/memdir/memdir.ts | 159 +- src/memdir/memoryAge.ts | 32 +- src/memdir/memoryScan.ts | 28 +- src/memdir/memoryTypes.ts | 90 +- src/memdir/paths.ts | 172 +- src/memdir/teamMemPaths.ts | 174 +- src/memdir/teamMemPrompts.ts | 6 +- .../migrateAutoUpdatesToSettings.ts | 18 +- ...rateBypassPermissionsAcceptedToSettings.ts | 6 +- ...ateEnableAllProjectMcpServersToSettings.ts | 28 +- src/migrations/migrateFennecToOpus.ts | 9 +- src/migrations/migrateLegacyOpusToCurrent.ts | 22 +- src/migrations/migrateOpusToOpus1m.ts | 14 +- ...plBridgeEnabledToRemoteControlAtStartup.ts | 13 +- src/migrations/migrateSonnet1mToSonnet45.ts | 20 +- src/migrations/migrateSonnet45ToSonnet46.ts | 18 +- .../resetAutoModeOptInForDefaultOffer.ts | 22 +- src/migrations/resetProToOpusDefault.ts | 6 +- src/projectOnboardingState.ts | 8 +- src/query.ts | 575 +- src/remote/RemoteSessionManager.ts | 73 +- src/remote/SessionsWebSocket.ts | 88 +- src/remote/remotePermissionBridge.ts | 12 +- src/remote/sdkMessageAdapter.ts | 85 +- src/services/PromptSuggestion/speculation.ts | 2 +- src/services/tools/StreamingToolExecutor.ts | 119 +- src/services/tools/toolExecution.ts | 302 +- src/services/tools/toolHooks.ts | 74 +- src/services/tools/toolOrchestration.ts | 14 +- src/services/voiceKeyterms.ts | 44 +- src/services/voiceStreamSTT.ts | 250 +- src/setup.ts | 199 +- src/tools.ts | 125 +- src/tools/BashTool/BashTool.tsx | 354 +- src/tools/BashTool/BashToolResultMessage.tsx | 18 +- src/tools/BashTool/UI.tsx | 12 +- src/tools/BashTool/bashCommandHelpers.ts | 24 +- src/tools/BashTool/bashPermissions.ts | 172 +- src/tools/BashTool/bashSecurity.ts | 1381 +- src/tools/BashTool/commandMatching.ts | 319 + src/tools/BashTool/commandSemantics.ts | 40 +- .../BashTool/destructiveCommandWarning.ts | 19 +- src/tools/BashTool/pathValidation.ts | 87 +- src/tools/BashTool/prompt.ts | 14 +- src/tools/BashTool/readOnlyValidation.ts | 2 +- src/tools/BashTool/sedValidation.ts | 307 +- src/tools/BashTool/shouldUseSandbox.ts | 49 +- src/tools/BashTool/toolName.ts | 2 +- src/tools/BashTool/utils.ts | 60 +- src/tools/PowerShellTool/PowerShellTool.tsx | 396 +- src/tools/PowerShellTool/prompt.ts | 10 +- .../PowerShellTool/readOnlyValidation.ts | 328 +- src/voice/voiceModeEnabled.ts | 45 +- 205 files changed, 160885 insertions(+), 7646 deletions(-) create mode 100644 comment_counts.txt create mode 100644 comment_matches.txt create mode 100644 docs/README.md create mode 100644 docs/architecture-design.md create mode 100644 docs/bridge-remote-control.md create mode 100644 docs/command-tool-task-system.md create mode 100644 docs/request-lifecycle.md create mode 100644 docs/runtime-startup.md create mode 100644 docs/services-layer.md create mode 100644 docs/source-code-reading-guide.md create mode 100644 docs/state-and-data-flow.md create mode 100644 real_comment_counts.json create mode 100644 real_comment_extract.json create mode 100644 services_tools_comments.json create mode 100644 services_tools_comments_after.txt create mode 100644 src/tools/BashTool/commandMatching.ts diff --git a/comment_counts.txt b/comment_counts.txt new file mode 100644 index 000000000..72c743743 --- /dev/null +++ b/comment_counts.txt @@ -0,0 +1,693 @@ +959 src/utils\sessionStorage.ts +922 src/utils\bash\ast.ts +647 src/utils\hooks.ts +610 src/utils\messages.ts +576 src/utils\plugins\pluginLoader.ts +552 src/utils\plugins\marketplaceManager.ts +542 src/utils\attachments.ts +457 src/services\api\claude.ts +427 src/utils\bash\bashParser.ts +424 src/utils\powershell\parser.ts +408 src/services\mcp\client.ts +395 src/utils\permissions\filesystem.ts +362 src/utils\shell\readOnlyCommandValidation.ts +338 src/services\mcp\auth.ts +319 src/utils\bash\commands.ts +316 src/utils\bash\heredoc.ts +313 src/utils\plugins\schemas.ts +304 src/utils\config.ts +286 src/utils\auth.ts +269 src/services\analytics\growthbook.ts +263 src/utils\toolResultStorage.ts +263 src/utils\permissions\permissionSetup.ts +258 src/utils\claudemd.ts +244 src/utils\worktree.ts +232 src/utils\plugins\installedPluginsManager.ts +229 src/services\compact\compact.ts +222 src/services\mcp\config.ts +211 src/services\teamMemorySync\index.ts +211 src/utils\nativeInstaller\installer.ts +208 src/utils\swarm\inProcessRunner.ts +205 src/utils\teleport.tsx +200 src/utils\permissions\yoloClassifier.ts +189 src/services\plugins\pluginOperations.ts +184 src/utils\forkedAgent.ts +184 src/utils\permissions\permissions.ts +175 src/utils\sandbox\sandbox-adapter.ts +175 src/utils\git.ts +173 src/utils\Cursor.ts +171 src/utils\ide.ts +168 src/utils\toolSearch.ts +162 src/services\mcp\useManageMCPConnections.ts +161 src/utils\collapseReadSearch.ts +155 src/utils\gracefulShutdown.ts +153 src/utils\fsOperations.ts +151 src/utils\processUserInput\processSlashCommand.tsx +151 src/utils\cronScheduler.ts +151 src/utils\plugins\mcpbHandler.ts +150 src/services\tools\toolExecution.ts +148 src/utils\cronTasks.ts +145 src/utils\settings\settings.ts +145 src/services\analytics\metadata.ts +143 src/utils\git\gitFilesystem.ts +133 src/services\voiceStreamSTT.ts +133 src/utils\commitAttribution.ts +132 src/utils\computerUse\executor.ts +132 src/services\api\errors.ts +132 src/utils\teammateMailbox.ts +130 src/utils\swarm\permissionSync.ts +128 src/utils\markdownConfigLoader.ts +128 src/utils\analyzeContext.ts +127 src/services\remoteManagedSettings\index.ts +124 src/utils\fileHistory.ts +124 src/utils\conversationRecovery.ts +124 src/utils\telemetry\perfettoTracing.ts +123 src/services\compact\sessionMemoryCompact.ts +123 src/utils\tasks.ts +120 src/utils\sessionRestore.ts +117 src/utils\plugins\validatePlugin.ts +116 src/services\api\withRetry.ts +115 src/utils\swarm\backends\types.ts +114 src/utils\model\model.ts +113 src/utils\imageResizer.ts +112 src/types\textInputTypes.ts +112 src/utils\bash\treeSitterAnalysis.ts +111 src/utils\plugins\pluginInstallationHelpers.ts +110 src/utils\settings\types.ts +109 src/utils\tmuxSocket.ts +108 src/services\compact\microCompact.ts +108 src/utils\plugins\pluginOptionsStorage.ts +107 src/utils\powershell\staticPrefix.ts +107 src/utils\api.ts +107 src/utils\stats.ts +107 src/utils\suggestions\commandSuggestions.ts +106 src/services\lsp\LSPServerInstance.ts +105 src/services\mcp\utils.ts +104 src/utils\plugins\mcpPluginIntegration.ts +103 src/utils\frontmatterParser.ts +103 src/utils\ripgrep.ts +103 src/utils\deepLink\terminalLauncher.ts +103 src/utils\bash\ShellSnapshot.ts +102 src/utils\file.ts +100 src/utils\sessionStoragePortable.ts +100 src/services\extractMemories\extractMemories.ts +99 src/utils\permissions\pathValidation.ts +98 src/utils\swarm\teamHelpers.ts +97 src/services\mcp\channelNotification.ts +97 src/utils\settings\changeDetector.ts +96 src/utils\messageQueueManager.ts +95 src/utils\swarm\backends\registry.ts +95 src/services\api\client.ts +95 src/utils\plugins\marketplaceHelpers.ts +94 src/services\analytics\firstPartyEventLogger.ts +94 src/utils\handlePromptSubmit.ts +94 src/services\teamMemorySync\watcher.ts +93 src/utils\plugins\zipCache.ts +92 src/services\api\promptCacheBreakDetection.ts +91 src/services\voice.ts +90 src/utils\proxy.ts +90 src/constants\prompts.ts +89 src/utils\telemetry\sessionTracing.ts +89 src/services\mockRateLimits.ts +89 src/services\api\filesApi.ts +88 src/utils\Shell.ts +87 src/utils\plugins\dependencyResolver.ts +85 src/services\mcp\channelPermissions.ts +85 src/services\mcp\xaa.ts +84 src/utils\bash\bashPipeCommand.ts +83 src/utils\listSessionsImpl.ts +82 src/utils\telemetry\betaSessionTracing.ts +81 src/utils\fullscreen.ts +81 src/utils\betas.ts +79 src/utils\swarm\backends\ITermBackend.ts +79 src/utils\gitDiff.ts +77 src/types\permissions.ts +77 src/utils\processUserInput\processUserInput.ts +77 src/utils\telemetry\instrumentation.ts +76 src/utils\autoUpdater.ts +75 src/services\lsp\manager.ts +75 src/utils\bash\shellQuote.ts +75 src/utils\swarm\backends\TmuxBackend.ts +75 src/utils\queryHelpers.ts +75 src/services\lsp\LSPDiagnosticRegistry.ts +75 src/services\policyLimits\index.ts +74 src/utils\releaseNotes.ts +74 src/utils\task\diskOutput.ts +73 src/services\SessionMemory\sessionMemory.ts +72 src/utils\log.ts +72 src/utils\nativeInstaller\pidLock.ts +72 src/utils\imagePaste.ts +71 src/utils\doctorDiagnostic.ts +70 src/utils\plugins\loadPluginCommands.ts +70 src/utils\computerUse\wrapper.tsx +70 src/services\api\sessionIngress.ts +69 src/services\mcp\xaaIdpLogin.ts +69 src/services\analytics\firstPartyEventLoggingExporter.ts +68 src/services\tokenEstimation.ts +67 src/utils\teammate.ts +67 src/utils\plugins\pluginStartupCheck.ts +67 src/utils\tokens.ts +66 src/utils\plugins\officialMarketplaceGcs.ts +66 src/services\lsp\LSPServerManager.ts +66 src/utils\ultraplan\ccrSession.ts +66 src/utils\agentContext.ts +65 src/utils\shell\bashProvider.ts +65 src/utils\slowOperations.ts +63 src/utils\memoryFileDetection.ts +63 src/utils\swarm\spawnInProcess.ts +63 src/utils\plugins\officialMarketplaceStartupCheck.ts +63 src/utils\plugins\pluginDirectories.ts +63 src/utils\hooks\ssrfGuard.ts +62 src/utils\plugins\loadPluginHooks.ts +62 src/utils\managedEnv.ts +61 src/utils\memoize.ts +61 src/utils\theme.ts +61 src/utils\attribution.ts +61 src/services\compact\autoCompact.ts +60 src/utils\deepLink\registerProtocol.ts +60 src/utils\plans.ts +60 src/utils\effort.ts +59 src/utils\skills\skillChangeDetector.ts +59 src/services\tools\StreamingToolExecutor.ts +59 src/utils\task\TaskOutput.ts +58 src/utils\statsCache.ts +58 src/utils\settings\mdm\settings.ts +58 src/utils\plugins\lspRecommendation.ts +58 src/utils\permissions\shadowedRuleDetection.ts +57 src/utils\plugins\refresh.ts +57 src/types\logs.ts +57 src/utils\telemetry\pluginTelemetry.ts +56 src/utils\swarm\backends\InProcessBackend.ts +56 src/services\claudeAiLimits.ts +56 src/utils\plugins\pluginAutoupdate.ts +55 src/utils\errors.ts +55 src/utils\transcriptSearch.ts +55 src/services\settingsSync\index.ts +55 src/utils\permissions\permissionRuleParser.ts +54 src/utils\path.ts +53 src/utils\hooks\execHttpHook.ts +53 src/services\teamMemorySync\secretScanner.ts +52 src/utils\json.ts +52 src/utils\hooks\sessionHooks.ts +52 src/utils\nativeInstaller\packageManagers.ts +52 src/utils\stringUtils.ts +51 src/utils\cron.ts +51 src/utils\powershell\dangerousCmdlets.ts +50 src/utils\plugins\pluginVersioning.ts +50 src/utils\claudeCodeHints.ts +49 src/services\analytics\index.ts +49 src/utils\swarm\backends\PaneBackendExecutor.ts +49 src/utils\task\framework.ts +49 src/services\api\errorUtils.ts +48 src/utils\ShellCommand.ts +48 src/utils\permissions\shellRuleMatching.ts +48 src/utils\editor.ts +48 src/utils\fastMode.ts +47 src/utils\ansiToPng.ts +47 src/utils\plugins\lspPluginIntegration.ts +47 src/utils\queryProfiler.ts +47 src/utils\shell\powershellProvider.ts +47 src/services\lsp\LSPClient.ts +46 src/utils\hooks\hooksConfigSnapshot.ts +46 src/services\diagnosticTracking.ts +46 src/utils\nativeInstaller\download.ts +46 src/utils\deepLink\parseDeepLink.ts +46 src/services\rateLimitMessages.ts +46 src/utils\env.ts +46 src/utils\readFileInRange.ts +46 src/utils\bash\shellQuoting.ts +45 src/services\api\grove.ts +45 src/utils\teleport\api.ts +45 src/utils\earlyInput.ts +45 src/utils\sideQuery.ts +45 src/utils\permissions\permissionsLoader.ts +45 src/utils\shell\prefix.ts +44 src/utils\settings\permissionValidation.ts +44 src/utils\codeIndexing.ts +44 src/utils\claudeInChrome\chromeNativeHost.ts +44 src/utils\plugins\parseMarketplaceInput.ts +44 src/services\mcp\SdkControlTransport.ts +44 src/utils\swarm\backends\detection.ts +44 src/utils\claudeInChrome\setup.ts +44 src/utils\computerUse\appNames.ts +43 src/utils\argumentSubstitution.ts +43 src/utils\model\bedrock.ts +43 src/utils\dxt\zip.ts +43 src/utils\promptShellExecution.ts +42 src/utils\secureStorage\macOsKeychainStorage.ts +42 src/services\autoDream\autoDream.ts +42 src/utils\debugFilter.ts +42 src/utils\secureStorage\macOsKeychainHelpers.ts +42 src/utils\sessionState.ts +41 src/utils\plugins\installCounts.ts +41 src/utils\git\gitConfigParser.ts +41 src/utils\detectRepository.ts +41 src/utils\computerUse\computerUseLock.ts +41 src/utils\headlessProfiler.ts +40 src/utils\model\modelOptions.ts +40 src/utils\model\modelAllowlist.ts +40 src/services\PromptSuggestion\speculation.ts +40 src/utils\deepLink\protocolHandler.ts +40 src/utils\concurrentSessions.ts +40 src/services\lsp\passiveFeedback.ts +40 src/services\plugins\pluginCliCommands.ts +40 src/services\oauth\client.ts +40 src/utils\secureStorage\keychainPrefetch.ts +39 src/utils\cleanup.ts +39 src/services\remoteManagedSettings\syncCache.ts +39 src/utils\QueryGuard.ts +39 src/utils\plugins\reconciler.ts +39 src/types\command.ts +39 src/utils\envUtils.ts +39 src/utils\plugins\headlessPluginInstall.ts +38 src/utils\markdown.ts +38 src/services\SessionMemory\sessionMemoryUtils.ts +38 src/utils\authFileDescriptor.ts +37 src/constants\apiLimits.ts +37 src/utils\claudeInChrome\mcpServer.ts +37 src/services\api\logging.ts +37 src/services\teamMemorySync\types.ts +37 src/utils\swarm\spawnUtils.ts +36 src/utils\truncate.ts +36 src/utils\sideQuestion.ts +36 src/utils\bash\ParsedCommand.ts +36 src/utils\hooks\execAgentHook.ts +36 src/utils\startupProfiler.ts +36 src/services\tools\toolHooks.ts +35 src/utils\swarm\backends\it2Setup.ts +35 src/services\mcp\mcpStringUtils.ts +35 src/utils\teleport\gitBundle.ts +35 src/utils\deepLink\banner.ts +35 src/utils\managedEnvConstants.ts +34 src/utils\readEditContext.ts +34 src/utils\cronTasksLock.ts +34 src/services\preventSleep.ts +34 src/utils\teammateContext.ts +34 src/utils\subprocessEnv.ts +34 src/utils\agenticSessionSearch.ts +33 src/services\PromptSuggestion\promptSuggestion.ts +33 src/services\compact\postCompactCleanup.ts +33 src/utils\filePersistence\filePersistence.ts +33 src/services\remoteManagedSettings\syncCacheState.ts +33 src/utils\windowsPaths.ts +33 src/utils\asciicast.ts +33 src/utils\bash\shellCompletion.ts +32 src/utils\plugins\fetchTelemetry.ts +32 src/utils\plugins\pluginIdentifier.ts +32 src/utils\logoV2Utils.ts +32 src/utils\plugins\orphanedPluginFilter.ts +32 src/services\MagicDocs\magicDocs.ts +32 src/constants\oauth.ts +32 src/utils\caCertsConfig.ts +31 src/utils\heapDumpService.ts +31 src/utils\model\modelStrings.ts +31 src/utils\systemTheme.ts +31 src/utils\ansiToSvg.ts +31 src/services\api\metricsOptOut.ts +31 src/utils\githubRepoPathMapping.ts +31 src/services\compact\grouping.ts +31 src/utils\caCerts.ts +31 src/utils\desktopDeepLink.ts +31 src/utils\envDynamic.ts +31 src/utils\plugins\hintRecommendation.ts +31 src/utils\permissions\PermissionUpdate.ts +30 src/utils\settings\constants.ts +30 src/utils\genericProcessUtils.ts +30 src/utils\thinking.ts +30 src/utils\abortController.ts +30 src/utils\shellConfig.ts +30 src/utils\shell\specPrefix.ts +30 src/utils\model\agent.ts +30 src/services\analytics\datadog.ts +29 src/services\analytics\sink.ts +29 src/utils\debug.ts +29 src/utils\cronJitterConfig.ts +29 src/utils\inProcessTeammateHelpers.ts +29 src/utils\claudeInChrome\common.ts +29 src/utils\terminalPanel.ts +29 src/utils\ultraplan\keyword.ts +29 src/utils\terminal.ts +29 src/types\plugin.ts +28 src/utils\suggestions\directoryCompletion.ts +28 src/services\AgentSummary\agentSummary.ts +28 src/utils\format.ts +28 src/services\vcr.ts +28 src/utils\messages\mappers.ts +28 src/utils\plugins\gitAvailability.ts +28 src/services\oauth\index.ts +28 src/utils\plugins\loadPluginAgents.ts +28 src/utils\bash\parser.ts +28 src/utils\shell\powershellDetection.ts +28 src/utils\apiPreconnect.ts +27 src/utils\sliceAnsi.ts +27 src/utils\sessionStart.ts +27 src/services\autoDream\consolidationLock.ts +27 src/utils\queryContext.ts +27 src/utils\plugins\zipCacheAdapters.ts +27 src/utils\http.ts +27 src/utils\queueProcessor.ts +27 src/utils\errorLogSink.ts +27 src/utils\workloadContext.ts +27 src/utils\pdf.ts +27 src/utils\mcpInstructionsDelta.ts +27 src/utils\sessionIngressAuth.ts +26 src/utils\horizontalScroll.ts +26 src/utils\streamJsonStdoutGuard.ts +26 src/constants\toolLimits.ts +26 src/utils\glob.ts +26 src/services\api\referral.ts +26 src/utils\agentId.ts +26 src/utils\context.ts +26 src/utils\permissions\dangerousPatterns.ts +26 src/utils\sanitization.ts +26 src/services\rateLimitMocking.ts +25 src/utils\promptEditor.ts +25 src/utils\background\remote\preconditions.ts +25 src/utils\processUserInput\processBashCommand.tsx +25 src/utils\systemPrompt.ts +25 src/services\oauth\auth-code-listener.ts +25 src/utils\hooks\hooksSettings.ts +25 src/utils\undercover.ts +24 src/services\plugins\PluginInstallationManager.ts +24 src/utils\sdkEventQueue.ts +24 src/utils\plugins\performStartupChecks.tsx +24 src/utils\settings\validation.ts +24 src/utils\settings\pluginOnlyPolicy.ts +24 src/services\mcp\channelAllowlist.ts +24 src/utils\toolPool.ts +24 src/utils\displayTags.ts +24 src/utils\mcpOutputStorage.ts +24 src/utils\modelCost.ts +23 src/utils\swarm\teammateLayoutManager.ts +23 src/utils\exportRenderer.tsx +23 src/services\mcp\elicitationHandler.ts +23 src/utils\heatmap.ts +23 src/constants\files.ts +23 src/services\compact\prompt.ts +23 src/services\SessionMemory\prompts.ts +23 src/utils\suggestions\shellHistoryCompletion.ts +23 src/services\voiceKeyterms.ts +23 src/utils\localInstaller.ts +23 src/utils\plugins\pluginFlagging.ts +22 src/utils\warningHandler.ts +22 src/services\api\overageCreditGrant.ts +22 src/utils\settings\applySettingsChange.ts +22 src/constants\system.ts +22 src/utils\computerUse\common.ts +22 src/utils\cliArgs.ts +22 src/utils\staticRender.tsx +22 src/utils\fileStateCache.ts +21 src/utils\plugins\pluginBlocklist.ts +21 src/utils\settings\mdm\rawRead.ts +21 src/utils\filePersistence\outputsScanner.ts +21 src/utils\git\gitignore.ts +21 src/services\mcp\claudeai.ts +21 src/utils\sessionFileAccessHooks.ts +21 src/utils\fileRead.ts +21 src/utils\computerUse\cleanup.ts +21 src/utils\user.ts +21 src/utils\exampleCommands.ts +20 src/utils\mcp\dateTimeParser.ts +20 src/utils\sleep.ts +20 src/utils\swarm\backends\teammateModeSnapshot.ts +20 src/utils\words.ts +20 src/utils\bash\prefix.ts +20 src/constants\tools.ts +20 src/utils\claudeInChrome\setupPortable.ts +20 src/services\api\dumpPrompts.ts +20 src/utils\plugins\cacheUtils.ts +20 src/utils\planModeV2.ts +19 src/utils\computerUse\drainRunLoop.ts +19 src/utils\permissions\classifierDecision.ts +19 src/utils\sessionTitle.ts +19 src/utils\permissions\bypassPermissionsKillswitch.ts +19 src/utils\settings\mdm\constants.ts +19 src/constants\xml.ts +19 src/utils\activityManager.ts +18 src/utils\streamlinedTransform.ts +18 src/services\mcp\headersHelper.ts +18 src/utils\generatedFiles.ts +18 src/utils\pdfUtils.ts +18 src/utils\claudeInChrome\toolRendering.tsx +18 src/services\compact\timeBasedMCConfig.ts +18 src/utils\settings\toolValidationConfig.ts +18 src/utils\computerUse\mcpServer.ts +18 src/utils\permissions\permissionExplainer.ts +18 src/constants\product.ts +18 src/utils\diff.ts +17 src/utils\diagLogs.ts +17 src/utils\swarm\teammateInit.ts +17 src/utils\model\validateModel.ts +17 src/utils\fingerprint.ts +17 src/utils\mtls.ts +17 src/utils\getWorktreePaths.ts +17 src/utils\suggestions\slackChannelSuggestions.ts +17 src/utils\privacyLevel.ts +17 src/utils\deepLink\terminalPreference.ts +17 src/utils\swarm\reconnection.ts +16 src/types\hooks.ts +16 src/utils\contentArray.ts +16 src/utils\renderOptions.ts +16 src/utils\groupToolUses.ts +16 src/constants\cyberRiskInstruction.ts +16 src/utils\xdg.ts +16 src/utils\semanticNumber.ts +16 src/utils\messages\systemInit.ts +16 src/utils\imageValidation.ts +15 src/utils\mcp\elicitationValidation.ts +15 src/utils\cliHighlight.ts +15 src/utils\jetbrains.ts +15 src/utils\mcpWebSocketTransport.ts +15 src/utils\computerUse\escHotkey.ts +15 src/utils\pasteStore.ts +15 src/utils\hooks\hooksConfigManager.ts +15 src/utils\formatBriefTimestamp.ts +15 src/utils\mcpValidation.ts +15 src/utils\sessionActivity.ts +14 src/utils\intl.ts +14 src/services\lsp\config.ts +14 src/utils\fileReadCache.ts +14 src/utils\doctorContextWarnings.ts +14 src/types\ids.ts +14 src/utils\execFileNoThrow.ts +14 src/utils\agentSwarmsEnabled.ts +14 src/utils\idePathConversion.ts +14 src/utils\slashCommandParsing.ts +14 src/services\mcp\types.ts +14 src/utils\permissions\getNextPermissionMode.ts +14 src/utils\signal.ts +13 src/utils\imageStore.ts +13 src/utils\ghPrStatus.ts +13 src/services\extractMemories\prompts.ts +13 src/utils\process.ts +13 src/utils\semanticBoolean.ts +13 src/utils\teleport\environmentSelection.ts +13 src/utils\which.ts +13 src/utils\plugins\addDirPluginSettings.ts +13 src/services\compact\apiMicrocompact.ts +13 src/services\mcp\vscodeSdkMcp.ts +13 src/utils\claudeInChrome\prompt.ts +13 src/utils\computerUse\gates.ts +13 src/utils\model\check1mAccess.ts +12 src/services\analytics\config.ts +12 src/utils\permissions\PermissionPromptToolResultSchema.ts +12 src/utils\platform.ts +12 src/utils\computerUse\setup.ts +12 src/utils\settings\internalWrites.ts +12 src/utils\sessionUrl.ts +12 src/services\remoteManagedSettings\securityCheck.tsx +12 src/utils\permissions\PermissionUpdateSchema.ts +12 src/utils\secureStorage\fallbackStorage.ts +12 src/services\MagicDocs\prompts.ts +12 src/utils\suggestions\skillUsageTracking.ts +12 src/utils\hooks\apiQueryHookHelper.ts +12 src/utils\hooks\execPromptHook.ts +12 src/utils\hash.ts +12 src/utils\hyperlink.ts +11 src/utils\computerUse\hostAdapter.ts +11 src/utils\computerUse\inputLoader.ts +11 src/utils\collapseBackgroundBashNotifications.ts +11 src/services\mcp\oauthPort.ts +11 src/utils\settings\allErrors.ts +11 src/constants\common.ts +11 src/services\mcp\InProcessTransport.ts +11 src/utils\hooks\hookEvents.ts +11 src/utils\execFileNoThrowPortable.ts +11 src/utils\taggedId.ts +11 src/utils\tempfile.ts +11 src/utils\treeify.ts +10 src/utils\completionCache.ts +10 src/utils\CircularBuffer.ts +10 src/utils\screenshotClipboard.ts +10 src/services\teamMemorySync\teamMemSecretGuard.ts +10 src/utils\plugins\walkPluginMarkdown.ts +10 src/utils\bufferedWriter.ts +10 src/utils\permissions\PermissionRule.ts +10 src/utils\profilerBase.ts +10 src/utils\binaryCheck.ts +10 src/utils\settings\settingsCache.ts +10 src/utils\settings\validateEditTool.ts +10 src/utils\crypto.ts +10 src/utils\hooks\registerSkillHooks.ts +10 src/utils\hooks\registerFrontmatterHooks.ts +10 src/utils\backgroundHousekeeping.ts +10 src/utils\promptCategory.ts +10 src/services\analytics\sinkKillswitch.ts +10 src/utils\billing.ts +10 src/utils\embeddedTools.ts +10 src/utils\swarm\constants.ts +10 src/utils\background\remote\remoteSession.ts +10 src/services\settingsSync\types.ts +9 src/utils\plugins\officialMarketplace.ts +9 src/utils\telemetry\bigqueryExporter.ts +9 src/utils\claudeDesktop.ts +9 src/utils\toolSchemaCache.ts +9 src/utils\bash\shellPrefix.ts +9 src/utils\contextAnalysis.ts +9 src/utils\model\deprecation.ts +9 src/utils\peerAddress.ts +9 src/utils\telemetry\events.ts +9 src/services\tips\tipRegistry.ts +9 src/utils\sessionEnvironment.ts +9 src/utils\combinedAbortSignal.ts +9 src/constants\errorIds.ts +9 src/utils\processUserInput\processTextPrompt.ts +9 src/utils\dxt\helpers.ts +9 src/constants\systemPromptSections.ts +9 src/services\toolUseSummary\toolUseSummaryGenerator.ts +9 src/utils\fileOperationAnalytics.ts +9 src/utils\timeouts.ts +9 src/services\internalLogging.ts +8 src/utils\computerUse\swiftLoader.ts +8 src/utils\aws.ts +8 src/constants\betas.ts +8 src/utils\statusNoticeDefinitions.tsx +8 src/utils\toolErrors.ts +8 src/utils\autoRunIssue.tsx +8 src/utils\sequential.ts +8 src/utils\controlMessageCompat.ts +8 src/utils\teamDiscovery.ts +8 src/utils\plugins\loadPluginOutputStyles.ts +8 src/utils\hooks\postSamplingHooks.ts +8 src/utils\idleTimeout.ts +8 src/services\api\adminRequests.ts +8 src/utils\standaloneAgent.ts +8 src/utils\plugins\pluginPolicy.ts +8 src/services\mcp\normalization.ts +8 src/utils\modifiers.ts +8 src/utils\awsAuthStatusManager.ts +8 src/utils\cleanupRegistry.ts +7 src/services\tools\toolOrchestration.ts +7 src/services\mcp\envExpansion.ts +7 src/constants\outputStyles.ts +7 src/constants\figures.ts +7 src/utils\hooks\skillImprovement.ts +7 src/utils\jsonRead.ts +7 src/services\api\bootstrap.ts +7 src/utils\lockfile.ts +7 src/utils\hooks\hookHelpers.ts +7 src/utils\status.tsx +7 src/utils\permissions\classifierShared.ts +7 src/utils\systemDirectories.ts +7 src/utils\uuid.ts +7 src/utils\computerUse\toolRendering.tsx +7 src/utils\bundledMode.ts +7 src/utils\swarm\leaderPermissionBridge.ts +7 src/utils\configConstants.ts +7 src/utils\settings\validationTips.ts +7 src/utils\crossProjectResume.ts +6 src/services\mcp\officialRegistry.ts +6 src/utils\execSyncWrapper.ts +6 src/utils\advisor.ts +6 src/utils\ink.ts +6 src/utils\github\ghAuthStatus.ts +6 src/utils\tokenBudget.ts +6 src/utils\sinks.ts +6 src/utils\cwd.ts +6 src/utils\model\configs.ts +6 src/services\autoDream\config.ts +6 src/utils\gitSettings.ts +6 src/utils\shell\shellToolUtils.ts +5 src/utils\hooks\AsyncHookRegistry.ts +5 src/utils\teleport\environments.ts +5 src/utils\xml.ts +5 src/utils\notebook.ts +5 src/utils\yaml.ts +5 src/utils\shell\resolveDefaultShell.ts +5 src/utils\zodToJsonSchema.ts +5 src/utils\plugins\managedPlugins.ts +5 src/utils\permissions\autoModeState.ts +5 src/utils\textHighlighting.ts +5 src/utils\worktreeModeEnabled.ts +5 src/services\tips\tipScheduler.ts +5 src/utils\shell\shellProvider.ts +5 src/utils\permissions\PermissionMode.ts +5 src/utils\browser.ts +5 src/services\compact\compactWarningState.ts +5 src/utils\settings\managedPath.ts +5 src/utils\findExecutable.ts +5 src/utils\cachePaths.ts +5 src/utils\semver.ts +4 src/utils\hooks\fileChangedWatcher.ts +4 src/services\awaySummary.ts +4 src/utils\immediateCommand.ts +4 src/services\remoteManagedSettings\types.ts +4 src/utils\userPromptKeywords.ts +4 src/utils\generators.ts +4 src/utils\model\modelCapabilities.ts +4 src/utils\collapseHookSummaries.ts +4 src/utils\teamMemoryOps.ts +4 src/utils\sandbox\sandbox-ui-utils.ts +4 src/utils\telemetry\skillLoadedEvent.ts +4 src/utils\model\contextWindowUpgradeCheck.ts +4 src/services\compact\compactWarningHook.ts +4 src/utils\set.ts +4 src/utils\swarm\teammateModel.ts +4 src/utils\task\sdkProgress.ts +4 src/utils\nativeInstaller\index.ts +4 src/services\api\firstTokenDate.ts +4 src/utils\contextSuggestions.ts +4 src/utils\getWorktreePathsPortable.ts +3 src/utils\swarm\teammatePromptAddendum.ts +3 src/services\api\ultrareviewQuota.ts +3 src/services\api\emptyUsage.ts +3 src/utils\messagePredicates.ts +3 src/utils\userAgent.ts +3 src/utils\model\providers.ts +3 src/utils\directMemberMessage.ts +3 src/utils\memory\versions.ts +3 src/utils\task\outputFormatting.ts +3 src/utils\keyboardShortcuts.ts +3 src/utils\model\aliases.ts +3 src/utils\model\antModels.ts +3 src/utils\sessionEnvVars.ts +3 src/utils\permissions\PermissionResult.ts +3 src/utils\secureStorage\plainTextStorage.ts +3 src/utils\autoModeDenials.ts +3 src/utils\permissions\denialTracking.ts +3 src/utils\telemetryAttributes.ts +3 src/services\policyLimits\types.ts +3 src/utils\systemPromptType.ts +3 src/utils\highlightMatch.tsx +3 src/services\mcpServerApproval.tsx +3 src/utils\classifierApprovalsHook.ts +2 src/services\notifier.ts +2 src/utils\preflightChecks.tsx +2 src/utils\model\modelSupportOverrides.ts +2 src/services\autoDream\consolidationPrompt.ts +2 src/utils\withResolvers.ts +2 src/utils\classifierApprovals.ts +2 src/utils\collapseTeammateShutdowns.ts +2 src/services\oauth\getOauthProfile.ts +2 src/constants\keys.ts +2 src/utils\secureStorage\index.ts +2 src/utils\lazySchema.ts +2 src/constants\turnCompletionVerbs.ts +1 src/utils\statusNoticeHelpers.ts +1 src/utils\permissions\bashClassifier.ts +1 src/utils\objectGroupBy.ts +1 src/utils\filePersistence\types.ts +1 src/constants\spinnerVerbs.ts +1 src/utils\swarm\It2SetupPrompt.tsx +1 src/services\mcp\MCPConnectionManager.tsx +1 src/services\api\usage.ts diff --git a/comment_matches.txt b/comment_matches.txt new file mode 100644 index 000000000..1ef09a077 --- /dev/null +++ b/comment_matches.txt @@ -0,0 +1,37172 @@ +src/constants\common.ts:3:// This ensures you get the LOCAL date in ISO format +src/constants\common.ts:5: // Check for ant-only date override +src/constants\common.ts:17:// Memoized for prompt-cache stability �captures the date once at session start. +src/constants\common.ts:18:// The main interactive path gets this behavior via memoize(getUserContext) in +src/constants\common.ts:19:// context.ts; simple mode (--bare) calls getSystemPrompt per-request and needs +src/constants\common.ts:20:// an explicit memoized date to avoid busting the cached prefix at midnight. +src/constants\common.ts:21:// When midnight rolls over, getDateChangeAttachments appends the new date at +src/constants\common.ts:22:// the tail (though simple mode disables attachments, so the trade-off there is: +src/constants\common.ts:23:// stale date after midnight vs. ~entire-conversation cache bust �stale wins). +src/constants\common.ts:26:// Returns "Month YYYY" (e.g. "February 2026") in the user's local timezone. +src/constants\common.ts:27:// Changes monthly, not daily �used in tool prompts to minimize cache busting. +src/utils\abortController.ts:4: * Default max listeners for standard operations +src/utils\abortController.ts:9: * Creates an AbortController with proper event listener limits set. +src/utils\abortController.ts:10: * This prevents MaxListenersExceededWarning when multiple listeners +src/utils\abortController.ts:11: * are attached to the abort signal. +src/utils\abortController.ts:13: * @param maxListeners - Maximum number of listeners (default: 50) +src/utils\abortController.ts:14: * @returns AbortController with configured listener limit +src/utils\abortController.ts:25: * Propagates abort from a parent to a weakly-referenced child controller. +src/utils\abortController.ts:26: * Both parent and child are weakly held �neither direction creates a +src/utils\abortController.ts:27: * strong reference that could prevent GC. +src/utils\abortController.ts:28: * Module-scope function avoids per-call closure allocation. +src/utils\abortController.ts:39: * Removes an abort handler from a weakly-referenced parent signal. +src/utils\abortController.ts:40: * Both parent and handler are weakly held �if either has been GC'd +src/utils\abortController.ts:41: * or the parent already aborted ({once: true}), this is a no-op. +src/utils\abortController.ts:42: * Module-scope function avoids per-call closure allocation. +src/utils\abortController.ts:56: * Creates a child AbortController that aborts when its parent aborts. +src/utils\abortController.ts:57: * Aborting the child does NOT affect the parent. +src/utils\abortController.ts:59: * Memory-safe: Uses WeakRef so the parent doesn't retain abandoned children. +src/utils\abortController.ts:60: * If the child is dropped without being aborted, it can still be GC'd. +src/utils\abortController.ts:61: * When the child IS aborted, the parent listener is removed to prevent +src/utils\abortController.ts:62: * accumulation of dead handlers. +src/utils\abortController.ts:64: * @param parent - The parent AbortController +src/utils\abortController.ts:65: * @param maxListeners - Maximum number of listeners (default: 50) +src/utils\abortController.ts:66: * @returns Child AbortController +src/utils\abortController.ts:74: // Fast path: parent already aborted, no listener setup needed +src/utils\abortController.ts:80: // WeakRef prevents the parent from keeping an abandoned child alive. +src/utils\abortController.ts:81: // If all strong references to child are dropped without aborting it, +src/utils\abortController.ts:82: // the child can still be GC'd �the parent only holds a dead WeakRef. +src/utils\abortController.ts:89: // Auto-cleanup: remove parent listener when child is aborted (from any source). +src/utils\abortController.ts:90: // Both parent and handler are weakly held �if either has been GC'd or the +src/utils\abortController.ts:91: // parent already aborted ({once: true}), the cleanup is a harmless no-op. +src/constants\betas.ts:10:// Tool search beta headers differ by provider: +src/constants\betas.ts:11:// - Claude API / Foundry: advanced-tool-use-2025-11-20 +src/constants\betas.ts:12:// - Vertex AI / Bedrock: tool-search-tool-2025-10-19 +src/constants\betas.ts:34: * Bedrock only supports a limited number of beta headers and only through +src/constants\betas.ts:35: * extraBodyParams. This set maintains the beta strings that should be in +src/constants\betas.ts:36: * Bedrock extraBodyParams *and not* in Bedrock headers. +src/constants\betas.ts:45: * Betas allowed on Vertex countTokens API. +src/constants\betas.ts:46: * Other betas will cause 400 errors. +src/constants\apiLimits.ts:2: * Anthropic API Limits +src/constants\apiLimits.ts:4: * These constants define server-side limits enforced by the Anthropic API. +src/constants\apiLimits.ts:5: * Keep this file dependency-free to prevent circular imports. +src/constants\apiLimits.ts:7: * Last verified: 2025-12-22 +src/constants\apiLimits.ts:8: * Source: api/api/schemas/messages/blocks/ and api/api/config.py +src/constants\apiLimits.ts:10: * Future: See issue #13240 for dynamic limits fetching from server. +src/constants\apiLimits.ts:14:// IMAGE LIMITS +src/constants\apiLimits.ts:18: * Maximum base64-encoded image size (API enforced). +src/constants\apiLimits.ts:19: * The API rejects images where the base64 string length exceeds this value. +src/constants\apiLimits.ts:20: * Note: This is the base64 length, NOT raw bytes. Base64 increases size by ~33%. +src/constants\apiLimits.ts:25: * Target raw image size to stay under base64 limit after encoding. +src/constants\apiLimits.ts:26: * Base64 encoding increases size by 4/3, so we derive the max raw size: +src/constants\apiLimits.ts:27: * raw_size * 4/3 = base64_size �raw_size = base64_size * 3/4 +src/constants\apiLimits.ts:32: * Client-side maximum dimensions for image resizing. +src/constants\apiLimits.ts:34: * Note: The API internally resizes images larger than 1568px (source: +src/constants\apiLimits.ts:35: * encoding/full_encoding.py), but this is handled server-side and doesn't +src/constants\apiLimits.ts:36: * cause errors. These client-side limits (2000px) are slightly larger to +src/constants\apiLimits.ts:37: * preserve quality when beneficial. +src/constants\apiLimits.ts:39: * The API_IMAGE_MAX_BASE64_SIZE (5MB) is the actual hard limit that causes +src/constants\apiLimits.ts:40: * API errors if exceeded. +src/constants\apiLimits.ts:46:// PDF LIMITS +src/constants\apiLimits.ts:50: * Maximum raw PDF file size that fits within the API request limit after encoding. +src/constants\apiLimits.ts:51: * The API has a 32MB total request size limit. Base64 encoding increases size by +src/constants\apiLimits.ts:52: * ~33% (4/3), so 20MB raw �~27MB base64, leaving room for conversation context. +src/constants\apiLimits.ts:57: * Maximum number of pages in a PDF accepted by the API. +src/constants\apiLimits.ts:62: * Size threshold above which PDFs are extracted into page images +src/constants\apiLimits.ts:63: * instead of being sent as base64 document blocks. This applies to +src/constants\apiLimits.ts:64: * first-party API only; non-first-party always uses extraction. +src/constants\apiLimits.ts:69: * Maximum PDF file size for the page extraction path. PDFs larger than +src/constants\apiLimits.ts:70: * this are rejected to avoid processing extremely large files. +src/constants\apiLimits.ts:75: * Max pages the Read tool will extract in a single call with the pages parameter. +src/constants\apiLimits.ts:80: * PDFs with more pages than this get the reference treatment on @ mention +src/constants\apiLimits.ts:81: * instead of being inlined into context. +src/constants\apiLimits.ts:86:// MEDIA LIMITS +src/constants\apiLimits.ts:90: * Maximum number of media items (images + PDFs) allowed per API request. +src/constants\apiLimits.ts:91: * The API rejects requests exceeding this limit with a confusing error. +src/constants\apiLimits.ts:92: * We validate client-side to provide a clear error message. +src/utils\activityManager.ts:9: * ActivityManager handles generic activity tracking for both user and CLI operations. +src/utils\activityManager.ts:10: * It automatically deduplicates overlapping activities and provides separate metrics +src/utils\activityManager.ts:11: * for user vs CLI active time. +src/utils\activityManager.ts:43: * Reset the singleton instance (for testing purposes) +src/utils\activityManager.ts:50: * Create a new instance with custom options (for testing purposes) +src/utils\activityManager.ts:58: * Called when user interacts with the CLI (typing, commands, etc.) +src/utils\activityManager.ts:61: // Don't record user time if CLI is active (CLI takes precedence) +src/utils\activityManager.ts:71: // Only record time if within the timeout window +src/utils\activityManager.ts:79: // Update the last user activity timestamp +src/utils\activityManager.ts:84: * Starts tracking CLI activity (tool execution, AI response, etc.) +src/utils\activityManager.ts:87: // If operation already exists, it likely means the previous one didn't clean up +src/utils\activityManager.ts:88: // properly (e.g., component crashed/unmounted without calling end). Force cleanup +src/utils\activityManager.ts:89: // to avoid overestimating time - better to underestimate than overestimate. +src/utils\activityManager.ts:104: * Stops tracking CLI activity +src/utils\activityManager.ts:110: // Last operation ended - CLI becoming inactive +src/utils\activityManager.ts:111: // Record the CLI time before switching to inactive +src/utils\activityManager.ts:128: * Convenience method to track an async operation automatically (mainly for testing/debugging) +src/utils\activityManager.ts:143: * Gets current activity states (mainly for testing/debugging) +src/utils\activityManager.ts:163:// Export singleton instance +src/services\claudeAiLimits.ts:20:// Re-export message functions from centralized location +src/services\claudeAiLimits.ts:50:// Early warning configurations in priority order (checked first to last) +src/services\claudeAiLimits.ts:51:// Used as fallback when server doesn't send surpassed-threshold header +src/services\claudeAiLimits.ts:52:// Warns users when they're consuming quota faster than the time window allows +src/services\claudeAiLimits.ts:72:// Maps claim abbreviations to rate limit types for header-based detection +src/services\claudeAiLimits.ts:92: * Calculate what fraction of a time window has elapsed. +src/services\claudeAiLimits.ts:93: * Used for time-relative early warning fallback. +src/services\claudeAiLimits.ts:94: * @param resetsAt - Unix epoch timestamp in seconds when the limit resets +src/services\claudeAiLimits.ts:95: * @param windowSeconds - Duration of the window in seconds +src/services\claudeAiLimits.ts:96: * @returns fraction (0-1) of the window that has elapsed +src/services\claudeAiLimits.ts:105:// Reason why overage is disabled/rejected +src/services\claudeAiLimits.ts:106:// These values come from the API's unified limiter +src/services\claudeAiLimits.ts:124: // unifiedRateLimitFallbackAvailable is currently used to warn users that set +src/services\claudeAiLimits.ts:125: // their model to Opus whenever they are about to run out of quota. It does +src/services\claudeAiLimits.ts:126: // not change the actual model that is used. +src/services\claudeAiLimits.ts:138:// Exported for testing only +src/services\claudeAiLimits.ts:146: * Raw per-window utilization from response headers, tracked on every API +src/services\claudeAiLimits.ts:147: * response (unlike currentLimits.utilization which is only set when a warning +src/services\claudeAiLimits.ts:148: * threshold fires). Exposed to statusline scripts via getRawUtilization(). +src/services\claudeAiLimits.ts:208: // biome-ignore lint/plugin: quota check needs raw response access via asResponse() +src/services\claudeAiLimits.ts:221: // Skip network requests if nonessential traffic is disabled +src/services\claudeAiLimits.ts:226: // Check if we should process rate limits (real subscriber or mock testing) +src/services\claudeAiLimits.ts:231: // In non-interactive mode (-p), the real query follows immediately and +src/services\claudeAiLimits.ts:232: // extractQuotaStatusFromHeaders() will update limits from its response +src/services\claudeAiLimits.ts:233: // headers (claude.ts), so skip this pre-check API call. +src/services\claudeAiLimits.ts:239: // Make a minimal request to check quota +src/services\claudeAiLimits.ts:242: // Update limits based on the response +src/services\claudeAiLimits.ts:252: * Check if early warning should be triggered based on surpassed-threshold header. +src/services\claudeAiLimits.ts:253: * Returns ClaudeAILimits if a threshold was surpassed, null otherwise. +src/services\claudeAiLimits.ts:259: // Check each claim type for surpassed threshold header +src/services\claudeAiLimits.ts:267: // If threshold header is present, user has crossed a warning threshold +src/services\claudeAiLimits.ts:297: * Check if time-relative early warning should be triggered for a rate limit type. +src/services\claudeAiLimits.ts:298: * Fallback when server doesn't send surpassed-threshold header. +src/services\claudeAiLimits.ts:299: * Returns ClaudeAILimits if thresholds are exceeded, null otherwise. +src/services\claudeAiLimits.ts:323: // Check if any threshold is exceeded: high usage early in the window +src/services\claudeAiLimits.ts:343: * Get early warning limits using header-based detection with time-relative fallback. +src/services\claudeAiLimits.ts:344: * 1. First checks for surpassed-threshold header (new server-side approach) +src/services\claudeAiLimits.ts:345: * 2. Falls back to time-relative thresholds (client-side calculation) +src/services\claudeAiLimits.ts:351: // Try header-based detection first (preferred when API sends the header) +src/services\claudeAiLimits.ts:360: // Fallback: Use time-relative thresholds (client-side calculation) +src/services\claudeAiLimits.ts:361: // This catches users burning quota faster than sustainable +src/services\claudeAiLimits.ts:387: // Headers for rate limit type and overage support +src/services\claudeAiLimits.ts:401: // Reason why overage is disabled (spending cap or wallet empty) +src/services\claudeAiLimits.ts:406: // Determine if we're using overage (standard limits rejected but overage allowed) +src/services\claudeAiLimits.ts:411: // Check for early warning based on surpassed-threshold header +src/services\claudeAiLimits.ts:412: // If status is allowed/allowed_warning and we find a surpassed threshold, show warning +src/services\claudeAiLimits.ts:422: // No early warning threshold surpassed +src/services\claudeAiLimits.ts:439: * Cache the extra usage disabled reason from API headers. +src/services\claudeAiLimits.ts:442: // A null reason means extra usage is enabled (no disabled reason header) +src/services\claudeAiLimits.ts:457: // Check if we need to process rate limits +src/services\claudeAiLimits.ts:461: // If we have any rate limit state, clear it +src/services\claudeAiLimits.ts:474: // Process headers (applies mocks from /mock-limits command if active) +src/services\claudeAiLimits.ts:479: // Cache extra usage status (persists across sessions) +src/services\claudeAiLimits.ts:498: // Process headers (applies mocks from /mock-limits command if active) +src/services\claudeAiLimits.ts:503: // Cache extra usage status (persists across sessions) +src/services\claudeAiLimits.ts:506: // For errors, always set status to rejected even if headers are not present. +src/services\awaySummary.ts:14:// Recap only needs recent context �truncate to avoid "prompt too long" on +src/services\awaySummary.ts:15:// large sessions. 30 messages �~15 exchanges, plenty for "where we left off." +src/services\awaySummary.ts:26: * Generates a short session recap for the "while you were away" card. +src/services\awaySummary.ts:27: * Returns null on abort, empty transcript, or error. +src/services\diagnosticTracking.ts:37: // Track when files were last processed/fetched +src/services\diagnosticTracking.ts:40: // Track which files have received right file diagnostics and if they've changed +src/services\diagnosticTracking.ts:41: // Map +src/services\diagnosticTracking.ts:56: // TODO: Do not cache the connected mcpClient since it can change. +src/services\diagnosticTracking.ts:69: * Reset tracking state while keeping the service initialized. +src/services\diagnosticTracking.ts:70: * This clears all tracked files and diagnostics. +src/services\diagnosticTracking.ts:79: // Remove our protocol prefixes +src/services\diagnosticTracking.ts:94: // Use shared utility for platform-aware path normalization +src/services\diagnosticTracking.ts:95: // (handles Windows case-insensitivity and path separators) +src/services\diagnosticTracking.ts:100: * Ensure a file is opened in the IDE before processing. +src/services\diagnosticTracking.ts:101: * This is important for language services like diagnostics to work properly. +src/services\diagnosticTracking.ts:113: // Call the openFile tool to ensure the file is loaded +src/services\diagnosticTracking.ts:132: * Capture baseline diagnostics for a specific file before editing. +src/services\diagnosticTracking.ts:133: * This is called before editing a file to ensure we have a baseline to compare against. +src/services\diagnosticTracking.ts:154: // Compare normalized paths (handles protocol prefixes and Windows case-insensitivity) +src/services\diagnosticTracking.ts:169: // Store with normalized path key for consistent lookups on Windows +src/services\diagnosticTracking.ts:174: // No diagnostic file returned, store an empty baseline +src/services\diagnosticTracking.ts:180: // Fail silently if IDE doesn't support diagnostics +src/services\diagnosticTracking.ts:185: * Get new diagnostics from file://, _claude_fs_right, and _claude_fs_ URIs that aren't in the baseline. +src/services\diagnosticTracking.ts:186: * Only processes diagnostics for files that have been edited. +src/services\diagnosticTracking.ts:197: // Check if we have any files with diagnostic changes +src/services\diagnosticTracking.ts:207: // If fetching all diagnostics fails, return empty +src/services\diagnosticTracking.ts:230: // Process file:// protocol diagnostics +src/services\diagnosticTracking.ts:235: // Get the _claude_fs_right file if it exists +src/services\diagnosticTracking.ts:239: // Determine which file to use based on the state of right file diagnostics +src/services\diagnosticTracking.ts:246: // Use _claude_fs_right if: +src/services\diagnosticTracking.ts:247: // 1. We've never gotten right file diagnostics for this file (previousRightDiagnostics === undefined) +src/services\diagnosticTracking.ts:248: // 2. OR the right file diagnostics have just changed +src/services\diagnosticTracking.ts:259: // Update our tracking of right file diagnostics +src/services\diagnosticTracking.ts:266: // Find new diagnostics that aren't in the baseline +src/services\diagnosticTracking.ts:278: // Update baseline with current diagnostics +src/services\diagnosticTracking.ts:312: // Check if every diagnostic in 'a' exists in 'b' +src/services\diagnosticTracking.ts:322: * Handle the start of a new query. This method: +src/services\diagnosticTracking.ts:323: * - Initializes the diagnostic tracker if not already initialized +src/services\diagnosticTracking.ts:324: * - Resets the tracker if already initialized (for new query loops) +src/services\diagnosticTracking.ts:325: * - Automatically finds the IDE client from the provided clients list +src/services\diagnosticTracking.ts:327: * @param clients Array of MCP clients that may include an IDE client +src/services\diagnosticTracking.ts:328: * @param shouldQuery Whether a query is actually being made (not just a command) +src/services\diagnosticTracking.ts:331: // Only proceed if we should query and have clients +src/services\diagnosticTracking.ts:333: // Find the connected IDE client +src/services\diagnosticTracking.ts:340: // Reset diagnostic tracking for new query loops +src/services\diagnosticTracking.ts:346: * Format diagnostics into a human-readable summary string. +src/services\diagnosticTracking.ts:347: * This is useful for displaying diagnostics in messages or logs. +src/services\diagnosticTracking.ts:349: * @param files Array of diagnostic files to format +src/services\diagnosticTracking.ts:350: * @returns Formatted string representation of the diagnostics +src/services\diagnosticTracking.ts:383: * Get the severity symbol for a diagnostic +src/services\autoDream\consolidationPrompt.ts:1:// Extracted from dream.ts so auto-dream ships independently of KAIROS +src/services\autoDream\consolidationPrompt.ts:2:// feature flags (dream.ts is behind a feature()-gated require). +src/services\compact\timeBasedMCConfig.ts:4: * GrowthBook config for time-based microcompact. +src/services\compact\timeBasedMCConfig.ts:6: * Triggers content-clearing microcompact when the gap since the last main-loop +src/services\compact\timeBasedMCConfig.ts:7: * assistant message exceeds a threshold �the server-side prompt cache has +src/services\compact\timeBasedMCConfig.ts:8: * almost certainly expired, so the full prefix will be rewritten anyway. +src/services\compact\timeBasedMCConfig.ts:9: * Clearing old tool results before the request shrinks what gets rewritten. +src/services\compact\timeBasedMCConfig.ts:11: * Runs BEFORE the API call (in microcompactMessages, upstream of callModel) +src/services\compact\timeBasedMCConfig.ts:12: * so the shrunk prompt is what actually gets sent. Running after the first +src/services\compact\timeBasedMCConfig.ts:13: * miss would only help subsequent turns. +src/services\compact\timeBasedMCConfig.ts:15: * Main thread only �subagents have short lifetimes where gap-based eviction +src/services\compact\timeBasedMCConfig.ts:16: * doesn't apply. +src/services\compact\timeBasedMCConfig.ts:19: /** Master switch. When false, time-based microcompact is a no-op. */ +src/services\compact\timeBasedMCConfig.ts:21: /** Trigger when (now �last assistant timestamp) exceeds this many minutes. +src/services\compact\timeBasedMCConfig.ts:22: * 60 is the safe choice: the server's 1h cache TTL is guaranteed expired +src/services\compact\timeBasedMCConfig.ts:23: * for all users, so we never force a miss that wouldn't have happened. */ +src/services\compact\timeBasedMCConfig.ts:25: /** Keep this many most-recent compactable tool results. +src/services\compact\timeBasedMCConfig.ts:26: * When set, takes priority over any default; older results are cleared. */ +src/services\compact\timeBasedMCConfig.ts:37: // Hoist the GB read so exposure fires on every eval path, not just when +src/services\compact\timeBasedMCConfig.ts:38: // the caller's other conditions (querySource, messages.length) pass. +src/services\analytics\sinkKillswitch.ts:3:// Mangled name: per-sink analytics killswitch +src/services\analytics\sinkKillswitch.ts:9: * GrowthBook JSON config that disables individual analytics sinks. +src/services\analytics\sinkKillswitch.ts:10: * Shape: { datadog?: boolean, firstParty?: boolean } +src/services\analytics\sinkKillswitch.ts:11: * A value of true for a key stops all dispatch to that sink. +src/services\analytics\sinkKillswitch.ts:12: * Default {} (nothing killed). Fail-open: missing/malformed config = sink stays on. +src/services\analytics\sinkKillswitch.ts:14: * NOTE: Must NOT be called from inside is1PEventLoggingEnabled() - +src/services\analytics\sinkKillswitch.ts:15: * growthbook.ts:isGrowthBookEnabled() calls that, so a lookup here would recurse. +src/services\analytics\sinkKillswitch.ts:16: * Call at per-event dispatch sites instead. +src/services\analytics\sinkKillswitch.ts:22: // getFeatureValue_CACHED_MAY_BE_STALE guards on `!== undefined`, so a +src/services\analytics\sinkKillswitch.ts:23: // cached JSON null leaks through instead of falling back to {}. +src/types\command.ts:38: // Hooks to register when this skill is invoked +src/types\command.ts:40: // Base directory for skill resources (used to set CLAUDE_PLUGIN_ROOT environment variable for skill hooks) +src/types\command.ts:42: // Execution context: 'inline' (default) or 'fork' (run as sub-agent) +src/types\command.ts:43: // 'inline' = skill content expands into the current conversation +src/types\command.ts:44: // 'fork' = skill runs in a sub-agent with separate context and token budget +src/types\command.ts:46: // Agent type to use when forked (e.g., 'Bash', 'general-purpose') +src/types\command.ts:47: // Only applicable when context is 'fork' +src/types\command.ts:50: // Glob patterns for file paths this skill applies to +src/types\command.ts:51: // When set, the skill is only visible after the model touches matching files +src/types\command.ts:60: * The call signature for a local command implementation. +src/types\command.ts:68: * Module shape returned by load() for lazy-loaded local commands. +src/types\command.ts:110: * Callback when a command completes. +src/types\command.ts:111: * @param result - Optional user-visible message to display +src/types\command.ts:112: * @param options - Optional configuration for command completion +src/types\command.ts:113: * @param options.display - How to display the result: 'skip' | 'system' | 'user' (default) +src/types\command.ts:114: * @param options.shouldQuery - If true, send messages to the model after command completes +src/types\command.ts:115: * @param options.metaMessages - Additional messages to insert as isMeta (model-visible but hidden) +src/types\command.ts:129: * The call signature for a local JSX command implementation. +src/types\command.ts:138: * Module shape returned by load() for lazy-loaded commands. +src/types\command.ts:147: * Lazy-load the command implementation. +src/types\command.ts:148: * Returns a module with a call() function. +src/types\command.ts:149: * This defers loading heavy dependencies until the command is invoked. +src/types\command.ts:155: * Declares which auth/provider environments a command is available in. +src/types\command.ts:157: * This is separate from `isEnabled()`: +src/types\command.ts:158: * - `availability` = who can use this (auth/provider requirement, static) +src/types\command.ts:159: * - `isEnabled()` = is this turned on right now (GrowthBook, platform, env vars) +src/types\command.ts:161: * Commands without `availability` are available everywhere. +src/types\command.ts:162: * Commands with `availability` are only shown if the user matches at least one +src/types\command.ts:163: * of the listed auth types. See meetsAvailabilityRequirement() in commands.ts. +src/types\command.ts:165: * Example: `availability: ['claude-ai', 'console']` shows the command to +src/types\command.ts:166: * claude.ai subscribers and direct Console API key users (api.anthropic.com), +src/types\command.ts:167: * but hides it from Bedrock/Vertex/Foundry users and custom base URL users. +src/types\command.ts:170: // claude.ai OAuth subscriber (Pro/Max/Team/Enterprise via claude.ai) +src/types\command.ts:172: // Console API key user (direct api.anthropic.com, not via claude.ai OAuth) +src/types\command.ts:179: /** Defaults to true. Only set when the command has conditional enablement (feature flags, env checks, etc). */ +src/types\command.ts:181: /** Defaults to false. Only set when the command should be hidden from typeahead/help. */ +src/types\command.ts:201: /** Defaults to `name`. Only override when the displayed name differs (e.g. plugin prefix stripping). */ +src/types\command.ts:208:/** Resolves the user-visible name, falling back to `cmd.name` when not overridden. */ +src/types\command.ts:213:/** Resolves whether the command is enabled, defaulting to true. */ +src/services\compact\compactWarningState.ts:4: * Tracks whether the "context left until autocompact" warning should be suppressed. +src/services\compact\compactWarningState.ts:5: * We suppress immediately after successful compaction since we don't have accurate +src/services\compact\compactWarningState.ts:6: * token counts until the next API response. +src/services\compact\compactWarningState.ts:10:/** Suppress the compact warning. Call after successful compaction. */ +src/services\compact\compactWarningState.ts:15:/** Clear the compact warning suppression. Called at start of new compact attempt. */ +src/services\AgentSummary\agentSummary.ts:2: * Periodic background summarization for coordinator mode sub-agents. +src/services\AgentSummary\agentSummary.ts:4: * Forks the sub-agent's conversation every ~30s using runForkedAgent() +src/services\AgentSummary\agentSummary.ts:5: * to generate a 1-2 sentence progress summary. The summary is stored +src/services\AgentSummary\agentSummary.ts:6: * on AgentProgress for UI display. +src/services\AgentSummary\agentSummary.ts:8: * Cache sharing: uses the same CacheSafeParams as the parent agent +src/services\AgentSummary\agentSummary.ts:9: * to share the prompt cache. Tools are kept in the request for cache +src/services\AgentSummary\agentSummary.ts:10: * key matching but denied via canUseTool callback. +src/services\AgentSummary\agentSummary.ts:52: // Drop forkContextMessages from the closure �runSummary rebuilds it each +src/services\AgentSummary\agentSummary.ts:53: // tick from getAgentTranscript(). Without this, the original fork messages +src/services\AgentSummary\agentSummary.ts:54: // (passed from AgentTool.tsx) are pinned for the lifetime of the timer. +src/services\AgentSummary\agentSummary.ts:67: // Read current messages from transcript +src/services\AgentSummary\agentSummary.ts:70: // Not enough context yet �finally block will schedule next attempt +src/services\AgentSummary\agentSummary.ts:77: // Filter to clean message state +src/services\AgentSummary\agentSummary.ts:80: // Build fork params with current messages +src/services\AgentSummary\agentSummary.ts:90: // Create abort controller for this summary +src/services\AgentSummary\agentSummary.ts:93: // Deny tools via callback, NOT by passing tools:[] - that busts cache +src/services\AgentSummary\agentSummary.ts:100: // DO NOT set maxOutputTokens here. The fork piggybacks on the main +src/services\AgentSummary\agentSummary.ts:101: // thread's prompt cache by sending identical cache-key params (system, +src/services\AgentSummary\agentSummary.ts:102: // tools, model, messages prefix, thinking config). Setting maxOutputTokens +src/services\AgentSummary\agentSummary.ts:103: // would clamp budget_tokens, creating a thinking config mismatch that +src/services\AgentSummary\agentSummary.ts:104: // invalidates the cache. +src/services\AgentSummary\agentSummary.ts:106: // ContentReplacementState is cloned by default in createSubagentContext +src/services\AgentSummary\agentSummary.ts:107: // from forkParams.toolUseContext (the subagent's LIVE state captured at +src/services\AgentSummary\agentSummary.ts:108: // onCacheSafeParams time). No explicit override needed. +src/services\AgentSummary\agentSummary.ts:123: // Extract summary text from result +src/services\AgentSummary\agentSummary.ts:126: // Skip API error messages +src/services\AgentSummary\agentSummary.ts:150: // Reset timer on completion (not initiation) to prevent overlapping summaries +src/services\AgentSummary\agentSummary.ts:175: // Start the first timer +src/types\textInputTypes.ts:13: * Inline ghost text for mid-input command autocomplete +src/types\textInputTypes.ts:16: /** The ghost text to display (e.g., "mit" for /commit) */ +src/types\textInputTypes.ts:18: /** The full command name (e.g., "commit") */ +src/types\textInputTypes.ts:20: /** Position in the input where the ghost text should appear */ +src/types\textInputTypes.ts:25: * Base props for text input components +src/types\textInputTypes.ts:29: * Optional callback for handling history navigation on up arrow at start of input +src/types\textInputTypes.ts:34: * Optional callback for handling history navigation on down arrow at end of input +src/types\textInputTypes.ts:39: * Text to display when `value` is empty. +src/types\textInputTypes.ts:44: * Allow multi-line input via line ending with backslash (default: `true`) +src/types\textInputTypes.ts:49: * Listen to user's input. Useful in case there are multiple input components +src/types\textInputTypes.ts:50: * at the same time and input must be "routed" to a specific component. +src/types\textInputTypes.ts:55: * Replace all chars and mask the value. Useful for password inputs. +src/types\textInputTypes.ts:60: * Whether to show cursor and allow navigation inside text input with arrow keys. +src/types\textInputTypes.ts:65: * Highlight pasted text +src/types\textInputTypes.ts:70: * Value to display in a text input. +src/types\textInputTypes.ts:75: * Function to call when value updates. +src/types\textInputTypes.ts:80: * Function to call when `Enter` is pressed, where first argument is a value of the input. +src/types\textInputTypes.ts:85: * Function to call when Ctrl+C is pressed to exit. +src/types\textInputTypes.ts:90: * Optional callback to show exit message +src/types\textInputTypes.ts:95: * Optional callback to show custom message +src/types\textInputTypes.ts:97: // readonly onMessage?: (show: boolean, message?: string) => void +src/types\textInputTypes.ts:100: * Optional callback to reset history position +src/types\textInputTypes.ts:105: * Optional callback when input is cleared (e.g., double-escape) +src/types\textInputTypes.ts:110: * Number of columns to wrap text at +src/types\textInputTypes.ts:115: * Maximum visible lines for the input viewport. When the wrapped input +src/types\textInputTypes.ts:116: * exceeds this many lines, only lines around the cursor are rendered. +src/types\textInputTypes.ts:121: * Optional callback when an image is pasted +src/types\textInputTypes.ts:132: * Optional callback when a large text (over 800 chars) is pasted +src/types\textInputTypes.ts:137: * Callback when the pasting state changes +src/types\textInputTypes.ts:142: * Whether to disable cursor movement for up/down arrow keys +src/types\textInputTypes.ts:147: * Skip the text-level double-press escape handler. Set this when a +src/types\textInputTypes.ts:148: * keybinding context (e.g. Autocomplete) owns escape �the keybinding's +src/types\textInputTypes.ts:149: * stopImmediatePropagation can't shield the text input because child +src/types\textInputTypes.ts:150: * effects register useInput listeners before parent effects. +src/types\textInputTypes.ts:155: * The offset of the cursor within the text +src/types\textInputTypes.ts:160: * Callback to set the offset of the cursor +src/types\textInputTypes.ts:165: * Optional hint text to display after command input +src/types\textInputTypes.ts:166: * Used for showing available arguments for commands +src/types\textInputTypes.ts:171: * Optional callback for undo functionality +src/types\textInputTypes.ts:176: * Whether to render the text with dim color +src/types\textInputTypes.ts:181: * Optional text highlights for search results or other highlighting +src/types\textInputTypes.ts:186: * Optional custom React element to render as placeholder. +src/types\textInputTypes.ts:187: * When provided, overrides the standard `placeholder` string rendering. +src/types\textInputTypes.ts:192: * Optional inline ghost text for mid-input command autocomplete +src/types\textInputTypes.ts:197: * Optional filter applied to raw input before key routing. Return the +src/types\textInputTypes.ts:198: * (possibly transformed) input string; returning '' for a non-empty +src/types\textInputTypes.ts:199: * input drops the event. +src/types\textInputTypes.ts:205: * Extended props for VimTextInput +src/types\textInputTypes.ts:209: * Initial vim mode to use +src/types\textInputTypes.ts:214: * Optional callback for mode changes +src/types\textInputTypes.ts:220: * Vim editor modes +src/types\textInputTypes.ts:225: * Common properties for input hook results +src/types\textInputTypes.ts:232: /** Cursor line (0-indexed) within the rendered text, accounting for wrapping. */ +src/types\textInputTypes.ts:234: /** Cursor column (display-width) within the current line. */ +src/types\textInputTypes.ts:236: /** Character offset in the full text where the viewport starts (0 when no windowing). */ +src/types\textInputTypes.ts:238: /** Character offset in the full text where the viewport ends (text.length when no windowing). */ +src/types\textInputTypes.ts:241: // For paste handling +src/types\textInputTypes.ts:250: * State for text input +src/types\textInputTypes.ts:255: * State for vim input with mode +src/types\textInputTypes.ts:263: * Input modes for the prompt +src/types\textInputTypes.ts:277: * Queue priority levels. Same semantics in both normal and proactive mode. +src/types\textInputTypes.ts:279: * - `now` �Interrupt and send immediately. Aborts any in-flight tool +src/types\textInputTypes.ts:280: * call (equivalent to Esc + send). Consumers (print.ts, +src/types\textInputTypes.ts:281: * REPL.tsx) subscribe to queue changes and abort when they +src/types\textInputTypes.ts:282: * see a 'now' command. +src/types\textInputTypes.ts:283: * - `next` �Mid-turn drain. Let the current tool call finish, then +src/types\textInputTypes.ts:284: * send this message between the tool result and the next API +src/types\textInputTypes.ts:285: * round-trip. Wakes an in-progress SleepTool call. +src/types\textInputTypes.ts:286: * - `later` �End-of-turn drain. Wait for the current turn to finish, +src/types\textInputTypes.ts:287: * then process as a new query. Wakes an in-progress SleepTool +src/types\textInputTypes.ts:288: * call (query.ts upgrades the drain threshold after sleep so +src/types\textInputTypes.ts:289: * the message is attached to the same turn). +src/types\textInputTypes.ts:291: * The SleepTool is only available in proactive mode, so "wakes SleepTool" +src/types\textInputTypes.ts:292: * is a no-op in normal mode. +src/types\textInputTypes.ts:297: * Queued command type +src/types\textInputTypes.ts:302: /** Defaults to the priority implied by `mode` when enqueued. */ +src/types\textInputTypes.ts:306: /** Raw pasted contents including images. Images are resized at execution time. */ +src/types\textInputTypes.ts:309: * The input string before [Pasted text #N] placeholders were expanded. +src/types\textInputTypes.ts:310: * Used for ultraplan keyword detection so pasted content containing the +src/types\textInputTypes.ts:311: * keyword does not trigger a CCR session. Falls back to `value` when +src/types\textInputTypes.ts:312: * unset (bridge/UDS/MCP sources have no paste expansion). +src/types\textInputTypes.ts:316: * When true, the input is treated as plain text even if it starts with `/`. +src/types\textInputTypes.ts:317: * Used for remotely-received messages (e.g. bridge/CCR) that should not +src/types\textInputTypes.ts:318: * trigger local slash commands or skills. +src/types\textInputTypes.ts:322: * When true, slash commands are dispatched but filtered through +src/types\textInputTypes.ts:323: * isBridgeSafeCommand() �'local-jsx' and terminal-only commands return +src/types\textInputTypes.ts:324: * a helpful error instead of executing. Set by the Remote Control bridge +src/types\textInputTypes.ts:325: * inbound path so mobile/web clients can run skills and benign commands +src/types\textInputTypes.ts:326: * without re-exposing the PR #19134 bug (/model popping the local picker). +src/types\textInputTypes.ts:330: * When true, the resulting UserMessage gets `isMeta: true` �hidden in the +src/types\textInputTypes.ts:331: * transcript UI but visible to the model. Used by system-generated prompts +src/types\textInputTypes.ts:332: * (proactive ticks, teammate messages, resource updates) that route through +src/types\textInputTypes.ts:333: * the queue instead of calling `onQuery` directly. +src/types\textInputTypes.ts:337: * Provenance of this command. Stamped onto the resulting UserMessage so the +src/types\textInputTypes.ts:338: * transcript records origin structurally (not just via XML tags in content). +src/types\textInputTypes.ts:339: * undefined = human (keyboard). +src/types\textInputTypes.ts:343: * Workload tag threaded through to cc_workload= in the billing-header +src/types\textInputTypes.ts:344: * attribution block. The queue is the async boundary between the cron +src/types\textInputTypes.ts:345: * scheduler firing and the turn actually running �a user prompt can slip +src/types\textInputTypes.ts:346: * in between �so the tag rides on the QueuedCommand itself and is only +src/types\textInputTypes.ts:347: * hoisted into bootstrap state when THIS command is dequeued. +src/types\textInputTypes.ts:351: * Agent that should receive this notification. Undefined = main thread. +src/types\textInputTypes.ts:352: * Subagents run in-process and share the module-level command queue; the +src/types\textInputTypes.ts:353: * drain gate in query.ts filters by this field so a subagent's background +src/types\textInputTypes.ts:354: * task notifications don't leak into the coordinator's context (PR #18453 +src/types\textInputTypes.ts:355: * unified the queue but lost the isolation the dual-queue accidentally had). +src/types\textInputTypes.ts:361: * Type guard for image PastedContent with non-empty data. Empty-content +src/types\textInputTypes.ts:362: * images (e.g. from a 0-byte file drag) yield empty base64 strings that +src/types\textInputTypes.ts:363: * the API rejects with `image cannot be empty`. Use this at every site +src/types\textInputTypes.ts:364: * that converts PastedContent �ImageBlockParam so the filter and the +src/types\textInputTypes.ts:365: * ID list stay in sync. +src/types\textInputTypes.ts:371:/** Extract image paste IDs from a QueuedCommand's pastedContents. */ +src/services\voiceStreamSTT.ts:1:// Anthropic voice_stream speech-to-text client for push-to-talk. +src/services\voiceStreamSTT.ts:3:// Only reachable in ant builds (gated by feature('VOICE_MODE') in useVoice.ts import). +src/services\voiceStreamSTT.ts:5:// Connects to Anthropic's voice_stream WebSocket endpoint using the same +src/services\voiceStreamSTT.ts:6:// OAuth credentials as Claude Code. The endpoint uses conversation_engine +src/services\voiceStreamSTT.ts:7:// backed models for speech-to-text. Designed for hold-to-talk: hold the +src/services\voiceStreamSTT.ts:8:// keybinding to record, release to stop and submit. +src/services\voiceStreamSTT.ts:10:// The wire protocol uses JSON control messages (KeepAlive, CloseStream) and +src/services\voiceStreamSTT.ts:11:// binary audio frames. The server responds with TranscriptText and +src/services\voiceStreamSTT.ts:12:// TranscriptEndpoint JSON messages. +src/services\voiceStreamSTT.ts:34:// ─── Constants ─────────────────────────────────────────────────────── +src/services\voiceStreamSTT.ts:40:// finalize() resolution timers. `noData` fires when no TranscriptText +src/services\voiceStreamSTT.ts:41:// arrives post-CloseStream �the server has nothing; don't wait out the +src/services\voiceStreamSTT.ts:42:// full ~3-5s WS teardown to confirm emptiness. `safety` is the last- +src/services\voiceStreamSTT.ts:43:// resort cap if the WS hangs. Exported so tests can shorten them. +src/services\voiceStreamSTT.ts:49:// ─── Types ────────────────────────────────────────────────────────── +src/services\voiceStreamSTT.ts:58:// How finalize() resolved. `no_data_timeout` means zero server messages +src/services\voiceStreamSTT.ts:59:// after CloseStream �the silent-drop signature (anthropics/anthropic#287008). +src/services\voiceStreamSTT.ts:74:// The voice_stream endpoint returns transcript chunks and endpoint markers. +src/services\voiceStreamSTT.ts:96:// ─── Availability ────────────────────────────────────────────────────── +src/services\voiceStreamSTT.ts:99: // voice_stream uses the same OAuth as Claude Code �available when the +src/services\voiceStreamSTT.ts:100: // user is authenticated with Anthropic (Claude.ai subscriber or has +src/services\voiceStreamSTT.ts:101: // valid OAuth tokens). +src/services\voiceStreamSTT.ts:109:// ─── Connection ──────────────────────────────────────────────────────── +src/services\voiceStreamSTT.ts:115: // Ensure OAuth token is fresh before connecting +src/services\voiceStreamSTT.ts:124: // voice_stream is a private_api route, but /api/ws/ is also exposed on +src/services\voiceStreamSTT.ts:125: // the api.anthropic.com listener (service_definitions.yaml private-api: +src/services\voiceStreamSTT.ts:126: // visibility.external: true). We target that host instead of claude.ai +src/services\voiceStreamSTT.ts:127: // because the claude.ai CF zone uses TLS fingerprinting and challenges +src/services\voiceStreamSTT.ts:128: // non-browser clients (anthropics/claude-code#34094). Same private-api +src/services\voiceStreamSTT.ts:129: // pod, same OAuth Bearer auth �just a CF zone that doesn't block us. +src/services\voiceStreamSTT.ts:130: // Desktop dictation still uses claude.ai (Swift URLSession has a +src/services\voiceStreamSTT.ts:131: // browser-class JA3 fingerprint, so CF lets it through). +src/services\voiceStreamSTT.ts:153: // Route through conversation-engine with Deepgram Nova 3 (bypassing +src/services\voiceStreamSTT.ts:154: // the server's project_bell_v2_config GrowthBook gate). The server +src/services\voiceStreamSTT.ts:155: // side is anthropics/anthropic#278327 + #281372; this lets us ramp +src/services\voiceStreamSTT.ts:156: // clients independently. +src/services\voiceStreamSTT.ts:167: // Append keyterms as query params �the voice_stream proxy forwards +src/services\voiceStreamSTT.ts:168: // these to the STT service which applies appropriate boosting. +src/services\voiceStreamSTT.ts:199: // Set to true once CloseStream has been sent (or the ws is closed). +src/services\voiceStreamSTT.ts:200: // After this, further audio sends are dropped. +src/services\voiceStreamSTT.ts:202: // Set to true when finalize() is first called, to prevent double-fire. +src/services\voiceStreamSTT.ts:204: // Set when the HTTP upgrade was rejected (unexpected-response). The +src/services\voiceStreamSTT.ts:205: // close event that follows (1006 from our req.destroy()) is just +src/services\voiceStreamSTT.ts:206: // mechanical teardown; the upgrade handler already reported the error. +src/services\voiceStreamSTT.ts:208: // Resolves finalize(). Four triggers: TranscriptEndpoint post-CloseStream +src/services\voiceStreamSTT.ts:209: // (~300ms); no-data timer (1.5s); WS close (~3-5s); safety timer (5s). +src/services\voiceStreamSTT.ts:213: // Define the connection object before event handlers so it can be passed +src/services\voiceStreamSTT.ts:214: // to onReady when the WebSocket opens. +src/services\voiceStreamSTT.ts:221: // After CloseStream has been sent, the server rejects further audio. +src/services\voiceStreamSTT.ts:222: // Drop the chunk to avoid a protocol error. +src/services\voiceStreamSTT.ts:231: // Copy the buffer before sending: NAPI Buffer objects from native +src/services\voiceStreamSTT.ts:232: // modules may share a pooled ArrayBuffer. Creating a view with +src/services\voiceStreamSTT.ts:233: // `new Uint8Array(buf.buffer, offset, len)` can reference stale or +src/services\voiceStreamSTT.ts:234: // overlapping memory by the time the ws library reads it. +src/services\voiceStreamSTT.ts:235: // `Buffer.from()` makes an owned copy that the ws library can safely +src/services\voiceStreamSTT.ts:236: // consume as a binary WebSocket frame. +src/services\voiceStreamSTT.ts:241: // Already finalized or WebSocket already closed �resolve immediately. +src/services\voiceStreamSTT.ts:265: // Legacy Deepgram can leave an interim in lastTranscriptText +src/services\voiceStreamSTT.ts:266: // with no TranscriptEndpoint (websocket_manager.py sends +src/services\voiceStreamSTT.ts:267: // TranscriptChunk and TranscriptEndpoint as independent +src/services\voiceStreamSTT.ts:268: // channel items). All resolve triggers must promote it; +src/services\voiceStreamSTT.ts:269: // centralize here. No-op when the close handler already did. +src/services\voiceStreamSTT.ts:282: // If the WebSocket is already closed, resolve immediately. +src/services\voiceStreamSTT.ts:291: // Defer CloseStream to the next event-loop iteration so any audio +src/services\voiceStreamSTT.ts:292: // callbacks already queued by the native recording module are flushed +src/services\voiceStreamSTT.ts:293: // to the WebSocket before the server is told to stop accepting audio. +src/services\voiceStreamSTT.ts:294: // Without this, stopRecording() can return synchronously while the +src/services\voiceStreamSTT.ts:295: // native module still has a pending onData callback in the event queue, +src/services\voiceStreamSTT.ts:296: // causing audio to arrive after CloseStream. +src/services\voiceStreamSTT.ts:326: // Send an immediate KeepAlive so the server knows the client is active. +src/services\voiceStreamSTT.ts:327: // Audio hardware initialisation can take >1s, so this prevents the +src/services\voiceStreamSTT.ts:328: // server from closing the connection before audio capture starts. +src/services\voiceStreamSTT.ts:332: // Send periodic keepalive to prevent idle timeout +src/services\voiceStreamSTT.ts:344: // Pass the connection to the caller so it can start sending audio. +src/services\voiceStreamSTT.ts:345: // This fires only after the WebSocket is truly open, guaranteeing +src/services\voiceStreamSTT.ts:346: // that send() calls will not be silently dropped. +src/services\voiceStreamSTT.ts:350: // Track the last TranscriptText so that when TranscriptEndpoint arrives +src/services\voiceStreamSTT.ts:351: // we can emit it as the final transcript. The server sometimes sends +src/services\voiceStreamSTT.ts:352: // multiple non-cumulative TranscriptText messages without endpoints +src/services\voiceStreamSTT.ts:353: // between them; the TranscriptText handler auto-finalizes previous +src/services\voiceStreamSTT.ts:354: // segments when it detects the text has changed non-cumulatively. +src/services\voiceStreamSTT.ts:373: // Data arrived after CloseStream �disarm the no-data timer so +src/services\voiceStreamSTT.ts:374: // a slow-but-real flush isn't cut off. Only disarm once finalized +src/services\voiceStreamSTT.ts:375: // (CloseStream sent); pre-CloseStream data racing the deferred +src/services\voiceStreamSTT.ts:376: // send would cancel the timer prematurely, falling back to the +src/services\voiceStreamSTT.ts:377: // slower 5s safety timeout instead of the 1.5s no-data timer. +src/services\voiceStreamSTT.ts:382: // Detect when the server has moved to a new speech segment. +src/services\voiceStreamSTT.ts:383: // Progressive refinements extend or shorten the previous text +src/services\voiceStreamSTT.ts:384: // (e.g., "hello" �"hello world", or "hello wor" �"hello wo"). +src/services\voiceStreamSTT.ts:385: // A new segment starts with completely different text (neither +src/services\voiceStreamSTT.ts:386: // is a prefix of the other). When detected, emit the previous +src/services\voiceStreamSTT.ts:387: // text as final so the caller can accumulate it, preventing +src/services\voiceStreamSTT.ts:388: // the new segment from overwriting and losing the old one. +src/services\voiceStreamSTT.ts:390: // Nova 3's interims are cumulative across segments AND can +src/services\voiceStreamSTT.ts:391: // revise earlier text ("Hello?" �"Hello."). Revision breaks +src/services\voiceStreamSTT.ts:392: // the prefix check, causing false auto-finalize �the same +src/services\voiceStreamSTT.ts:393: // text committed once AND re-appearing in the cumulative +src/services\voiceStreamSTT.ts:394: // interim = duplication. Nova 3 only endpoints on the final +src/services\voiceStreamSTT.ts:395: // flush, so auto-finalize is never correct for it. +src/services\voiceStreamSTT.ts:412: // Emit as interim so the caller can show a live preview. +src/services\voiceStreamSTT.ts:421: // The server signals the end of an utterance. Emit the last +src/services\voiceStreamSTT.ts:422: // TranscriptText as a final transcript so the caller can commit it. +src/services\voiceStreamSTT.ts:428: // When TranscriptEndpoint arrives after CloseStream was sent, +src/services\voiceStreamSTT.ts:429: // the server has flushed its final transcript �nothing more is +src/services\voiceStreamSTT.ts:430: // coming. Resolve finalize now so the caller reads the +src/services\voiceStreamSTT.ts:431: // accumulated buffer immediately (~300ms) instead of waiting +src/services\voiceStreamSTT.ts:432: // for the WebSocket close event (~3-5s of server teardown). +src/services\voiceStreamSTT.ts:433: // `finalized` (not `finalizing`) is the right gate: it flips +src/services\voiceStreamSTT.ts:434: // inside the setTimeout(0) that actually sends CloseStream, so +src/services\voiceStreamSTT.ts:435: // a TranscriptEndpoint that races the deferred send still waits. +src/services\voiceStreamSTT.ts:473: // If the server closed the connection before sending TranscriptEndpoint, +src/services\voiceStreamSTT.ts:474: // promote the last interim transcript to final so no text is lost. +src/services\voiceStreamSTT.ts:483: // During finalize, suppress onError �the session already delivered +src/services\voiceStreamSTT.ts:484: // whatever it had. useVoice's onError path wipes accumulatedRef, +src/services\voiceStreamSTT.ts:485: // which would destroy the transcript before the finalize .then() +src/services\voiceStreamSTT.ts:486: // reads it. `finalizing` (not resolveFinalize) is the gate: set once +src/services\voiceStreamSTT.ts:487: // at finalize() entry, never cleared, so it stays accurate after the +src/services\voiceStreamSTT.ts:488: // fast path or a timer already resolved. +src/services\voiceStreamSTT.ts:498: // The ws library fires 'unexpected-response' when the HTTP upgrade +src/services\voiceStreamSTT.ts:499: // returns a non-101 status. Listening lets us surface the actual status +src/services\voiceStreamSTT.ts:500: // and flag 4xx as fatal (same token/TLS fingerprint won't change on +src/services\voiceStreamSTT.ts:501: // retry). With a listener registered, ws does NOT abort on our behalf � +src/services\voiceStreamSTT.ts:502: // we destroy the request; 'error' does not fire, 'close' does (suppressed +src/services\voiceStreamSTT.ts:503: // via upgradeRejected above). +src/services\voiceStreamSTT.ts:505: // Bun's ws shim historically didn't implement this event (a warning +src/services\voiceStreamSTT.ts:506: // is logged once at registration). Under Bun a non-101 upgrade falls +src/services\voiceStreamSTT.ts:507: // through to the generic 'error' + 'close' 1002 path with no recoverable +src/services\voiceStreamSTT.ts:508: // status; the attemptGenRef guard in useVoice.ts still surfaces the +src/services\voiceStreamSTT.ts:509: // retry-attempt failure, the user just sees "Expected 101 status code" +src/services\voiceStreamSTT.ts:510: // instead of "HTTP 503". No harm �the gen fix is the load-bearing part. +src/services\voiceStreamSTT.ts:513: // Bun's ws implementation on Windows can fire this event for a +src/services\voiceStreamSTT.ts:514: // successful 101 Switching Protocols response (anthropics/claude-code#40510). +src/services\voiceStreamSTT.ts:515: // 101 is never a rejection �bail before we destroy a working upgrade. +src/constants\xml.ts:1:// XML tag names used to mark skill/command metadata in messages +src/constants\xml.ts:6:// XML tag names for terminal/bash command input and output in user messages +src/constants\xml.ts:7:// These wrap content that represents terminal activity, not actual user prompts +src/constants\xml.ts:15:// All terminal-related tags that indicate a message is terminal output, not a user prompt +src/constants\xml.ts:27:// XML tag names for task notifications (background task completions) +src/constants\xml.ts:40:// XML tag names for ultraplan mode (remote parallel planning sessions) +src/constants\xml.ts:43:// XML tag name for remote /review results (teleported review session output). +src/constants\xml.ts:44:// Remote session wraps its final review in this tag; local poller extracts it. +src/constants\xml.ts:47:// run_hunt.sh's heartbeat echoes the orchestrator's progress.json inside this +src/constants\xml.ts:48:// tag every ~10s. Local poller parses the latest for the task-status line. +src/constants\xml.ts:51:// XML tag name for teammate messages (swarm inter-agent communication) +src/constants\xml.ts:54:// XML tag name for external channel messages +src/constants\xml.ts:58:// XML tag name for cross-session UDS messages (another Claude session's inbox) +src/constants\xml.ts:61:// XML tag wrapping the rules/format boilerplate in a fork child's first message. +src/constants\xml.ts:62:// Lets the transcript renderer collapse the boilerplate and show only the directive. +src/constants\xml.ts:64:// Prefix before the directive text, stripped by the renderer. Keep in sync +src/constants\xml.ts:65:// across buildChildMessage (generates) and UserForkBoilerplateMessage (parses). +src/constants\xml.ts:68:// Common argument patterns for slash commands that request help +src/constants\xml.ts:71:// Common argument patterns for slash commands that request current state/info +src/services\api\withRetry.ts:57:// Foreground query sources where the user IS blocking on the result �these +src/services\api\withRetry.ts:58:// retry on 529. Everything else (summaries, titles, suggestions, classifiers) +src/services\api\withRetry.ts:59:// bails immediately: during a capacity cascade each retry is 3-10× gateway +src/services\api\withRetry.ts:60:// amplification, and the user never sees those fail anyway. New sources +src/services\api\withRetry.ts:61:// default to no-retry �add here only if the user is waiting on the result. +src/services\api\withRetry.ts:76: // Security classifiers �must complete for auto-mode correctness. +src/services\api\withRetry.ts:77: // yoloClassifier.ts uses 'auto_mode' (not 'yolo_classifier' �that's +src/services\api\withRetry.ts:78: // type-only). bash_classifier is ant-only; feature-gate so the string +src/services\api\withRetry.ts:79: // tree-shakes out of external builds (excluded-strings.txt). +src/services\api\withRetry.ts:85: // undefined �retry (conservative for untagged call paths) +src/services\api\withRetry.ts:91:// CLAUDE_CODE_UNATTENDED_RETRY: for unattended sessions (ant-only). Retries 429/529 +src/services\api\withRetry.ts:92:// indefinitely with higher backoff and periodic keep-alive yields so the host +src/services\api\withRetry.ts:93:// environment does not mark the session idle mid-wait. +src/services\api\withRetry.ts:94:// TODO(ANT-344): the keep-alive via SystemAPIErrorMessage yields is a stopgap +src/services\api\withRetry.ts:95:// until there's a dedicated keep-alive channel. +src/services\api\withRetry.ts:136: * Pre-seed the consecutive 529 counter. Used when this retry loop is a +src/services\api\withRetry.ts:137: * non-streaming fallback after a streaming 529 �the streaming 529 should +src/services\api\withRetry.ts:138: * count toward MAX_529_RETRIES so total 529s-before-fallback is consistent +src/services\api\withRetry.ts:139: * regardless of which request mode hit the overload. +src/services\api\withRetry.ts:153: // Preserve the original stack trace if available +src/services\api\withRetry.ts:194: // Capture whether fast mode is active before this attempt +src/services\api\withRetry.ts:195: // (fallback may change the state mid-loop) +src/services\api\withRetry.ts:201: // Check for mock rate limits (used by /mock-limits command for Ant employees) +src/services\api\withRetry.ts:212: // Get a fresh client instance on first attempt or after authentication errors +src/services\api\withRetry.ts:213: // - 401 for first-party API authentication failures +src/services\api\withRetry.ts:214: // - 403 "OAuth token has been revoked" (another process refreshed the token) +src/services\api\withRetry.ts:215: // - Bedrock-specific auth errors (403 or CredentialsProviderError) +src/services\api\withRetry.ts:216: // - Vertex-specific auth errors (credential refresh failures, 401) +src/services\api\withRetry.ts:217: // - ECONNRESET/EPIPE: stale keep-alive socket; disable pooling and reconnect +src/services\api\withRetry.ts:240: // On 401 "token expired" or 403 "token revoked", force a token refresh +src/services\api\withRetry.ts:261: // Fast mode fallback: on 429/529, either wait and retry (short delays) +src/services\api\withRetry.ts:262: // or fall back to standard speed (long delays) to avoid cache thrashing. +src/services\api\withRetry.ts:263: // Skip in persistent mode: the short-retry path below loops with fast +src/services\api\withRetry.ts:264: // mode still active, so its `continue` never reaches the attempt clamp +src/services\api\withRetry.ts:265: // and the for-loop terminates. Persistent sessions want the chunked +src/services\api\withRetry.ts:266: // keep-alive path instead of fast-mode cache-preservation anyway. +src/services\api\withRetry.ts:273: // If the 429 is specifically because extra usage (overage) is not +src/services\api\withRetry.ts:274: // available, permanently disable fast mode with a specific message. +src/services\api\withRetry.ts:286: // Short retry-after: wait and retry with fast mode still active +src/services\api\withRetry.ts:287: // to preserve prompt cache (same model name on retry). +src/services\api\withRetry.ts:291: // Long or unknown retry-after: enter cooldown (switches to standard +src/services\api\withRetry.ts:292: // speed model), with a minimum floor to avoid flip-flopping. +src/services\api\withRetry.ts:307: // Fast mode fallback: if the API rejects the fast mode parameter +src/services\api\withRetry.ts:308: // (e.g., org doesn't have fast mode enabled), permanently disable fast +src/services\api\withRetry.ts:309: // mode and retry at standard speed. +src/services\api\withRetry.ts:316: // Non-foreground sources bail immediately on 529 �no retry amplification +src/services\api\withRetry.ts:317: // during capacity cascades. User never sees these fail. +src/services\api\withRetry.ts:326: // Track consecutive 529 errors +src/services\api\withRetry.ts:329: // If FALLBACK_FOR_ALL_PRIMARY_MODELS is not set, fall through only if the primary model is a non-custom Opus model. +src/services\api\withRetry.ts:330: // TODO: Revisit if the isNonCustomOpusModel check should still exist, or if isNonCustomOpusModel is a stale artifact of when Claude Code was hardcoded on Opus. +src/services\api\withRetry.ts:336: // Check if fallback model is specified +src/services\api\withRetry.ts:346: // Throw special error to indicate fallback was triggered +src/services\api\withRetry.ts:367: // Only retry if the error indicates we should +src/services\api\withRetry.ts:374: // AWS/GCP errors aren't always APIError, but can be retried +src/services\api\withRetry.ts:384: // Handle max tokens context overflow errors by adjusting max_tokens for the next attempt +src/services\api\withRetry.ts:385: // NOTE: With extended-context-window beta, this 400 error should not occur. +src/services\api\withRetry.ts:386: // The API now returns 'model_context_window_exceeded' stop_reason instead. +src/services\api\withRetry.ts:387: // Keeping for backward compatibility. +src/services\api\withRetry.ts:406: // Ensure we have enough tokens for thinking + at least 1 output token +src/services\api\withRetry.ts:429: // For other errors, proceed with normal retry logic +src/services\api\withRetry.ts:430: // Get retry-after header if available +src/services\api\withRetry.ts:435: // Window-based limits (e.g. 5hr Max/Pro) include a reset timestamp. +src/services\api\withRetry.ts:436: // Wait until reset rather than polling every 5 min uselessly. +src/services\api\withRetry.ts:450: // Retry-After is a server directive and bypasses maxDelayMs inside +src/services\api\withRetry.ts:451: // getRetryDelay (intentional �honoring it is correct). Cap at the +src/services\api\withRetry.ts:452: // 6hr reset-cap here so a pathological header can't wait unbounded. +src/services\api\withRetry.ts:465: // In persistent mode the for-loop `attempt` is clamped at maxRetries+1; +src/services\api\withRetry.ts:466: // use persistentAttempt for telemetry/yields so they show the true count. +src/services\api\withRetry.ts:486: // Chunk long sleeps so the host sees periodic stdout activity and +src/services\api\withRetry.ts:487: // does not mark the session idle. Each yield surfaces as +src/services\api\withRetry.ts:488: // {type:'system', subtype:'api_retry'} on stdout via QueryEngine. +src/services\api\withRetry.ts:504: // Clamp so the for-loop never terminates. Backoff uses the separate +src/services\api\withRetry.ts:505: // persistentAttempt counter which keeps growing to the 5-min cap. +src/services\api\withRetry.ts:524: // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins +src/services\api\withRetry.ts:569: // Example format: "input length and `max_tokens` exceed context limit: 188059 + 20000 > 200000" +src/services\api\withRetry.ts:597:// TODO: Replace with a response header check once the API adds a dedicated +src/services\api\withRetry.ts:598:// header for fast-mode rejection (e.g., x-fast-mode-rejected). String-matching +src/services\api\withRetry.ts:599:// the error message is fragile and will break if the API wording changes. +src/services\api\withRetry.ts:615: // Check for 529 status code or overloaded error in message +src/services\api\withRetry.ts:618: // See below: the SDK sometimes fails to properly pass the 529 status code during streaming +src/services\api\withRetry.ts:633: // AWS libs reject without an API call if .aws holds a past Expiration value +src/services\api\withRetry.ts:634: // otherwise, API calls that receive expired tokens give generic 403 +src/services\api\withRetry.ts:635: // "The security token included in the request is invalid" +src/services\api\withRetry.ts:647: * Clear AWS auth caches if appropriate. +src/services\api\withRetry.ts:648: * @returns true if action was taken. +src/services\api\withRetry.ts:658:// google-auth-library throws plain Error (no typed name like AWS's +src/services\api\withRetry.ts:659:// CredentialsProviderError). Match common SDK-level credential-failure messages. +src/services\api\withRetry.ts:672: // SDK-level: google-auth-library fails in prepareOptions() before the HTTP call +src/services\api\withRetry.ts:676: // Server-side: Vertex returns 401 for expired/invalid tokens +src/services\api\withRetry.ts:685: * Clear GCP auth caches if appropriate. +src/services\api\withRetry.ts:686: * @returns true if action was taken. +src/services\api\withRetry.ts:697: // Never retry mock errors - they're from /mock-limits command for testing +src/services\api\withRetry.ts:702: // Persistent mode: 429/529 always retryable, bypass subscriber gates and +src/services\api\withRetry.ts:703: // x-should-retry header. +src/services\api\withRetry.ts:708: // CCR mode: auth is via infrastructure-provided JWTs, so a 401/403 is a +src/services\api\withRetry.ts:709: // transient blip (auth service flap, network hiccup) rather than bad +src/services\api\withRetry.ts:710: // credentials. Bypass x-should-retry:false �the server assumes we'd retry +src/services\api\withRetry.ts:711: // the same bad key, but our key is fine. +src/services\api\withRetry.ts:719: // Check for overloaded errors first by examining the message content +src/services\api\withRetry.ts:720: // The SDK sometimes fails to properly pass the 529 status code during streaming, +src/services\api\withRetry.ts:721: // so we need to check the error message directly +src/services\api\withRetry.ts:726: // Check for max tokens context overflow errors that we can handle +src/services\api\withRetry.ts:731: // Note this is not a standard header. +src/services\api\withRetry.ts:734: // If the server explicitly says whether or not to retry, obey. +src/services\api\withRetry.ts:735: // For Max and Pro users, should-retry is true, but in several hours, so we shouldn't. +src/services\api\withRetry.ts:736: // Enterprise users can retry because they typically use PAYG instead of rate limits. +src/services\api\withRetry.ts:744: // Ants can ignore x-should-retry: false for 5xx server errors only. +src/services\api\withRetry.ts:745: // For other status codes (401, 403, 400, 429, etc.), respect the header. +src/services\api\withRetry.ts:759: // Retry on request timeouts. +src/services\api\withRetry.ts:762: // Retry on lock timeouts. +src/services\api\withRetry.ts:765: // Retry on rate limits, but not for ClaudeAI Subscription users +src/services\api\withRetry.ts:766: // Enterprise users can retry because they typically use PAYG instead of rate limits +src/services\api\withRetry.ts:771: // Clear API key cache on 401 and allow retry. +src/services\api\withRetry.ts:772: // OAuth token handling is done in the main retry loop via handleOAuth401Error. +src/services\api\withRetry.ts:778: // Retry on 403 "token revoked" (same refresh logic as 401, see above) +src/services\api\withRetry.ts:783: // Retry internal errors. +src/types\logs.ts:68: * AI-generated session title. Distinct from CustomTitleMessage so that: +src/types\logs.ts:69: * - User renames (custom-title) always win over AI titles in read preference +src/types\logs.ts:70: * - reAppendSessionMetadata never re-appends AI titles (they're ephemeral/ +src/types\logs.ts:71: * regeneratable; re-appending would clobber user renames on resume) +src/types\logs.ts:72: * - VS Code's onlyIfNoCustomTitle CAS check only matches user titles, +src/types\logs.ts:73: * allowing AI to overwrite its own previous AI title but not user titles +src/types\logs.ts:88: * Periodic fork-generated summary of what the agent is currently doing. +src/types\logs.ts:89: * Written every min(5 steps, 2min) by forking the main thread mid-turn so +src/types\logs.ts:90: * `claude ps` can show something more useful than the last user prompt +src/types\logs.ts:91: * (which is often "ok go" or "fix it"). +src/types\logs.ts:125: * PR link message stored in session transcript. +src/types\logs.ts:126: * Links a session to a GitHub pull request for tracking and navigation. +src/types\logs.ts:144: * Worktree session state persisted to the transcript for resume. +src/types\logs.ts:145: * Subset of WorktreeSession from utils/worktree.ts �excludes ephemeral +src/types\logs.ts:146: * fields (creationDurationMs, usedSparsePaths) that are only used for +src/types\logs.ts:147: * first-run analytics. +src/types\logs.ts:162: * Records whether the session is currently inside a worktree created by +src/types\logs.ts:163: * EnterWorktree or --worktree. Last-wins: an enter writes the session, +src/types\logs.ts:164: * an exit writes null. On --resume, restored only if the worktreePath +src/types\logs.ts:165: * still exists on disk (the /exit dialog may have removed it). +src/types\logs.ts:174: * Records content blocks whose in-context representation was replaced with a +src/types\logs.ts:175: * smaller stub (the full content was persisted elsewhere). Replayed on resume +src/types\logs.ts:176: * for prompt cache stability. Written once per enforcement pass that replaces +src/types\logs.ts:177: * at least one block. When agentId is set, the record belongs to a subagent +src/types\logs.ts:178: * sidechain (AgentTool resume reads these); when absent, it's main-thread +src/types\logs.ts:179: * (/resume reads these). +src/types\logs.ts:196: * Per-file attribution state tracking Claude's character contributions. +src/types\logs.ts:205: * Attribution snapshot message stored in session transcript. +src/types\logs.ts:206: * Tracks character-level contributions by Claude for commit attribution. +src/types\logs.ts:240: * Persisted context-collapse commit. The archived messages themselves are +src/types\logs.ts:241: * NOT persisted �they're already in the transcript as ordinary user/ +src/types\logs.ts:242: * assistant messages. We only persist enough to reconstruct the splice +src/types\logs.ts:243: * instruction (boundary uuids) and the summary placeholder (which is NOT +src/types\logs.ts:244: * in the transcript because it's never yielded to the REPL). +src/types\logs.ts:246: * On restore, the store reconstructs CommittedCollapse with archived=[]; +src/types\logs.ts:247: * projectView lazily fills the archive the first time it finds the span. +src/types\logs.ts:249: * Discriminator is obfuscated to match the gate name. sessionStorage.ts +src/types\logs.ts:250: * isn't feature-gated (it's the generic transcript plumbing used by every +src/types\logs.ts:251: * entry type), so a descriptive string here would leak into external builds +src/types\logs.ts:252: * via the appendEntry dispatch / loadTranscriptFile parser even though +src/types\logs.ts:253: * nothing in an external build ever writes or reads this entry. +src/types\logs.ts:258: /** 16-digit collapse ID. Max across entries reseeds the ID counter. */ +src/types\logs.ts:260: /** The summary placeholder's uuid �registerSummary() needs it. */ +src/types\logs.ts:262: /** Full text string for the placeholder. */ +src/types\logs.ts:264: /** Plain summary text for ctx_inspect. */ +src/types\logs.ts:266: /** Span boundaries �projectView finds these in the resumed Message[]. */ +src/types\logs.ts:272: * Snapshot of the staged queue and spawn trigger state. Unlike commits +src/types\logs.ts:273: * (append-only, replay-all), snapshots are last-wins �only the most +src/types\logs.ts:274: * recent snapshot entry is applied on restore. Written after every +src/types\logs.ts:275: * ctx-agent spawn resolves (when staged contents may have changed). +src/types\logs.ts:277: * Staged boundaries are UUIDs (session-stable), not collapse IDs (which +src/types\logs.ts:278: * reset with the uuidToId bimap). Restoring a staged span issues fresh +src/types\logs.ts:279: * collapse IDs for those messages on the next decorate/display, but the +src/types\logs.ts:280: * span itself resolves correctly. +src/types\logs.ts:292: /** Spawn trigger state �so the +interval clock picks up where it left off. */ +src/types\logs.ts:321: // Sort by modified date (newest first) +src/types\logs.ts:327: // If modified dates are equal, sort by created date (newest first) +src/services\autoDream\consolidationLock.ts:1:// Lock file whose mtime IS lastConsolidatedAt. Body is the holder's PID. +src/services\autoDream\consolidationLock.ts:3:// Lives inside the memory dir (getAutoMemPath) so it keys on git-root +src/services\autoDream\consolidationLock.ts:4:// like memory does, and so it's writable even when the memory path comes +src/services\autoDream\consolidationLock.ts:5:// from an env/settings override whose parent may not be. +src/services\autoDream\consolidationLock.ts:18:// Stale past this even if the PID is live (PID reuse guard). +src/services\autoDream\consolidationLock.ts:26: * mtime of the lock file = lastConsolidatedAt. 0 if absent. +src/services\autoDream\consolidationLock.ts:27: * Per-turn cost: one stat. +src/services\autoDream\consolidationLock.ts:39: * Acquire: write PID �mtime = now. Returns the pre-acquire mtime +src/services\autoDream\consolidationLock.ts:40: * (for rollback), or null if blocked / lost a race. +src/services\autoDream\consolidationLock.ts:42: * Success �do nothing. mtime stays at now. +src/services\autoDream\consolidationLock.ts:43: * Failure �rollbackConsolidationLock(priorMtime) rewinds mtime. +src/services\autoDream\consolidationLock.ts:44: * Crash �mtime stuck, dead PID �next process reclaims. +src/services\autoDream\consolidationLock.ts:57: // ENOENT �no prior lock. +src/services\autoDream\consolidationLock.ts:67: // Dead PID or unparseable body �reclaim. +src/services\autoDream\consolidationLock.ts:70: // Memory dir may not exist yet. +src/services\autoDream\consolidationLock.ts:74: // Two reclaimers both write �last wins the PID. Loser bails on re-read. +src/services\autoDream\consolidationLock.ts:87: * Rewind mtime to pre-acquire after a failed fork. Clears the PID body � +src/services\autoDream\consolidationLock.ts:88: * otherwise our still-running process would look like it's holding. +src/services\autoDream\consolidationLock.ts:89: * priorMtime 0 �unlink (restore no-file). +src/services\autoDream\consolidationLock.ts:111: * Session IDs with mtime after sinceMs. listCandidates handles UUID +src/services\autoDream\consolidationLock.ts:112: * validation (excludes agent-*.jsonl) and parallel stat. +src/services\autoDream\consolidationLock.ts:114: * Uses mtime (sessions TOUCHED since), not birthtime (0 on ext4). +src/services\autoDream\consolidationLock.ts:115: * Caller excludes the current session. Scans per-cwd transcripts �it's +src/services\autoDream\consolidationLock.ts:116: * a skip-gate, so undercounting worktree sessions is safe. +src/services\autoDream\consolidationLock.ts:127: * Stamp from manual /dream. Optimistic �fires at prompt-build time, +src/services\autoDream\consolidationLock.ts:128: * no post-skill completion hook. Best-effort. +src/services\autoDream\consolidationLock.ts:132: // Memory dir may not exist yet (manual /dream before any auto-trigger). +src/services\analytics\sink.ts:2: * Analytics sink implementation +src/services\analytics\sink.ts:4: * This module contains the actual analytics routing logic and should be +src/services\analytics\sink.ts:5: * initialized during app startup. It routes events to Datadog and 1P event +src/services\analytics\sink.ts:6: * logging. +src/services\analytics\sink.ts:8: * Usage: Call initializeAnalyticsSink() during app startup to attach the sink. +src/services\analytics\sink.ts:17:// Local type matching the logEvent metadata signature +src/services\analytics\sink.ts:22:// Module-level gate state - starts undefined, initialized during startup +src/services\analytics\sink.ts:26: * Check if Datadog tracking is enabled. +src/services\analytics\sink.ts:27: * Falls back to cached value from previous session if not yet initialized. +src/services\analytics\sink.ts:37: // Fallback to cached value from previous session +src/services\analytics\sink.ts:46: * Log an event (synchronous implementation) +src/services\analytics\sink.ts:49: // Check if this event should be sampled +src/services\analytics\sink.ts:52: // If sample result is 0, the event was not selected for logging +src/services\analytics\sink.ts:57: // If sample result is a positive number, add it to metadata +src/services\analytics\sink.ts:64: // Datadog is a general-access backend �strip _PROTO_* keys +src/services\analytics\sink.ts:65: // (unredacted PII-tagged values meant only for the 1P privileged column). +src/services\analytics\sink.ts:69: // 1P receives the full payload including _PROTO_* �the exporter +src/services\analytics\sink.ts:70: // destructures and routes those keys to proto fields itself. +src/services\analytics\sink.ts:75: * Log an event (asynchronous implementation) +src/services\analytics\sink.ts:77: * With Segment removed the two remaining sinks are fire-and-forget, so this +src/services\analytics\sink.ts:78: * just wraps the sync impl �kept to preserve the sink interface contract. +src/services\analytics\sink.ts:89: * Initialize analytics gates during startup. +src/services\analytics\sink.ts:91: * Updates gate values from server. Early events use cached values from previous +src/services\analytics\sink.ts:92: * session to avoid data loss during initialization. +src/services\analytics\sink.ts:94: * Called from main.tsx during setupBackend(). +src/services\analytics\sink.ts:102: * Initialize the analytics sink. +src/services\analytics\sink.ts:104: * Call this during app startup to attach the analytics backend. +src/services\analytics\sink.ts:105: * Any events logged before this is called will be queued and drained. +src/services\analytics\sink.ts:107: * Idempotent: safe to call multiple times (subsequent calls are no-ops). +src/services\compact\sessionMemoryCompact.ts:2: * EXPERIMENT: Session memory compaction +src/services\compact\sessionMemoryCompact.ts:45: * Configuration for session memory compaction thresholds +src/services\compact\sessionMemoryCompact.ts:48: /** Minimum tokens to preserve after compaction */ +src/services\compact\sessionMemoryCompact.ts:50: /** Minimum number of messages with text blocks to keep */ +src/services\compact\sessionMemoryCompact.ts:52: /** Maximum tokens to preserve after compaction (hard cap) */ +src/services\compact\sessionMemoryCompact.ts:56:// Default configuration values (exported for use in tests) +src/services\compact\sessionMemoryCompact.ts:63:// Current configuration (starts with defaults) +src/services\compact\sessionMemoryCompact.ts:68:// Track whether config has been initialized from remote +src/services\compact\sessionMemoryCompact.ts:72: * Set the session memory compact configuration +src/services\compact\sessionMemoryCompact.ts:84: * Get the current session memory compact configuration +src/services\compact\sessionMemoryCompact.ts:91: * Reset config state (useful for testing) +src/services\compact\sessionMemoryCompact.ts:99: * Initialize configuration from remote config (GrowthBook). +src/services\compact\sessionMemoryCompact.ts:100: * Only fetches once per session - subsequent calls return immediately. +src/services\compact\sessionMemoryCompact.ts:108: // Load config from GrowthBook, merging with defaults +src/services\compact\sessionMemoryCompact.ts:113: // Only use remote values if they are explicitly set (positive numbers) +src/services\compact\sessionMemoryCompact.ts:114: // This ensures sensible defaults aren't overridden by zero values +src/services\compact\sessionMemoryCompact.ts:133: * Check if a message contains text blocks (text content for user/assistant interaction) +src/services\compact\sessionMemoryCompact.ts:153: * Check if a message contains tool_result blocks and return their tool_use_ids +src/services\compact\sessionMemoryCompact.ts:173: * Check if a message contains tool_use blocks with any of the given ids +src/services\compact\sessionMemoryCompact.ts:189: * Adjust the start index to ensure we don't split tool_use/tool_result pairs +src/services\compact\sessionMemoryCompact.ts:190: * or thinking blocks that share the same message.id with kept assistant messages. +src/services\compact\sessionMemoryCompact.ts:192: * If ANY message we're keeping contains tool_result blocks, we need to +src/services\compact\sessionMemoryCompact.ts:193: * include the preceding assistant message(s) that contain the matching tool_use blocks. +src/services\compact\sessionMemoryCompact.ts:195: * Additionally, if ANY assistant message in the kept range has the same message.id +src/services\compact\sessionMemoryCompact.ts:196: * as a preceding assistant message (which may contain thinking blocks), we need to +src/services\compact\sessionMemoryCompact.ts:197: * include those messages so they can be properly merged by normalizeMessagesForAPI. +src/services\compact\sessionMemoryCompact.ts:199: * This handles the case where streaming yields separate messages per content block +src/services\compact\sessionMemoryCompact.ts:200: * (thinking, tool_use, etc.) with the same message.id but different uuids. If the +src/services\compact\sessionMemoryCompact.ts:201: * startIndex lands on one of these streaming messages, we need to look at ALL kept +src/services\compact\sessionMemoryCompact.ts:202: * messages for tool_results, not just the first one. +src/services\compact\sessionMemoryCompact.ts:204: * Example bug scenarios this fixes: +src/services\compact\sessionMemoryCompact.ts:206: * Tool pair scenario: +src/services\compact\sessionMemoryCompact.ts:207: * Session storage (before compaction): +src/services\compact\sessionMemoryCompact.ts:208: * Index N: assistant, message.id: X, content: [thinking] +src/services\compact\sessionMemoryCompact.ts:209: * Index N+1: assistant, message.id: X, content: [tool_use: ORPHAN_ID] +src/services\compact\sessionMemoryCompact.ts:210: * Index N+2: assistant, message.id: X, content: [tool_use: VALID_ID] +src/services\compact\sessionMemoryCompact.ts:211: * Index N+3: user, content: [tool_result: ORPHAN_ID, tool_result: VALID_ID] +src/services\compact\sessionMemoryCompact.ts:213: * If startIndex = N+2: +src/services\compact\sessionMemoryCompact.ts:214: * - Old code: checked only message N+2 for tool_results, found none, returned N+2 +src/services\compact\sessionMemoryCompact.ts:215: * - After slicing and normalizeMessagesForAPI merging by message.id: +src/services\compact\sessionMemoryCompact.ts:216: * msg[1]: assistant with [tool_use: VALID_ID] (ORPHAN tool_use was excluded!) +src/services\compact\sessionMemoryCompact.ts:217: * msg[2]: user with [tool_result: ORPHAN_ID, tool_result: VALID_ID] +src/services\compact\sessionMemoryCompact.ts:218: * - API error: orphan tool_result references non-existent tool_use +src/services\compact\sessionMemoryCompact.ts:220: * Thinking block scenario: +src/services\compact\sessionMemoryCompact.ts:221: * Session storage (before compaction): +src/services\compact\sessionMemoryCompact.ts:222: * Index N: assistant, message.id: X, content: [thinking] +src/services\compact\sessionMemoryCompact.ts:223: * Index N+1: assistant, message.id: X, content: [tool_use: ID] +src/services\compact\sessionMemoryCompact.ts:224: * Index N+2: user, content: [tool_result: ID] +src/services\compact\sessionMemoryCompact.ts:226: * If startIndex = N+1: +src/services\compact\sessionMemoryCompact.ts:227: * - Without this fix: thinking block at N is excluded +src/services\compact\sessionMemoryCompact.ts:228: * - After normalizeMessagesForAPI: thinking block is lost (no message to merge with) +src/services\compact\sessionMemoryCompact.ts:230: * Fixed code: detects that message N+1 has same message.id as N, adjusts to N. +src/services\compact\sessionMemoryCompact.ts:242: // Step 1: Handle tool_use/tool_result pairs +src/services\compact\sessionMemoryCompact.ts:243: // Collect tool_result IDs from ALL messages in the kept range +src/services\compact\sessionMemoryCompact.ts:250: // Collect tool_use IDs already in the kept range +src/services\compact\sessionMemoryCompact.ts:263: // Only look for tool_uses that are NOT already in the kept range +src/services\compact\sessionMemoryCompact.ts:268: // Find the assistant message(s) with matching tool_use blocks +src/services\compact\sessionMemoryCompact.ts:273: // Remove found tool_use_ids from the set +src/services\compact\sessionMemoryCompact.ts:288: // Step 2: Handle thinking blocks that share message.id with kept assistant messages +src/services\compact\sessionMemoryCompact.ts:289: // Collect all message.ids from assistant messages in the kept range +src/services\compact\sessionMemoryCompact.ts:298: // Look backwards for assistant messages with the same message.id that are not in the kept range +src/services\compact\sessionMemoryCompact.ts:299: // These may contain thinking blocks that need to be merged by normalizeMessagesForAPI +src/services\compact\sessionMemoryCompact.ts:307: // This message has the same message.id as one in the kept range +src/services\compact\sessionMemoryCompact.ts:308: // Include it so thinking blocks can be properly merged +src/services\compact\sessionMemoryCompact.ts:317: * Calculate the starting index for messages to keep after compaction. +src/services\compact\sessionMemoryCompact.ts:318: * Starts from lastSummarizedMessageId, then expands backwards to meet minimums: +src/services\compact\sessionMemoryCompact.ts:319: * - At least config.minTokens tokens +src/services\compact\sessionMemoryCompact.ts:320: * - At least config.minTextBlockMessages messages with text blocks +src/services\compact\sessionMemoryCompact.ts:321: * Stops expanding if config.maxTokens is reached. +src/services\compact\sessionMemoryCompact.ts:322: * Also ensures tool_use/tool_result pairs are not split. +src/services\compact\sessionMemoryCompact.ts:334: // Start from the message after lastSummarizedIndex +src/services\compact\sessionMemoryCompact.ts:335: // If lastSummarizedIndex is -1 (not found) or messages.length (no summarized id), +src/services\compact\sessionMemoryCompact.ts:336: // we start with no messages kept +src/services\compact\sessionMemoryCompact.ts:340: // Calculate current tokens and text-block message count from startIndex to end +src/services\compact\sessionMemoryCompact.ts:351: // Check if we already hit the max cap +src/services\compact\sessionMemoryCompact.ts:356: // Check if we already meet both minimums +src/services\compact\sessionMemoryCompact.ts:364: // Expand backwards until we meet both minimums or hit max cap. +src/services\compact\sessionMemoryCompact.ts:365: // Floor at the last boundary: the preserved-segment chain has a disk +src/services\compact\sessionMemoryCompact.ts:366: // discontinuity there (att[0]→summary shortcut from dedup-skip), which +src/services\compact\sessionMemoryCompact.ts:367: // would let the loader's tail→head walk bypass inner preserved messages +src/services\compact\sessionMemoryCompact.ts:368: // and then prune them. Reactive compact already slices at the boundary +src/services\compact\sessionMemoryCompact.ts:369: // via getMessagesAfterCompactBoundary; this is the same invariant. +src/services\compact\sessionMemoryCompact.ts:381: // Stop if we hit the max cap +src/services\compact\sessionMemoryCompact.ts:386: // Stop if we meet both minimums +src/services\compact\sessionMemoryCompact.ts:395: // Adjust for tool pairs +src/services\compact\sessionMemoryCompact.ts:400: * Check if we should use session memory for compaction +src/services\compact\sessionMemoryCompact.ts:401: * Uses cached gate values to avoid blocking on Statsig initialization +src/services\compact\sessionMemoryCompact.ts:404: // Allow env var override for eval runs and testing +src/services\compact\sessionMemoryCompact.ts:422: // Log flag states for debugging (ant-only to avoid noise in external logs) +src/services\compact\sessionMemoryCompact.ts:435: * Create a CompactionResult from session memory +src/services\compact\sessionMemoryCompact.ts:459: // Truncate oversized sections to prevent session memory from consuming +src/services\compact\sessionMemoryCompact.ts:460: // the entire post-compact token budget +src/services\compact\sessionMemoryCompact.ts:498: // SM-compact has no compact-API-call, so postCompactTokenCount (kept for +src/services\compact\sessionMemoryCompact.ts:499: // event continuity) and truePostCompactTokenCount converge to the same value. +src/services\compact\sessionMemoryCompact.ts:506: * Try to use session memory for compaction instead of traditional compaction. +src/services\compact\sessionMemoryCompact.ts:507: * Returns null if session memory compaction cannot be used. +src/services\compact\sessionMemoryCompact.ts:509: * Handles two scenarios: +src/services\compact\sessionMemoryCompact.ts:510: * 1. Normal case: lastSummarizedMessageId is set, keep only messages after that ID +src/services\compact\sessionMemoryCompact.ts:511: * 2. Resumed session: lastSummarizedMessageId is not set but session memory has content, +src/services\compact\sessionMemoryCompact.ts:512: * keep all messages but use session memory as the summary +src/services\compact\sessionMemoryCompact.ts:523: // Initialize config from remote (only fetches once) +src/services\compact\sessionMemoryCompact.ts:526: // Wait for any in-progress session memory extraction to complete (with timeout) +src/services\compact\sessionMemoryCompact.ts:532: // No session memory file exists at all +src/services\compact\sessionMemoryCompact.ts:538: // Session memory exists but matches the template (no actual content extracted) +src/services\compact\sessionMemoryCompact.ts:539: // Fall back to legacy compact behavior +src/services\compact\sessionMemoryCompact.ts:549: // Normal case: we know exactly which messages have been summarized +src/services\compact\sessionMemoryCompact.ts:555: // The summarized message ID doesn't exist in current messages +src/services\compact\sessionMemoryCompact.ts:556: // This can happen if messages were modified - fall back to legacy compact +src/services\compact\sessionMemoryCompact.ts:557: // since we can't determine the boundary between summarized and unsummarized messages +src/services\compact\sessionMemoryCompact.ts:562: // Resumed session case: session memory has content but we don't know the boundary +src/services\compact\sessionMemoryCompact.ts:563: // Set lastSummarizedIndex to last message so startIndex becomes messages.length (no messages kept initially) +src/services\compact\sessionMemoryCompact.ts:568: // Calculate the starting index for messages to keep +src/services\compact\sessionMemoryCompact.ts:569: // This starts from lastSummarizedIndex, expands to meet minimums, +src/services\compact\sessionMemoryCompact.ts:570: // and adjusts to not split tool_use/tool_result pairs +src/services\compact\sessionMemoryCompact.ts:575: // Filter out old compact boundary messages from messagesToKeep. +src/services\compact\sessionMemoryCompact.ts:576: // After REPL pruning, old boundaries re-yielded from messagesToKeep would +src/services\compact\sessionMemoryCompact.ts:577: // trigger an unwanted second prune (isCompactBoundaryMessage returns true), +src/services\compact\sessionMemoryCompact.ts:578: // discarding the new boundary and summary. +src/services\compact\sessionMemoryCompact.ts:583: // Run session start hooks to restore CLAUDE.md and other context +src/services\compact\sessionMemoryCompact.ts:588: // Get transcript path for the summary message +src/services\compact\sessionMemoryCompact.ts:604: // Only check threshold if one was provided (for autocompact) +src/services\compact\sessionMemoryCompact.ts:622: // Use logEvent instead of logError since errors here are expected +src/services\compact\sessionMemoryCompact.ts:623: // (e.g., file not found, path issues) and shouldn't go to error logs +src/services\compact\compactWarningHook.ts:5: * React hook to subscribe to compact warning suppression state. +src/services\compact\compactWarningHook.ts:7: * Lives in its own file so that compactWarningState.ts stays React-free: +src/services\compact\compactWarningHook.ts:8: * microCompact.ts imports the pure state functions, and pulling React into +src/services\compact\compactWarningHook.ts:9: * that module graph would drag it into the print-mode startup path. +src/services\compact\autoCompact.ts:28:// Reserve this many tokens for output during compaction +src/services\compact\autoCompact.ts:29:// Based on p99.99 of compact summary output being 17,387 tokens. +src/services\compact\autoCompact.ts:32:// Returns the context window size minus the max output tokens for the model +src/services\compact\autoCompact.ts:54: // Unique ID per turn +src/services\compact\autoCompact.ts:56: // Consecutive autocompact failures. Reset on success. +src/services\compact\autoCompact.ts:57: // Used as a circuit breaker to stop retrying when the context is +src/services\compact\autoCompact.ts:58: // irrecoverably over the limit (e.g., prompt_too_long). +src/services\compact\autoCompact.ts:67:// Stop trying autocompact after this many consecutive failures. +src/services\compact\autoCompact.ts:68:// BQ 2026-03-10: 1,279 sessions had 50+ consecutive failures (up to 3,272) +src/services\compact\autoCompact.ts:69:// in a single session, wasting ~250K API calls/day globally. +src/services\compact\autoCompact.ts:78: // Override for easier testing of autocompact +src/services\compact\autoCompact.ts:126: // Allow override for testing +src/services\compact\autoCompact.ts:151: // Allow disabling just auto-compact (keeps manual /compact working) +src/services\compact\autoCompact.ts:155: // Check if user has disabled auto-compact in their settings +src/services\compact\autoCompact.ts:164: // Snip removes messages but the surviving assistant's usage still reflects +src/services\compact\autoCompact.ts:165: // pre-snip context, so tokenCountWithEstimation can't see the savings. +src/services\compact\autoCompact.ts:166: // Subtract the rough-delta that snip already computed. +src/services\compact\autoCompact.ts:169: // Recursion guards. session_memory and compact are forked agents that +src/services\compact\autoCompact.ts:170: // would deadlock. +src/services\compact\autoCompact.ts:174: // marble_origami is the ctx-agent �if ITS context blows up and +src/services\compact\autoCompact.ts:175: // autocompact fires, runPostCompactCleanup calls resetContextCollapse() +src/services\compact\autoCompact.ts:176: // which destroys the MAIN thread's committed log (module-level state +src/services\compact\autoCompact.ts:177: // shared across forks). Inside feature() so the string DCEs from +src/services\compact\autoCompact.ts:178: // external builds (it's in excluded-strings.txt). +src/services\compact\autoCompact.ts:189: // Reactive-only mode: suppress proactive autocompact, let reactive compact +src/services\compact\autoCompact.ts:190: // catch the API's prompt-too-long. feature() wrapper keeps the flag string +src/services\compact\autoCompact.ts:191: // out of external builds (REACTIVE_COMPACT is ant-only). +src/services\compact\autoCompact.ts:192: // Note: returning false here also means autoCompactIfNeeded never reaches +src/services\compact\autoCompact.ts:193: // trySessionMemoryCompaction in the query loop �the /compact call site +src/services\compact\autoCompact.ts:194: // still tries session memory first. Revisit if reactive-only graduates. +src/services\compact\autoCompact.ts:201: // Context-collapse mode: same suppression. Collapse IS the context +src/services\compact\autoCompact.ts:202: // management system when it's on �the 90% commit / 95% blocking-spawn +src/services\compact\autoCompact.ts:203: // flow owns the headroom problem. Autocompact firing at effective-13k +src/services\compact\autoCompact.ts:204: // (~93% of effective) sits right between collapse's commit-start (90%) +src/services\compact\autoCompact.ts:205: // and blocking (95%), so it would race collapse and usually win, nuking +src/services\compact\autoCompact.ts:206: // granular context that collapse was about to save. Gating here rather +src/services\compact\autoCompact.ts:207: // than in isAutoCompactEnabled() keeps reactiveCompact alive as the 413 +src/services\compact\autoCompact.ts:208: // fallback (it consults isAutoCompactEnabled directly) and leaves +src/services\compact\autoCompact.ts:209: // sessionMemory + manual /compact working. +src/services\compact\autoCompact.ts:211: // Consult isContextCollapseEnabled (not the raw gate) so the +src/services\compact\autoCompact.ts:212: // CLAUDE_CONTEXT_COLLAPSE env override is honored here too. require() +src/services\compact\autoCompact.ts:213: // inside the block breaks the init-time cycle (this file exports +src/services\compact\autoCompact.ts:214: // getEffectiveContextWindowSize which collapse's index imports). +src/services\compact\autoCompact.ts:216: /* eslint-disable @typescript-eslint/no-require-imports */ +src/services\compact\autoCompact.ts:219: /* eslint-enable @typescript-eslint/no-require-imports */ +src/services\compact\autoCompact.ts:257: // Circuit breaker: stop retrying after N consecutive failures. +src/services\compact\autoCompact.ts:258: // Without this, sessions where context is irrecoverably over the limit +src/services\compact\autoCompact.ts:259: // hammer the API with doomed compaction attempts on every turn. +src/services\compact\autoCompact.ts:287: // EXPERIMENT: Try session memory compaction first +src/services\compact\autoCompact.ts:294: // Reset lastSummarizedMessageId since session memory compaction prunes messages +src/services\compact\autoCompact.ts:295: // and the old message UUID will no longer exist after the REPL replaces messages +src/services\compact\autoCompact.ts:298: // Reset cache read baseline so the post-compact drop isn't flagged as a +src/services\compact\autoCompact.ts:299: // break. compactConversation does this internally; SM-compact doesn't. +src/services\compact\autoCompact.ts:300: // BQ 2026-03-01: missing this made 20% of tengu_prompt_cache_break events +src/services\compact\autoCompact.ts:301: // false positives (systemPromptChanged=true, timeSinceLastAssistantMsg=-1). +src/services\compact\autoCompact.ts:323: // Reset lastSummarizedMessageId since legacy compaction replaces all messages +src/services\compact\autoCompact.ts:324: // and the old message UUID will no longer exist in the new messages array +src/services\compact\autoCompact.ts:331: // Reset failure count on success +src/services\compact\autoCompact.ts:338: // Increment consecutive failure count for circuit breaker. +src/services\compact\autoCompact.ts:339: // The caller threads this through autoCompactTracking so the +src/services\compact\autoCompact.ts:340: // next query loop iteration can skip futile retry attempts. +src/services\compact\compact.ts:5:/* eslint-disable @typescript-eslint/no-require-imports */ +src/services\compact\compact.ts:82:/* eslint-enable @typescript-eslint/no-require-imports */ +src/services\compact\compact.ts:125:// Skills can be large (verify=18.7KB, claude-api=20.1KB). Previously re-injected +src/services\compact\compact.ts:126:// unbounded on every compact �5-10K tok/compact. Per-skill truncation beats +src/services\compact\compact.ts:127:// dropping �instructions at the top of a skill file are usually the critical +src/services\compact\compact.ts:128:// part. Budget sized to hold ~5 skills at the per-skill cap. +src/services\compact\compact.ts:134: * Strip image blocks from user messages before sending for compaction. +src/services\compact\compact.ts:135: * Images are not needed for generating a conversation summary and can +src/services\compact\compact.ts:136: * cause the compaction API call itself to hit the prompt-too-long limit, +src/services\compact\compact.ts:137: * especially in CCD sessions where users frequently attach images. +src/services\compact\compact.ts:138: * Replaces image blocks with a text marker so the summary still notes +src/services\compact\compact.ts:139: * that an image was shared. +src/services\compact\compact.ts:141: * Note: Only user messages contain images (either directly attached or within +src/services\compact\compact.ts:142: * tool_result content from tools). Assistant messages contain text, tool_use, +src/services\compact\compact.ts:143: * and thinking blocks but not images. +src/services\compact\compact.ts:166: // Also strip images/documents nested inside tool_result content arrays +src/services\compact\compact.ts:203: * Strip attachment types that are re-injected post-compaction anyway. +src/services\compact\compact.ts:204: * skill_discovery/skill_listing are re-surfaced by resetSentSkillNames() +src/services\compact\compact.ts:205: * + the next turn's discovery signal, so feeding them to the summarizer +src/services\compact\compact.ts:206: * wastes tokens and pollutes the summary with stale skill suggestions. +src/services\compact\compact.ts:208: * No-op when EXPERIMENTAL_SKILL_SEARCH is off (the attachment types +src/services\compact\compact.ts:209: * don't exist on external builds). +src/services\compact\compact.ts:231: * Drops the oldest API-round groups from messages until tokenGap is covered. +src/services\compact\compact.ts:232: * Falls back to dropping 20% of groups when the gap is unparseable (some +src/services\compact\compact.ts:233: * Vertex/Bedrock error formats). Returns null when nothing can be dropped +src/services\compact\compact.ts:234: * without leaving an empty summarize set. +src/services\compact\compact.ts:236: * This is the last-resort escape hatch for CC-1180 �when the compact request +src/services\compact\compact.ts:237: * itself hits prompt-too-long, the user is otherwise stuck. Dropping the +src/services\compact\compact.ts:238: * oldest context is lossy but unblocks them. The reactive-compact path +src/services\compact\compact.ts:239: * (compactMessages.ts) has the proper retry loop that peels from the tail; +src/services\compact\compact.ts:240: * this helper is the dumb-but-safe fallback for the proactive/manual path +src/services\compact\compact.ts:241: * that wasn't migrated in bfdb472f's unification. +src/services\compact\compact.ts:247: // Strip our own synthetic marker from a previous retry before grouping. +src/services\compact\compact.ts:248: // Otherwise it becomes its own group 0 and the 20% fallback stalls +src/services\compact\compact.ts:249: // (drops only the marker, re-adds it, zero progress on retry 2+). +src/services\compact\compact.ts:274: // Keep at least one group so there's something to summarize. +src/services\compact\compact.ts:279: // groupMessagesByApiRound puts the preamble in group 0 and starts every +src/services\compact\compact.ts:280: // subsequent group with an assistant message. Dropping group 0 leaves an +src/services\compact\compact.ts:281: // assistant-first sequence which the API rejects (first message must be +src/services\compact\compact.ts:282: // role=user). Prepend a synthetic user marker �ensureToolResultPairing +src/services\compact\compact.ts:283: // already handles any orphaned tool_results this creates. +src/services\compact\compact.ts:313: * Diagnosis context passed from autoCompactIfNeeded into compactConversation. +src/services\compact\compact.ts:314: * Lets the tengu_compact event disambiguate same-chain loops (H2) from +src/services\compact\compact.ts:315: * cross-agent (H1/H5) and manual-vs-auto (H3) compactions without joins. +src/services\compact\compact.ts:326: * Build the base post-compact messages array from a CompactionResult. +src/services\compact\compact.ts:327: * This ensures consistent ordering across all compaction paths. +src/services\compact\compact.ts:328: * Order: boundaryMarker, summaryMessages, messagesToKeep, attachments, hookResults +src/services\compact\compact.ts:341: * Annotate a compact boundary with relink metadata for messagesToKeep. +src/services\compact\compact.ts:342: * Preserved messages keep their original parentUuids on disk (dedup-skipped); +src/services\compact\compact.ts:343: * the loader uses this to patch head→anchor and anchor's-other-children→tail. +src/services\compact\compact.ts:345: * `anchorUuid` = what sits immediately before keep[0] in the desired chain: +src/services\compact\compact.ts:346: * - suffix-preserving (reactive/session-memory): last summary message +src/services\compact\compact.ts:347: * - prefix-preserving (partial compact): the boundary itself +src/services\compact\compact.ts:370: * Merges user-supplied custom instructions with hook-provided instructions. +src/services\compact\compact.ts:371: * User instructions come first; hook instructions are appended. +src/services\compact\compact.ts:372: * Empty strings normalize to undefined. +src/services\compact\compact.ts:384: * Creates a compact version of a conversation by summarizing older messages +src/services\compact\compact.ts:385: * and preserving recent conversation history. +src/services\compact\compact.ts:411: // Execute PreCompact hooks +src/services\compact\compact.ts:426: // Show requesting mode with up arrow and custom message +src/services\compact\compact.ts:431: // 3P default: true �forked-agent path reuses main conversation's prompt cache. +src/services\compact\compact.ts:432: // Experiment (Jan 2026) confirmed: false path is 98% cache miss, costs ~0.76% of +src/services\compact\compact.ts:433: // fleet cache_creation (~38B tok/day), concentrated in ephemeral envs (CCR/GHA/SDK) +src/services\compact\compact.ts:434: // with cold GB cache and 3P providers where GB is disabled. GB gate kept as kill-switch. +src/services\compact\compact.ts:462: // CC-1180: compact request itself hit prompt-too-long. Truncate the +src/services\compact\compact.ts:463: // oldest API-round groups and retry rather than leaving the user stuck. +src/services\compact\compact.ts:485: // The forked-agent path reads from cacheSafeParams.forkContextMessages, +src/services\compact\compact.ts:486: // not the messages param �thread the truncated set through both paths. +src/services\compact\compact.ts:517: // Store the current file state before clearing +src/services\compact\compact.ts:520: // Clear the cache +src/services\compact\compact.ts:524: // Intentionally NOT resetting sentSkillNames: re-injecting the full +src/services\compact\compact.ts:525: // skill_listing (~4K tokens) post-compact is pure cache_creation with +src/services\compact\compact.ts:526: // marginal benefit. The model still has SkillTool in its schema and +src/services\compact\compact.ts:527: // invoked_skills attachment (below) preserves used-skill content. Ants +src/services\compact\compact.ts:528: // with EXPERIMENTAL_SKILL_SEARCH already skip re-injection via the +src/services\compact\compact.ts:529: // early-return in getSkillListingAttachments. +src/services\compact\compact.ts:531: // Run async attachment generation in parallel +src/services\compact\compact.ts:550: // Add plan mode instructions if currently in plan mode, so the model +src/services\compact\compact.ts:551: // continues operating in plan mode after compaction +src/services\compact\compact.ts:557: // Add skill attachment if skills were invoked in this session +src/services\compact\compact.ts:563: // Compaction ate prior delta attachments. Re-announce from the current +src/services\compact\compact.ts:564: // state so the model has tool/instruction context on the first +src/services\compact\compact.ts:565: // post-compact turn. Empty message history �diff against nothing � +src/services\compact\compact.ts:566: // announces the full set. +src/services\compact\compact.ts:591: // Execute SessionStart hooks after successful compaction +src/services\compact\compact.ts:596: // Create the compact boundary marker and summary messages before the +src/services\compact\compact.ts:597: // event so we can compute the true resulting-context size. +src/services\compact\compact.ts:603: // Carry loaded-tool state �the summary doesn't preserve tool_reference +src/services\compact\compact.ts:604: // blocks, so the post-compact schema filter needs this to keep sending +src/services\compact\compact.ts:605: // already-loaded deferred tool schemas to the API. +src/services\compact\compact.ts:626: // Previously "postCompactTokenCount" �renamed because this is the +src/services\compact\compact.ts:627: // compact API call's total usage (input_tokens �preCompactTokenCount), +src/services\compact\compact.ts:628: // NOT the size of the resulting context. Kept for event-field continuity. +src/services\compact\compact.ts:633: // Message-payload estimate of the resulting context. The next iteration's +src/services\compact\compact.ts:634: // shouldAutoCompact will see this PLUS ~20-40K for system prompt + tools + +src/services\compact\compact.ts:635: // userContext (via API usage.input_tokens). So `willRetriggerNextTurn: true` +src/services\compact\compact.ts:636: // is a strong signal; `false` may still retrigger when this is close to threshold. +src/services\compact\compact.ts:644: // Extract compaction API usage metrics +src/services\compact\compact.ts:652: // Kept for continuity �semantically the compact API call's total usage +src/services\compact\compact.ts:682: // analyzeContext walks every content block (~11ms on a 4.5K-message +src/services\compact\compact.ts:683: // session) purely for this telemetry breakdown. Computed here, past +src/services\compact\compact.ts:684: // the compaction-API await, so the sync walk doesn't starve the +src/services\compact\compact.ts:685: // render loop before compaction even starts. Same deferral pattern +src/services\compact\compact.ts:686: // as reactiveCompact.ts. +src/services\compact\compact.ts:697: // Reset cache read baseline so the post-compact drop isn't flagged as a break +src/services\compact\compact.ts:706: // Re-append session metadata (custom title, tag) so it stays within +src/services\compact\compact.ts:707: // the 16KB tail window that readLiteMetadata reads for --resume display. +src/services\compact\compact.ts:708: // Without this, enough post-compaction messages push the metadata entry +src/services\compact\compact.ts:709: // out of the window, causing --resume to show the auto-generated title +src/services\compact\compact.ts:710: // instead of the user-set session name. +src/services\compact\compact.ts:713: // Write a reduced transcript segment for the pre-compaction messages +src/services\compact\compact.ts:714: // (assistant mode only). Fire-and-forget �errors are logged internally. +src/services\compact\compact.ts:750: // Only show the error notification for manual /compact. +src/services\compact\compact.ts:751: // Auto-compact failures are retried on the next turn and the +src/services\compact\compact.ts:752: // notification is confusing when compaction eventually succeeds. +src/services\compact\compact.ts:766: * Performs a partial compaction around the selected message index. +src/services\compact\compact.ts:767: * Direction 'from': summarizes messages after the index, keeps earlier ones. +src/services\compact\compact.ts:768: * Prompt cache for kept (earlier) messages is preserved. +src/services\compact\compact.ts:769: * Direction 'up_to': summarizes messages before the index, keeps later ones. +src/services\compact\compact.ts:770: * Prompt cache is invalidated since the summary precedes the kept messages. +src/services\compact\compact.ts:785: // 'up_to' must strip old compact boundaries/summaries: for 'up_to', +src/services\compact\compact.ts:786: // summary_B sits BEFORE kept, so a stale boundary_A in kept wins +src/services\compact\compact.ts:787: // findLastCompactBoundaryIndex's backward scan and drops summary_B. +src/services\compact\compact.ts:788: // 'from' keeps them: summary_B sits AFTER kept (backward scan still +src/services\compact\compact.ts:789: // works), and removing an old summary would lose its covered history. +src/services\compact\compact.ts:826: // Merge hook instructions with user feedback +src/services\compact\compact.ts:852: // 'up_to' prefix hits cache directly; 'from' sends all (tail wouldn't cache). +src/services\compact\compact.ts:853: // PTL retry breaks the cache prefix but unblocks the user (CC-1180). +src/services\compact\compact.ts:918: // Store the current file state before clearing +src/services\compact\compact.ts:922: // Intentionally NOT resetting sentSkillNames �see compactConversation() +src/services\compact\compact.ts:923: // for rationale (~4K tokens saved per compact event). +src/services\compact\compact.ts:944: // Add plan mode instructions if currently in plan mode +src/services\compact\compact.ts:955: // Re-announce only what was in the summarized portion �messagesToKeep +src/services\compact\compact.ts:956: // is scanned, so anything already announced there is skipped. +src/services\compact\compact.ts:1007: // Progress messages aren't loggable, so forkSessionImpl would null out +src/services\compact\compact.ts:1008: // a logicalParentUuid pointing at one. Both directions skip them. +src/services\compact\compact.ts:1021: // allMessages not just messagesToSummarize �set union is idempotent, +src/services\compact\compact.ts:1022: // simpler than tracking which half each tool lived in. +src/services\compact\compact.ts:1055: // Re-append session metadata (custom title, tag) so it stays within +src/services\compact\compact.ts:1056: // the 16KB tail window that readLiteMetadata reads for --resume display. +src/services\compact\compact.ts:1077: // 'from': prefix-preserving �boundary; 'up_to': suffix �last summary +src/services\compact\compact.ts:1151: // When prompt cache sharing is enabled, use forked agent to reuse the +src/services\compact\compact.ts:1152: // main conversation's cached prefix (system prompt, tools, context messages). +src/services\compact\compact.ts:1153: // Falls back to regular streaming path on failure. +src/services\compact\compact.ts:1154: // 3P default: true �see comment at the other tengu_compact_cache_prefix read above. +src/services\compact\compact.ts:1159: // Send keep-alive signals during compaction to prevent remote session +src/services\compact\compact.ts:1160: // WebSocket idle timeouts from dropping bridge connections. Compaction +src/services\compact\compact.ts:1161: // API calls can take 5-10+ seconds, during which no other messages +src/services\compact\compact.ts:1162: // flow through the transport �without keep-alives, the server may +src/services\compact\compact.ts:1163: // close the WebSocket for inactivity. +src/services\compact\compact.ts:1164: // Two signals: (1) PUT /worker heartbeat via sessionActivity, and +src/services\compact\compact.ts:1165: // (2) re-emit 'compacting' status so the SDK event stream stays active +src/services\compact\compact.ts:1166: // and the server doesn't consider the session stale. +src/services\compact\compact.ts:1181: // DO NOT set maxOutputTokens here. The fork piggybacks on the main thread's +src/services\compact\compact.ts:1182: // prompt cache by sending identical cache-key params (system, tools, model, +src/services\compact\compact.ts:1183: // messages prefix, thinking config). Setting maxOutputTokens would clamp +src/services\compact\compact.ts:1184: // budget_tokens via Math.min(budget, maxOutputTokens-1) in claude.ts, +src/services\compact\compact.ts:1185: // creating a thinking config mismatch that invalidates the cache. +src/services\compact\compact.ts:1186: // The streaming fallback path (below) can safely set maxOutputTokensOverride +src/services\compact\compact.ts:1187: // since it doesn't share cache with the main thread. +src/services\compact\compact.ts:1196: // Pass the compact context's abortController so user Esc aborts the +src/services\compact\compact.ts:1197: // fork �same signal the streaming fallback uses at +src/services\compact\compact.ts:1198: // `signal: context.abortController.signal` below. +src/services\compact\compact.ts:1205: // Guard isApiErrorMessage: query() catches API errors (including +src/services\compact\compact.ts:1206: // APIUserAbortError on ESC) and yields them as synthetic assistant +src/services\compact\compact.ts:1207: // messages. Without this check, an aborted compact "succeeds" with +src/services\compact\compact.ts:1208: // "Request was aborted." as the summary �the text doesn't start with +src/services\compact\compact.ts:1209: // "API Error" so the caller's startsWithApiErrorPrefix guard misses it. +src/services\compact\compact.ts:1211: // Skip success logging for PTL error text �it's returned so the +src/services\compact\compact.ts:1212: // caller's retry loop catches it, but it's not a successful summary. +src/services\compact\compact.ts:1250: // Regular streaming path (fallback when cache sharing fails or is disabled) +src/services\compact\compact.ts:1258: // Reset state for retry +src/services\compact\compact.ts:1263: // Check if tool search is enabled using the main loop's tools list. +src/services\compact\compact.ts:1264: // context.options.tools includes MCP tools merged via useMergedTools. +src/services\compact\compact.ts:1273: // When tool search is enabled, include ToolSearchTool and MCP tools. They get +src/services\compact\compact.ts:1274: // defer_loading: true and don't count against context - the API filters them out +src/services\compact\compact.ts:1275: // of system_prompt_tools before token counting (see api/token_count_api/counting.py:188 +src/services\compact\compact.ts:1276: // and api/public_api/messages/handler.py:324). +src/services\compact\compact.ts:1277: // Filter MCP tools from context.options.tools (not appState.mcp.tools) so we +src/services\compact\compact.ts:1278: // get the permission-filtered set from useMergedTools �same source used for +src/services\compact\compact.ts:1279: // isToolSearchEnabled above and normalizeMessagesForAPI below. +src/services\compact\compact.ts:1280: // Deduplicate by name to avoid API errors when MCP tools share names with built-in tools. +src/services\compact\compact.ts:1391: // This should never be reached due to the throw above, but TypeScript needs it +src/services\compact\compact.ts:1399: * Creates attachment messages for recently accessed files to restore them after compaction. +src/services\compact\compact.ts:1400: * This prevents the model from having to re-read files that were recently accessed. +src/services\compact\compact.ts:1401: * Re-reads files using FileReadTool to get fresh content with proper validation. +src/services\compact\compact.ts:1402: * Files are selected based on recency, but constrained by both file count and token budget limits. +src/services\compact\compact.ts:1404: * Files already present as Read tool results in preservedMessages are skipped � +src/services\compact\compact.ts:1405: * re-injecting identical content the model can already see in the preserved tail +src/services\compact\compact.ts:1406: * is pure waste (up to 25K tok/compact). Mirrors the diff-against-preserved +src/services\compact\compact.ts:1407: * pattern that getDeferredToolsDeltaAttachment uses at the same call sites. +src/services\compact\compact.ts:1409: * @param readFileState The current file state tracking recently read files +src/services\compact\compact.ts:1410: * @param toolUseContext The tool use context for calling FileReadTool +src/services\compact\compact.ts:1411: * @param maxFiles Maximum number of files to restore (default: 5) +src/services\compact\compact.ts:1412: * @param preservedMessages Messages kept post-compact; Read results here are skipped +src/services\compact\compact.ts:1413: * @returns Array of attachment messages for the most recently accessed files that fit within token budget +src/services\compact\compact.ts:1467: * Creates a plan file attachment if a plan file exists for the current session. +src/services\compact\compact.ts:1468: * This ensures the plan is preserved after compaction. +src/services\compact\compact.ts:1489: * Creates an attachment for invoked skills to preserve their content across compaction. +src/services\compact\compact.ts:1490: * Only includes skills scoped to the given agent (or main session when agentId is null/undefined). +src/services\compact\compact.ts:1491: * This ensures skill guidelines remain available after the conversation is summarized +src/services\compact\compact.ts:1492: * without leaking skills from other agent contexts. +src/services\compact\compact.ts:1503: // Sorted most-recent-first so budget pressure drops the least-relevant skills. +src/services\compact\compact.ts:1504: // Per-skill truncation keeps the head of each file (where setup/usage +src/services\compact\compact.ts:1505: // instructions typically live) rather than dropping whole skills. +src/services\compact\compact.ts:1537: * Creates a plan_mode attachment if the user is currently in plan mode. +src/services\compact\compact.ts:1538: * This ensures the model continues to operate in plan mode after compaction +src/services\compact\compact.ts:1539: * (otherwise it would lose the plan mode instructions since those are +src/services\compact\compact.ts:1540: * normally only injected on tool-use turns via getAttachmentMessages). +src/services\compact\compact.ts:1563: * Creates attachments for async agents so the model knows about them after +src/services\compact\compact.ts:1564: * compaction. Covers both agents still running in the background (so the model +src/services\compact\compact.ts:1565: * doesn't spawn a duplicate) and agents that have finished but whose results +src/services\compact\compact.ts:1566: * haven't been retrieved yet. +src/services\compact\compact.ts:1602: * Scan messages for Read tool_use blocks and collect their file_path inputs +src/services\compact\compact.ts:1603: * (normalized via expandPath). Used to dedup post-compact file restoration +src/services\compact\compact.ts:1604: * against what's already visible in the preserved tail. +src/services\compact\compact.ts:1606: * Skips Reads whose tool_result is a dedup stub �the stub points at an +src/services\compact\compact.ts:1607: * earlier full Read that may have been compacted away, so we want +src/services\compact\compact.ts:1608: * createPostCompactFileAttachments to re-inject the real content. +src/services\compact\compact.ts:1661: * Truncate content to roughly maxTokens, keeping the head. roughTokenCountEstimation +src/services\compact\compact.ts:1662: * uses ~4 chars/token (its default bytesPerToken), so char budget = maxTokens * 4 +src/services\compact\compact.ts:1663: * minus the marker so the result stays within budget. Marker tells the model it +src/services\compact\compact.ts:1664: * can Read the full file if needed. +src/services\compact\compact.ts:1679: // Exclude plan files +src/services\compact\compact.ts:1686: // If we can't get plan file path, continue with other checks +src/services\compact\compact.ts:1689: // Exclude all types of claude.md files +src/services\compact\compact.ts:1690: // TODO: Refactor to use isMemoryFilePath() from claudemd.ts for consistency +src/services\compact\compact.ts:1691: // and to also match child directory memory files (.claude/rules/*.md, etc.) +src/services\compact\compact.ts:1701: // If we can't get memory paths, continue +src/types\plugin.ts:14: * Definition for a built-in plugin that ships with the CLI. +src/types\plugin.ts:15: * Built-in plugins appear in the /plugin UI and can be enabled/disabled by +src/types\plugin.ts:16: * users (persisted to user settings). +src/types\plugin.ts:19: /** Plugin name (used in `{name}@builtin` identifier) */ +src/types\plugin.ts:21: /** Description shown in the /plugin UI */ +src/types\plugin.ts:23: /** Optional version string */ +src/types\plugin.ts:25: /** Skills provided by this plugin */ +src/types\plugin.ts:27: /** Hooks provided by this plugin */ +src/types\plugin.ts:29: /** MCP servers provided by this plugin */ +src/types\plugin.ts:31: /** Whether this plugin is available (e.g. based on system capabilities). Unavailable plugins are hidden entirely. */ +src/types\plugin.ts:33: /** Default enabled state before the user sets a preference (defaults to true) */ +src/types\plugin.ts:80: * Discriminated union of plugin error types. +src/types\plugin.ts:81: * Each error type has specific contextual data for better debugging and user guidance. +src/types\plugin.ts:83: * This replaces the previous string-based error matching approach with type-safe +src/types\plugin.ts:84: * error handling that can't break when error messages change. +src/types\plugin.ts:86: * IMPLEMENTATION STATUS: +src/types\plugin.ts:87: * Currently used in production (2 types): +src/types\plugin.ts:88: * - generic-error: Used for various plugin loading failures +src/types\plugin.ts:89: * - plugin-not-found: Used when plugin not found in marketplace +src/types\plugin.ts:91: * Planned for future use (10 types - see TODOs in pluginLoader.ts): +src/types\plugin.ts:92: * - path-not-found, git-auth-failed, git-timeout, network-error +src/types\plugin.ts:93: * - manifest-parse-error, manifest-validation-error +src/types\plugin.ts:94: * - marketplace-not-found, marketplace-load-failed +src/types\plugin.ts:95: * - mcp-config-invalid, hook-load-failed, component-load-failed +src/types\plugin.ts:97: * These unused types support UI formatting and provide a clear roadmap for +src/types\plugin.ts:98: * improving error specificity. They can be incrementally implemented as +src/types\plugin.ts:99: * error creation sites are refactored. +src/types\plugin.ts:292: * Helper function to get a display message from any PluginError +src/types\plugin.ts:293: * Useful for logging and simple error displays +src/services\voiceKeyterms.ts:1:// Voice keyterms for improving STT accuracy in the voice_stream endpoint. +src/services\voiceKeyterms.ts:3:// Provides domain-specific vocabulary hints (Deepgram "keywords") so the STT +src/services\voiceKeyterms.ts:4:// engine correctly recognises coding terminology, project names, and branch +src/services\voiceKeyterms.ts:5:// names that would otherwise be misheard. +src/services\voiceKeyterms.ts:11:// ─── Global keyterms ──────────────────────────────────────────────── +src/services\voiceKeyterms.ts:14: // Terms Deepgram consistently mangles without keyword hints. +src/services\voiceKeyterms.ts:15: // Note: "Claude" and "Anthropic" are already server-side base keyterms. +src/services\voiceKeyterms.ts:16: // Avoid terms nobody speaks aloud as-spelled (stdout �"standard out"). +src/services\voiceKeyterms.ts:33:// ─── Helpers ──────────────────────────────────────────────────────── +src/services\voiceKeyterms.ts:36: * Split an identifier (camelCase, PascalCase, kebab-case, snake_case, or +src/services\voiceKeyterms.ts:37: * path segments) into individual words. Fragments of 2 chars or fewer are +src/services\voiceKeyterms.ts:38: * discarded to avoid noise. +src/services\voiceKeyterms.ts:53:// ─── Public API ───────────────────────────────────────────────────── +src/services\voiceKeyterms.ts:58: * Build a list of keyterms for the voice_stream STT endpoint. +src/services\voiceKeyterms.ts:60: * Combines hardcoded global coding terms with session context (project name, +src/services\voiceKeyterms.ts:61: * git branch, recent files) without any model calls. +src/services\voiceKeyterms.ts:68: // Project root basename as a single term �users say "claude CLI internal" +src/services\voiceKeyterms.ts:69: // as a phrase, not isolated words. Keeping the whole basename lets the +src/services\voiceKeyterms.ts:70: // STT's keyterm boosting match the phrase regardless of separator. +src/services\voiceKeyterms.ts:80: // getProjectRoot() may throw if not initialised yet �ignore +src/services\voiceKeyterms.ts:83: // Git branch words (e.g. "feat/voice-keyterms" �"feat", "voice", "keyterms") +src/services\voiceKeyterms.ts:92: // getBranch() may fail if not in a git repo �ignore +src/services\voiceKeyterms.ts:95: // Recent file names �only scan enough to fill remaining slots +src/constants\turnCompletionVerbs.ts:1:// Past tense verbs for turn completion messages +src/constants\turnCompletionVerbs.ts:2:// These verbs work naturally with "for [duration]" (e.g., "Worked for 5s") +src/utils\zodToJsonSchema.ts:2: * Converts Zod v4 schemas to JSON Schema using native toJSONSchema. +src/utils\zodToJsonSchema.ts:9:// toolToAPISchema() runs this for every tool on every API request (~60-250 +src/utils\zodToJsonSchema.ts:10:// times/turn). Tool schemas are wrapped with lazySchema() which guarantees the +src/utils\zodToJsonSchema.ts:11:// same ZodTypeAny reference per session, so we can cache by identity. +src/utils\zodToJsonSchema.ts:15: * Converts a Zod v4 schema to JSON Schema format. +src/services\api\usage.ts:38: // Skip API call if OAuth token is expired to avoid 401 errors +src/types\ids.ts:2: * Branded types for session and agent IDs. +src/types\ids.ts:3: * These prevent accidentally mixing up session IDs and agent IDs at compile time. +src/types\ids.ts:7: * A session ID uniquely identifies a Claude Code session. +src/types\ids.ts:8: * Returned by getSessionId(). +src/types\ids.ts:13: * An agent ID uniquely identifies a subagent within a session. +src/types\ids.ts:14: * Returned by createAgentId(). +src/types\ids.ts:15: * When present, indicates the context is a subagent (not the main session). +src/types\ids.ts:20: * Cast a raw string to SessionId. +src/types\ids.ts:21: * Use sparingly - prefer getSessionId() when possible. +src/types\ids.ts:28: * Cast a raw string to AgentId. +src/types\ids.ts:29: * Use sparingly - prefer createAgentId() when possible. +src/types\ids.ts:38: * Validate and brand a string as AgentId. +src/types\ids.ts:39: * Matches the format produced by createAgentId(): `a` + optional `