caches.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. /**
  2. * Session cache clearing utilities.
  3. * This module is imported at startup by main.tsx, so keep imports minimal.
  4. */
  5. import { feature } from 'bun:bundle'
  6. import {
  7. clearInvokedSkills,
  8. setLastEmittedDate,
  9. } from '../../bootstrap/state.js'
  10. import { clearCommandsCache } from '../../commands.js'
  11. import { getSessionStartDate } from '../../constants/common.js'
  12. import {
  13. getGitStatus,
  14. getSystemContext,
  15. getUserContext,
  16. setSystemPromptInjection,
  17. } from '../../context.js'
  18. import { clearFileSuggestionCaches } from '../../hooks/fileSuggestions.js'
  19. import { clearAllPendingCallbacks } from '../../hooks/useSwarmPermissionPoller.js'
  20. import { clearAllDumpState } from '../../services/api/dumpPrompts.js'
  21. import { resetPromptCacheBreakDetection } from '../../services/api/promptCacheBreakDetection.js'
  22. import { clearAllSessions } from '../../services/api/sessionIngress.js'
  23. import { runPostCompactCleanup } from '../../services/compact/postCompactCleanup.js'
  24. import { resetAllLSPDiagnosticState } from '../../services/lsp/LSPDiagnosticRegistry.js'
  25. import { clearTrackedMagicDocs } from '../../services/MagicDocs/magicDocs.js'
  26. import { clearDynamicSkills } from '../../skills/loadSkillsDir.js'
  27. import { resetSentSkillNames } from '../../utils/attachments.js'
  28. import { clearCommandPrefixCaches } from '../../utils/bash/commands.js'
  29. import { resetGetMemoryFilesCache } from '../../utils/claudemd.js'
  30. import { clearRepositoryCaches } from '../../utils/detectRepository.js'
  31. import { clearResolveGitDirCache } from '../../utils/git/gitFilesystem.js'
  32. import { clearStoredImagePaths } from '../../utils/imageStore.js'
  33. import { clearSessionEnvVars } from '../../utils/sessionEnvVars.js'
  34. /**
  35. * Clear all session-related caches.
  36. * Call this when resuming a session to ensure fresh file/skill discovery.
  37. * This is a subset of what clearConversation does - it only clears caches
  38. * without affecting messages, session ID, or triggering hooks.
  39. *
  40. * @param preservedAgentIds - Agent IDs whose per-agent state should survive
  41. * the clear (e.g., background tasks preserved across /clear). When non-empty,
  42. * agentId-keyed state (invoked skills) is selectively cleared and requestId-keyed
  43. * state (pending permission callbacks, dump state, cache-break tracking) is left
  44. * intact since it cannot be safely scoped to the main session.
  45. */
  46. export function clearSessionCaches(
  47. preservedAgentIds: ReadonlySet<string> = new Set(),
  48. ): void {
  49. const hasPreserved = preservedAgentIds.size > 0
  50. // Clear context caches
  51. getUserContext.cache.clear?.()
  52. getSystemContext.cache.clear?.()
  53. getGitStatus.cache.clear?.()
  54. getSessionStartDate.cache.clear?.()
  55. // Clear file suggestion caches (for @ mentions)
  56. clearFileSuggestionCaches()
  57. // Clear commands/skills cache
  58. clearCommandsCache()
  59. // Clear prompt cache break detection state
  60. if (!hasPreserved) resetPromptCacheBreakDetection()
  61. // Clear system prompt injection (cache breaker)
  62. setSystemPromptInjection(null)
  63. // Clear last emitted date so it's re-detected on next turn
  64. setLastEmittedDate(null)
  65. // Run post-compaction cleanup (clears system prompt sections, microcompact tracking,
  66. // classifier approvals, speculative checks, and — for main-thread compacts — memory
  67. // files cache with load_reason 'compact').
  68. runPostCompactCleanup()
  69. // Reset sent skill names so the skill listing is re-sent after /clear.
  70. // runPostCompactCleanup intentionally does NOT reset this (post-compact
  71. // re-injection costs ~4K tokens), but /clear wipes messages entirely so
  72. // the model needs the full listing again.
  73. resetSentSkillNames()
  74. // Override the memory cache reset with 'session_start': clearSessionCaches is called
  75. // from /clear and --resume/--continue, which are NOT compaction events. Without this,
  76. // the InstructionsLoaded hook would fire with load_reason 'compact' instead of
  77. // 'session_start' on the next getMemoryFiles() call.
  78. resetGetMemoryFilesCache('session_start')
  79. // Clear stored image paths cache
  80. clearStoredImagePaths()
  81. // Clear all session ingress caches (lastUuidMap, sequentialAppendBySession)
  82. clearAllSessions()
  83. // Clear swarm permission pending callbacks
  84. if (!hasPreserved) clearAllPendingCallbacks()
  85. // Clear tungsten session usage tracking
  86. if (process.env.USER_TYPE === 'ant') {
  87. void import('../../tools/TungstenTool/TungstenTool.js').then(
  88. ({ clearSessionsWithTungstenUsage, resetInitializationState }) => {
  89. clearSessionsWithTungstenUsage()
  90. resetInitializationState()
  91. },
  92. )
  93. }
  94. // Clear attribution caches (file content cache, pending bash states)
  95. // Dynamic import to preserve dead code elimination for COMMIT_ATTRIBUTION feature flag
  96. if (feature('COMMIT_ATTRIBUTION')) {
  97. void import('../../utils/attributionHooks.js').then(
  98. ({ clearAttributionCaches }) => clearAttributionCaches(),
  99. )
  100. }
  101. // Clear repository detection caches
  102. clearRepositoryCaches()
  103. // Clear bash command prefix caches (Haiku-extracted prefixes)
  104. clearCommandPrefixCaches()
  105. // Clear dump prompts state
  106. if (!hasPreserved) clearAllDumpState()
  107. // Clear invoked skills cache (each entry holds full skill file content)
  108. clearInvokedSkills(preservedAgentIds)
  109. // Clear git dir resolution cache
  110. clearResolveGitDirCache()
  111. // Clear dynamic skills (loaded from skill directories)
  112. clearDynamicSkills()
  113. // Clear LSP diagnostic tracking state
  114. resetAllLSPDiagnosticState()
  115. // Clear tracked magic docs
  116. clearTrackedMagicDocs()
  117. // Clear session environment variables
  118. clearSessionEnvVars()
  119. // Clear WebFetch URL cache (up to 50MB of cached page content)
  120. void import('../../tools/WebFetchTool/utils.js').then(
  121. ({ clearWebFetchCache }) => clearWebFetchCache(),
  122. )
  123. // Clear ToolSearch description cache (full tool prompts, ~500KB for 50 MCP tools)
  124. void import('../../tools/ToolSearchTool/ToolSearchTool.js').then(
  125. ({ clearToolSearchDescriptionCache }) => clearToolSearchDescriptionCache(),
  126. )
  127. // Clear agent definitions cache (accumulates per-cwd via EnterWorktreeTool)
  128. void import('../../tools/AgentTool/loadAgentsDir.js').then(
  129. ({ clearAgentDefinitionsCache }) => clearAgentDefinitionsCache(),
  130. )
  131. // Clear SkillTool prompt cache (accumulates per project root)
  132. void import('../../tools/SkillTool/prompt.js').then(({ clearPromptCache }) =>
  133. clearPromptCache(),
  134. )
  135. }