thaddeus 1.0.26 → 1.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2082) hide show
  1. package/package.json +14 -5
  2. package/src/QueryEngine.js +926 -0
  3. package/src/Task.js +49 -0
  4. package/src/Tool.js +61 -0
  5. package/src/assistant/gate.js +5 -0
  6. package/src/assistant/index.js +106 -0
  7. package/src/assistant/sessionHistory.js +145 -0
  8. package/src/bootstrap/state.js +1163 -0
  9. package/src/bridge/bridgeApi.js +304 -0
  10. package/src/bridge/bridgeConfig.js +39 -0
  11. package/src/bridge/bridgeDebug.js +73 -0
  12. package/src/bridge/bridgeEnabled.js +185 -0
  13. package/src/bridge/bridgeMain.js +2289 -0
  14. package/src/bridge/bridgeMessaging.js +353 -0
  15. package/src/bridge/bridgePermissionCallbacks.js +10 -0
  16. package/src/bridge/bridgePointer.js +175 -0
  17. package/src/bridge/bridgeStatusUtil.js +105 -0
  18. package/src/bridge/bridgeUI.js +411 -0
  19. package/src/bridge/capacityWake.js +35 -0
  20. package/src/bridge/codeSessionApi.js +111 -0
  21. package/src/bridge/createSession.js +273 -0
  22. package/src/bridge/debugUtils.js +115 -0
  23. package/src/bridge/envLessBridgeConfig.js +120 -0
  24. package/src/bridge/flushGate.js +65 -0
  25. package/src/bridge/inboundAttachments.js +152 -0
  26. package/src/bridge/inboundMessages.js +63 -0
  27. package/src/bridge/initReplBridge.js +431 -0
  28. package/src/bridge/jwtUtils.js +185 -0
  29. package/src/bridge/peerSessions.js +5 -0
  30. package/src/bridge/pollConfig.js +85 -0
  31. package/src/bridge/pollConfigDefaults.js +62 -0
  32. package/src/bridge/remoteBridgeCore.js +712 -0
  33. package/src/bridge/replBridge.js +1719 -0
  34. package/src/bridge/replBridgeHandle.js +30 -0
  35. package/src/bridge/replBridgeTransport.js +236 -0
  36. package/src/bridge/sessionIdCompat.js +56 -0
  37. package/src/bridge/sessionRunner.js +421 -0
  38. package/src/bridge/trustedDevice.js +170 -0
  39. package/src/bridge/types.js +9 -0
  40. package/src/bridge/webhookSanitizer.js +6 -0
  41. package/src/bridge/workSecret.js +99 -0
  42. package/src/buddy/CompanionSprite.js +348 -0
  43. package/src/buddy/companion.js +107 -0
  44. package/src/buddy/prompt.js +33 -0
  45. package/src/buddy/sprites.js +488 -0
  46. package/src/buddy/types.js +90 -0
  47. package/src/buddy/useBuddyNotification.js +85 -0
  48. package/src/cli/bg.js +17 -0
  49. package/src/cli/exit.js +30 -0
  50. package/src/cli/handlers/agents.js +55 -0
  51. package/src/cli/handlers/auth.js +249 -0
  52. package/src/cli/handlers/autoMode.js +128 -0
  53. package/src/cli/handlers/mcp.js +335 -0
  54. package/src/cli/handlers/plugins.js +634 -0
  55. package/src/cli/handlers/templateJobs.js +19 -0
  56. package/src/cli/handlers/util.js +76 -0
  57. package/src/cli/ndjsonSafeStringify.js +27 -0
  58. package/src/cli/print.js +4294 -0
  59. package/src/cli/remoteIO.js +208 -0
  60. package/src/cli/structuredIO.js +644 -0
  61. package/src/cli/transports/HybridTransport.js +233 -0
  62. package/src/cli/transports/SSETransport.js +538 -0
  63. package/src/cli/transports/SerialBatchEventUploader.js +224 -0
  64. package/src/cli/transports/WebSocketTransport.js +613 -0
  65. package/src/cli/transports/WorkerStateUploader.js +88 -0
  66. package/src/cli/transports/ccrClient.js +711 -0
  67. package/src/cli/transports/transportUtils.js +39 -0
  68. package/src/cli/update.js +314 -0
  69. package/src/commandCenter/launch.js +39 -0
  70. package/src/commandCenter/phoneApi.js +168 -0
  71. package/src/commandCenter/phoneStore.js +159 -0
  72. package/src/commandCenter/reactorBus.js +130 -0
  73. package/src/commandCenter/server.js +288 -0
  74. package/src/commandCenter/server.ts +42 -7
  75. package/src/commandCenter/tunnel.js +199 -0
  76. package/src/commands/add-dir/add-dir.js +121 -0
  77. package/src/commands/add-dir/index.js +8 -0
  78. package/src/commands/add-dir/validation.js +76 -0
  79. package/src/commands/advisor.js +88 -0
  80. package/src/commands/agents/agents.js +10 -0
  81. package/src/commands/agents/index.js +7 -0
  82. package/src/commands/agents-platform/index.js +2 -0
  83. package/src/commands/assistant/index.js +86 -0
  84. package/src/commands/backup/index.js +31 -0
  85. package/src/commands/branch/branch.js +205 -0
  86. package/src/commands/branch/index.js +11 -0
  87. package/src/commands/bridge/bridge.js +513 -0
  88. package/src/commands/bridge/index.js +22 -0
  89. package/src/commands/bridge-kick.js +179 -0
  90. package/src/commands/brief.js +89 -0
  91. package/src/commands/btw/btw.js +235 -0
  92. package/src/commands/btw/index.js +9 -0
  93. package/src/commands/buddy/buddy.js +100 -0
  94. package/src/commands/buddy/index.js +11 -0
  95. package/src/commands/chrome/chrome.js +291 -0
  96. package/src/commands/chrome/index.js +10 -0
  97. package/src/commands/clear/caches.js +116 -0
  98. package/src/commands/clear/clear.js +5 -0
  99. package/src/commands/clear/conversation.js +189 -0
  100. package/src/commands/clear/index.js +9 -0
  101. package/src/commands/color/color.js +58 -0
  102. package/src/commands/color/index.js +9 -0
  103. package/src/commands/commit-push-pr.js +137 -0
  104. package/src/commands/commit.js +80 -0
  105. package/src/commands/compact/compact.js +194 -0
  106. package/src/commands/compact/index.js +11 -0
  107. package/src/commands/config/config.js +6 -0
  108. package/src/commands/config/index.js +8 -0
  109. package/src/commands/context/context-noninteractive.js +219 -0
  110. package/src/commands/context/context.js +45 -0
  111. package/src/commands/context/index.js +21 -0
  112. package/src/commands/coordinator.js +34 -0
  113. package/src/commands/copy/copy.js +366 -0
  114. package/src/commands/copy/index.js +7 -0
  115. package/src/commands/cost/cost.js +21 -0
  116. package/src/commands/cost/index.js +16 -0
  117. package/src/commands/createMovedToPluginCommand.js +33 -0
  118. package/src/commands/desktop/desktop.js +6 -0
  119. package/src/commands/desktop/index.js +22 -0
  120. package/src/commands/diff/diff.js +6 -0
  121. package/src/commands/diff/index.js +6 -0
  122. package/src/commands/doctor/doctor.js +6 -0
  123. package/src/commands/doctor/index.js +9 -0
  124. package/src/commands/effort/effort.js +166 -0
  125. package/src/commands/effort/index.js +11 -0
  126. package/src/commands/exit/exit.js +32 -0
  127. package/src/commands/exit/index.js +9 -0
  128. package/src/commands/export/export.js +87 -0
  129. package/src/commands/export/index.js +8 -0
  130. package/src/commands/extra-usage/extra-usage-core.js +99 -0
  131. package/src/commands/extra-usage/extra-usage-noninteractive.js +13 -0
  132. package/src/commands/extra-usage/extra-usage.js +15 -0
  133. package/src/commands/extra-usage/index.js +29 -0
  134. package/src/commands/fast/fast.js +276 -0
  135. package/src/commands/fast/index.js +19 -0
  136. package/src/commands/feedback/feedback.js +11 -0
  137. package/src/commands/feedback/index.js +20 -0
  138. package/src/commands/files/files.js +11 -0
  139. package/src/commands/files/index.js +9 -0
  140. package/src/commands/force-snip.js +19 -0
  141. package/src/commands/fork/index.js +67 -0
  142. package/src/commands/heapdump/heapdump.js +14 -0
  143. package/src/commands/heapdump/index.js +9 -0
  144. package/src/commands/help/help.js +6 -0
  145. package/src/commands/help/index.js +7 -0
  146. package/src/commands/hooks/hooks.js +12 -0
  147. package/src/commands/hooks/index.js +8 -0
  148. package/src/commands/ide/ide.js +615 -0
  149. package/src/commands/ide/index.js +8 -0
  150. package/src/commands/init-verifiers.js +258 -0
  151. package/src/commands/init.js +248 -0
  152. package/src/commands/insights.js +2554 -0
  153. package/src/commands/install-github-app/ApiKeyStep.js +230 -0
  154. package/src/commands/install-github-app/CheckExistingSecretStep.js +194 -0
  155. package/src/commands/install-github-app/CheckGitHubStep.js +16 -0
  156. package/src/commands/install-github-app/ChooseRepoStep.js +211 -0
  157. package/src/commands/install-github-app/CreatingStep.js +53 -0
  158. package/src/commands/install-github-app/ErrorStep.js +84 -0
  159. package/src/commands/install-github-app/ExistingWorkflowStep.js +105 -0
  160. package/src/commands/install-github-app/InstallAppStep.js +97 -0
  161. package/src/commands/install-github-app/OAuthFlowStep.js +190 -0
  162. package/src/commands/install-github-app/SuccessStep.js +94 -0
  163. package/src/commands/install-github-app/WarningsStep.js +71 -0
  164. package/src/commands/install-github-app/index.js +10 -0
  165. package/src/commands/install-github-app/install-github-app.js +593 -0
  166. package/src/commands/install-github-app/setupGitHubActions.js +227 -0
  167. package/src/commands/install-slack-app/index.js +9 -0
  168. package/src/commands/install-slack-app/install-slack-app.js +25 -0
  169. package/src/commands/install.js +198 -0
  170. package/src/commands/keybindings/index.js +10 -0
  171. package/src/commands/keybindings/keybindings.js +47 -0
  172. package/src/commands/login/index.js +21 -0
  173. package/src/commands/login/login.js +135 -0
  174. package/src/commands/logout/index.js +11 -0
  175. package/src/commands/logout/logout.js +75 -0
  176. package/src/commands/mcp/addCommand.js +183 -0
  177. package/src/commands/mcp/index.js +9 -0
  178. package/src/commands/mcp/mcp.js +78 -0
  179. package/src/commands/mcp/xaaIdpCommand.js +193 -0
  180. package/src/commands/memories/index.js +9 -0
  181. package/src/commands/memories/index.ts +12 -0
  182. package/src/commands/memories/memories.tsx +949 -0
  183. package/src/commands/memory/index.js +7 -0
  184. package/src/commands/memory/memory.js +71 -0
  185. package/src/commands/mobile/index.js +9 -0
  186. package/src/commands/mobile/mobile.js +279 -0
  187. package/src/commands/model/index.js +14 -0
  188. package/src/commands/model/model.js +284 -0
  189. package/src/commands/output-style/index.js +8 -0
  190. package/src/commands/output-style/output-style.js +6 -0
  191. package/src/commands/passes/index.js +17 -0
  192. package/src/commands/passes/passes.js +23 -0
  193. package/src/commands/peers/index.js +68 -0
  194. package/src/commands/permissions/index.js +8 -0
  195. package/src/commands/permissions/permissions.js +9 -0
  196. package/src/commands/plan/index.js +8 -0
  197. package/src/commands/plan/plan.js +116 -0
  198. package/src/commands/plugin/AddMarketplace.js +96 -0
  199. package/src/commands/plugin/BrowseMarketplace.js +582 -0
  200. package/src/commands/plugin/DiscoverPlugins.js +613 -0
  201. package/src/commands/plugin/ManageMarketplaces.js +583 -0
  202. package/src/commands/plugin/ManagePlugins.js +1783 -0
  203. package/src/commands/plugin/PluginErrors.js +124 -0
  204. package/src/commands/plugin/PluginOptionsDialog.js +367 -0
  205. package/src/commands/plugin/PluginOptionsFlow.js +97 -0
  206. package/src/commands/plugin/PluginSettings.js +1041 -0
  207. package/src/commands/plugin/PluginTrustWarning.js +35 -0
  208. package/src/commands/plugin/UnifiedInstalledCell.js +616 -0
  209. package/src/commands/plugin/ValidatePlugin.js +96 -0
  210. package/src/commands/plugin/index.js +10 -0
  211. package/src/commands/plugin/parseArgs.js +71 -0
  212. package/src/commands/plugin/plugin.js +6 -0
  213. package/src/commands/plugin/pluginDetailsHelpers.js +95 -0
  214. package/src/commands/plugin/usePagination.js +89 -0
  215. package/src/commands/pr_comments/index.js +49 -0
  216. package/src/commands/privacy-settings/index.js +11 -0
  217. package/src/commands/privacy-settings/privacy-settings.js +55 -0
  218. package/src/commands/proactive.js +29 -0
  219. package/src/commands/rate-limit-options/index.js +15 -0
  220. package/src/commands/rate-limit-options/rate-limit-options.js +213 -0
  221. package/src/commands/release-notes/index.js +8 -0
  222. package/src/commands/release-notes/release-notes.js +38 -0
  223. package/src/commands/reload-plugins/index.js +11 -0
  224. package/src/commands/reload-plugins/reload-plugins.js +52 -0
  225. package/src/commands/remote-env/index.js +12 -0
  226. package/src/commands/remote-env/remote-env.js +6 -0
  227. package/src/commands/remote-setup/api.js +155 -0
  228. package/src/commands/remote-setup/index.js +15 -0
  229. package/src/commands/remote-setup/remote-setup.js +150 -0
  230. package/src/commands/remoteControlServer/index.js +58 -0
  231. package/src/commands/rename/generateSessionName.js +58 -0
  232. package/src/commands/rename/index.js +9 -0
  233. package/src/commands/rename/rename.js +52 -0
  234. package/src/commands/resume/index.js +9 -0
  235. package/src/commands/resume/resume.js +239 -0
  236. package/src/commands/review/UltrareviewOverageDialog.js +97 -0
  237. package/src/commands/review/reviewRemote.js +259 -0
  238. package/src/commands/review/ultrareviewCommand.js +58 -0
  239. package/src/commands/review/ultrareviewEnabled.js +10 -0
  240. package/src/commands/review.js +53 -0
  241. package/src/commands/rewind/index.js +10 -0
  242. package/src/commands/rewind/rewind.js +7 -0
  243. package/src/commands/sandbox-toggle/index.js +41 -0
  244. package/src/commands/sandbox-toggle/sandbox-toggle.js +73 -0
  245. package/src/commands/security-review.js +231 -0
  246. package/src/commands/session/index.js +13 -0
  247. package/src/commands/session/session.js +143 -0
  248. package/src/commands/skills/index.js +7 -0
  249. package/src/commands/skills/skills.js +6 -0
  250. package/src/commands/speak.js +21 -0
  251. package/src/commands/start-business.js +1575 -0
  252. package/src/commands/start-business.ts +1581 -0
  253. package/src/commands/stats/index.js +7 -0
  254. package/src/commands/stats/stats.js +6 -0
  255. package/src/commands/status/index.js +8 -0
  256. package/src/commands/status/status.js +6 -0
  257. package/src/commands/statusline.js +22 -0
  258. package/src/commands/stickers/index.js +8 -0
  259. package/src/commands/stickers/stickers.js +14 -0
  260. package/src/commands/subscribe-pr.js +131 -0
  261. package/src/commands/tag/index.js +9 -0
  262. package/src/commands/tag/tag.js +215 -0
  263. package/src/commands/tasks/index.js +8 -0
  264. package/src/commands/tasks/tasks.js +6 -0
  265. package/src/commands/terminalSetup/index.js +18 -0
  266. package/src/commands/terminalSetup/terminalSetup.js +491 -0
  267. package/src/commands/thaddeus-usage/index.js +17 -0
  268. package/src/commands/theme/index.js +7 -0
  269. package/src/commands/theme/theme.js +51 -0
  270. package/src/commands/thinkback/index.js +9 -0
  271. package/src/commands/thinkback/thinkback.js +528 -0
  272. package/src/commands/thinkback-play/index.js +13 -0
  273. package/src/commands/thinkback-play/thinkback-play.js +34 -0
  274. package/src/commands/torch.js +122 -0
  275. package/src/commands/ultraplan.js +416 -0
  276. package/src/commands/upgrade/index.js +12 -0
  277. package/src/commands/upgrade/upgrade.js +38 -0
  278. package/src/commands/usage/index.js +7 -0
  279. package/src/commands/usage/usage.js +6 -0
  280. package/src/commands/version.js +17 -0
  281. package/src/commands/vim/index.js +8 -0
  282. package/src/commands/vim/vim.js +25 -0
  283. package/src/commands/voice/index.js +13 -0
  284. package/src/commands/voice/voice.js +44 -0
  285. package/src/commands/workflows/index.js +123 -0
  286. package/src/commands.js +614 -0
  287. package/src/commands.ts +4 -0
  288. package/src/components/AgentProgressLine.js +112 -0
  289. package/src/components/AntModelSwitchCallout.js +8 -0
  290. package/src/components/App.js +46 -0
  291. package/src/components/ApproveApiKey.js +125 -0
  292. package/src/components/AutoModeOptInDialog.js +140 -0
  293. package/src/components/AutoUpdater.js +156 -0
  294. package/src/components/AutoUpdaterWrapper.js +78 -0
  295. package/src/components/AwsAuthStatusBox.js +88 -0
  296. package/src/components/BaseTextInput.js +105 -0
  297. package/src/components/BashModeProgress.js +49 -0
  298. package/src/components/BridgeDialog.js +415 -0
  299. package/src/components/BypassPermissionsModeDialog.js +87 -0
  300. package/src/components/ChannelDowngradeDialog.js +101 -0
  301. package/src/components/ClaudeInChromeOnboarding.js +126 -0
  302. package/src/components/ClaudeMdExternalIncludesDialog.js +137 -0
  303. package/src/components/ClickableImageRef.js +65 -0
  304. package/src/components/CompactSummary.js +120 -0
  305. package/src/components/ConfigurableShortcutHint.js +35 -0
  306. package/src/components/ConsoleOAuthFlow.js +554 -0
  307. package/src/components/ContextSuggestions.js +44 -0
  308. package/src/components/ContextVisualization.js +482 -0
  309. package/src/components/CoordinatorAgentStatus.js +261 -0
  310. package/src/components/CostThresholdDialog.js +49 -0
  311. package/src/components/CtrlOToExpand.js +50 -0
  312. package/src/components/CustomSelect/SelectMulti.js +150 -0
  313. package/src/components/CustomSelect/index.js +2 -0
  314. package/src/components/CustomSelect/option-map.js +32 -0
  315. package/src/components/CustomSelect/select-input-option.js +426 -0
  316. package/src/components/CustomSelect/select-option.js +24 -0
  317. package/src/components/CustomSelect/select.js +518 -0
  318. package/src/components/CustomSelect/use-multi-select-state.js +214 -0
  319. package/src/components/CustomSelect/use-select-input.js +170 -0
  320. package/src/components/CustomSelect/use-select-navigation.js +366 -0
  321. package/src/components/CustomSelect/use-select-state.js +22 -0
  322. package/src/components/DesktopHandoff.js +195 -0
  323. package/src/components/DesktopUpsell/DesktopUpsellStartup.js +174 -0
  324. package/src/components/DevBar.js +51 -0
  325. package/src/components/DevChannelsDialog.js +104 -0
  326. package/src/components/DiagnosticsDisplay.js +91 -0
  327. package/src/components/EffortCallout.js +264 -0
  328. package/src/components/EffortIndicator.js +28 -0
  329. package/src/components/ExitFlow.js +41 -0
  330. package/src/components/ExportDialog.js +101 -0
  331. package/src/components/FallbackToolUseErrorMessage.js +116 -0
  332. package/src/components/FallbackToolUseRejectedMessage.js +17 -0
  333. package/src/components/FastIcon.js +43 -0
  334. package/src/components/Feedback.js +369 -0
  335. package/src/components/FeedbackSurvey/FeedbackSurvey.js +151 -0
  336. package/src/components/FeedbackSurvey/FeedbackSurveyView.js +104 -0
  337. package/src/components/FeedbackSurvey/TranscriptSharePrompt.js +84 -0
  338. package/src/components/FeedbackSurvey/submitTranscriptShare.js +10 -0
  339. package/src/components/FeedbackSurvey/useDebouncedDigitInput.js +51 -0
  340. package/src/components/FeedbackSurvey/useFeedbackSurvey.js +258 -0
  341. package/src/components/FeedbackSurvey/useFrustrationDetection.js +8 -0
  342. package/src/components/FeedbackSurvey/useMemorySurvey.js +191 -0
  343. package/src/components/FeedbackSurvey/usePostCompactSurvey.js +202 -0
  344. package/src/components/FeedbackSurvey/useSurveyState.js +80 -0
  345. package/src/components/FileEditToolDiff.js +167 -0
  346. package/src/components/FileEditToolUpdatedMessage.js +112 -0
  347. package/src/components/FileEditToolUseRejectedMessage.js +158 -0
  348. package/src/components/FilePathLink.js +35 -0
  349. package/src/components/FullscreenLayout.js +578 -0
  350. package/src/components/GlobalSearchDialog.js +340 -0
  351. package/src/components/HelpV2/Commands.js +66 -0
  352. package/src/components/HelpV2/General.js +25 -0
  353. package/src/components/HelpV2/HelpV2.js +186 -0
  354. package/src/components/HighlightedCode/Fallback.js +193 -0
  355. package/src/components/HighlightedCode.js +185 -0
  356. package/src/components/HistorySearchDialog.js +93 -0
  357. package/src/components/IdeAutoConnectDialog.js +154 -0
  358. package/src/components/IdeOnboardingDialog.js +175 -0
  359. package/src/components/IdeStatusIndicator.js +50 -0
  360. package/src/components/IdleReturnDialog.js +117 -0
  361. package/src/components/InterruptedByUser.js +16 -0
  362. package/src/components/InvalidConfigDialog.js +135 -0
  363. package/src/components/InvalidSettingsDialog.js +85 -0
  364. package/src/components/KeybindingWarnings.js +55 -0
  365. package/src/components/LanguagePicker.js +84 -0
  366. package/src/components/LogSelector.js +1579 -0
  367. package/src/components/LogoV2/AnimatedAsterisk.js +43 -0
  368. package/src/components/LogoV2/AnimatedClawd.js +64 -0
  369. package/src/components/LogoV2/ChannelsNotice.js +262 -0
  370. package/src/components/LogoV2/Clawd.js +33 -0
  371. package/src/components/LogoV2/CondensedLogo.js +160 -0
  372. package/src/components/LogoV2/EmergencyTip.js +48 -0
  373. package/src/components/LogoV2/Feed.js +85 -0
  374. package/src/components/LogoV2/FeedColumn.js +55 -0
  375. package/src/components/LogoV2/GuestPassesUpsell.js +71 -0
  376. package/src/components/LogoV2/LogoV2.js +565 -0
  377. package/src/components/LogoV2/Opus1mMergeNotice.js +57 -0
  378. package/src/components/LogoV2/OverageCreditUpsell.js +161 -0
  379. package/src/components/LogoV2/VoiceModeNotice.js +71 -0
  380. package/src/components/LogoV2/WelcomeV2.js +14 -0
  381. package/src/components/LogoV2/feedConfigs.js +79 -0
  382. package/src/components/LspRecommendation/LspRecommendationMenu.js +46 -0
  383. package/src/components/MCPServerApprovalDialog.js +114 -0
  384. package/src/components/MCPServerDesktopImportDialog.js +206 -0
  385. package/src/components/MCPServerDialogCopy.js +16 -0
  386. package/src/components/MCPServerMultiselectDialog.js +134 -0
  387. package/src/components/ManagedSettingsSecurityDialog/ManagedSettingsSecurityDialog.js +150 -0
  388. package/src/components/ManagedSettingsSecurityDialog/utils.js +105 -0
  389. package/src/components/Markdown.js +233 -0
  390. package/src/components/MarkdownTable.js +280 -0
  391. package/src/components/MemoryUsageIndicator.js +28 -0
  392. package/src/components/Message.js +564 -0
  393. package/src/components/MessageModel.js +37 -0
  394. package/src/components/MessageResponse.js +73 -0
  395. package/src/components/MessageRow.js +346 -0
  396. package/src/components/MessageSelector.js +744 -0
  397. package/src/components/MessageTimestamp.js +58 -0
  398. package/src/components/Messages.js +645 -0
  399. package/src/components/ModelPicker.js +452 -0
  400. package/src/components/NativeAutoUpdater.js +152 -0
  401. package/src/components/NotebookEditToolUseRejectedMessage.js +84 -0
  402. package/src/components/OffscreenFreeze.js +35 -0
  403. package/src/components/Onboarding.js +174 -0
  404. package/src/components/OutputStylePicker.js +103 -0
  405. package/src/components/PackageManagerAutoUpdater.js +99 -0
  406. package/src/components/Passes/Passes.js +114 -0
  407. package/src/components/PrBadge.js +91 -0
  408. package/src/components/PressEnterToContinue.js +16 -0
  409. package/src/components/PromptInput/HistorySearchInput.js +45 -0
  410. package/src/components/PromptInput/IssueFlagBanner.js +8 -0
  411. package/src/components/PromptInput/Notifications.js +220 -0
  412. package/src/components/PromptInput/PromptInput.js +2014 -0
  413. package/src/components/PromptInput/PromptInputFooter.js +85 -0
  414. package/src/components/PromptInput/PromptInputFooterLeftSide.js +408 -0
  415. package/src/components/PromptInput/PromptInputFooterSuggestions.js +281 -0
  416. package/src/components/PromptInput/PromptInputHelpMenu.js +380 -0
  417. package/src/components/PromptInput/PromptInputModeIndicator.js +73 -0
  418. package/src/components/PromptInput/PromptInputQueuedCommands.js +105 -0
  419. package/src/components/PromptInput/PromptInputStashNotice.js +21 -0
  420. package/src/components/PromptInput/SandboxPromptFooterHint.js +66 -0
  421. package/src/components/PromptInput/ShimmeredInput.js +133 -0
  422. package/src/components/PromptInput/VoiceIndicator.js +137 -0
  423. package/src/components/PromptInput/inputModes.js +24 -0
  424. package/src/components/PromptInput/inputPaste.js +62 -0
  425. package/src/components/PromptInput/useMaybeTruncateInput.js +33 -0
  426. package/src/components/PromptInput/usePromptInputPlaceholder.js +53 -0
  427. package/src/components/PromptInput/useShowFastIconHint.js +23 -0
  428. package/src/components/PromptInput/useSwarmBanner.js +112 -0
  429. package/src/components/PromptInput/utils.js +50 -0
  430. package/src/components/QuickOpenDialog.js +244 -0
  431. package/src/components/RemoteCallout.js +53 -0
  432. package/src/components/RemoteEnvironmentDialog.js +346 -0
  433. package/src/components/ResumeTask.js +173 -0
  434. package/src/components/SandboxViolationExpandedView.js +106 -0
  435. package/src/components/ScrollKeybindingHandler.js +982 -0
  436. package/src/components/SearchBox.js +56 -0
  437. package/src/components/SentryErrorBoundary.js +16 -0
  438. package/src/components/SessionBackgroundHint.js +105 -0
  439. package/src/components/SessionPreview.js +200 -0
  440. package/src/components/Settings/Config.js +1626 -0
  441. package/src/components/Settings/Settings.js +131 -0
  442. package/src/components/Settings/Status.js +230 -0
  443. package/src/components/Settings/Usage.js +341 -0
  444. package/src/components/ShowInIDEPrompt.js +152 -0
  445. package/src/components/SkillImprovementSurvey.js +130 -0
  446. package/src/components/Spinner/FlashingChar.js +52 -0
  447. package/src/components/Spinner/GlimmerMessage.js +329 -0
  448. package/src/components/Spinner/ShimmerChar.js +23 -0
  449. package/src/components/Spinner/SpinnerAnimationRow.js +170 -0
  450. package/src/components/Spinner/SpinnerGlyph.js +70 -0
  451. package/src/components/Spinner/TeammateSpinnerLine.js +171 -0
  452. package/src/components/Spinner/TeammateSpinnerTree.js +269 -0
  453. package/src/components/Spinner/index.js +9 -0
  454. package/src/components/Spinner/teammateSelectHint.js +1 -0
  455. package/src/components/Spinner/useShimmerAnimation.js +22 -0
  456. package/src/components/Spinner/useStalledAnimation.js +63 -0
  457. package/src/components/Spinner/utils.js +78 -0
  458. package/src/components/Spinner.js +474 -0
  459. package/src/components/Stats.js +1000 -0
  460. package/src/components/StatusLine.js +286 -0
  461. package/src/components/StatusNotices.js +50 -0
  462. package/src/components/StructuredDiff/Fallback.js +336 -0
  463. package/src/components/StructuredDiff/colorDiff.js +37 -0
  464. package/src/components/StructuredDiff.js +153 -0
  465. package/src/components/StructuredDiffList.js +9 -0
  466. package/src/components/TagTabs.js +101 -0
  467. package/src/components/TaskListV2.js +333 -0
  468. package/src/components/TeammateViewHeader.js +88 -0
  469. package/src/components/TeleportError.js +191 -0
  470. package/src/components/TeleportProgress.js +131 -0
  471. package/src/components/TeleportRepoMismatchDialog.js +98 -0
  472. package/src/components/TeleportResumeWrapper.js +158 -0
  473. package/src/components/TeleportStash.js +82 -0
  474. package/src/components/TextInput.js +108 -0
  475. package/src/components/ThaddeusHint/PluginHintMenu.js +37 -0
  476. package/src/components/ThemePicker.js +331 -0
  477. package/src/components/ThinkingToggle.js +154 -0
  478. package/src/components/TokenWarning.js +171 -0
  479. package/src/components/ToolUseLoader.js +35 -0
  480. package/src/components/TrustDialog/TrustDialog.js +301 -0
  481. package/src/components/TrustDialog/utils.js +199 -0
  482. package/src/components/UndercoverAutoCallout.js +5 -0
  483. package/src/components/ValidationErrorsList.js +147 -0
  484. package/src/components/VimTextInput.js +136 -0
  485. package/src/components/VirtualMessageList.js +893 -0
  486. package/src/components/WorkflowMultiselectDialog.js +118 -0
  487. package/src/components/WorktreeExitDialog.js +220 -0
  488. package/src/components/agents/AgentDetail.js +227 -0
  489. package/src/components/agents/AgentEditor.js +147 -0
  490. package/src/components/agents/AgentNavigationFooter.js +22 -0
  491. package/src/components/agents/AgentsList.js +436 -0
  492. package/src/components/agents/AgentsMenu.js +849 -0
  493. package/src/components/agents/ColorPicker.js +110 -0
  494. package/src/components/agents/ModelSelector.js +63 -0
  495. package/src/components/agents/SnapshotUpdateDialog.js +14 -0
  496. package/src/components/agents/ToolSelector.js +557 -0
  497. package/src/components/agents/agentFileUtils.js +179 -0
  498. package/src/components/agents/generateAgent.js +161 -0
  499. package/src/components/agents/new-agent-creation/CreateAgentWizard.js +89 -0
  500. package/src/components/agents/new-agent-creation/wizard-steps/ColorStep.js +81 -0
  501. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStep.js +387 -0
  502. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStepWrapper.js +63 -0
  503. package/src/components/agents/new-agent-creation/wizard-steps/DescriptionStep.js +126 -0
  504. package/src/components/agents/new-agent-creation/wizard-steps/GenerateStep.js +118 -0
  505. package/src/components/agents/new-agent-creation/wizard-steps/LocationStep.js +80 -0
  506. package/src/components/agents/new-agent-creation/wizard-steps/MemoryStep.js +108 -0
  507. package/src/components/agents/new-agent-creation/wizard-steps/MethodStep.js +80 -0
  508. package/src/components/agents/new-agent-creation/wizard-steps/ModelStep.js +49 -0
  509. package/src/components/agents/new-agent-creation/wizard-steps/PromptStep.js +131 -0
  510. package/src/components/agents/new-agent-creation/wizard-steps/ToolsStep.js +52 -0
  511. package/src/components/agents/new-agent-creation/wizard-steps/TypeStep.js +100 -0
  512. package/src/components/agents/types.js +4 -0
  513. package/src/components/agents/utils.js +14 -0
  514. package/src/components/agents/validateAgent.js +79 -0
  515. package/src/components/design-system/Byline.js +72 -0
  516. package/src/components/design-system/Dialog.js +117 -0
  517. package/src/components/design-system/Divider.js +110 -0
  518. package/src/components/design-system/FuzzyPicker.js +191 -0
  519. package/src/components/design-system/KeyboardShortcutHint.js +68 -0
  520. package/src/components/design-system/ListItem.js +184 -0
  521. package/src/components/design-system/LoadingState.js +69 -0
  522. package/src/components/design-system/Pane.js +69 -0
  523. package/src/components/design-system/ProgressBar.js +63 -0
  524. package/src/components/design-system/Ratchet.js +71 -0
  525. package/src/components/design-system/StatusIcon.js +70 -0
  526. package/src/components/design-system/Tabs.js +269 -0
  527. package/src/components/design-system/ThemeProvider.js +137 -0
  528. package/src/components/design-system/ThemedBox.js +126 -0
  529. package/src/components/design-system/ThemedText.js +60 -0
  530. package/src/components/design-system/color.js +22 -0
  531. package/src/components/diff/DiffDetailView.js +285 -0
  532. package/src/components/diff/DiffDialog.js +387 -0
  533. package/src/components/diff/DiffFileList.js +292 -0
  534. package/src/components/grove/Grove.js +483 -0
  535. package/src/components/hooks/HooksConfigMenu.js +583 -0
  536. package/src/components/hooks/PromptDialog.js +82 -0
  537. package/src/components/hooks/SelectEventMode.js +118 -0
  538. package/src/components/hooks/SelectHookMode.js +101 -0
  539. package/src/components/hooks/SelectMatcherMode.js +131 -0
  540. package/src/components/hooks/ViewHookMode.js +204 -0
  541. package/src/components/mcp/CapabilitiesSection.js +56 -0
  542. package/src/components/mcp/ElicitationDialog.js +945 -0
  543. package/src/components/mcp/MCPAgentServerMenu.js +95 -0
  544. package/src/components/mcp/MCPListPanel.js +505 -0
  545. package/src/components/mcp/MCPReconnect.js +168 -0
  546. package/src/components/mcp/MCPRemoteServerMenu.js +460 -0
  547. package/src/components/mcp/MCPSettings.js +414 -0
  548. package/src/components/mcp/MCPStdioServerMenu.js +95 -0
  549. package/src/components/mcp/MCPToolDetailView.js +219 -0
  550. package/src/components/mcp/MCPToolListView.js +137 -0
  551. package/src/components/mcp/McpParsingWarnings.js +212 -0
  552. package/src/components/mcp/index.js +8 -0
  553. package/src/components/mcp/utils/reconnectHelpers.js +35 -0
  554. package/src/components/memory/MemoryFileSelector.js +454 -0
  555. package/src/components/memory/MemoryUpdateNotification.js +43 -0
  556. package/src/components/messageActions.js +418 -0
  557. package/src/components/messages/AdvisorMessage.js +152 -0
  558. package/src/components/messages/AssistantRedactedThinkingMessage.js +28 -0
  559. package/src/components/messages/AssistantTextMessage.js +287 -0
  560. package/src/components/messages/AssistantThinkingMessage.js +70 -0
  561. package/src/components/messages/AssistantToolUseMessage.js +324 -0
  562. package/src/components/messages/AttachmentMessage.js +418 -0
  563. package/src/components/messages/CollapsedReadSearchContent.js +363 -0
  564. package/src/components/messages/CompactBoundaryMessage.js +19 -0
  565. package/src/components/messages/GroupedToolUseContent.js +37 -0
  566. package/src/components/messages/HighlightedThinkingText.js +165 -0
  567. package/src/components/messages/HookProgressMessage.js +111 -0
  568. package/src/components/messages/PlanApprovalMessage.js +213 -0
  569. package/src/components/messages/RateLimitMessage.js +149 -0
  570. package/src/components/messages/ShutdownMessage.js +124 -0
  571. package/src/components/messages/SnipBoundaryMessage.js +7 -0
  572. package/src/components/messages/SystemAPIErrorMessage.js +136 -0
  573. package/src/components/messages/SystemTextMessage.js +842 -0
  574. package/src/components/messages/TaskAssignmentMessage.js +72 -0
  575. package/src/components/messages/UserAgentNotificationMessage.js +78 -0
  576. package/src/components/messages/UserBashInputMessage.js +52 -0
  577. package/src/components/messages/UserBashOutputMessage.js +55 -0
  578. package/src/components/messages/UserChannelMessage.js +130 -0
  579. package/src/components/messages/UserCommandMessage.js +107 -0
  580. package/src/components/messages/UserCrossSessionMessage.js +11 -0
  581. package/src/components/messages/UserForkBoilerplateMessage.js +11 -0
  582. package/src/components/messages/UserGitHubWebhookMessage.js +12 -0
  583. package/src/components/messages/UserImageMessage.js +54 -0
  584. package/src/components/messages/UserLocalCommandOutputMessage.js +170 -0
  585. package/src/components/messages/UserMemoryInputMessage.js +73 -0
  586. package/src/components/messages/UserPlanMessage.js +38 -0
  587. package/src/components/messages/UserPromptMessage.js +63 -0
  588. package/src/components/messages/UserResourceUpdateMessage.js +102 -0
  589. package/src/components/messages/UserTeammateMessage.js +156 -0
  590. package/src/components/messages/UserTextMessage.js +270 -0
  591. package/src/components/messages/UserToolResultMessage/RejectedPlanMessage.js +28 -0
  592. package/src/components/messages/UserToolResultMessage/RejectedToolUseMessage.js +17 -0
  593. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.js +17 -0
  594. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.js +92 -0
  595. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.js +74 -0
  596. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.js +84 -0
  597. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.js +58 -0
  598. package/src/components/messages/UserToolResultMessage/utils.js +43 -0
  599. package/src/components/messages/nullRenderingAttachments.js +58 -0
  600. package/src/components/messages/teamMemCollapsed.js +142 -0
  601. package/src/components/messages/teamMemSaved.js +16 -0
  602. package/src/components/permissions/AskUserQuestionPermissionRequest/AskUserQuestionPermissionRequest.js +659 -0
  603. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewBox.js +219 -0
  604. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewQuestionView.js +227 -0
  605. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionNavigationBar.js +175 -0
  606. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionView.js +444 -0
  607. package/src/components/permissions/AskUserQuestionPermissionRequest/SubmitQuestionsView.js +137 -0
  608. package/src/components/permissions/AskUserQuestionPermissionRequest/use-multiple-choice-state.js +100 -0
  609. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.js +404 -0
  610. package/src/components/permissions/BashPermissionRequest/bashToolUseOptions.js +110 -0
  611. package/src/components/permissions/ComputerUseApproval/ComputerUseApproval.js +449 -0
  612. package/src/components/permissions/EnterPlanModePermissionRequest/EnterPlanModePermissionRequest.js +126 -0
  613. package/src/components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js +653 -0
  614. package/src/components/permissions/FallbackPermissionRequest.js +349 -0
  615. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.js +185 -0
  616. package/src/components/permissions/FilePermissionDialog/FilePermissionDialog.js +108 -0
  617. package/src/components/permissions/FilePermissionDialog/ideDiffConfig.js +13 -0
  618. package/src/components/permissions/FilePermissionDialog/permissionOptions.js +137 -0
  619. package/src/components/permissions/FilePermissionDialog/useFilePermissionDialog.js +131 -0
  620. package/src/components/permissions/FilePermissionDialog/usePermissionHandler.js +86 -0
  621. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.js +164 -0
  622. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.js +79 -0
  623. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +113 -0
  624. package/src/components/permissions/MonitorPermissionRequest/MonitorPermissionRequest.js +7 -0
  625. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditPermissionRequest.js +164 -0
  626. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditToolDiff.js +218 -0
  627. package/src/components/permissions/PermissionDecisionDebugInfo.js +467 -0
  628. package/src/components/permissions/PermissionDialog.js +55 -0
  629. package/src/components/permissions/PermissionExplanation.js +269 -0
  630. package/src/components/permissions/PermissionPrompt.js +316 -0
  631. package/src/components/permissions/PermissionRequest.js +159 -0
  632. package/src/components/permissions/PermissionRequestTitle.js +58 -0
  633. package/src/components/permissions/PermissionRuleExplanation.js +110 -0
  634. package/src/components/permissions/PowerShellPermissionRequest/PowerShellPermissionRequest.js +178 -0
  635. package/src/components/permissions/PowerShellPermissionRequest/powershellToolUseOptions.js +73 -0
  636. package/src/components/permissions/ReviewArtifactPermissionRequest/ReviewArtifactPermissionRequest.js +7 -0
  637. package/src/components/permissions/SandboxPermissionRequest.js +162 -0
  638. package/src/components/permissions/SedEditPermissionRequest/SedEditPermissionRequest.js +228 -0
  639. package/src/components/permissions/SkillPermissionRequest/SkillPermissionRequest.js +385 -0
  640. package/src/components/permissions/WebFetchPermissionRequest/WebFetchPermissionRequest.js +259 -0
  641. package/src/components/permissions/WorkerBadge.js +44 -0
  642. package/src/components/permissions/WorkerPendingPermission.js +107 -0
  643. package/src/components/permissions/hooks.js +163 -0
  644. package/src/components/permissions/rules/AddPermissionRules.js +171 -0
  645. package/src/components/permissions/rules/AddWorkspaceDirectory.js +335 -0
  646. package/src/components/permissions/rules/PermissionRuleDescription.js +78 -0
  647. package/src/components/permissions/rules/PermissionRuleInput.js +136 -0
  648. package/src/components/permissions/rules/PermissionRuleList.js +1190 -0
  649. package/src/components/permissions/rules/RecentDenialsTab.js +205 -0
  650. package/src/components/permissions/rules/RemoveWorkspaceDirectory.js +103 -0
  651. package/src/components/permissions/rules/WorkspaceTab.js +133 -0
  652. package/src/components/permissions/shellPermissionHelpers.js +112 -0
  653. package/src/components/permissions/useShellPermissionFeedback.js +108 -0
  654. package/src/components/permissions/utils.js +14 -0
  655. package/src/components/sandbox/SandboxConfigTab.js +48 -0
  656. package/src/components/sandbox/SandboxDependenciesTab.js +123 -0
  657. package/src/components/sandbox/SandboxDoctorSection.js +47 -0
  658. package/src/components/sandbox/SandboxOverridesTab.js +193 -0
  659. package/src/components/sandbox/SandboxSettings.js +297 -0
  660. package/src/components/shell/ExpandShellOutputContext.js +33 -0
  661. package/src/components/shell/OutputLine.js +110 -0
  662. package/src/components/shell/ShellProgressMessage.js +144 -0
  663. package/src/components/shell/ShellTimeDisplay.js +72 -0
  664. package/src/components/skills/SkillsMenu.js +239 -0
  665. package/src/components/tasks/AsyncAgentDetailDialog.js +235 -0
  666. package/src/components/tasks/BackgroundTask.js +364 -0
  667. package/src/components/tasks/BackgroundTaskStatus.js +419 -0
  668. package/src/components/tasks/BackgroundTasksDialog.js +494 -0
  669. package/src/components/tasks/DreamDetailDialog.js +251 -0
  670. package/src/components/tasks/InProcessTeammateDetailDialog.js +275 -0
  671. package/src/components/tasks/MonitorMcpDetailDialog.js +7 -0
  672. package/src/components/tasks/RemoteSessionDetailDialog.js +868 -0
  673. package/src/components/tasks/RemoteSessionProgress.js +249 -0
  674. package/src/components/tasks/ShellDetailDialog.js +403 -0
  675. package/src/components/tasks/ShellProgress.js +77 -0
  676. package/src/components/tasks/WorkflowDetailDialog.js +7 -0
  677. package/src/components/tasks/renderToolActivity.js +29 -0
  678. package/src/components/tasks/taskStatusUtils.js +94 -0
  679. package/src/components/teams/TeamStatus.js +77 -0
  680. package/src/components/teams/TeamsDialog.js +673 -0
  681. package/src/components/ui/OrderedList.js +66 -0
  682. package/src/components/ui/OrderedListItem.js +41 -0
  683. package/src/components/ui/TreeSelect.js +300 -0
  684. package/src/components/wizard/WizardDialogLayout.js +48 -0
  685. package/src/components/wizard/WizardNavigationFooter.js +11 -0
  686. package/src/components/wizard/WizardProvider.js +217 -0
  687. package/src/components/wizard/index.js +4 -0
  688. package/src/components/wizard/useWizard.js +9 -0
  689. package/src/constants/apiLimits.js +81 -0
  690. package/src/constants/betas.js +45 -0
  691. package/src/constants/common.js +29 -0
  692. package/src/constants/cyberRiskInstruction.js +23 -0
  693. package/src/constants/errorIds.js +14 -0
  694. package/src/constants/figures.js +38 -0
  695. package/src/constants/files.js +150 -0
  696. package/src/constants/github-app.js +139 -0
  697. package/src/constants/identity.js +112 -0
  698. package/src/constants/keys.js +10 -0
  699. package/src/constants/messages.js +1 -0
  700. package/src/constants/oauth.js +175 -0
  701. package/src/constants/outputStyles.js +162 -0
  702. package/src/constants/product.js +54 -0
  703. package/src/constants/prompts.js +994 -0
  704. package/src/constants/spinnerVerbs.js +98 -0
  705. package/src/constants/system.js +77 -0
  706. package/src/constants/systemPromptSections.js +39 -0
  707. package/src/constants/toolLimits.js +50 -0
  708. package/src/constants/tools.js +103 -0
  709. package/src/constants/turnCompletionVerbs.js +12 -0
  710. package/src/constants/xml.js +73 -0
  711. package/src/context/QueuedMessageContext.js +51 -0
  712. package/src/context/fpsMetrics.js +22 -0
  713. package/src/context/mailbox.js +35 -0
  714. package/src/context/modalContext.js +34 -0
  715. package/src/context/notifications.js +199 -0
  716. package/src/context/overlayContext.js +149 -0
  717. package/src/context/promptOverlayContext.js +118 -0
  718. package/src/context/stats.js +207 -0
  719. package/src/context/voice.js +74 -0
  720. package/src/context.js +146 -0
  721. package/src/coordinator/coordinatorMode.js +345 -0
  722. package/src/coordinator/workerAgent.js +24 -0
  723. package/src/cost-tracker.js +208 -0
  724. package/src/costHook.js +17 -0
  725. package/src/daemon/main.js +19 -0
  726. package/src/dialogLaunchers.js +77 -0
  727. package/src/entrypoints/agentSdkTypes.js +202 -0
  728. package/src/entrypoints/cli.js +226 -0
  729. package/src/entrypoints/init.js +265 -0
  730. package/src/entrypoints/mcp.js +141 -0
  731. package/src/entrypoints/sandboxTypes.js +112 -0
  732. package/src/entrypoints/sdk/controlSchemas.js +452 -0
  733. package/src/entrypoints/sdk/controlTypes.js +1 -0
  734. package/src/entrypoints/sdk/coreSchemas.js +1331 -0
  735. package/src/entrypoints/sdk/coreTypes.generated.js +3 -0
  736. package/src/entrypoints/sdk/coreTypes.js +49 -0
  737. package/src/entrypoints/sdk/runtimeTypes.js +1 -0
  738. package/src/entrypoints/sdk/sdkUtilityTypes.js +1 -0
  739. package/src/entrypoints/sdk/settingsTypes.generated.js +1 -0
  740. package/src/entrypoints/sdk/toolTypes.js +1 -0
  741. package/src/environment-runner/main.js +8 -0
  742. package/src/history.js +386 -0
  743. package/src/hooks/fileSuggestions.js +635 -0
  744. package/src/hooks/notifs/useAntOrgWarningNotification.js +5 -0
  745. package/src/hooks/notifs/useAutoModeUnavailableNotification.js +47 -0
  746. package/src/hooks/notifs/useCanSwitchToExistingSubscription.js +58 -0
  747. package/src/hooks/notifs/useDeprecationWarningNotification.js +43 -0
  748. package/src/hooks/notifs/useFastModeNotification.js +164 -0
  749. package/src/hooks/notifs/useIDEStatusIndicator.js +174 -0
  750. package/src/hooks/notifs/useInstallMessages.js +27 -0
  751. package/src/hooks/notifs/useLspInitializationNotification.js +144 -0
  752. package/src/hooks/notifs/useMcpConnectivityStatus.js +81 -0
  753. package/src/hooks/notifs/useModelMigrationNotifications.js +53 -0
  754. package/src/hooks/notifs/useNpmDeprecationNotification.js +25 -0
  755. package/src/hooks/notifs/usePluginAutoupdateNotification.js +83 -0
  756. package/src/hooks/notifs/usePluginInstallationStatus.js +128 -0
  757. package/src/hooks/notifs/useRateLimitWarningNotification.js +119 -0
  758. package/src/hooks/notifs/useSettingsErrors.js +64 -0
  759. package/src/hooks/notifs/useStartupNotification.js +33 -0
  760. package/src/hooks/notifs/useTeammateShutdownNotification.js +64 -0
  761. package/src/hooks/renderPlaceholder.js +26 -0
  762. package/src/hooks/toolPermission/PermissionContext.js +211 -0
  763. package/src/hooks/toolPermission/handlers/coordinatorHandler.js +44 -0
  764. package/src/hooks/toolPermission/handlers/interactiveHandler.js +397 -0
  765. package/src/hooks/toolPermission/handlers/swarmWorkerHandler.js +108 -0
  766. package/src/hooks/toolPermission/permissionLogging.js +145 -0
  767. package/src/hooks/unifiedSuggestions.js +130 -0
  768. package/src/hooks/useAfterFirstRender.js +12 -0
  769. package/src/hooks/useApiKeyVerification.js +63 -0
  770. package/src/hooks/useArrowKeyHistory.js +203 -0
  771. package/src/hooks/useAssistantHistory.js +193 -0
  772. package/src/hooks/useAwaySummary.js +105 -0
  773. package/src/hooks/useBackgroundTaskNavigation.js +204 -0
  774. package/src/hooks/useBlink.js +28 -0
  775. package/src/hooks/useCanUseTool.js +193 -0
  776. package/src/hooks/useCancelRequest.js +195 -0
  777. package/src/hooks/useChromeExtensionNotification.js +50 -0
  778. package/src/hooks/useClipboardImageHint.js +59 -0
  779. package/src/hooks/useCommandKeybindings.js +87 -0
  780. package/src/hooks/useCommandQueue.js +10 -0
  781. package/src/hooks/useCopyOnSelect.js +88 -0
  782. package/src/hooks/useDeferredHookMessages.js +43 -0
  783. package/src/hooks/useDiffData.js +69 -0
  784. package/src/hooks/useDiffInIDE.js +252 -0
  785. package/src/hooks/useDirectConnect.js +150 -0
  786. package/src/hooks/useDoublePress.js +44 -0
  787. package/src/hooks/useDynamicConfig.js +17 -0
  788. package/src/hooks/useElapsedTime.js +25 -0
  789. package/src/hooks/useExitOnCtrlCD.js +57 -0
  790. package/src/hooks/useExitOnCtrlCDWithKeybindings.js +17 -0
  791. package/src/hooks/useFileHistorySnapshotInit.js +14 -0
  792. package/src/hooks/useGlobalKeybindings.js +213 -0
  793. package/src/hooks/useHistorySearch.js +241 -0
  794. package/src/hooks/useIDEIntegration.js +56 -0
  795. package/src/hooks/useIdeAtMentioned.js +51 -0
  796. package/src/hooks/useIdeConnectionStatus.js +21 -0
  797. package/src/hooks/useIdeLogging.js +29 -0
  798. package/src/hooks/useIdeSelection.js +106 -0
  799. package/src/hooks/useInboxPoller.js +709 -0
  800. package/src/hooks/useInputBuffer.js +73 -0
  801. package/src/hooks/useIssueFlagBanner.js +115 -0
  802. package/src/hooks/useLogMessages.js +98 -0
  803. package/src/hooks/useLspPluginRecommendation.js +176 -0
  804. package/src/hooks/useMailboxBridge.js +15 -0
  805. package/src/hooks/useMainLoopModel.js +25 -0
  806. package/src/hooks/useManagePlugins.js +261 -0
  807. package/src/hooks/useMemoryUsage.js +28 -0
  808. package/src/hooks/useMergedClients.js +11 -0
  809. package/src/hooks/useMergedCommands.js +10 -0
  810. package/src/hooks/useMergedTools.js +32 -0
  811. package/src/hooks/useMinDisplayTime.js +26 -0
  812. package/src/hooks/useNotifyAfterTimeout.js +51 -0
  813. package/src/hooks/useOfficialMarketplaceNotification.js +47 -0
  814. package/src/hooks/usePasteHandler.js +195 -0
  815. package/src/hooks/usePluginRecommendationBase.js +101 -0
  816. package/src/hooks/usePrStatus.js +91 -0
  817. package/src/hooks/usePromptSuggestion.js +128 -0
  818. package/src/hooks/usePromptsFromClaudeInChrome.js +66 -0
  819. package/src/hooks/useQueueProcessor.js +46 -0
  820. package/src/hooks/useRemoteSession.js +431 -0
  821. package/src/hooks/useReplBridge.js +715 -0
  822. package/src/hooks/useSSHSession.js +167 -0
  823. package/src/hooks/useScheduledTasks.js +104 -0
  824. package/src/hooks/useSearchInput.js +302 -0
  825. package/src/hooks/useSessionBackgrounding.js +132 -0
  826. package/src/hooks/useSettings.js +10 -0
  827. package/src/hooks/useSettingsChange.js +13 -0
  828. package/src/hooks/useSkillImprovementSurvey.js +69 -0
  829. package/src/hooks/useSkillsChange.js +51 -0
  830. package/src/hooks/useSwarmInitialization.js +67 -0
  831. package/src/hooks/useSwarmPermissionPoller.js +215 -0
  832. package/src/hooks/useTaskListWatcher.js +157 -0
  833. package/src/hooks/useTasksV2.js +220 -0
  834. package/src/hooks/useTeammateViewAutoExit.js +55 -0
  835. package/src/hooks/useTeleportResume.js +81 -0
  836. package/src/hooks/useTerminalSize.js +9 -0
  837. package/src/hooks/useTextInput.js +397 -0
  838. package/src/hooks/useThaddeusHintRecommendation.js +117 -0
  839. package/src/hooks/useTimeout.js +10 -0
  840. package/src/hooks/useTurnDiffs.js +160 -0
  841. package/src/hooks/useTypeahead.js +1250 -0
  842. package/src/hooks/useUpdateNotification.js +21 -0
  843. package/src/hooks/useVimInput.js +232 -0
  844. package/src/hooks/useVirtualScroll.js +627 -0
  845. package/src/hooks/useVoice.js +952 -0
  846. package/src/hooks/useVoiceEnabled.js +21 -0
  847. package/src/hooks/useVoiceIntegration.js +629 -0
  848. package/src/infrastructure/audit.js +210 -0
  849. package/src/infrastructure/guardrails.js +513 -0
  850. package/src/infrastructure/index.js +11 -0
  851. package/src/ink/Ansi.js +269 -0
  852. package/src/ink/bidi.js +117 -0
  853. package/src/ink/clearTerminal.js +58 -0
  854. package/src/ink/colorize.js +198 -0
  855. package/src/ink/components/AlternateScreen.js +74 -0
  856. package/src/ink/components/App.js +562 -0
  857. package/src/ink/components/AppContext.js +11 -0
  858. package/src/ink/components/Box.js +155 -0
  859. package/src/ink/components/Button.js +166 -0
  860. package/src/ink/components/ClockContext.js +108 -0
  861. package/src/ink/components/CursorDeclarationContext.js +3 -0
  862. package/src/ink/components/ErrorOverview.js +50 -0
  863. package/src/ink/components/Link.js +34 -0
  864. package/src/ink/components/Newline.js +30 -0
  865. package/src/ink/components/NoSelect.js +57 -0
  866. package/src/ink/components/RawAnsi.js +46 -0
  867. package/src/ink/components/ScrollBox.js +171 -0
  868. package/src/ink/components/Spacer.js +20 -0
  869. package/src/ink/components/StdinContext.js +16 -0
  870. package/src/ink/components/TerminalFocusContext.js +45 -0
  871. package/src/ink/components/TerminalSizeContext.js +3 -0
  872. package/src/ink/components/Text.js +195 -0
  873. package/src/ink/constants.js +2 -0
  874. package/src/ink/dom.js +298 -0
  875. package/src/ink/events/click-event.js +36 -0
  876. package/src/ink/events/dispatcher.js +172 -0
  877. package/src/ink/events/emitter.js +31 -0
  878. package/src/ink/events/event-handlers.js +30 -0
  879. package/src/ink/events/event.js +9 -0
  880. package/src/ink/events/focus-event.js +16 -0
  881. package/src/ink/events/input-event.js +161 -0
  882. package/src/ink/events/keyboard-event.js +46 -0
  883. package/src/ink/events/terminal-event.js +78 -0
  884. package/src/ink/events/terminal-focus-event.js +15 -0
  885. package/src/ink/focus.js +158 -0
  886. package/src/ink/frame.js +30 -0
  887. package/src/ink/get-max-width.js +23 -0
  888. package/src/ink/hit-test.js +113 -0
  889. package/src/ink/hooks/use-animation-frame.js +48 -0
  890. package/src/ink/hooks/use-app.js +7 -0
  891. package/src/ink/hooks/use-declared-cursor.js +60 -0
  892. package/src/ink/hooks/use-input.js +70 -0
  893. package/src/ink/hooks/use-interval.js +54 -0
  894. package/src/ink/hooks/use-search-highlight.js +32 -0
  895. package/src/ink/hooks/use-selection.js +60 -0
  896. package/src/ink/hooks/use-stdin.js +7 -0
  897. package/src/ink/hooks/use-tab-status.js +57 -0
  898. package/src/ink/hooks/use-terminal-focus.js +15 -0
  899. package/src/ink/hooks/use-terminal-title.js +29 -0
  900. package/src/ink/hooks/use-terminal-viewport.js +77 -0
  901. package/src/ink/ink.js +1645 -0
  902. package/src/ink/instances.js +7 -0
  903. package/src/ink/layout/engine.js +4 -0
  904. package/src/ink/layout/geometry.js +61 -0
  905. package/src/ink/layout/node.js +62 -0
  906. package/src/ink/layout/yoga.js +237 -0
  907. package/src/ink/line-width-cache.js +19 -0
  908. package/src/ink/log-update.js +583 -0
  909. package/src/ink/measure-element.js +8 -0
  910. package/src/ink/measure-text.js +35 -0
  911. package/src/ink/node-cache.js +30 -0
  912. package/src/ink/optimizer.js +81 -0
  913. package/src/ink/output.js +556 -0
  914. package/src/ink/parse-keypress.js +695 -0
  915. package/src/ink/reconciler.js +384 -0
  916. package/src/ink/render-border.js +134 -0
  917. package/src/ink/render-node-to-output.js +1216 -0
  918. package/src/ink/render-to-screen.js +171 -0
  919. package/src/ink/renderer.js +129 -0
  920. package/src/ink/root.js +80 -0
  921. package/src/ink/screen.js +1132 -0
  922. package/src/ink/searchHighlight.js +78 -0
  923. package/src/ink/selection.js +792 -0
  924. package/src/ink/squash-text-nodes.js +56 -0
  925. package/src/ink/stringWidth.js +200 -0
  926. package/src/ink/styles.js +299 -0
  927. package/src/ink/supports-hyperlinks.js +40 -0
  928. package/src/ink/tabstops.js +39 -0
  929. package/src/ink/terminal-focus-state.js +35 -0
  930. package/src/ink/terminal-querier.js +173 -0
  931. package/src/ink/terminal.js +208 -0
  932. package/src/ink/termio/ansi.js +70 -0
  933. package/src/ink/termio/csi.js +260 -0
  934. package/src/ink/termio/dec.js +53 -0
  935. package/src/ink/termio/esc.js +55 -0
  936. package/src/ink/termio/osc.js +432 -0
  937. package/src/ink/termio/parser.js +356 -0
  938. package/src/ink/termio/sgr.js +292 -0
  939. package/src/ink/termio/tokenize.js +264 -0
  940. package/src/ink/termio/types.js +55 -0
  941. package/src/ink/termio.js +24 -0
  942. package/src/ink/useTerminalNotification.js +57 -0
  943. package/src/ink/warn.js +10 -0
  944. package/src/ink/widest-line.js +14 -0
  945. package/src/ink/wrap-text.js +54 -0
  946. package/src/ink/wrapAnsi.js +6 -0
  947. package/src/ink.js +50 -0
  948. package/src/integrations/credentialStore.js +176 -0
  949. package/src/integrations/index.js +5 -0
  950. package/src/integrations/integrationManager.js +180 -0
  951. package/src/integrations/providers/BaseProvider.js +180 -0
  952. package/src/integrations/providers/GitHubProvider.js +217 -0
  953. package/src/integrations/providers/GmailProvider.js +204 -0
  954. package/src/integrations/providers/GoogleCalendarProvider.js +113 -0
  955. package/src/integrations/providers/HubSpotProvider.js +159 -0
  956. package/src/integrations/providers/JiraProvider.js +216 -0
  957. package/src/integrations/providers/NotionProvider.js +221 -0
  958. package/src/integrations/providers/QuickBooksProvider.js +176 -0
  959. package/src/integrations/providers/SlackProvider.js +174 -0
  960. package/src/integrations/providers/StripeProvider.js +206 -0
  961. package/src/integrations/providers/TwilioProvider.js +239 -0
  962. package/src/integrations/providers/_template.js +112 -0
  963. package/src/integrations/types.js +7 -0
  964. package/src/interactiveHelpers.js +308 -0
  965. package/src/jobs/classifier.js +6 -0
  966. package/src/keybindings/KeybindingContext.js +184 -0
  967. package/src/keybindings/KeybindingProviderSetup.js +259 -0
  968. package/src/keybindings/defaultBindings.js +333 -0
  969. package/src/keybindings/loadUserBindings.js +393 -0
  970. package/src/keybindings/match.js +111 -0
  971. package/src/keybindings/parser.js +184 -0
  972. package/src/keybindings/reservedShortcuts.js +109 -0
  973. package/src/keybindings/resolver.js +182 -0
  974. package/src/keybindings/schema.js +205 -0
  975. package/src/keybindings/shortcutFormat.js +48 -0
  976. package/src/keybindings/template.js +40 -0
  977. package/src/keybindings/useKeybinding.js +161 -0
  978. package/src/keybindings/useShortcutDisplay.js +43 -0
  979. package/src/keybindings/validate.js +395 -0
  980. package/src/main.js +4128 -0
  981. package/src/memdir/findRelevantMemories.js +99 -0
  982. package/src/memdir/memdir.js +406 -0
  983. package/src/memdir/memoryAge.js +52 -0
  984. package/src/memdir/memoryScan.js +65 -0
  985. package/src/memdir/memoryShapeTelemetry.js +8 -0
  986. package/src/memdir/memoryTypes.js +260 -0
  987. package/src/memdir/paths.js +235 -0
  988. package/src/memdir/teamMemPaths.js +261 -0
  989. package/src/memdir/teamMemPrompts.js +82 -0
  990. package/src/migrations/migrateAutoUpdatesToSettings.js +47 -0
  991. package/src/migrations/migrateBypassPermissionsAcceptedToSettings.js +32 -0
  992. package/src/migrations/migrateEnableAllProjectMcpServersToSettings.js +83 -0
  993. package/src/migrations/migrateFennecToOpus.js +39 -0
  994. package/src/migrations/migrateLegacyOpusToCurrent.js +44 -0
  995. package/src/migrations/migrateOpusToOpus1m.js +31 -0
  996. package/src/migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.js +23 -0
  997. package/src/migrations/migrateSonnet1mToSonnet45.js +38 -0
  998. package/src/migrations/migrateSonnet45ToSonnet46.js +48 -0
  999. package/src/migrations/resetAutoModeOptInForDefaultOffer.js +47 -0
  1000. package/src/migrations/resetProToOpusDefault.js +46 -0
  1001. package/src/moreright/useMoreRight.js +13 -0
  1002. package/src/native-ts/color-diff/index.js +819 -0
  1003. package/src/native-ts/file-index/index.js +328 -0
  1004. package/src/native-ts/yoga-layout/enums.js +101 -0
  1005. package/src/native-ts/yoga-layout/index.js +2113 -0
  1006. package/src/outputStyles/loadOutputStylesDir.js +71 -0
  1007. package/src/plugins/builtinPlugins.js +132 -0
  1008. package/src/plugins/bundled/index.js +22 -0
  1009. package/src/proactive/index.js +138 -0
  1010. package/src/proactive/useProactive.js +82 -0
  1011. package/src/projectOnboardingState.js +61 -0
  1012. package/src/query/config.js +17 -0
  1013. package/src/query/deps.js +12 -0
  1014. package/src/query/stopHooks.js +332 -0
  1015. package/src/query/tokenBudget.js +49 -0
  1016. package/src/query.js +1264 -0
  1017. package/src/remote/RemoteSessionManager.js +172 -0
  1018. package/src/remote/SessionsWebSocket.js +308 -0
  1019. package/src/remote/remotePermissionBridge.js +70 -0
  1020. package/src/remote/sdkMessageAdapter.js +227 -0
  1021. package/src/replLauncher.js +7 -0
  1022. package/src/schemas/hooks.js +174 -0
  1023. package/src/screens/Doctor.js +580 -0
  1024. package/src/screens/REPL.js +4500 -0
  1025. package/src/screens/ResumeConversation.js +339 -0
  1026. package/src/self-hosted-runner/main.js +8 -0
  1027. package/src/server/backends/dangerousBackend.js +8 -0
  1028. package/src/server/connectHeadless.js +6 -0
  1029. package/src/server/createDirectConnectSession.js +62 -0
  1030. package/src/server/directConnectManager.js +153 -0
  1031. package/src/server/lockfile.js +11 -0
  1032. package/src/server/parseConnectUrl.js +20 -0
  1033. package/src/server/server.js +12 -0
  1034. package/src/server/serverBanner.js +9 -0
  1035. package/src/server/serverLog.js +11 -0
  1036. package/src/server/sessionManager.js +19 -0
  1037. package/src/server/types.js +7 -0
  1038. package/src/services/AgentSummary/agentSummary.js +147 -0
  1039. package/src/services/MagicDocs/magicDocs.js +193 -0
  1040. package/src/services/MagicDocs/prompts.js +110 -0
  1041. package/src/services/PromptSuggestion/promptSuggestion.js +402 -0
  1042. package/src/services/PromptSuggestion/speculation.js +643 -0
  1043. package/src/services/SessionMemory/prompts.js +254 -0
  1044. package/src/services/SessionMemory/sessionMemory.js +358 -0
  1045. package/src/services/SessionMemory/sessionMemoryUtils.js +157 -0
  1046. package/src/services/analytics/config.js +27 -0
  1047. package/src/services/analytics/datadog.js +26 -0
  1048. package/src/services/analytics/firstPartyEventLogger.js +65 -0
  1049. package/src/services/analytics/firstPartyEventLoggingExporter.js +595 -0
  1050. package/src/services/analytics/growthbook.js +103 -0
  1051. package/src/services/analytics/index.js +91 -0
  1052. package/src/services/analytics/metadata.js +696 -0
  1053. package/src/services/analytics/sink.js +19 -0
  1054. package/src/services/analytics/sinkKillswitch.js +19 -0
  1055. package/src/services/api/adminRequests.js +57 -0
  1056. package/src/services/api/bootstrap.js +118 -0
  1057. package/src/services/api/claude.js +2466 -0
  1058. package/src/services/api/client.js +335 -0
  1059. package/src/services/api/dumpPrompts.js +174 -0
  1060. package/src/services/api/emptyUsage.js +20 -0
  1061. package/src/services/api/errorUtils.js +203 -0
  1062. package/src/services/api/errors.js +926 -0
  1063. package/src/services/api/filesApi.js +523 -0
  1064. package/src/services/api/firstTokenDate.js +49 -0
  1065. package/src/services/api/grove.js +44 -0
  1066. package/src/services/api/logging.js +484 -0
  1067. package/src/services/api/metricsOptOut.js +15 -0
  1068. package/src/services/api/overageCreditGrant.js +123 -0
  1069. package/src/services/api/promptCacheBreakDetection.js +510 -0
  1070. package/src/services/api/referral.js +219 -0
  1071. package/src/services/api/sessionIngress.js +358 -0
  1072. package/src/services/api/ultrareviewQuota.js +29 -0
  1073. package/src/services/api/usage.js +31 -0
  1074. package/src/services/api/withRetry.js +587 -0
  1075. package/src/services/api/xai/anthropic-shim.js +885 -0
  1076. package/src/services/api/xai/brightDataSearch.js +161 -0
  1077. package/src/services/api/xai/thaddeus-engine.js +605 -0
  1078. package/src/services/api/xai/xai-client.js +276 -0
  1079. package/src/services/autoDream/autoDream.js +244 -0
  1080. package/src/services/autoDream/config.js +17 -0
  1081. package/src/services/autoDream/consolidationLock.js +122 -0
  1082. package/src/services/autoDream/consolidationPrompt.js +55 -0
  1083. package/src/services/awaySummary.js +61 -0
  1084. package/src/services/claudeAiLimits.js +331 -0
  1085. package/src/services/claudeAiLimitsHook.js +15 -0
  1086. package/src/services/compact/apiMicrocompact.js +97 -0
  1087. package/src/services/compact/autoCompact.js +234 -0
  1088. package/src/services/compact/cachedMCConfig.js +5 -0
  1089. package/src/services/compact/compact.js +1256 -0
  1090. package/src/services/compact/compactWarningHook.js +12 -0
  1091. package/src/services/compact/compactWarningState.js +15 -0
  1092. package/src/services/compact/grouping.js +58 -0
  1093. package/src/services/compact/microCompact.js +414 -0
  1094. package/src/services/compact/postCompactCleanup.js +70 -0
  1095. package/src/services/compact/prompt.js +325 -0
  1096. package/src/services/compact/reactiveCompact.js +20 -0
  1097. package/src/services/compact/sessionMemoryCompact.js +467 -0
  1098. package/src/services/compact/snipCompact.js +23 -0
  1099. package/src/services/compact/snipProjection.js +11 -0
  1100. package/src/services/compact/timeBasedMCConfig.js +11 -0
  1101. package/src/services/contextCollapse/index.js +33 -0
  1102. package/src/services/contextCollapse/operations.js +5 -0
  1103. package/src/services/contextCollapse/persist.js +5 -0
  1104. package/src/services/diagnosticTracking.js +282 -0
  1105. package/src/services/elevenlabsTTS.js +245 -0
  1106. package/src/services/extractMemories/extractMemories.js +442 -0
  1107. package/src/services/extractMemories/prompts.js +129 -0
  1108. package/src/services/internalLogging.js +68 -0
  1109. package/src/services/lsp/LSPClient.js +306 -0
  1110. package/src/services/lsp/LSPDiagnosticRegistry.js +277 -0
  1111. package/src/services/lsp/LSPServerInstance.js +388 -0
  1112. package/src/services/lsp/LSPServerManager.js +305 -0
  1113. package/src/services/lsp/config.js +57 -0
  1114. package/src/services/lsp/manager.js +246 -0
  1115. package/src/services/lsp/passiveFeedback.js +226 -0
  1116. package/src/services/mcp/InProcessTransport.js +54 -0
  1117. package/src/services/mcp/MCPConnectionManager.js +50 -0
  1118. package/src/services/mcp/SdkControlTransport.js +115 -0
  1119. package/src/services/mcp/auth.js +1882 -0
  1120. package/src/services/mcp/channelAllowlist.js +57 -0
  1121. package/src/services/mcp/channelNotification.js +235 -0
  1122. package/src/services/mcp/channelPermissions.js +192 -0
  1123. package/src/services/mcp/claudeai.js +123 -0
  1124. package/src/services/mcp/client.js +2478 -0
  1125. package/src/services/mcp/config.js +1271 -0
  1126. package/src/services/mcp/elicitationHandler.js +192 -0
  1127. package/src/services/mcp/envExpansion.js +30 -0
  1128. package/src/services/mcp/headersHelper.js +93 -0
  1129. package/src/services/mcp/mcpStringUtils.js +85 -0
  1130. package/src/services/mcp/normalization.js +21 -0
  1131. package/src/services/mcp/oauthPort.js +69 -0
  1132. package/src/services/mcp/officialRegistry.js +20 -0
  1133. package/src/services/mcp/types.js +94 -0
  1134. package/src/services/mcp/useManageMCPConnections.js +818 -0
  1135. package/src/services/mcp/utils.js +433 -0
  1136. package/src/services/mcp/vscodeSdkMcp.js +69 -0
  1137. package/src/services/mcp/xaa.js +342 -0
  1138. package/src/services/mcp/xaaIdpLogin.js +377 -0
  1139. package/src/services/mcpServerApproval.js +30 -0
  1140. package/src/services/mockRateLimits.js +666 -0
  1141. package/src/services/notifier.js +114 -0
  1142. package/src/services/oauth/auth-code-listener.js +165 -0
  1143. package/src/services/oauth/client.js +397 -0
  1144. package/src/services/oauth/crypto.js +19 -0
  1145. package/src/services/oauth/getOauthProfile.js +48 -0
  1146. package/src/services/oauth/index.js +133 -0
  1147. package/src/services/plugins/PluginInstallationManager.js +139 -0
  1148. package/src/services/plugins/pluginCliCommands.js +230 -0
  1149. package/src/services/plugins/pluginOperations.js +826 -0
  1150. package/src/services/policyLimits/index.js +547 -0
  1151. package/src/services/policyLimits/types.js +9 -0
  1152. package/src/services/preventSleep.js +143 -0
  1153. package/src/services/rateLimitMessages.js +271 -0
  1154. package/src/services/rateLimitMocking.js +91 -0
  1155. package/src/services/remoteManagedSettings/index.js +534 -0
  1156. package/src/services/remoteManagedSettings/securityCheck.js +60 -0
  1157. package/src/services/remoteManagedSettings/syncCache.js +90 -0
  1158. package/src/services/remoteManagedSettings/syncCacheState.js +89 -0
  1159. package/src/services/remoteManagedSettings/types.js +12 -0
  1160. package/src/services/sessionTranscript/sessionTranscript.js +5 -0
  1161. package/src/services/settingsSync/index.js +478 -0
  1162. package/src/services/settingsSync/types.js +35 -0
  1163. package/src/services/skillSearch/featureCheck.js +8 -0
  1164. package/src/services/skillSearch/localSearch.js +5 -0
  1165. package/src/services/skillSearch/prefetch.js +8 -0
  1166. package/src/services/skillSearch/remoteSkillLoader.js +8 -0
  1167. package/src/services/skillSearch/remoteSkillState.js +11 -0
  1168. package/src/services/skillSearch/signals.js +3 -0
  1169. package/src/services/skillSearch/telemetry.js +8 -0
  1170. package/src/services/teamMemorySync/index.js +976 -0
  1171. package/src/services/teamMemorySync/secretScanner.js +275 -0
  1172. package/src/services/teamMemorySync/teamMemSecretGuard.js +33 -0
  1173. package/src/services/teamMemorySync/types.js +47 -0
  1174. package/src/services/teamMemorySync/watcher.js +326 -0
  1175. package/src/services/thaddeusAuth.js +485 -0
  1176. package/src/services/thaddeusAuthTypes.js +9 -0
  1177. package/src/services/thaddeusLoginFlow.js +236 -0
  1178. package/src/services/tips/tipHistory.js +17 -0
  1179. package/src/services/tips/tipRegistry.js +593 -0
  1180. package/src/services/tips/tipScheduler.js +40 -0
  1181. package/src/services/tokenEstimation.js +365 -0
  1182. package/src/services/toolUseSummary/toolUseSummaryGenerator.js +87 -0
  1183. package/src/services/tools/StreamingToolExecutor.js +413 -0
  1184. package/src/services/tools/toolExecution.js +1309 -0
  1185. package/src/services/tools/toolHooks.js +454 -0
  1186. package/src/services/tools/toolOrchestration.js +110 -0
  1187. package/src/services/vcr.js +291 -0
  1188. package/src/services/voice.js +392 -0
  1189. package/src/services/voiceKeyterms.js +94 -0
  1190. package/src/services/voiceStreamSTT.js +405 -0
  1191. package/src/setup.js +310 -0
  1192. package/src/skills/bundled/batch.js +114 -0
  1193. package/src/skills/bundled/claudeApi.js +145 -0
  1194. package/src/skills/bundled/claudeApiContent.js +71 -0
  1195. package/src/skills/bundled/claudeInChrome.js +27 -0
  1196. package/src/skills/bundled/debug.js +99 -0
  1197. package/src/skills/bundled/dream.js +49 -0
  1198. package/src/skills/bundled/emailSetup.js +196 -0
  1199. package/src/skills/bundled/hunter.js +28 -0
  1200. package/src/skills/bundled/index.js +80 -0
  1201. package/src/skills/bundled/keybindings.js +292 -0
  1202. package/src/skills/bundled/loop.js +81 -0
  1203. package/src/skills/bundled/loremIpsum.js +264 -0
  1204. package/src/skills/bundled/reactor.js +31 -0
  1205. package/src/skills/bundled/remember.js +73 -0
  1206. package/src/skills/bundled/runSkillGenerator.js +12 -0
  1207. package/src/skills/bundled/scheduleRemoteAgents.js +373 -0
  1208. package/src/skills/bundled/simplify.js +66 -0
  1209. package/src/skills/bundled/skillify.js +182 -0
  1210. package/src/skills/bundled/stuck.js +69 -0
  1211. package/src/skills/bundled/updateConfig.js +463 -0
  1212. package/src/skills/bundled/verify.js +23 -0
  1213. package/src/skills/bundled/verifyContent.js +10 -0
  1214. package/src/skills/bundledSkills.js +159 -0
  1215. package/src/skills/loadSkillsDir.js +736 -0
  1216. package/src/skills/mcpSkillBuilders.js +10 -0
  1217. package/src/skills/mcpSkills.js +5 -0
  1218. package/src/state/AppState.js +182 -0
  1219. package/src/state/AppStateStore.js +117 -0
  1220. package/src/state/onChangeAppState.js +132 -0
  1221. package/src/state/selectors.js +51 -0
  1222. package/src/state/store.js +21 -0
  1223. package/src/state/teammateViewHelpers.js +124 -0
  1224. package/src/stubs/ant-chrome-mcp/index.js +4 -0
  1225. package/src/stubs/ant-computer-use-input/index.js +2 -0
  1226. package/src/stubs/ant-computer-use-mcp/index.js +7 -0
  1227. package/src/stubs/ant-computer-use-mcp/sentinelApps.js +2 -0
  1228. package/src/stubs/ant-computer-use-mcp/types.js +3 -0
  1229. package/src/stubs/ant-computer-use-swift/index.js +1 -0
  1230. package/src/stubs/anthropic-sandbox/index.js +34 -0
  1231. package/src/tasks/DreamTask/DreamTask.js +99 -0
  1232. package/src/tasks/InProcessTeammateTask/InProcessTeammateTask.js +116 -0
  1233. package/src/tasks/InProcessTeammateTask/types.js +35 -0
  1234. package/src/tasks/LocalAgentTask/LocalAgentTask.js +507 -0
  1235. package/src/tasks/LocalMainSessionTask.js +338 -0
  1236. package/src/tasks/LocalShellTask/LocalShellTask.js +475 -0
  1237. package/src/tasks/LocalShellTask/guards.js +9 -0
  1238. package/src/tasks/LocalShellTask/killShellTasks.js +59 -0
  1239. package/src/tasks/LocalWorkflowTask/LocalWorkflowTask.js +7 -0
  1240. package/src/tasks/MonitorMcpTask/MonitorMcpTask.js +20 -0
  1241. package/src/tasks/RemoteAgentTask/RemoteAgentTask.js +742 -0
  1242. package/src/tasks/pillLabel.js +69 -0
  1243. package/src/tasks/stopTask.js +67 -0
  1244. package/src/tasks/types.js +18 -0
  1245. package/src/tasks.js +37 -0
  1246. package/src/tools/AIEmployeesTool/AIEmployeesTool.js +674 -0
  1247. package/src/tools/AIEmployeesTool/constants.js +1 -0
  1248. package/src/tools/AIEmployeesTool/prompt.js +56 -0
  1249. package/src/tools/AgentTool/AgentTool.js +1221 -0
  1250. package/src/tools/AgentTool/UI.js +593 -0
  1251. package/src/tools/AgentTool/agentColorManager.js +43 -0
  1252. package/src/tools/AgentTool/agentDisplay.js +72 -0
  1253. package/src/tools/AgentTool/agentMemory.js +125 -0
  1254. package/src/tools/AgentTool/agentMemorySnapshot.js +136 -0
  1255. package/src/tools/AgentTool/agentToolUtils.js +456 -0
  1256. package/src/tools/AgentTool/built-in/exploreAgent.js +76 -0
  1257. package/src/tools/AgentTool/built-in/generalPurposeAgent.js +28 -0
  1258. package/src/tools/AgentTool/built-in/planAgent.js +87 -0
  1259. package/src/tools/AgentTool/built-in/statuslineSetup.js +140 -0
  1260. package/src/tools/AgentTool/built-in/thaddeusGuideAgent.js +174 -0
  1261. package/src/tools/AgentTool/built-in/verificationAgent.js +146 -0
  1262. package/src/tools/AgentTool/builtInAgents.js +56 -0
  1263. package/src/tools/AgentTool/constants.js +11 -0
  1264. package/src/tools/AgentTool/forkSubagent.js +177 -0
  1265. package/src/tools/AgentTool/loadAgentsDir.js +497 -0
  1266. package/src/tools/AgentTool/prompt.js +260 -0
  1267. package/src/tools/AgentTool/resumeAgent.js +182 -0
  1268. package/src/tools/AgentTool/runAgent.js +627 -0
  1269. package/src/tools/AppointmentsTool/AppointmentsTool.js +628 -0
  1270. package/src/tools/AppointmentsTool/constants.js +1 -0
  1271. package/src/tools/AppointmentsTool/prompt.js +15 -0
  1272. package/src/tools/AskUserQuestionTool/AskUserQuestionTool.js +238 -0
  1273. package/src/tools/AskUserQuestionTool/prompt.js +38 -0
  1274. package/src/tools/BashTool/BashTool.js +1009 -0
  1275. package/src/tools/BashTool/BashToolResultMessage.js +169 -0
  1276. package/src/tools/BashTool/UI.js +134 -0
  1277. package/src/tools/BashTool/bashCommandHelpers.js +184 -0
  1278. package/src/tools/BashTool/bashPermissions.js +2023 -0
  1279. package/src/tools/BashTool/bashSecurity.js +2267 -0
  1280. package/src/tools/BashTool/commandSemantics.js +105 -0
  1281. package/src/tools/BashTool/commentLabel.js +14 -0
  1282. package/src/tools/BashTool/destructiveCommandWarning.js +88 -0
  1283. package/src/tools/BashTool/modeValidation.js +86 -0
  1284. package/src/tools/BashTool/pathValidation.js +1079 -0
  1285. package/src/tools/BashTool/prompt.js +333 -0
  1286. package/src/tools/BashTool/readOnlyValidation.js +1794 -0
  1287. package/src/tools/BashTool/sedEditParser.js +282 -0
  1288. package/src/tools/BashTool/sedValidation.js +580 -0
  1289. package/src/tools/BashTool/shouldUseSandbox.js +125 -0
  1290. package/src/tools/BashTool/toolName.js +2 -0
  1291. package/src/tools/BashTool/utils.js +180 -0
  1292. package/src/tools/BriefTool/BriefTool.js +173 -0
  1293. package/src/tools/BriefTool/UI.js +67 -0
  1294. package/src/tools/BriefTool/attachments.js +86 -0
  1295. package/src/tools/BriefTool/prompt.js +19 -0
  1296. package/src/tools/BriefTool/upload.js +136 -0
  1297. package/src/tools/CalendarTool/CalendarTool.js +498 -0
  1298. package/src/tools/CalendarTool/constants.js +1 -0
  1299. package/src/tools/CalendarTool/prompt.js +11 -0
  1300. package/src/tools/ConfigTool/ConfigTool.js +398 -0
  1301. package/src/tools/ConfigTool/UI.js +25 -0
  1302. package/src/tools/ConfigTool/constants.js +1 -0
  1303. package/src/tools/ConfigTool/prompt.js +82 -0
  1304. package/src/tools/ConfigTool/supportedSettings.js +180 -0
  1305. package/src/tools/ContactsTool/ContactsTool.js +648 -0
  1306. package/src/tools/ContactsTool/constants.js +1 -0
  1307. package/src/tools/ContactsTool/prompt.js +15 -0
  1308. package/src/tools/CtxInspectTool/CtxInspectTool.js +44 -0
  1309. package/src/tools/DiscoverSkillsTool/prompt.js +4 -0
  1310. package/src/tools/EmailReadTool/index.js +410 -0
  1311. package/src/tools/EmailSendTool/index.js +178 -0
  1312. package/src/tools/EnterPlanModeTool/EnterPlanModeTool.js +98 -0
  1313. package/src/tools/EnterPlanModeTool/UI.js +14 -0
  1314. package/src/tools/EnterPlanModeTool/constants.js +1 -0
  1315. package/src/tools/EnterPlanModeTool/prompt.js +164 -0
  1316. package/src/tools/EnterWorktreeTool/EnterWorktreeTool.js +104 -0
  1317. package/src/tools/EnterWorktreeTool/UI.js +9 -0
  1318. package/src/tools/EnterWorktreeTool/constants.js +1 -0
  1319. package/src/tools/EnterWorktreeTool/prompt.js +30 -0
  1320. package/src/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js +383 -0
  1321. package/src/tools/ExitPlanModeTool/UI.js +32 -0
  1322. package/src/tools/ExitPlanModeTool/constants.js +2 -0
  1323. package/src/tools/ExitPlanModeTool/prompt.js +27 -0
  1324. package/src/tools/ExitWorktreeTool/ExitWorktreeTool.js +257 -0
  1325. package/src/tools/ExitWorktreeTool/UI.js +10 -0
  1326. package/src/tools/ExitWorktreeTool/constants.js +1 -0
  1327. package/src/tools/ExitWorktreeTool/prompt.js +32 -0
  1328. package/src/tools/FileEditTool/FileEditTool.js +480 -0
  1329. package/src/tools/FileEditTool/UI.js +202 -0
  1330. package/src/tools/FileEditTool/constants.js +7 -0
  1331. package/src/tools/FileEditTool/prompt.js +24 -0
  1332. package/src/tools/FileEditTool/types.js +50 -0
  1333. package/src/tools/FileEditTool/utils.js +579 -0
  1334. package/src/tools/FileReadTool/FileReadTool.js +889 -0
  1335. package/src/tools/FileReadTool/UI.js +126 -0
  1336. package/src/tools/FileReadTool/imageProcessor.js +46 -0
  1337. package/src/tools/FileReadTool/limits.js +70 -0
  1338. package/src/tools/FileReadTool/prompt.js +31 -0
  1339. package/src/tools/FileWriteTool/FileWriteTool.js +341 -0
  1340. package/src/tools/FileWriteTool/UI.js +339 -0
  1341. package/src/tools/FileWriteTool/prompt.js +15 -0
  1342. package/src/tools/GlobTool/GlobTool.js +161 -0
  1343. package/src/tools/GlobTool/UI.js +40 -0
  1344. package/src/tools/GlobTool/prompt.js +6 -0
  1345. package/src/tools/GrepTool/GrepTool.js +439 -0
  1346. package/src/tools/GrepTool/UI.js +155 -0
  1347. package/src/tools/GrepTool/prompt.js +16 -0
  1348. package/src/tools/IntegrationsTool/IntegrationsTool.js +217 -0
  1349. package/src/tools/IntegrationsTool/constants.js +1 -0
  1350. package/src/tools/IntegrationsTool/prompt.js +41 -0
  1351. package/src/tools/InteractionsTool/InteractionsTool.js +525 -0
  1352. package/src/tools/InteractionsTool/constants.js +1 -0
  1353. package/src/tools/InteractionsTool/prompt.js +14 -0
  1354. package/src/tools/InvoicesTool/InvoicesTool.js +581 -0
  1355. package/src/tools/InvoicesTool/constants.js +1 -0
  1356. package/src/tools/InvoicesTool/prompt.js +15 -0
  1357. package/src/tools/LSPTool/LSPTool.js +660 -0
  1358. package/src/tools/LSPTool/UI.js +205 -0
  1359. package/src/tools/LSPTool/formatters.js +445 -0
  1360. package/src/tools/LSPTool/prompt.js +20 -0
  1361. package/src/tools/LSPTool/schemas.js +197 -0
  1362. package/src/tools/LSPTool/symbolContext.js +75 -0
  1363. package/src/tools/LeadScorerTool/LeadScorerTool.js +509 -0
  1364. package/src/tools/LeadScorerTool/constants.js +1 -0
  1365. package/src/tools/LeadScorerTool/prompt.js +11 -0
  1366. package/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +100 -0
  1367. package/src/tools/ListMcpResourcesTool/UI.js +17 -0
  1368. package/src/tools/ListMcpResourcesTool/prompt.js +18 -0
  1369. package/src/tools/ListPeersTool/ListPeersTool.js +45 -0
  1370. package/src/tools/MCPTool/MCPTool.js +60 -0
  1371. package/src/tools/MCPTool/UI.js +343 -0
  1372. package/src/tools/MCPTool/classifyForCollapse.js +597 -0
  1373. package/src/tools/MCPTool/prompt.js +3 -0
  1374. package/src/tools/McpAuthTool/McpAuthTool.js +162 -0
  1375. package/src/tools/MonitorTool/MonitorTool.js +55 -0
  1376. package/src/tools/NotebookEditTool/NotebookEditTool.js +421 -0
  1377. package/src/tools/NotebookEditTool/UI.js +41 -0
  1378. package/src/tools/NotebookEditTool/constants.js +2 -0
  1379. package/src/tools/NotebookEditTool/prompt.js +2 -0
  1380. package/src/tools/OverflowTestTool/OverflowTestTool.js +51 -0
  1381. package/src/tools/PhoneBridgeTool/PhoneBridgeTool.js +301 -0
  1382. package/src/tools/PhoneBridgeTool/constants.js +1 -0
  1383. package/src/tools/PhoneBridgeTool/prompt.js +26 -0
  1384. package/src/tools/PowerShellTool/PowerShellTool.js +900 -0
  1385. package/src/tools/PowerShellTool/UI.js +58 -0
  1386. package/src/tools/PowerShellTool/clmTypes.js +207 -0
  1387. package/src/tools/PowerShellTool/commandSemantics.js +115 -0
  1388. package/src/tools/PowerShellTool/commonParameters.js +27 -0
  1389. package/src/tools/PowerShellTool/destructiveCommandWarning.js +92 -0
  1390. package/src/tools/PowerShellTool/gitSafety.js +185 -0
  1391. package/src/tools/PowerShellTool/modeValidation.js +357 -0
  1392. package/src/tools/PowerShellTool/pathValidation.js +1712 -0
  1393. package/src/tools/PowerShellTool/powershellPermissions.js +1351 -0
  1394. package/src/tools/PowerShellTool/powershellSecurity.js +942 -0
  1395. package/src/tools/PowerShellTool/prompt.js +132 -0
  1396. package/src/tools/PowerShellTool/readOnlyValidation.js +1633 -0
  1397. package/src/tools/PowerShellTool/toolName.js +2 -0
  1398. package/src/tools/PushNotificationTool/PushNotificationTool.js +35 -0
  1399. package/src/tools/REPLTool/REPLTool.js +44 -0
  1400. package/src/tools/REPLTool/constants.js +43 -0
  1401. package/src/tools/REPLTool/primitiveTools.js +36 -0
  1402. package/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +112 -0
  1403. package/src/tools/ReadMcpResourceTool/UI.js +24 -0
  1404. package/src/tools/ReadMcpResourceTool/prompt.js +15 -0
  1405. package/src/tools/RemoteTriggerTool/RemoteTriggerTool.js +142 -0
  1406. package/src/tools/RemoteTriggerTool/UI.js +12 -0
  1407. package/src/tools/RemoteTriggerTool/prompt.js +12 -0
  1408. package/src/tools/ReviewArtifactTool/ReviewArtifactTool.js +51 -0
  1409. package/src/tools/ScheduleCronTool/CronCreateTool.js +120 -0
  1410. package/src/tools/ScheduleCronTool/CronDeleteTool.js +74 -0
  1411. package/src/tools/ScheduleCronTool/CronListTool.js +77 -0
  1412. package/src/tools/ScheduleCronTool/UI.js +29 -0
  1413. package/src/tools/ScheduleCronTool/prompt.js +115 -0
  1414. package/src/tools/SendMessageTool/SendMessageTool.js +673 -0
  1415. package/src/tools/SendMessageTool/UI.js +24 -0
  1416. package/src/tools/SendMessageTool/constants.js +1 -0
  1417. package/src/tools/SendMessageTool/prompt.js +47 -0
  1418. package/src/tools/SendUserFileTool/SendUserFileTool.js +35 -0
  1419. package/src/tools/SendUserFileTool/prompt.js +5 -0
  1420. package/src/tools/SkillTool/SkillTool.js +825 -0
  1421. package/src/tools/SkillTool/UI.js +61 -0
  1422. package/src/tools/SkillTool/constants.js +1 -0
  1423. package/src/tools/SkillTool/prompt.js +184 -0
  1424. package/src/tools/SleepTool/SleepTool.js +42 -0
  1425. package/src/tools/SleepTool/prompt.js +14 -0
  1426. package/src/tools/SnipTool/SnipTool.js +47 -0
  1427. package/src/tools/SnipTool/prompt.js +5 -0
  1428. package/src/tools/SubscribePRTool/SubscribePRTool.js +49 -0
  1429. package/src/tools/SuggestBackgroundPRTool/SuggestBackgroundPRTool.js +44 -0
  1430. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.js +138 -0
  1431. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.ts +1 -1
  1432. package/src/tools/TaskCreateTool/TaskCreateTool.js +104 -0
  1433. package/src/tools/TaskCreateTool/constants.js +1 -0
  1434. package/src/tools/TaskCreateTool/prompt.js +52 -0
  1435. package/src/tools/TaskGetTool/TaskGetTool.js +106 -0
  1436. package/src/tools/TaskGetTool/constants.js +1 -0
  1437. package/src/tools/TaskGetTool/prompt.js +23 -0
  1438. package/src/tools/TaskListTool/TaskListTool.js +89 -0
  1439. package/src/tools/TaskListTool/constants.js +1 -0
  1440. package/src/tools/TaskListTool/prompt.js +44 -0
  1441. package/src/tools/TaskOutputTool/TaskOutputTool.js +536 -0
  1442. package/src/tools/TaskOutputTool/constants.js +1 -0
  1443. package/src/tools/TaskStopTool/TaskStopTool.js +110 -0
  1444. package/src/tools/TaskStopTool/UI.js +31 -0
  1445. package/src/tools/TaskStopTool/prompt.js +7 -0
  1446. package/src/tools/TaskUpdateTool/TaskUpdateTool.js +301 -0
  1447. package/src/tools/TaskUpdateTool/constants.js +1 -0
  1448. package/src/tools/TaskUpdateTool/prompt.js +76 -0
  1449. package/src/tools/TeamCreateTool/TeamCreateTool.js +177 -0
  1450. package/src/tools/TeamCreateTool/UI.js +4 -0
  1451. package/src/tools/TeamCreateTool/constants.js +1 -0
  1452. package/src/tools/TeamCreateTool/prompt.js +113 -0
  1453. package/src/tools/TeamDeleteTool/TeamDeleteTool.js +102 -0
  1454. package/src/tools/TeamDeleteTool/UI.js +13 -0
  1455. package/src/tools/TeamDeleteTool/constants.js +1 -0
  1456. package/src/tools/TeamDeleteTool/prompt.js +16 -0
  1457. package/src/tools/TerminalCaptureTool/TerminalCaptureTool.js +47 -0
  1458. package/src/tools/TerminalCaptureTool/prompt.js +11 -0
  1459. package/src/tools/TodoWriteTool/TodoWriteTool.js +99 -0
  1460. package/src/tools/TodoWriteTool/constants.js +1 -0
  1461. package/src/tools/TodoWriteTool/prompt.js +181 -0
  1462. package/src/tools/ToolSearchTool/ToolSearchTool.js +357 -0
  1463. package/src/tools/ToolSearchTool/constants.js +1 -0
  1464. package/src/tools/ToolSearchTool/prompt.js +97 -0
  1465. package/src/tools/TungstenTool/TungstenLiveMonitor.js +7 -0
  1466. package/src/tools/TungstenTool/TungstenTool.js +3 -0
  1467. package/src/tools/VerifyPlanExecutionTool/VerifyPlanExecutionTool.js +45 -0
  1468. package/src/tools/VerifyPlanExecutionTool/constants.js +2 -0
  1469. package/src/tools/WebBrowserTool/WebBrowserPanel.js +5 -0
  1470. package/src/tools/WebBrowserTool/WebBrowserTool.js +58 -0
  1471. package/src/tools/WebFetchTool/UI.js +31 -0
  1472. package/src/tools/WebFetchTool/WebFetchTool.js +246 -0
  1473. package/src/tools/WebFetchTool/preapproved.js +154 -0
  1474. package/src/tools/WebFetchTool/prompt.js +39 -0
  1475. package/src/tools/WebFetchTool/utils.js +368 -0
  1476. package/src/tools/WebSearchTool/UI.js +67 -0
  1477. package/src/tools/WebSearchTool/WebSearchTool.js +396 -0
  1478. package/src/tools/WebSearchTool/prompt.js +32 -0
  1479. package/src/tools/WorkflowTool/WorkflowPermissionRequest.js +7 -0
  1480. package/src/tools/WorkflowTool/WorkflowTool.js +51 -0
  1481. package/src/tools/WorkflowTool/bundled/index.js +5 -0
  1482. package/src/tools/WorkflowTool/constants.js +1 -0
  1483. package/src/tools/WorkflowTool/createWorkflowCommand.js +5 -0
  1484. package/src/tools/shared/gitOperationTracking.js +220 -0
  1485. package/src/tools/shared/spawnMultiAgent.js +805 -0
  1486. package/src/tools/testing/TestingPermissionTool.js +72 -0
  1487. package/src/tools/utils.js +24 -0
  1488. package/src/tools.js +365 -0
  1489. package/src/types/command.js +8 -0
  1490. package/src/types/connectorText.js +3 -0
  1491. package/src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.js +673 -0
  1492. package/src/types/generated/events_mono/common/v1/auth.js +49 -0
  1493. package/src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.js +147 -0
  1494. package/src/types/generated/google/protobuf/timestamp.js +38 -0
  1495. package/src/types/hooks.js +153 -0
  1496. package/src/types/ids.js +27 -0
  1497. package/src/types/logs.js +11 -0
  1498. package/src/types/permissions.js +25 -0
  1499. package/src/types/plugin.js +72 -0
  1500. package/src/types/textInputTypes.js +20 -0
  1501. package/src/upstreamproxy/relay.js +346 -0
  1502. package/src/upstreamproxy/upstreamproxy.js +234 -0
  1503. package/src/utils/CircularBuffer.js +75 -0
  1504. package/src/utils/Cursor.js +1229 -0
  1505. package/src/utils/QueryGuard.js +115 -0
  1506. package/src/utils/Shell.js +374 -0
  1507. package/src/utils/ShellCommand.js +336 -0
  1508. package/src/utils/abortController.js +74 -0
  1509. package/src/utils/activityManager.js +127 -0
  1510. package/src/utils/advisor.js +77 -0
  1511. package/src/utils/agentContext.js +91 -0
  1512. package/src/utils/agentId.js +83 -0
  1513. package/src/utils/agentSwarmsEnabled.js +37 -0
  1514. package/src/utils/agenticSessionSearch.js +255 -0
  1515. package/src/utils/analyzeContext.js +846 -0
  1516. package/src/utils/ansiToPng.js +259 -0
  1517. package/src/utils/ansiToSvg.js +207 -0
  1518. package/src/utils/api.js +555 -0
  1519. package/src/utils/apiPreconnect.js +62 -0
  1520. package/src/utils/appleTerminalBackup.js +95 -0
  1521. package/src/utils/argumentSubstitution.js +114 -0
  1522. package/src/utils/array.js +12 -0
  1523. package/src/utils/asciicast.js +200 -0
  1524. package/src/utils/attachments.js +2518 -0
  1525. package/src/utils/attribution.js +308 -0
  1526. package/src/utils/auth.js +1598 -0
  1527. package/src/utils/authFileDescriptor.js +152 -0
  1528. package/src/utils/authPortable.js +14 -0
  1529. package/src/utils/autoModeDenials.js +15 -0
  1530. package/src/utils/autoRunIssue.js +113 -0
  1531. package/src/utils/autoUpdater.js +457 -0
  1532. package/src/utils/aws.js +44 -0
  1533. package/src/utils/awsAuthStatusManager.js +66 -0
  1534. package/src/utils/background/remote/preconditions.js +175 -0
  1535. package/src/utils/background/remote/remoteSession.js +53 -0
  1536. package/src/utils/backgroundHousekeeping.js +64 -0
  1537. package/src/utils/bash/ParsedCommand.js +241 -0
  1538. package/src/utils/bash/ShellSnapshot.js +489 -0
  1539. package/src/utils/bash/ast.js +2590 -0
  1540. package/src/utils/bash/bashParser.js +4355 -0
  1541. package/src/utils/bash/bashPipeCommand.js +249 -0
  1542. package/src/utils/bash/commands.js +1131 -0
  1543. package/src/utils/bash/heredoc.js +647 -0
  1544. package/src/utils/bash/parser.js +195 -0
  1545. package/src/utils/bash/prefix.js +154 -0
  1546. package/src/utils/bash/registry.js +23 -0
  1547. package/src/utils/bash/shellCompletion.js +196 -0
  1548. package/src/utils/bash/shellPrefix.js +25 -0
  1549. package/src/utils/bash/shellQuote.js +253 -0
  1550. package/src/utils/bash/shellQuoting.js +106 -0
  1551. package/src/utils/bash/specs/alias.js +11 -0
  1552. package/src/utils/bash/specs/index.js +16 -0
  1553. package/src/utils/bash/specs/nohup.js +10 -0
  1554. package/src/utils/bash/specs/pyright.js +88 -0
  1555. package/src/utils/bash/specs/sleep.js +10 -0
  1556. package/src/utils/bash/specs/srun.js +28 -0
  1557. package/src/utils/bash/specs/time.js +10 -0
  1558. package/src/utils/bash/specs/timeout.js +17 -0
  1559. package/src/utils/bash/treeSitterAnalysis.js +407 -0
  1560. package/src/utils/betas.js +331 -0
  1561. package/src/utils/billing.js +54 -0
  1562. package/src/utils/binaryCheck.js +40 -0
  1563. package/src/utils/browser.js +58 -0
  1564. package/src/utils/bufferedWriter.js +77 -0
  1565. package/src/utils/bundledMode.js +19 -0
  1566. package/src/utils/businessDb.js +390 -0
  1567. package/src/utils/caCerts.js +91 -0
  1568. package/src/utils/caCertsConfig.js +77 -0
  1569. package/src/utils/cachePaths.js +28 -0
  1570. package/src/utils/classifierApprovals.js +66 -0
  1571. package/src/utils/classifierApprovalsHook.js +10 -0
  1572. package/src/utils/claudeDesktop.js +108 -0
  1573. package/src/utils/claudeInChrome/chromeNativeHost.js +416 -0
  1574. package/src/utils/claudeInChrome/common.js +466 -0
  1575. package/src/utils/claudeInChrome/mcpServer.js +237 -0
  1576. package/src/utils/claudeInChrome/prompt.js +79 -0
  1577. package/src/utils/claudeInChrome/setup.js +304 -0
  1578. package/src/utils/claudeInChrome/setupPortable.js +172 -0
  1579. package/src/utils/claudeInChrome/toolRendering.js +235 -0
  1580. package/src/utils/claudemd.js +1052 -0
  1581. package/src/utils/cleanup.js +514 -0
  1582. package/src/utils/cleanupRegistry.js +22 -0
  1583. package/src/utils/cliArgs.js +53 -0
  1584. package/src/utils/cliHighlight.js +45 -0
  1585. package/src/utils/codeIndexing.js +149 -0
  1586. package/src/utils/collapseBackgroundBashNotifications.js +70 -0
  1587. package/src/utils/collapseHookSummaries.js +48 -0
  1588. package/src/utils/collapseReadSearch.js +869 -0
  1589. package/src/utils/collapseTeammateShutdowns.js +44 -0
  1590. package/src/utils/combinedAbortSignal.js +40 -0
  1591. package/src/utils/commandLifecycle.js +7 -0
  1592. package/src/utils/commitAttribution.js +718 -0
  1593. package/src/utils/completionCache.js +138 -0
  1594. package/src/utils/computerUse/appNames.js +170 -0
  1595. package/src/utils/computerUse/cleanup.js +65 -0
  1596. package/src/utils/computerUse/common.js +56 -0
  1597. package/src/utils/computerUse/computerUseLock.js +183 -0
  1598. package/src/utils/computerUse/drainRunLoop.js +71 -0
  1599. package/src/utils/computerUse/escHotkey.js +53 -0
  1600. package/src/utils/computerUse/executor.js +480 -0
  1601. package/src/utils/computerUse/gates.js +55 -0
  1602. package/src/utils/computerUse/hostAdapter.js +62 -0
  1603. package/src/utils/computerUse/inputLoader.js +25 -0
  1604. package/src/utils/computerUse/mcpServer.js +84 -0
  1605. package/src/utils/computerUse/setup.js +42 -0
  1606. package/src/utils/computerUse/swiftLoader.js +18 -0
  1607. package/src/utils/computerUse/toolRendering.js +101 -0
  1608. package/src/utils/computerUse/wrapper.js +317 -0
  1609. package/src/utils/concurrentSessions.js +179 -0
  1610. package/src/utils/config.js +1078 -0
  1611. package/src/utils/configConstants.js +18 -0
  1612. package/src/utils/contentArray.js +45 -0
  1613. package/src/utils/context.js +185 -0
  1614. package/src/utils/contextAnalysis.js +171 -0
  1615. package/src/utils/contextSuggestions.js +158 -0
  1616. package/src/utils/controlMessageCompat.js +31 -0
  1617. package/src/utils/conversationRecovery.js +434 -0
  1618. package/src/utils/cron.js +260 -0
  1619. package/src/utils/cronJitterConfig.js +62 -0
  1620. package/src/utils/cronScheduler.js +388 -0
  1621. package/src/utils/cronTasks.js +328 -0
  1622. package/src/utils/cronTasksLock.js +159 -0
  1623. package/src/utils/crossProjectResume.js +46 -0
  1624. package/src/utils/crypto.js +13 -0
  1625. package/src/utils/cwd.js +29 -0
  1626. package/src/utils/debug.js +220 -0
  1627. package/src/utils/debugFilter.js +125 -0
  1628. package/src/utils/deepLink/banner.js +103 -0
  1629. package/src/utils/deepLink/parseDeepLink.js +138 -0
  1630. package/src/utils/deepLink/protocolHandler.js +119 -0
  1631. package/src/utils/deepLink/registerProtocol.js +291 -0
  1632. package/src/utils/deepLink/terminalLauncher.js +455 -0
  1633. package/src/utils/deepLink/terminalPreference.js +51 -0
  1634. package/src/utils/desktopDeepLink.js +208 -0
  1635. package/src/utils/detectRepository.js +157 -0
  1636. package/src/utils/diagLogs.js +74 -0
  1637. package/src/utils/diff.js +108 -0
  1638. package/src/utils/directMemberMessage.js +34 -0
  1639. package/src/utils/displayTags.js +46 -0
  1640. package/src/utils/doctorContextWarnings.js +179 -0
  1641. package/src/utils/doctorDiagnostic.js +494 -0
  1642. package/src/utils/dxt/helpers.js +64 -0
  1643. package/src/utils/dxt/zip.js +167 -0
  1644. package/src/utils/earlyInput.js +166 -0
  1645. package/src/utils/editor.js +163 -0
  1646. package/src/utils/effort.js +271 -0
  1647. package/src/utils/embeddedTools.js +26 -0
  1648. package/src/utils/employeeChat.js +271 -0
  1649. package/src/utils/employeeDb.js +326 -0
  1650. package/src/utils/env.js +358 -0
  1651. package/src/utils/envDynamic.js +130 -0
  1652. package/src/utils/envUtils.js +161 -0
  1653. package/src/utils/envValidation.js +26 -0
  1654. package/src/utils/errorLogSink.js +196 -0
  1655. package/src/utils/errors.js +207 -0
  1656. package/src/utils/exampleCommands.js +165 -0
  1657. package/src/utils/execFileNoThrow.js +93 -0
  1658. package/src/utils/execFileNoThrowPortable.js +49 -0
  1659. package/src/utils/execSyncWrapper.js +6 -0
  1660. package/src/utils/exportRenderer.js +71 -0
  1661. package/src/utils/extraUsage.js +19 -0
  1662. package/src/utils/fastMode.js +393 -0
  1663. package/src/utils/file.js +467 -0
  1664. package/src/utils/fileHistory.js +851 -0
  1665. package/src/utils/fileOperationAnalytics.js +45 -0
  1666. package/src/utils/filePersistence/filePersistence.js +212 -0
  1667. package/src/utils/filePersistence/outputsScanner.js +104 -0
  1668. package/src/utils/filePersistence/types.js +4 -0
  1669. package/src/utils/fileRead.js +81 -0
  1670. package/src/utils/fileReadCache.js +78 -0
  1671. package/src/utils/fileStateCache.js +99 -0
  1672. package/src/utils/findExecutable.js +13 -0
  1673. package/src/utils/fingerprint.js +58 -0
  1674. package/src/utils/forkedAgent.js +410 -0
  1675. package/src/utils/format.js +238 -0
  1676. package/src/utils/formatBriefTimestamp.js +72 -0
  1677. package/src/utils/fpsTracker.js +34 -0
  1678. package/src/utils/frontmatterParser.js +260 -0
  1679. package/src/utils/fsOperations.js +555 -0
  1680. package/src/utils/fullscreen.js +194 -0
  1681. package/src/utils/generatedFiles.js +122 -0
  1682. package/src/utils/generators.js +67 -0
  1683. package/src/utils/genericProcessUtils.js +155 -0
  1684. package/src/utils/getWorktreePaths.js +56 -0
  1685. package/src/utils/getWorktreePathsPortable.js +23 -0
  1686. package/src/utils/ghPrStatus.js +71 -0
  1687. package/src/utils/git/gitConfigParser.js +226 -0
  1688. package/src/utils/git/gitFilesystem.js +606 -0
  1689. package/src/utils/git/gitignore.js +84 -0
  1690. package/src/utils/git.js +725 -0
  1691. package/src/utils/gitDiff.js +395 -0
  1692. package/src/utils/gitSettings.js +18 -0
  1693. package/src/utils/github/ghAuthStatus.js +23 -0
  1694. package/src/utils/githubRepoPathMapping.js +135 -0
  1695. package/src/utils/glob.js +90 -0
  1696. package/src/utils/gracefulShutdown.js +447 -0
  1697. package/src/utils/groupToolUses.js +126 -0
  1698. package/src/utils/handlePromptSubmit.js +398 -0
  1699. package/src/utils/hash.js +44 -0
  1700. package/src/utils/headlessProfiler.js +147 -0
  1701. package/src/utils/heapDumpService.js +201 -0
  1702. package/src/utils/heatmap.js +151 -0
  1703. package/src/utils/highlightMatch.js +29 -0
  1704. package/src/utils/hooks/AsyncHookRegistry.js +187 -0
  1705. package/src/utils/hooks/apiQueryHookHelper.js +77 -0
  1706. package/src/utils/hooks/execAgentHook.js +257 -0
  1707. package/src/utils/hooks/execHttpHook.js +184 -0
  1708. package/src/utils/hooks/execPromptHook.js +171 -0
  1709. package/src/utils/hooks/fileChangedWatcher.js +161 -0
  1710. package/src/utils/hooks/hookEvents.js +111 -0
  1711. package/src/utils/hooks/hookHelpers.js +60 -0
  1712. package/src/utils/hooks/hooksConfigManager.js +323 -0
  1713. package/src/utils/hooks/hooksConfigSnapshot.js +114 -0
  1714. package/src/utils/hooks/hooksSettings.js +204 -0
  1715. package/src/utils/hooks/postSamplingHooks.js +39 -0
  1716. package/src/utils/hooks/registerFrontmatterHooks.js +47 -0
  1717. package/src/utils/hooks/registerSkillHooks.js +40 -0
  1718. package/src/utils/hooks/sessionHooks.js +252 -0
  1719. package/src/utils/hooks/skillImprovement.js +211 -0
  1720. package/src/utils/hooks/ssrfGuard.js +258 -0
  1721. package/src/utils/hooks.js +3668 -0
  1722. package/src/utils/horizontalScroll.js +108 -0
  1723. package/src/utils/http.js +120 -0
  1724. package/src/utils/hyperlink.js +28 -0
  1725. package/src/utils/iTermBackup.js +48 -0
  1726. package/src/utils/ide.js +1195 -0
  1727. package/src/utils/idePathConversion.js +66 -0
  1728. package/src/utils/idleTimeout.js +44 -0
  1729. package/src/utils/imagePaste.js +343 -0
  1730. package/src/utils/imageResizer.js +664 -0
  1731. package/src/utils/imageStore.js +150 -0
  1732. package/src/utils/imageValidation.js +92 -0
  1733. package/src/utils/immediateCommand.js +12 -0
  1734. package/src/utils/inProcessTeammateHelpers.js +71 -0
  1735. package/src/utils/ink.js +20 -0
  1736. package/src/utils/intl.js +83 -0
  1737. package/src/utils/jetbrains.js +152 -0
  1738. package/src/utils/json.js +231 -0
  1739. package/src/utils/jsonRead.js +14 -0
  1740. package/src/utils/keyboardShortcuts.js +11 -0
  1741. package/src/utils/lazySchema.js +8 -0
  1742. package/src/utils/listSessionsImpl.js +332 -0
  1743. package/src/utils/localInstaller.js +130 -0
  1744. package/src/utils/lockfile.js +30 -0
  1745. package/src/utils/log.js +280 -0
  1746. package/src/utils/logoV2Utils.js +256 -0
  1747. package/src/utils/mailbox.js +50 -0
  1748. package/src/utils/managedEnv.js +160 -0
  1749. package/src/utils/managedEnvConstants.js +185 -0
  1750. package/src/utils/markdown.js +315 -0
  1751. package/src/utils/markdownConfigLoader.js +480 -0
  1752. package/src/utils/mcp/dateTimeParser.js +102 -0
  1753. package/src/utils/mcp/elicitationValidation.js +259 -0
  1754. package/src/utils/mcpInstructionsDelta.js +97 -0
  1755. package/src/utils/mcpOutputStorage.js +159 -0
  1756. package/src/utils/mcpValidation.js +165 -0
  1757. package/src/utils/mcpWebSocketTransport.js +180 -0
  1758. package/src/utils/memoize.js +205 -0
  1759. package/src/utils/memory/types.js +9 -0
  1760. package/src/utils/memory/versions.js +7 -0
  1761. package/src/utils/memoryFileDetection.js +245 -0
  1762. package/src/utils/messagePredicates.js +6 -0
  1763. package/src/utils/messageQueueManager.js +430 -0
  1764. package/src/utils/messages/mappers.js +240 -0
  1765. package/src/utils/messages/systemInit.js +72 -0
  1766. package/src/utils/messages.js +4286 -0
  1767. package/src/utils/model/agent.js +128 -0
  1768. package/src/utils/model/aliases.js +21 -0
  1769. package/src/utils/model/antModels.js +25 -0
  1770. package/src/utils/model/bedrock.js +220 -0
  1771. package/src/utils/model/check1mAccess.js +64 -0
  1772. package/src/utils/model/configs.js +86 -0
  1773. package/src/utils/model/contextWindowUpgradeCheck.js +41 -0
  1774. package/src/utils/model/deprecation.js +72 -0
  1775. package/src/utils/model/model.js +533 -0
  1776. package/src/utils/model/modelAllowlist.js +148 -0
  1777. package/src/utils/model/modelCapabilities.js +105 -0
  1778. package/src/utils/model/modelOptions.js +450 -0
  1779. package/src/utils/model/modelStrings.js +144 -0
  1780. package/src/utils/model/modelSupportOverrides.js +40 -0
  1781. package/src/utils/model/providers.js +35 -0
  1782. package/src/utils/model/validateModel.js +131 -0
  1783. package/src/utils/modelCost.js +160 -0
  1784. package/src/utils/modifiers.js +39 -0
  1785. package/src/utils/mtls.js +132 -0
  1786. package/src/utils/nativeInstaller/download.js +370 -0
  1787. package/src/utils/nativeInstaller/index.js +8 -0
  1788. package/src/utils/nativeInstaller/installer.js +1395 -0
  1789. package/src/utils/nativeInstaller/packageManagers.js +258 -0
  1790. package/src/utils/nativeInstaller/pidLock.js +347 -0
  1791. package/src/utils/notebook.js +176 -0
  1792. package/src/utils/objectGroupBy.js +15 -0
  1793. package/src/utils/pasteStore.js +93 -0
  1794. package/src/utils/path.js +140 -0
  1795. package/src/utils/pdf.js +236 -0
  1796. package/src/utils/pdfUtils.js +61 -0
  1797. package/src/utils/peerAddress.js +20 -0
  1798. package/src/utils/permissions/PermissionMode.js +95 -0
  1799. package/src/utils/permissions/PermissionPromptToolResultSchema.js +85 -0
  1800. package/src/utils/permissions/PermissionResult.js +11 -0
  1801. package/src/utils/permissions/PermissionRule.js +19 -0
  1802. package/src/utils/permissions/PermissionUpdate.js +268 -0
  1803. package/src/utils/permissions/PermissionUpdateSchema.js +61 -0
  1804. package/src/utils/permissions/autoModeState.js +31 -0
  1805. package/src/utils/permissions/bashClassifier.js +30 -0
  1806. package/src/utils/permissions/bypassPermissionsKillswitch.js +115 -0
  1807. package/src/utils/permissions/classifierDecision.js +86 -0
  1808. package/src/utils/permissions/classifierShared.js +28 -0
  1809. package/src/utils/permissions/dangerousPatterns.js +78 -0
  1810. package/src/utils/permissions/denialTracking.js +34 -0
  1811. package/src/utils/permissions/filesystem.js +1411 -0
  1812. package/src/utils/permissions/getNextPermissionMode.js +74 -0
  1813. package/src/utils/permissions/pathValidation.js +351 -0
  1814. package/src/utils/permissions/permissionExplainer.js +188 -0
  1815. package/src/utils/permissions/permissionRuleParser.js +175 -0
  1816. package/src/utils/permissions/permissionSetup.js +1162 -0
  1817. package/src/utils/permissions/permissions.js +1063 -0
  1818. package/src/utils/permissions/permissionsLoader.js +217 -0
  1819. package/src/utils/permissions/shadowedRuleDetection.js +149 -0
  1820. package/src/utils/permissions/shellRuleMatching.js +174 -0
  1821. package/src/utils/permissions/yoloClassifier.js +1193 -0
  1822. package/src/utils/planModeV2.js +75 -0
  1823. package/src/utils/plans.js +334 -0
  1824. package/src/utils/platform.js +122 -0
  1825. package/src/utils/plugins/addDirPluginSettings.js +53 -0
  1826. package/src/utils/plugins/cacheUtils.js +174 -0
  1827. package/src/utils/plugins/dependencyResolver.js +244 -0
  1828. package/src/utils/plugins/fetchTelemetry.js +108 -0
  1829. package/src/utils/plugins/gitAvailability.js +65 -0
  1830. package/src/utils/plugins/headlessPluginInstall.js +136 -0
  1831. package/src/utils/plugins/hintRecommendation.js +136 -0
  1832. package/src/utils/plugins/installCounts.js +221 -0
  1833. package/src/utils/plugins/installedPluginsManager.js +1003 -0
  1834. package/src/utils/plugins/loadPluginAgents.js +219 -0
  1835. package/src/utils/plugins/loadPluginCommands.js +595 -0
  1836. package/src/utils/plugins/loadPluginHooks.js +239 -0
  1837. package/src/utils/plugins/loadPluginOutputStyles.js +112 -0
  1838. package/src/utils/plugins/lspPluginIntegration.js +293 -0
  1839. package/src/utils/plugins/lspRecommendation.js +278 -0
  1840. package/src/utils/plugins/managedPlugins.js +26 -0
  1841. package/src/utils/plugins/marketplaceHelpers.js +470 -0
  1842. package/src/utils/plugins/marketplaceManager.js +1939 -0
  1843. package/src/utils/plugins/mcpPluginIntegration.js +465 -0
  1844. package/src/utils/plugins/mcpbHandler.js +708 -0
  1845. package/src/utils/plugins/officialMarketplace.js +19 -0
  1846. package/src/utils/plugins/officialMarketplaceGcs.js +202 -0
  1847. package/src/utils/plugins/officialMarketplaceStartupCheck.js +344 -0
  1848. package/src/utils/plugins/orphanedPluginFilter.js +96 -0
  1849. package/src/utils/plugins/parseMarketplaceInput.js +143 -0
  1850. package/src/utils/plugins/performStartupChecks.js +66 -0
  1851. package/src/utils/plugins/pluginAutoupdate.js +210 -0
  1852. package/src/utils/plugins/pluginBlocklist.js +93 -0
  1853. package/src/utils/plugins/pluginDirectories.js +170 -0
  1854. package/src/utils/plugins/pluginFlagging.js +173 -0
  1855. package/src/utils/plugins/pluginIdentifier.js +78 -0
  1856. package/src/utils/plugins/pluginInstallationHelpers.js +400 -0
  1857. package/src/utils/plugins/pluginLoader.js +2426 -0
  1858. package/src/utils/plugins/pluginOptionsStorage.js +311 -0
  1859. package/src/utils/plugins/pluginPolicy.js +18 -0
  1860. package/src/utils/plugins/pluginStartupCheck.js +261 -0
  1861. package/src/utils/plugins/pluginVersioning.js +128 -0
  1862. package/src/utils/plugins/reconciler.js +181 -0
  1863. package/src/utils/plugins/refresh.js +162 -0
  1864. package/src/utils/plugins/schemas.js +1283 -0
  1865. package/src/utils/plugins/validatePlugin.js +765 -0
  1866. package/src/utils/plugins/walkPluginMarkdown.js +49 -0
  1867. package/src/utils/plugins/zipCache.js +346 -0
  1868. package/src/utils/plugins/zipCacheAdapters.js +133 -0
  1869. package/src/utils/powershell/dangerousCmdlets.js +174 -0
  1870. package/src/utils/powershell/parser.js +1357 -0
  1871. package/src/utils/powershell/staticPrefix.js +277 -0
  1872. package/src/utils/preflightChecks.js +147 -0
  1873. package/src/utils/privacyLevel.js +49 -0
  1874. package/src/utils/process.js +56 -0
  1875. package/src/utils/processUserInput/processBashCommand.js +118 -0
  1876. package/src/utils/processUserInput/processSlashCommand.js +845 -0
  1877. package/src/utils/processUserInput/processTextPrompt.js +68 -0
  1878. package/src/utils/processUserInput/processUserInput.js +344 -0
  1879. package/src/utils/profilerBase.js +32 -0
  1880. package/src/utils/promptCategory.js +39 -0
  1881. package/src/utils/promptEditor.js +151 -0
  1882. package/src/utils/promptShellExecution.js +117 -0
  1883. package/src/utils/protectedNamespace.js +4 -0
  1884. package/src/utils/proxy.js +345 -0
  1885. package/src/utils/queryContext.js +110 -0
  1886. package/src/utils/queryHelpers.js +436 -0
  1887. package/src/utils/queryProfiler.js +242 -0
  1888. package/src/utils/queueProcessor.js +70 -0
  1889. package/src/utils/readEditContext.js +176 -0
  1890. package/src/utils/readFileInRange.js +278 -0
  1891. package/src/utils/releaseNotes.js +307 -0
  1892. package/src/utils/renderOptions.js +67 -0
  1893. package/src/utils/ripgrep.js +521 -0
  1894. package/src/utils/sandbox/sandbox-adapter.js +750 -0
  1895. package/src/utils/sandbox/sandbox-ui-utils.js +11 -0
  1896. package/src/utils/sanitization.js +72 -0
  1897. package/src/utils/screenshotClipboard.js +89 -0
  1898. package/src/utils/sdkEventQueue.js +49 -0
  1899. package/src/utils/secureStorage/fallbackStorage.js +59 -0
  1900. package/src/utils/secureStorage/index.js +13 -0
  1901. package/src/utils/secureStorage/keychainPrefetch.js +91 -0
  1902. package/src/utils/secureStorage/macOsKeychainHelpers.js +91 -0
  1903. package/src/utils/secureStorage/macOsKeychainStorage.js +192 -0
  1904. package/src/utils/secureStorage/plainTextStorage.js +81 -0
  1905. package/src/utils/semanticBoolean.js +23 -0
  1906. package/src/utils/semanticNumber.js +34 -0
  1907. package/src/utils/semver.js +51 -0
  1908. package/src/utils/sequential.js +43 -0
  1909. package/src/utils/sessionActivity.js +120 -0
  1910. package/src/utils/sessionEnvVars.js +18 -0
  1911. package/src/utils/sessionEnvironment.js +131 -0
  1912. package/src/utils/sessionFileAccessHooks.js +205 -0
  1913. package/src/utils/sessionIngressAuth.js +113 -0
  1914. package/src/utils/sessionRestore.js +357 -0
  1915. package/src/utils/sessionStart.js +165 -0
  1916. package/src/utils/sessionState.js +76 -0
  1917. package/src/utils/sessionStorage.js +4162 -0
  1918. package/src/utils/sessionStoragePortable.js +665 -0
  1919. package/src/utils/sessionTitle.js +120 -0
  1920. package/src/utils/sessionUrl.js +50 -0
  1921. package/src/utils/set.js +50 -0
  1922. package/src/utils/settings/allErrors.js +29 -0
  1923. package/src/utils/settings/applySettingsChange.js +65 -0
  1924. package/src/utils/settings/changeDetector.js +409 -0
  1925. package/src/utils/settings/constants.js +166 -0
  1926. package/src/utils/settings/internalWrites.js +33 -0
  1927. package/src/utils/settings/managedPath.js +29 -0
  1928. package/src/utils/settings/mdm/constants.js +62 -0
  1929. package/src/utils/settings/mdm/rawRead.js +97 -0
  1930. package/src/utils/settings/mdm/settings.js +254 -0
  1931. package/src/utils/settings/permissionValidation.js +224 -0
  1932. package/src/utils/settings/pluginOnlyPolicy.js +53 -0
  1933. package/src/utils/settings/schemaOutput.js +7 -0
  1934. package/src/utils/settings/settings.js +791 -0
  1935. package/src/utils/settings/settingsCache.js +47 -0
  1936. package/src/utils/settings/toolValidationConfig.js +76 -0
  1937. package/src/utils/settings/types.js +846 -0
  1938. package/src/utils/settings/validateEditTool.js +34 -0
  1939. package/src/utils/settings/validation.js +192 -0
  1940. package/src/utils/settings/validationTips.js +111 -0
  1941. package/src/utils/shell/bashProvider.js +202 -0
  1942. package/src/utils/shell/outputLimits.js +7 -0
  1943. package/src/utils/shell/powershellDetection.js +96 -0
  1944. package/src/utils/shell/powershellProvider.js +104 -0
  1945. package/src/utils/shell/prefix.js +246 -0
  1946. package/src/utils/shell/readOnlyCommandValidation.js +1776 -0
  1947. package/src/utils/shell/resolveDefaultShell.js +13 -0
  1948. package/src/utils/shell/shellProvider.js +2 -0
  1949. package/src/utils/shell/shellToolUtils.js +21 -0
  1950. package/src/utils/shell/specPrefix.js +198 -0
  1951. package/src/utils/shellConfig.js +136 -0
  1952. package/src/utils/sideQuery.js +134 -0
  1953. package/src/utils/sideQuestion.js +121 -0
  1954. package/src/utils/signal.js +34 -0
  1955. package/src/utils/sinks.js +15 -0
  1956. package/src/utils/skills/skillChangeDetector.js +264 -0
  1957. package/src/utils/slashCommandParsing.js +46 -0
  1958. package/src/utils/sleep.js +72 -0
  1959. package/src/utils/sliceAnsi.js +74 -0
  1960. package/src/utils/slowOperations.js +216 -0
  1961. package/src/utils/standaloneAgent.js +20 -0
  1962. package/src/utils/startupProfiler.js +149 -0
  1963. package/src/utils/staticRender.js +104 -0
  1964. package/src/utils/stats.js +802 -0
  1965. package/src/utils/statsCache.js +330 -0
  1966. package/src/utils/status.js +359 -0
  1967. package/src/utils/statusNoticeDefinitions.js +123 -0
  1968. package/src/utils/statusNoticeHelpers.js +15 -0
  1969. package/src/utils/stream.js +73 -0
  1970. package/src/utils/streamJsonStdoutGuard.js +107 -0
  1971. package/src/utils/streamlinedTransform.js +162 -0
  1972. package/src/utils/stringUtils.js +202 -0
  1973. package/src/utils/subprocessEnv.js +87 -0
  1974. package/src/utils/suggestions/commandSuggestions.js +458 -0
  1975. package/src/utils/suggestions/directoryCompletion.js +191 -0
  1976. package/src/utils/suggestions/shellHistoryCompletion.js +95 -0
  1977. package/src/utils/suggestions/skillUsageTracking.js +50 -0
  1978. package/src/utils/suggestions/slackChannelSuggestions.js +169 -0
  1979. package/src/utils/swarm/It2SetupPrompt.js +386 -0
  1980. package/src/utils/swarm/backends/ITermBackend.js +276 -0
  1981. package/src/utils/swarm/backends/InProcessBackend.js +237 -0
  1982. package/src/utils/swarm/backends/PaneBackendExecutor.js +250 -0
  1983. package/src/utils/swarm/backends/TmuxBackend.js +574 -0
  1984. package/src/utils/swarm/backends/detection.js +112 -0
  1985. package/src/utils/swarm/backends/it2Setup.js +185 -0
  1986. package/src/utils/swarm/backends/registry.js +369 -0
  1987. package/src/utils/swarm/backends/teammateModeSnapshot.js +68 -0
  1988. package/src/utils/swarm/backends/types.js +9 -0
  1989. package/src/utils/swarm/constants.js +29 -0
  1990. package/src/utils/swarm/inProcessRunner.js +1021 -0
  1991. package/src/utils/swarm/leaderPermissionBridge.js +31 -0
  1992. package/src/utils/swarm/permissionSync.js +667 -0
  1993. package/src/utils/swarm/reconnection.js +82 -0
  1994. package/src/utils/swarm/spawnInProcess.js +218 -0
  1995. package/src/utils/swarm/spawnUtils.js +123 -0
  1996. package/src/utils/swarm/teamHelpers.js +484 -0
  1997. package/src/utils/swarm/teammateInit.js +87 -0
  1998. package/src/utils/swarm/teammateLayoutManager.js +82 -0
  1999. package/src/utils/swarm/teammateModel.js +9 -0
  2000. package/src/utils/swarm/teammatePromptAddendum.js +17 -0
  2001. package/src/utils/systemDirectories.js +51 -0
  2002. package/src/utils/systemPrompt.js +88 -0
  2003. package/src/utils/systemPromptType.js +9 -0
  2004. package/src/utils/systemTheme.js +108 -0
  2005. package/src/utils/taggedId.js +49 -0
  2006. package/src/utils/task/TaskOutput.js +320 -0
  2007. package/src/utils/task/diskOutput.js +387 -0
  2008. package/src/utils/task/framework.js +236 -0
  2009. package/src/utils/task/outputFormatting.js +24 -0
  2010. package/src/utils/task/sdkProgress.js +24 -0
  2011. package/src/utils/taskSummary.js +3 -0
  2012. package/src/utils/tasks.js +672 -0
  2013. package/src/utils/teamDiscovery.js +48 -0
  2014. package/src/utils/teamMemoryOps.js +67 -0
  2015. package/src/utils/teammate.js +237 -0
  2016. package/src/utils/teammateContext.js +56 -0
  2017. package/src/utils/teammateMailbox.js +793 -0
  2018. package/src/utils/telemetry/betaSessionTracing.js +25 -0
  2019. package/src/utils/telemetry/bigqueryExporter.js +17 -0
  2020. package/src/utils/telemetry/events.js +7 -0
  2021. package/src/utils/telemetry/instrumentation.js +16 -0
  2022. package/src/utils/telemetry/logger.js +25 -0
  2023. package/src/utils/telemetry/perfettoTracing.js +882 -0
  2024. package/src/utils/telemetry/pluginTelemetry.js +76 -0
  2025. package/src/utils/telemetry/sessionTracing.js +62 -0
  2026. package/src/utils/telemetry/skillLoadedEvent.js +4 -0
  2027. package/src/utils/telemetryAttributes.js +56 -0
  2028. package/src/utils/teleport/api.js +299 -0
  2029. package/src/utils/teleport/environmentSelection.js +55 -0
  2030. package/src/utils/teleport/environments.js +84 -0
  2031. package/src/utils/teleport/gitBundle.js +192 -0
  2032. package/src/utils/teleport.js +1047 -0
  2033. package/src/utils/tempfile.js +26 -0
  2034. package/src/utils/terminal.js +105 -0
  2035. package/src/utils/terminalPanel.js +155 -0
  2036. package/src/utils/textHighlighting.js +113 -0
  2037. package/src/utils/thaddeusHints.js +142 -0
  2038. package/src/utils/theme.js +525 -0
  2039. package/src/utils/thinking.js +130 -0
  2040. package/src/utils/timeouts.js +35 -0
  2041. package/src/utils/tmuxSocket.js +373 -0
  2042. package/src/utils/todo/types.js +9 -0
  2043. package/src/utils/tokenBudget.js +62 -0
  2044. package/src/utils/tokens.js +223 -0
  2045. package/src/utils/toolErrors.js +101 -0
  2046. package/src/utils/toolPool.js +61 -0
  2047. package/src/utils/toolResultStorage.js +768 -0
  2048. package/src/utils/toolSchemaCache.js +7 -0
  2049. package/src/utils/toolSearch.js +551 -0
  2050. package/src/utils/transcriptSearch.js +200 -0
  2051. package/src/utils/treeify.js +111 -0
  2052. package/src/utils/truncate.js +164 -0
  2053. package/src/utils/udsClient.js +5 -0
  2054. package/src/utils/udsMessaging.js +23 -0
  2055. package/src/utils/ultraplan/ccrSession.js +264 -0
  2056. package/src/utils/ultraplan/keyword.js +122 -0
  2057. package/src/utils/unaryLogging.js +16 -0
  2058. package/src/utils/undercover.js +89 -0
  2059. package/src/utils/user.js +137 -0
  2060. package/src/utils/userAgent.js +9 -0
  2061. package/src/utils/userPromptKeywords.js +21 -0
  2062. package/src/utils/uuid.js +22 -0
  2063. package/src/utils/warningHandler.js +97 -0
  2064. package/src/utils/which.js +75 -0
  2065. package/src/utils/windowsPaths.js +146 -0
  2066. package/src/utils/withResolvers.js +13 -0
  2067. package/src/utils/words.js +793 -0
  2068. package/src/utils/workforceIntent.js +192 -0
  2069. package/src/utils/workloadContext.js +42 -0
  2070. package/src/utils/worktree.js +1142 -0
  2071. package/src/utils/worktreeModeEnabled.js +11 -0
  2072. package/src/utils/xdg.js +52 -0
  2073. package/src/utils/xml.js +15 -0
  2074. package/src/utils/yaml.js +14 -0
  2075. package/src/utils/zodToJsonSchema.js +19 -0
  2076. package/src/vim/motions.js +73 -0
  2077. package/src/vim/operators.js +401 -0
  2078. package/src/vim/textObjects.js +153 -0
  2079. package/src/vim/transitions.js +340 -0
  2080. package/src/vim/types.js +93 -0
  2081. package/src/voice/voiceModeEnabled.js +20 -0
  2082. package/thaddeus-terminal.ts +401 -3
@@ -0,0 +1,2518 @@
1
+ // biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
2
+ import { logEvent, } from 'src/services/analytics/index.js';
3
+ import { toolMatchesName, } from '../Tool.js';
4
+ import { FileReadTool, MaxFileReadTokenExceededError, readImageWithTokenBudget, } from '../tools/FileReadTool/FileReadTool.js';
5
+ import { FileTooLargeError, readFileInRange } from './readFileInRange.js';
6
+ import { expandPath } from './path.js';
7
+ import { countCharInString } from './stringUtils.js';
8
+ import { uniq } from './array.js';
9
+ import { getFsImplementation } from './fsOperations.js';
10
+ import { readdir, stat } from 'fs/promises';
11
+ import { TODO_WRITE_TOOL_NAME } from '../tools/TodoWriteTool/constants.js';
12
+ import { TASK_CREATE_TOOL_NAME } from '../tools/TaskCreateTool/constants.js';
13
+ import { TASK_UPDATE_TOOL_NAME } from '../tools/TaskUpdateTool/constants.js';
14
+ import { BASH_TOOL_NAME } from '../tools/BashTool/toolName.js';
15
+ import { SKILL_TOOL_NAME } from '../tools/SkillTool/constants.js';
16
+ import { listTasks, getTaskListId, isTodoV2Enabled, } from './tasks.js';
17
+ import { getPlanFilePath, getPlan } from './plans.js';
18
+ import { getConnectedIdeName } from './ide.js';
19
+ import { getManagedAndUserConditionalRules, getMemoryFilesForNestedDirectory, getConditionalRulesForCwdLevelDirectory, } from './claudemd.js';
20
+ import { dirname, parse, relative, resolve } from 'path';
21
+ import { getCwd } from 'src/utils/cwd.js';
22
+ import { getViewedTeammateTask } from '../state/selectors.js';
23
+ import { logError } from './log.js';
24
+ import { logAntError } from './debug.js';
25
+ import { isENOENT, toError } from './errors.js';
26
+ import { diagnosticTracker } from '../services/diagnosticTracking.js';
27
+ import { getImagePasteIds, isValidImagePaste, } from 'src/types/textInputTypes.js';
28
+ import { randomUUID } from 'crypto';
29
+ import { getSettings_DEPRECATED } from './settings/settings.js';
30
+ import { getSnippetForTwoFileDiff } from 'src/tools/FileEditTool/utils.js';
31
+ import { maybeResizeAndDownsampleImageBlock } from './imageResizer.js';
32
+ import { getSkillToolCommands, getMcpSkillCommands } from '../commands.js';
33
+ import uniqBy from 'lodash-es/uniqBy.js';
34
+ import { getProjectRoot } from '../bootstrap/state.js';
35
+ import { formatCommandsWithinBudget } from '../tools/SkillTool/prompt.js';
36
+ import { getContextWindowForModel } from './context.js';
37
+ // Conditional require for DCE. All skill-search string literals that would
38
+ // otherwise leak into external builds live inside these modules. The only
39
+ // surfaces in THIS file are: the maybe() call (gated via spread below) and
40
+ // the skill_listing suppression check (uses the same skillSearchModules null
41
+ // check). The type-only DiscoverySignal import above is erased at compile time.
42
+ /* eslint-disable @typescript-eslint/no-require-imports */
43
+ const skillSearchModules = feature('EXPERIMENTAL_SKILL_SEARCH')
44
+ ? {
45
+ featureCheck: require('../services/skillSearch/featureCheck.js'),
46
+ prefetch: require('../services/skillSearch/prefetch.js'),
47
+ }
48
+ : null;
49
+ const autoModeStateModule = feature('TRANSCRIPT_CLASSIFIER')
50
+ ? require('./permissions/autoModeState.js')
51
+ : null;
52
+ /* eslint-enable @typescript-eslint/no-require-imports */
53
+ import { MAX_LINES_TO_READ, FILE_READ_TOOL_NAME, } from 'src/tools/FileReadTool/prompt.js';
54
+ import { getDefaultFileReadingLimits } from 'src/tools/FileReadTool/limits.js';
55
+ import { cacheKeys } from './fileStateCache.js';
56
+ import { createAbortController, createChildAbortController, } from './abortController.js';
57
+ import { isAbortError } from './errors.js';
58
+ import { getFileModificationTimeAsync, isFileWithinReadSizeLimit, } from './file.js';
59
+ import { filterAgentsByMcpRequirements } from '../tools/AgentTool/loadAgentsDir.js';
60
+ import { AGENT_TOOL_NAME } from '../tools/AgentTool/constants.js';
61
+ import { formatAgentLine, shouldInjectAgentListInMessages, } from '../tools/AgentTool/prompt.js';
62
+ import { filterDeniedAgents } from './permissions/permissions.js';
63
+ import { getSubscriptionType } from './auth.js';
64
+ import { mcpInfoFromString } from '../services/mcp/mcpStringUtils.js';
65
+ import { matchingRuleForInput, pathInAllowedWorkingPath, } from './permissions/filesystem.js';
66
+ import { generateTaskAttachments, applyTaskOffsetsAndEvictions, } from './task/framework.js';
67
+ import { getTaskOutputPath } from './task/diskOutput.js';
68
+ import { drainPendingMessages } from '../tasks/LocalAgentTask/LocalAgentTask.js';
69
+ import { getOriginalCwd, getSessionId, getSdkBetas, getTotalCostUSD, getTotalOutputTokens, getCurrentTurnTokenBudget, getTurnOutputTokens, hasExitedPlanModeInSession, setHasExitedPlanMode, needsPlanModeExitAttachment, setNeedsPlanModeExitAttachment, needsAutoModeExitAttachment, setNeedsAutoModeExitAttachment, getLastEmittedDate, setLastEmittedDate, getKairosActive, } from '../bootstrap/state.js';
70
+ import { getDeferredToolsDelta, isDeferredToolsDeltaEnabled, isToolSearchEnabledOptimistic, isToolSearchToolAvailable, modelSupportsToolReference, } from './toolSearch.js';
71
+ import { getMcpInstructionsDelta, isMcpInstructionsDeltaEnabled, } from './mcpInstructionsDelta.js';
72
+ import { CLAUDE_IN_CHROME_MCP_SERVER_NAME } from './claudeInChrome/common.js';
73
+ import { CHROME_TOOL_SEARCH_INSTRUCTIONS } from './claudeInChrome/prompt.js';
74
+ import { checkForAsyncHookResponses, removeDeliveredAsyncHooks, } from './hooks/AsyncHookRegistry.js';
75
+ import { checkForLSPDiagnostics, clearAllLSPDiagnostics, } from '../services/lsp/LSPDiagnosticRegistry.js';
76
+ import { logForDebugging } from './debug.js';
77
+ import { extractTextContent, getUserMessageText, isThinkingMessage, } from './messages.js';
78
+ import { isHumanTurn } from './messagePredicates.js';
79
+ import { isEnvTruthy, getClaudeConfigHomeDir } from './envUtils.js';
80
+ import { feature } from 'bun:bundle';
81
+ /* eslint-disable @typescript-eslint/no-require-imports */
82
+ const BRIEF_TOOL_NAME = feature('KAIROS') || feature('KAIROS_BRIEF')
83
+ ? require('../tools/BriefTool/prompt.js').BRIEF_TOOL_NAME
84
+ : null;
85
+ const sessionTranscriptModule = feature('KAIROS')
86
+ ? require('../services/sessionTranscript/sessionTranscript.js')
87
+ : null;
88
+ /* eslint-enable @typescript-eslint/no-require-imports */
89
+ import { hasUltrathinkKeyword, isUltrathinkEnabled } from './thinking.js';
90
+ import { tokenCountFromLastAPIResponse, tokenCountWithEstimation, } from './tokens.js';
91
+ import { getEffectiveContextWindowSize, isAutoCompactEnabled, } from '../services/compact/autoCompact.js';
92
+ import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js';
93
+ import { hasInstructionsLoadedHook, executeInstructionsLoadedHooks, } from './hooks.js';
94
+ import { jsonStringify } from './slowOperations.js';
95
+ import { isPDFExtension } from './pdfUtils.js';
96
+ import { getLocalISODate } from '../constants/common.js';
97
+ import { getPDFPageCount } from './pdf.js';
98
+ import { PDF_AT_MENTION_INLINE_THRESHOLD } from '../constants/apiLimits.js';
99
+ import { isAgentSwarmsEnabled } from './agentSwarmsEnabled.js';
100
+ import { findRelevantMemories } from '../memdir/findRelevantMemories.js';
101
+ import { memoryAge, memoryFreshnessText } from '../memdir/memoryAge.js';
102
+ import { getAutoMemPath, isAutoMemoryEnabled } from '../memdir/paths.js';
103
+ import { getAgentMemoryDir } from '../tools/AgentTool/agentMemory.js';
104
+ import { readUnreadMessages, markMessagesAsReadByPredicate, isShutdownApproved, isStructuredProtocolMessage, isIdleNotification, } from './teammateMailbox.js';
105
+ import { getAgentName, getAgentId, getTeamName, isTeamLead, } from './teammate.js';
106
+ import { isInProcessTeammate } from './teammateContext.js';
107
+ import { removeTeammateFromTeamFile } from './swarm/teamHelpers.js';
108
+ import { unassignTeammateTasks } from './tasks.js';
109
+ import { getCompanionIntroAttachment } from '../buddy/prompt.js';
110
+ export const TODO_REMINDER_CONFIG = {
111
+ TURNS_SINCE_WRITE: 10,
112
+ TURNS_BETWEEN_REMINDERS: 10,
113
+ };
114
+ export const PLAN_MODE_ATTACHMENT_CONFIG = {
115
+ TURNS_BETWEEN_ATTACHMENTS: 5,
116
+ FULL_REMINDER_EVERY_N_ATTACHMENTS: 5,
117
+ };
118
+ export const AUTO_MODE_ATTACHMENT_CONFIG = {
119
+ TURNS_BETWEEN_ATTACHMENTS: 5,
120
+ FULL_REMINDER_EVERY_N_ATTACHMENTS: 5,
121
+ };
122
+ const MAX_MEMORY_LINES = 200;
123
+ // Line cap alone doesn't bound size (200 × 500-char lines = 100KB). The
124
+ // surfacer injects up to 5 files per turn via <system-reminder>, bypassing
125
+ // the per-message tool-result budget, so a tight per-file byte cap keeps
126
+ // aggregate injection bounded (5 × 4KB = 20KB/turn). Enforced via
127
+ // readFileInRange's truncateOnByteLimit option. Truncation means the
128
+ // most-relevant memory still surfaces: the frontmatter + opening context
129
+ // is usually what matters.
130
+ const MAX_MEMORY_BYTES = 4096;
131
+ export const RELEVANT_MEMORIES_CONFIG = {
132
+ // Per-turn cap (5 × 4KB = 20KB) bounds a single injection, but over a
133
+ // long session the selector keeps surfacing distinct files — ~26K tokens/
134
+ // session observed in prod. Cap the cumulative bytes: once hit, stop
135
+ // prefetching entirely. Budget is ~3 full injections; after that the
136
+ // most-relevant memories are already in context. Scanning messages
137
+ // (rather than tracking in toolUseContext) means compact naturally
138
+ // resets the counter — old attachments are gone from context, so
139
+ // re-surfacing is valid.
140
+ MAX_SESSION_BYTES: 60 * 1024,
141
+ };
142
+ export const VERIFY_PLAN_REMINDER_CONFIG = {
143
+ TURNS_BETWEEN_REMINDERS: 10,
144
+ };
145
+ /**
146
+ * This is janky
147
+ * TODO: Generate attachments when we create messages
148
+ */
149
+ export async function getAttachments(input, toolUseContext, ideSelection, queuedCommands, messages, querySource, options) {
150
+ if (isEnvTruthy(process.env.THADDEUS_DISABLE_ATTACHMENTS) ||
151
+ isEnvTruthy(process.env.THADDEUS_SIMPLE)) {
152
+ // query.ts:removeFromQueue dequeues these unconditionally after
153
+ // getAttachmentMessages runs — returning [] here silently drops them.
154
+ // Coworker runs with --bare and depends on task-notification for
155
+ // mid-tool-call notifications from Local*Task/Remote*Task.
156
+ return getQueuedCommandAttachments(queuedCommands);
157
+ }
158
+ // This will slow down submissions
159
+ // TODO: Compute attachments as the user types, not here (though we use this
160
+ // function for slash command prompts too)
161
+ const abortController = createAbortController();
162
+ const timeoutId = setTimeout(ac => ac.abort(), 1000, abortController);
163
+ const context = { ...toolUseContext, abortController };
164
+ const isMainThread = !toolUseContext.agentId;
165
+ // Attachments which are added in response to on user input
166
+ const userInputAttachments = input
167
+ ? [
168
+ maybe('at_mentioned_files', () => processAtMentionedFiles(input, context)),
169
+ maybe('mcp_resources', () => processMcpResourceAttachments(input, context)),
170
+ maybe('agent_mentions', () => Promise.resolve(processAgentMentions(input, toolUseContext.options.agentDefinitions.activeAgents))),
171
+ // Skill discovery on turn 0 (user input as signal). Inter-turn
172
+ // discovery runs via startSkillDiscoveryPrefetch in query.ts,
173
+ // gated on write-pivot detection — see skillSearch/prefetch.ts.
174
+ // feature() here lets DCE drop the 'skill_discovery' string (and the
175
+ // function it calls) from external builds.
176
+ //
177
+ // skipSkillDiscovery gates out the SKILL.md-expansion path
178
+ // (getMessagesForPromptSlashCommand). When a skill is invoked, its
179
+ // SKILL.md content is passed as `input` here to extract @-mentions —
180
+ // but that content is NOT user intent and must not trigger discovery.
181
+ // Without this gate, a 110KB SKILL.md fires ~3.3s of chunked AKI
182
+ // queries on every skill invocation (session 13a9afae).
183
+ ...(feature('EXPERIMENTAL_SKILL_SEARCH') &&
184
+ skillSearchModules &&
185
+ !options?.skipSkillDiscovery
186
+ ? [
187
+ maybe('skill_discovery', () => skillSearchModules.prefetch.getTurnZeroSkillDiscovery(input, messages ?? [], context)),
188
+ ]
189
+ : []),
190
+ ]
191
+ : [];
192
+ // Process user input attachments first (includes @mentioned files)
193
+ // This ensures files are added to nestedMemoryAttachmentTriggers before nested_memory processes them
194
+ const userAttachmentResults = await Promise.all(userInputAttachments);
195
+ // Thread-safe attachments available in sub-agents
196
+ // NOTE: These must be created AFTER userInputAttachments completes to ensure
197
+ // nestedMemoryAttachmentTriggers is populated before getNestedMemoryAttachments runs
198
+ const allThreadAttachments = [
199
+ // queuedCommands is already agent-scoped by the drain gate in query.ts —
200
+ // main thread gets agentId===undefined, subagents get their own agentId.
201
+ // Must run for all threads or subagent notifications drain into the void
202
+ // (removed from queue by removeFromQueue but never attached).
203
+ maybe('queued_commands', () => getQueuedCommandAttachments(queuedCommands)),
204
+ maybe('date_change', () => Promise.resolve(getDateChangeAttachments(messages))),
205
+ maybe('ultrathink_effort', () => Promise.resolve(getUltrathinkEffortAttachment(input))),
206
+ maybe('deferred_tools_delta', () => Promise.resolve(getDeferredToolsDeltaAttachment(toolUseContext.options.tools, toolUseContext.options.mainLoopModel, messages, {
207
+ callSite: isMainThread
208
+ ? 'attachments_main'
209
+ : 'attachments_subagent',
210
+ querySource,
211
+ }))),
212
+ maybe('agent_listing_delta', () => Promise.resolve(getAgentListingDeltaAttachment(toolUseContext, messages))),
213
+ maybe('mcp_instructions_delta', () => Promise.resolve(getMcpInstructionsDeltaAttachment(toolUseContext.options.mcpClients, toolUseContext.options.tools, toolUseContext.options.mainLoopModel, messages))),
214
+ ...(feature('BUDDY')
215
+ ? [
216
+ maybe('companion_intro', () => Promise.resolve(getCompanionIntroAttachment(messages))),
217
+ ]
218
+ : []),
219
+ maybe('changed_files', () => getChangedFiles(context)),
220
+ maybe('nested_memory', () => getNestedMemoryAttachments(context)),
221
+ // relevant_memories moved to async prefetch (startRelevantMemoryPrefetch)
222
+ maybe('dynamic_skill', () => getDynamicSkillAttachments(context)),
223
+ maybe('skill_listing', () => getSkillListingAttachments(context)),
224
+ // Inter-turn skill discovery now runs via startSkillDiscoveryPrefetch
225
+ // (query.ts, concurrent with the main turn). The blocking call that
226
+ // previously lived here was the assistant_turn signal — 97% of those
227
+ // Haiku calls found nothing in prod. Prefetch + await-at-collection
228
+ // replaces it; see src/services/skillSearch/prefetch.ts.
229
+ maybe('plan_mode', () => getPlanModeAttachments(messages, toolUseContext)),
230
+ maybe('plan_mode_exit', () => getPlanModeExitAttachment(toolUseContext)),
231
+ ...(feature('TRANSCRIPT_CLASSIFIER')
232
+ ? [
233
+ maybe('auto_mode', () => getAutoModeAttachments(messages, toolUseContext)),
234
+ maybe('auto_mode_exit', () => getAutoModeExitAttachment(toolUseContext)),
235
+ ]
236
+ : []),
237
+ maybe('todo_reminders', () => isTodoV2Enabled()
238
+ ? getTaskReminderAttachments(messages, toolUseContext)
239
+ : getTodoReminderAttachments(messages, toolUseContext)),
240
+ ...(isAgentSwarmsEnabled()
241
+ ? [
242
+ // Skip teammate mailbox for the session_memory forked agent.
243
+ // It shares AppState.teamContext with the leader, so isTeamLead resolves
244
+ // true and it reads+marks-as-read the leader's DMs as ephemeral attachments,
245
+ // silently stealing messages that should be delivered as permanent turns.
246
+ ...(querySource === 'session_memory'
247
+ ? []
248
+ : [
249
+ maybe('teammate_mailbox', async () => getTeammateMailboxAttachments(toolUseContext)),
250
+ ]),
251
+ maybe('team_context', async () => getTeamContextAttachment(messages ?? [])),
252
+ ]
253
+ : []),
254
+ maybe('agent_pending_messages', async () => getAgentPendingMessageAttachments(toolUseContext)),
255
+ maybe('critical_system_reminder', () => Promise.resolve(getCriticalSystemReminderAttachment(toolUseContext))),
256
+ ...(feature('COMPACTION_REMINDERS')
257
+ ? [
258
+ maybe('compaction_reminder', () => Promise.resolve(getCompactionReminderAttachment(messages ?? [], toolUseContext.options.mainLoopModel))),
259
+ ]
260
+ : []),
261
+ ...(feature('HISTORY_SNIP')
262
+ ? [
263
+ maybe('context_efficiency', () => Promise.resolve(getContextEfficiencyAttachment(messages ?? []))),
264
+ ]
265
+ : []),
266
+ ];
267
+ // Attachments which are semantically only for the main conversation or don't have concurrency-safe implementations
268
+ const mainThreadAttachments = isMainThread
269
+ ? [
270
+ maybe('ide_selection', async () => getSelectedLinesFromIDE(ideSelection, toolUseContext)),
271
+ maybe('ide_opened_file', async () => getOpenedFileFromIDE(ideSelection, toolUseContext)),
272
+ maybe('output_style', async () => Promise.resolve(getOutputStyleAttachment())),
273
+ maybe('diagnostics', async () => getDiagnosticAttachments(toolUseContext)),
274
+ maybe('lsp_diagnostics', async () => getLSPDiagnosticAttachments(toolUseContext)),
275
+ maybe('unified_tasks', async () => getUnifiedTaskAttachments(toolUseContext)),
276
+ maybe('async_hook_responses', async () => getAsyncHookResponseAttachments()),
277
+ maybe('token_usage', async () => Promise.resolve(getTokenUsageAttachment(messages ?? [], toolUseContext.options.mainLoopModel))),
278
+ maybe('budget_usd', async () => Promise.resolve(getMaxBudgetUsdAttachment(toolUseContext.options.maxBudgetUsd))),
279
+ maybe('output_token_usage', async () => Promise.resolve(getOutputTokenUsageAttachment())),
280
+ maybe('verify_plan_reminder', async () => getVerifyPlanReminderAttachment(messages, toolUseContext)),
281
+ ]
282
+ : [];
283
+ // Process thread and main thread attachments in parallel (no dependencies between them)
284
+ const [threadAttachmentResults, mainThreadAttachmentResults] = await Promise.all([
285
+ Promise.all(allThreadAttachments),
286
+ Promise.all(mainThreadAttachments),
287
+ ]);
288
+ clearTimeout(timeoutId);
289
+ // Defensive: a getter leaking [undefined] crashes .map(a => a.type) below.
290
+ return [
291
+ ...userAttachmentResults.flat(),
292
+ ...threadAttachmentResults.flat(),
293
+ ...mainThreadAttachmentResults.flat(),
294
+ ].filter(a => a !== undefined && a !== null);
295
+ }
296
+ async function maybe(label, f) {
297
+ const startTime = Date.now();
298
+ try {
299
+ const result = await f();
300
+ const duration = Date.now() - startTime;
301
+ // Log only 5% of events to reduce volume
302
+ if (Math.random() < 0.05) {
303
+ // jsonStringify(undefined) returns undefined, so .length would throw
304
+ const attachmentSizeBytes = result
305
+ .filter(a => a !== undefined && a !== null)
306
+ .reduce((total, attachment) => {
307
+ return total + jsonStringify(attachment).length;
308
+ }, 0);
309
+ logEvent('thaddeus_attachment_compute_duration', {
310
+ label,
311
+ duration_ms: duration,
312
+ attachment_size_bytes: attachmentSizeBytes,
313
+ attachment_count: result.length,
314
+ });
315
+ }
316
+ return result;
317
+ }
318
+ catch (e) {
319
+ const duration = Date.now() - startTime;
320
+ // Log only 5% of events to reduce volume
321
+ if (Math.random() < 0.05) {
322
+ logEvent('thaddeus_attachment_compute_duration', {
323
+ label,
324
+ duration_ms: duration,
325
+ error: true,
326
+ });
327
+ }
328
+ logError(e);
329
+ // For Ant users, log the full error to help with debugging
330
+ logAntError(`Attachment error in ${label}`, e);
331
+ return [];
332
+ }
333
+ }
334
+ const INLINE_NOTIFICATION_MODES = new Set(['prompt', 'task-notification']);
335
+ export async function getQueuedCommandAttachments(queuedCommands) {
336
+ if (!queuedCommands) {
337
+ return [];
338
+ }
339
+ // Include both 'prompt' and 'task-notification' commands as attachments.
340
+ // During proactive agentic loops, task-notification commands would otherwise
341
+ // stay in the queue permanently (useQueueProcessor can't run while a query
342
+ // is active), causing hasPendingNotifications() to return true and Sleep to
343
+ // wake immediately with 0ms duration in an infinite loop.
344
+ const filtered = queuedCommands.filter(_ => INLINE_NOTIFICATION_MODES.has(_.mode));
345
+ return Promise.all(filtered.map(async (_) => {
346
+ const imageBlocks = await buildImageContentBlocks(_.pastedContents);
347
+ let prompt = _.value;
348
+ if (imageBlocks.length > 0) {
349
+ // Build content block array with text + images so the model sees them
350
+ const textValue = typeof _.value === 'string'
351
+ ? _.value
352
+ : extractTextContent(_.value, '\n');
353
+ prompt = [{ type: 'text', text: textValue }, ...imageBlocks];
354
+ }
355
+ return {
356
+ type: 'queued_command',
357
+ prompt,
358
+ source_uuid: _.uuid,
359
+ imagePasteIds: getImagePasteIds(_.pastedContents),
360
+ commandMode: _.mode,
361
+ origin: _.origin,
362
+ isMeta: _.isMeta,
363
+ };
364
+ }));
365
+ }
366
+ export function getAgentPendingMessageAttachments(toolUseContext) {
367
+ const agentId = toolUseContext.agentId;
368
+ if (!agentId)
369
+ return [];
370
+ const drained = drainPendingMessages(agentId, toolUseContext.getAppState, toolUseContext.setAppStateForTasks ?? toolUseContext.setAppState);
371
+ return drained.map(msg => ({
372
+ type: 'queued_command',
373
+ prompt: msg,
374
+ origin: { kind: 'coordinator' },
375
+ isMeta: true,
376
+ }));
377
+ }
378
+ async function buildImageContentBlocks(pastedContents) {
379
+ if (!pastedContents) {
380
+ return [];
381
+ }
382
+ const imageContents = Object.values(pastedContents).filter(isValidImagePaste);
383
+ if (imageContents.length === 0) {
384
+ return [];
385
+ }
386
+ const results = await Promise.all(imageContents.map(async (img) => {
387
+ const imageBlock = {
388
+ type: 'image',
389
+ source: {
390
+ type: 'base64',
391
+ media_type: (img.mediaType ||
392
+ 'image/png'),
393
+ data: img.content,
394
+ },
395
+ };
396
+ try {
397
+ const resized = await maybeResizeAndDownsampleImageBlock(imageBlock);
398
+ return resized.block;
399
+ }
400
+ catch {
401
+ // Image resize failed (sharp/image-processor-napi missing) — send raw block
402
+ return imageBlock;
403
+ }
404
+ }));
405
+ return results;
406
+ }
407
+ function getPlanModeAttachmentTurnCount(messages) {
408
+ let turnsSinceLastAttachment = 0;
409
+ let foundPlanModeAttachment = false;
410
+ // Iterate backwards to find most recent plan_mode attachment.
411
+ // Count HUMAN turns (non-meta, non-tool-result user messages), not assistant
412
+ // messages — the tool loop in query.ts calls getAttachmentMessages on every
413
+ // tool round, so counting assistant messages would fire the reminder every
414
+ // 5 tool calls instead of every 5 human turns.
415
+ for (let i = messages.length - 1; i >= 0; i--) {
416
+ const message = messages[i];
417
+ if (message?.type === 'user' &&
418
+ !message.isMeta &&
419
+ !hasToolResultContent(message.message.content)) {
420
+ turnsSinceLastAttachment++;
421
+ }
422
+ else if (message?.type === 'attachment' &&
423
+ (message.attachment.type === 'plan_mode' ||
424
+ message.attachment.type === 'plan_mode_reentry')) {
425
+ foundPlanModeAttachment = true;
426
+ break;
427
+ }
428
+ }
429
+ return { turnCount: turnsSinceLastAttachment, foundPlanModeAttachment };
430
+ }
431
+ /**
432
+ * Count plan_mode attachments since the last plan_mode_exit (or from start if no exit).
433
+ * This ensures the full/sparse cycle resets when re-entering plan mode.
434
+ */
435
+ function countPlanModeAttachmentsSinceLastExit(messages) {
436
+ let count = 0;
437
+ // Iterate backwards - if we hit a plan_mode_exit, stop counting
438
+ for (let i = messages.length - 1; i >= 0; i--) {
439
+ const message = messages[i];
440
+ if (message?.type === 'attachment') {
441
+ if (message.attachment.type === 'plan_mode_exit') {
442
+ break; // Stop counting at the last exit
443
+ }
444
+ if (message.attachment.type === 'plan_mode') {
445
+ count++;
446
+ }
447
+ }
448
+ }
449
+ return count;
450
+ }
451
+ async function getPlanModeAttachments(messages, toolUseContext) {
452
+ const appState = toolUseContext.getAppState();
453
+ const permissionContext = appState.toolPermissionContext;
454
+ if (permissionContext.mode !== 'plan') {
455
+ return [];
456
+ }
457
+ // Check if we should attach based on turn count (except for first turn)
458
+ if (messages && messages.length > 0) {
459
+ const { turnCount, foundPlanModeAttachment } = getPlanModeAttachmentTurnCount(messages);
460
+ // Only throttle if we've already sent a plan_mode attachment before
461
+ // On first turn in plan mode, always attach
462
+ if (foundPlanModeAttachment &&
463
+ turnCount < PLAN_MODE_ATTACHMENT_CONFIG.TURNS_BETWEEN_ATTACHMENTS) {
464
+ return [];
465
+ }
466
+ }
467
+ const planFilePath = getPlanFilePath(toolUseContext.agentId);
468
+ const existingPlan = getPlan(toolUseContext.agentId);
469
+ const attachments = [];
470
+ // Check for re-entry: flag is set AND plan file exists
471
+ if (hasExitedPlanModeInSession() && existingPlan !== null) {
472
+ attachments.push({ type: 'plan_mode_reentry', planFilePath });
473
+ setHasExitedPlanMode(false); // Clear flag - one-time guidance
474
+ }
475
+ // Determine if this should be a full or sparse reminder
476
+ // Full reminder on 1st, 6th, 11th... (every Nth attachment)
477
+ const attachmentCount = countPlanModeAttachmentsSinceLastExit(messages ?? []) + 1;
478
+ const reminderType = attachmentCount %
479
+ PLAN_MODE_ATTACHMENT_CONFIG.FULL_REMINDER_EVERY_N_ATTACHMENTS ===
480
+ 1
481
+ ? 'full'
482
+ : 'sparse';
483
+ // Always add the main plan_mode attachment
484
+ attachments.push({
485
+ type: 'plan_mode',
486
+ reminderType,
487
+ isSubAgent: !!toolUseContext.agentId,
488
+ planFilePath,
489
+ planExists: existingPlan !== null,
490
+ });
491
+ return attachments;
492
+ }
493
+ /**
494
+ * Returns a plan_mode_exit attachment if we just exited plan mode.
495
+ * This is a one-time notification to tell the model it's no longer in plan mode.
496
+ */
497
+ async function getPlanModeExitAttachment(toolUseContext) {
498
+ // Only trigger if the flag is set (we just exited plan mode)
499
+ if (!needsPlanModeExitAttachment()) {
500
+ return [];
501
+ }
502
+ const appState = toolUseContext.getAppState();
503
+ if (appState.toolPermissionContext.mode === 'plan') {
504
+ setNeedsPlanModeExitAttachment(false);
505
+ return [];
506
+ }
507
+ // Clear the flag - this is a one-time notification
508
+ setNeedsPlanModeExitAttachment(false);
509
+ const planFilePath = getPlanFilePath(toolUseContext.agentId);
510
+ const planExists = getPlan(toolUseContext.agentId) !== null;
511
+ // Note: skill discovery does NOT fire on plan exit. By the time the plan is
512
+ // written, it's too late — the model should have had relevant skills WHILE
513
+ // planning. The user_message signal already fires on the request that
514
+ // triggers planning ("plan how to deploy this"), which is the right moment.
515
+ return [{ type: 'plan_mode_exit', planFilePath, planExists }];
516
+ }
517
+ function getAutoModeAttachmentTurnCount(messages) {
518
+ let turnsSinceLastAttachment = 0;
519
+ let foundAutoModeAttachment = false;
520
+ // Iterate backwards to find most recent auto_mode attachment.
521
+ // Count HUMAN turns (non-meta, non-tool-result user messages), not assistant
522
+ // messages — the tool loop in query.ts calls getAttachmentMessages on every
523
+ // tool round, so a single human turn with 100 tool calls would fire ~20
524
+ // reminders if we counted assistant messages. Auto mode's target use case is
525
+ // long agentic sessions, where this accumulated 60-105× per session.
526
+ for (let i = messages.length - 1; i >= 0; i--) {
527
+ const message = messages[i];
528
+ if (message?.type === 'user' &&
529
+ !message.isMeta &&
530
+ !hasToolResultContent(message.message.content)) {
531
+ turnsSinceLastAttachment++;
532
+ }
533
+ else if (message?.type === 'attachment' &&
534
+ message.attachment.type === 'auto_mode') {
535
+ foundAutoModeAttachment = true;
536
+ break;
537
+ }
538
+ else if (message?.type === 'attachment' &&
539
+ message.attachment.type === 'auto_mode_exit') {
540
+ // Exit resets the throttle — treat as if no prior attachment exists
541
+ break;
542
+ }
543
+ }
544
+ return { turnCount: turnsSinceLastAttachment, foundAutoModeAttachment };
545
+ }
546
+ /**
547
+ * Count auto_mode attachments since the last auto_mode_exit (or from start if no exit).
548
+ * This ensures the full/sparse cycle resets when re-entering auto mode.
549
+ */
550
+ function countAutoModeAttachmentsSinceLastExit(messages) {
551
+ let count = 0;
552
+ for (let i = messages.length - 1; i >= 0; i--) {
553
+ const message = messages[i];
554
+ if (message?.type === 'attachment') {
555
+ if (message.attachment.type === 'auto_mode_exit') {
556
+ break;
557
+ }
558
+ if (message.attachment.type === 'auto_mode') {
559
+ count++;
560
+ }
561
+ }
562
+ }
563
+ return count;
564
+ }
565
+ async function getAutoModeAttachments(messages, toolUseContext) {
566
+ const appState = toolUseContext.getAppState();
567
+ const permissionContext = appState.toolPermissionContext;
568
+ const inAuto = permissionContext.mode === 'auto';
569
+ const inPlanWithAuto = permissionContext.mode === 'plan' &&
570
+ (autoModeStateModule?.isAutoModeActive() ?? false);
571
+ if (!inAuto && !inPlanWithAuto) {
572
+ return [];
573
+ }
574
+ // Check if we should attach based on turn count (except for first turn)
575
+ if (messages && messages.length > 0) {
576
+ const { turnCount, foundAutoModeAttachment } = getAutoModeAttachmentTurnCount(messages);
577
+ // Only throttle if we've already sent an auto_mode attachment before
578
+ // On first turn in auto mode, always attach
579
+ if (foundAutoModeAttachment &&
580
+ turnCount < AUTO_MODE_ATTACHMENT_CONFIG.TURNS_BETWEEN_ATTACHMENTS) {
581
+ return [];
582
+ }
583
+ }
584
+ // Determine if this should be a full or sparse reminder
585
+ const attachmentCount = countAutoModeAttachmentsSinceLastExit(messages ?? []) + 1;
586
+ const reminderType = attachmentCount %
587
+ AUTO_MODE_ATTACHMENT_CONFIG.FULL_REMINDER_EVERY_N_ATTACHMENTS ===
588
+ 1
589
+ ? 'full'
590
+ : 'sparse';
591
+ return [{ type: 'auto_mode', reminderType }];
592
+ }
593
+ /**
594
+ * Returns an auto_mode_exit attachment if we just exited auto mode.
595
+ * This is a one-time notification to tell the model it's no longer in auto mode.
596
+ */
597
+ async function getAutoModeExitAttachment(toolUseContext) {
598
+ if (!needsAutoModeExitAttachment()) {
599
+ return [];
600
+ }
601
+ const appState = toolUseContext.getAppState();
602
+ // Suppress when auto is still active — covers both mode==='auto' and
603
+ // plan-with-auto-active (where mode==='plan' but classifier runs).
604
+ if (appState.toolPermissionContext.mode === 'auto' ||
605
+ (autoModeStateModule?.isAutoModeActive() ?? false)) {
606
+ setNeedsAutoModeExitAttachment(false);
607
+ return [];
608
+ }
609
+ setNeedsAutoModeExitAttachment(false);
610
+ return [{ type: 'auto_mode_exit' }];
611
+ }
612
+ /**
613
+ * Detects when the local date has changed since the last turn (user coding
614
+ * past midnight) and emits an attachment to notify the model.
615
+ *
616
+ * The date_change attachment is appended at the tail of the conversation,
617
+ * so the model learns the new date without mutating the cached prefix.
618
+ * messages[0] (from getUserContext → prependUserContext) intentionally
619
+ * keeps the stale date — clearing that cache would regenerate the prefix
620
+ * and turn the entire conversation into cache_creation on the next turn
621
+ * (~920K effective tokens per midnight crossing per overnight session).
622
+ *
623
+ * Exported for testing — regression guard for the cache-clear removal.
624
+ */
625
+ export function getDateChangeAttachments(messages) {
626
+ const currentDate = getLocalISODate();
627
+ const lastDate = getLastEmittedDate();
628
+ if (lastDate === null) {
629
+ // First turn — just record, no attachment needed
630
+ setLastEmittedDate(currentDate);
631
+ return [];
632
+ }
633
+ if (currentDate === lastDate) {
634
+ return [];
635
+ }
636
+ setLastEmittedDate(currentDate);
637
+ // Assistant mode: flush yesterday's transcript to the per-day file so
638
+ // the /dream skill (1–5am local) finds it even if no compaction fires
639
+ // today. Fire-and-forget; writeSessionTranscriptSegment buckets by
640
+ // message timestamp so a multi-day gap flushes each day correctly.
641
+ if (feature('KAIROS')) {
642
+ if (getKairosActive() && messages !== undefined) {
643
+ sessionTranscriptModule?.flushOnDateChange(messages, currentDate);
644
+ }
645
+ }
646
+ return [{ type: 'date_change', newDate: currentDate }];
647
+ }
648
+ function getUltrathinkEffortAttachment(input) {
649
+ if (!isUltrathinkEnabled() || !input || !hasUltrathinkKeyword(input)) {
650
+ return [];
651
+ }
652
+ logEvent('thaddeus_ultrathink', {});
653
+ return [{ type: 'ultrathink_effort', level: 'high' }];
654
+ }
655
+ // Exported for compact.ts — the gate must be identical at both call sites.
656
+ export function getDeferredToolsDeltaAttachment(tools, model, messages, scanContext) {
657
+ if (!isDeferredToolsDeltaEnabled())
658
+ return [];
659
+ // These three checks mirror the sync parts of isToolSearchEnabled —
660
+ // the attachment text says "available via ToolSearch", so ToolSearch
661
+ // has to actually be in the request. The async auto-threshold check
662
+ // is not replicated (would double-fire thaddeus_tool_search_mode_decision);
663
+ // in tst-auto below-threshold the attachment can fire while ToolSearch
664
+ // is filtered out, but that's a narrow case and the tools announced
665
+ // are directly callable anyway.
666
+ if (!isToolSearchEnabledOptimistic())
667
+ return [];
668
+ if (!modelSupportsToolReference(model))
669
+ return [];
670
+ if (!isToolSearchToolAvailable(tools))
671
+ return [];
672
+ const delta = getDeferredToolsDelta(tools, messages ?? [], scanContext);
673
+ if (!delta)
674
+ return [];
675
+ return [{ type: 'deferred_tools_delta', ...delta }];
676
+ }
677
+ /**
678
+ * Diff the current filtered agent pool against what's already been announced
679
+ * in this conversation (reconstructed from prior agent_listing_delta
680
+ * attachments). Returns [] if nothing changed or the gate is off.
681
+ *
682
+ * The agent list was embedded in AgentTool's description, causing ~10.2% of
683
+ * fleet cache_creation: MCP async connect, /reload-plugins, or
684
+ * permission-mode change → description changes → full tool-schema cache bust.
685
+ * Moving the list here keeps the tool description static.
686
+ *
687
+ * Exported for compact.ts — re-announces the full set after compaction eats
688
+ * prior deltas.
689
+ */
690
+ export function getAgentListingDeltaAttachment(toolUseContext, messages) {
691
+ if (!shouldInjectAgentListInMessages())
692
+ return [];
693
+ // Skip if AgentTool isn't in the pool — the listing would be unactionable.
694
+ if (!toolUseContext.options.tools.some(t => toolMatchesName(t, AGENT_TOOL_NAME))) {
695
+ return [];
696
+ }
697
+ const { activeAgents, allowedAgentTypes } = toolUseContext.options.agentDefinitions;
698
+ // Mirror AgentTool.prompt()'s filtering: MCP requirements → deny rules →
699
+ // allowedAgentTypes restriction. Keep this in sync with AgentTool.tsx.
700
+ const mcpServers = new Set();
701
+ for (const tool of toolUseContext.options.tools) {
702
+ const info = mcpInfoFromString(tool.name);
703
+ if (info)
704
+ mcpServers.add(info.serverName);
705
+ }
706
+ const permissionContext = toolUseContext.getAppState().toolPermissionContext;
707
+ let filtered = filterDeniedAgents(filterAgentsByMcpRequirements(activeAgents, [...mcpServers]), permissionContext, AGENT_TOOL_NAME);
708
+ if (allowedAgentTypes) {
709
+ filtered = filtered.filter(a => allowedAgentTypes.includes(a.agentType));
710
+ }
711
+ // Reconstruct announced set from prior deltas in the transcript.
712
+ const announced = new Set();
713
+ for (const msg of messages ?? []) {
714
+ if (msg.type !== 'attachment')
715
+ continue;
716
+ if (msg.attachment.type !== 'agent_listing_delta')
717
+ continue;
718
+ for (const t of msg.attachment.addedTypes)
719
+ announced.add(t);
720
+ for (const t of msg.attachment.removedTypes)
721
+ announced.delete(t);
722
+ }
723
+ const currentTypes = new Set(filtered.map(a => a.agentType));
724
+ const added = filtered.filter(a => !announced.has(a.agentType));
725
+ const removed = [];
726
+ for (const t of announced) {
727
+ if (!currentTypes.has(t))
728
+ removed.push(t);
729
+ }
730
+ if (added.length === 0 && removed.length === 0)
731
+ return [];
732
+ // Sort for deterministic output — agent load order is nondeterministic
733
+ // (plugin load races, MCP async connect).
734
+ added.sort((a, b) => a.agentType.localeCompare(b.agentType));
735
+ removed.sort();
736
+ return [
737
+ {
738
+ type: 'agent_listing_delta',
739
+ addedTypes: added.map(a => a.agentType),
740
+ addedLines: added.map(formatAgentLine),
741
+ removedTypes: removed,
742
+ isInitial: announced.size === 0,
743
+ showConcurrencyNote: getSubscriptionType() !== 'pro',
744
+ },
745
+ ];
746
+ }
747
+ // Exported for compact.ts / reactiveCompact.ts — single source of truth for the gate.
748
+ export function getMcpInstructionsDeltaAttachment(mcpClients, tools, model, messages) {
749
+ if (!isMcpInstructionsDeltaEnabled())
750
+ return [];
751
+ // The chrome ToolSearch hint is client-authored and ToolSearch-conditional;
752
+ // actual server `instructions` are unconditional. Decide the chrome part
753
+ // here, pass it into the pure diff as a synthesized entry.
754
+ const clientSide = [];
755
+ if (isToolSearchEnabledOptimistic() &&
756
+ modelSupportsToolReference(model) &&
757
+ isToolSearchToolAvailable(tools)) {
758
+ clientSide.push({
759
+ serverName: CLAUDE_IN_CHROME_MCP_SERVER_NAME,
760
+ block: CHROME_TOOL_SEARCH_INSTRUCTIONS,
761
+ });
762
+ }
763
+ const delta = getMcpInstructionsDelta(mcpClients, messages ?? [], clientSide);
764
+ if (!delta)
765
+ return [];
766
+ return [{ type: 'mcp_instructions_delta', ...delta }];
767
+ }
768
+ function getCriticalSystemReminderAttachment(toolUseContext) {
769
+ const reminder = toolUseContext.criticalSystemReminder_EXPERIMENTAL;
770
+ if (!reminder) {
771
+ return [];
772
+ }
773
+ return [{ type: 'critical_system_reminder', content: reminder }];
774
+ }
775
+ function getOutputStyleAttachment() {
776
+ const settings = getSettings_DEPRECATED();
777
+ const outputStyle = settings?.outputStyle || 'default';
778
+ // Only show for non-default styles
779
+ if (outputStyle === 'default') {
780
+ return [];
781
+ }
782
+ return [
783
+ {
784
+ type: 'output_style',
785
+ style: outputStyle,
786
+ },
787
+ ];
788
+ }
789
+ async function getSelectedLinesFromIDE(ideSelection, toolUseContext) {
790
+ const ideName = getConnectedIdeName(toolUseContext.options.mcpClients);
791
+ if (!ideName ||
792
+ ideSelection?.lineStart === undefined ||
793
+ !ideSelection.text ||
794
+ !ideSelection.filePath) {
795
+ return [];
796
+ }
797
+ const appState = toolUseContext.getAppState();
798
+ if (isFileReadDenied(ideSelection.filePath, appState.toolPermissionContext)) {
799
+ return [];
800
+ }
801
+ return [
802
+ {
803
+ type: 'selected_lines_in_ide',
804
+ ideName,
805
+ lineStart: ideSelection.lineStart,
806
+ lineEnd: ideSelection.lineStart + ideSelection.lineCount - 1,
807
+ filename: ideSelection.filePath,
808
+ content: ideSelection.text,
809
+ displayPath: relative(getCwd(), ideSelection.filePath),
810
+ },
811
+ ];
812
+ }
813
+ /**
814
+ * Computes the directories to process for nested memory file loading.
815
+ * Returns two lists:
816
+ * - nestedDirs: Directories between CWD and targetPath (processed for THADDEUS.md + all rules)
817
+ * - cwdLevelDirs: Directories from root to CWD (processed for conditional rules only)
818
+ *
819
+ * @param targetPath The target file path
820
+ * @param originalCwd The original current working directory
821
+ * @returns Object with nestedDirs and cwdLevelDirs arrays, both ordered from parent to child
822
+ */
823
+ export function getDirectoriesToProcess(targetPath, originalCwd) {
824
+ // Build list of directories from original CWD to targetPath's directory
825
+ const targetDir = dirname(resolve(targetPath));
826
+ const nestedDirs = [];
827
+ let currentDir = targetDir;
828
+ // Walk up from target directory to original CWD
829
+ while (currentDir !== originalCwd && currentDir !== parse(currentDir).root) {
830
+ if (currentDir.startsWith(originalCwd)) {
831
+ nestedDirs.push(currentDir);
832
+ }
833
+ currentDir = dirname(currentDir);
834
+ }
835
+ // Reverse to get order from CWD down to target
836
+ nestedDirs.reverse();
837
+ // Build list of directories from root to CWD (for conditional rules only)
838
+ const cwdLevelDirs = [];
839
+ currentDir = originalCwd;
840
+ while (currentDir !== parse(currentDir).root) {
841
+ cwdLevelDirs.push(currentDir);
842
+ currentDir = dirname(currentDir);
843
+ }
844
+ // Reverse to get order from root to CWD
845
+ cwdLevelDirs.reverse();
846
+ return { nestedDirs, cwdLevelDirs };
847
+ }
848
+ /**
849
+ * Converts memory files to attachments, filtering out already-loaded files.
850
+ *
851
+ * @param memoryFiles The memory files to convert
852
+ * @param toolUseContext The tool use context (for tracking loaded files)
853
+ * @returns Array of nested memory attachments
854
+ */
855
+ function isInstructionsMemoryType(type) {
856
+ return (type === 'User' ||
857
+ type === 'Project' ||
858
+ type === 'Local' ||
859
+ type === 'Managed');
860
+ }
861
+ /** Exported for testing — regression guard for LRU-eviction re-injection. */
862
+ export function memoryFilesToAttachments(memoryFiles, toolUseContext, triggerFilePath) {
863
+ const attachments = [];
864
+ const shouldFireHook = hasInstructionsLoadedHook();
865
+ for (const memoryFile of memoryFiles) {
866
+ // Dedup: loadedNestedMemoryPaths is a non-evicting Set; readFileState
867
+ // is a 100-entry LRU that drops entries in busy sessions, so relying
868
+ // on it alone re-injects the same THADDEUS.md on every eviction cycle.
869
+ if (toolUseContext.loadedNestedMemoryPaths?.has(memoryFile.path)) {
870
+ continue;
871
+ }
872
+ if (!toolUseContext.readFileState.has(memoryFile.path)) {
873
+ attachments.push({
874
+ type: 'nested_memory',
875
+ path: memoryFile.path,
876
+ content: memoryFile,
877
+ displayPath: relative(getCwd(), memoryFile.path),
878
+ });
879
+ toolUseContext.loadedNestedMemoryPaths?.add(memoryFile.path);
880
+ // Mark as loaded in readFileState — this provides cross-function and
881
+ // cross-turn dedup via the .has() check above.
882
+ //
883
+ // When the injected content doesn't match disk (stripped HTML comments,
884
+ // stripped frontmatter, truncated MEMORY.md), cache the RAW disk bytes
885
+ // with `isPartialView: true`. Edit/Write see the flag and require a real
886
+ // Read first; getChangedFiles sees real content + undefined offset/limit
887
+ // so mid-session change detection still works.
888
+ toolUseContext.readFileState.set(memoryFile.path, {
889
+ content: memoryFile.contentDiffersFromDisk
890
+ ? (memoryFile.rawContent ?? memoryFile.content)
891
+ : memoryFile.content,
892
+ timestamp: Date.now(),
893
+ offset: undefined,
894
+ limit: undefined,
895
+ isPartialView: memoryFile.contentDiffersFromDisk,
896
+ });
897
+ // Fire InstructionsLoaded hook for audit/observability (fire-and-forget)
898
+ if (shouldFireHook && isInstructionsMemoryType(memoryFile.type)) {
899
+ const loadReason = memoryFile.globs
900
+ ? 'path_glob_match'
901
+ : memoryFile.parent
902
+ ? 'include'
903
+ : 'nested_traversal';
904
+ void executeInstructionsLoadedHooks(memoryFile.path, memoryFile.type, loadReason, {
905
+ globs: memoryFile.globs,
906
+ triggerFilePath,
907
+ parentFilePath: memoryFile.parent,
908
+ });
909
+ }
910
+ }
911
+ }
912
+ return attachments;
913
+ }
914
+ /**
915
+ * Loads nested memory files for a given file path and returns them as attachments.
916
+ * This function performs directory traversal to find THADDEUS.md files and conditional rules
917
+ * that apply to the target file path.
918
+ *
919
+ * Processing order (must be preserved):
920
+ * 1. Managed/User conditional rules matching targetPath
921
+ * 2. Nested directories (CWD → target): THADDEUS.md + unconditional + conditional rules
922
+ * 3. CWD-level directories (root → CWD): conditional rules only
923
+ *
924
+ * @param filePath The file path to get nested memory files for
925
+ * @param toolUseContext The tool use context
926
+ * @param appState The app state containing tool permission context
927
+ * @returns Array of nested memory attachments
928
+ */
929
+ async function getNestedMemoryAttachmentsForFile(filePath, toolUseContext, appState) {
930
+ const attachments = [];
931
+ try {
932
+ // Early return if path is not in allowed working path
933
+ if (!pathInAllowedWorkingPath(filePath, appState.toolPermissionContext)) {
934
+ return attachments;
935
+ }
936
+ const processedPaths = new Set();
937
+ const originalCwd = getOriginalCwd();
938
+ // Phase 1: Process Managed and User conditional rules
939
+ const managedUserRules = await getManagedAndUserConditionalRules(filePath, processedPaths);
940
+ attachments.push(...memoryFilesToAttachments(managedUserRules, toolUseContext, filePath));
941
+ // Phase 2: Get directories to process
942
+ const { nestedDirs, cwdLevelDirs } = getDirectoriesToProcess(filePath, originalCwd);
943
+ const skipProjectLevel = getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_paper_halyard', false);
944
+ // Phase 3: Process nested directories (CWD → target)
945
+ // Each directory gets: THADDEUS.md + unconditional rules + conditional rules
946
+ for (const dir of nestedDirs) {
947
+ const memoryFiles = (await getMemoryFilesForNestedDirectory(dir, filePath, processedPaths)).filter(f => !skipProjectLevel || (f.type !== 'Project' && f.type !== 'Local'));
948
+ attachments.push(...memoryFilesToAttachments(memoryFiles, toolUseContext, filePath));
949
+ }
950
+ // Phase 4: Process CWD-level directories (root → CWD)
951
+ // Only conditional rules (unconditional rules are already loaded eagerly)
952
+ for (const dir of cwdLevelDirs) {
953
+ const conditionalRules = (await getConditionalRulesForCwdLevelDirectory(dir, filePath, processedPaths)).filter(f => !skipProjectLevel || (f.type !== 'Project' && f.type !== 'Local'));
954
+ attachments.push(...memoryFilesToAttachments(conditionalRules, toolUseContext, filePath));
955
+ }
956
+ }
957
+ catch (error) {
958
+ logError(error);
959
+ }
960
+ return attachments;
961
+ }
962
+ async function getOpenedFileFromIDE(ideSelection, toolUseContext) {
963
+ if (!ideSelection?.filePath || ideSelection.text) {
964
+ return [];
965
+ }
966
+ const appState = toolUseContext.getAppState();
967
+ if (isFileReadDenied(ideSelection.filePath, appState.toolPermissionContext)) {
968
+ return [];
969
+ }
970
+ // Get nested memory files
971
+ const nestedMemoryAttachments = await getNestedMemoryAttachmentsForFile(ideSelection.filePath, toolUseContext, appState);
972
+ // Return nested memory attachments followed by the opened file attachment
973
+ return [
974
+ ...nestedMemoryAttachments,
975
+ {
976
+ type: 'opened_file_in_ide',
977
+ filename: ideSelection.filePath,
978
+ },
979
+ ];
980
+ }
981
+ async function processAtMentionedFiles(input, toolUseContext) {
982
+ const files = extractAtMentionedFiles(input);
983
+ if (files.length === 0)
984
+ return [];
985
+ const appState = toolUseContext.getAppState();
986
+ const results = await Promise.all(files.map(async (file) => {
987
+ try {
988
+ const { filename, lineStart, lineEnd } = parseAtMentionedFileLines(file);
989
+ const absoluteFilename = expandPath(filename);
990
+ if (isFileReadDenied(absoluteFilename, appState.toolPermissionContext)) {
991
+ return null;
992
+ }
993
+ // Check if it's a directory
994
+ try {
995
+ const stats = await stat(absoluteFilename);
996
+ if (stats.isDirectory()) {
997
+ try {
998
+ const entries = await readdir(absoluteFilename, {
999
+ withFileTypes: true,
1000
+ });
1001
+ const MAX_DIR_ENTRIES = 1000;
1002
+ const truncated = entries.length > MAX_DIR_ENTRIES;
1003
+ const names = entries.slice(0, MAX_DIR_ENTRIES).map(e => e.name);
1004
+ if (truncated) {
1005
+ names.push(`\u2026 and ${entries.length - MAX_DIR_ENTRIES} more entries`);
1006
+ }
1007
+ const stdout = names.join('\n');
1008
+ logEvent('thaddeus_at_mention_extracting_directory_success', {});
1009
+ return {
1010
+ type: 'directory',
1011
+ path: absoluteFilename,
1012
+ content: stdout,
1013
+ displayPath: relative(getCwd(), absoluteFilename),
1014
+ };
1015
+ }
1016
+ catch {
1017
+ return null;
1018
+ }
1019
+ }
1020
+ }
1021
+ catch {
1022
+ // If stat fails, continue with file logic
1023
+ }
1024
+ return await generateFileAttachment(absoluteFilename, toolUseContext, 'thaddeus_at_mention_extracting_filename_success', 'thaddeus_at_mention_extracting_filename_error', 'at-mention', {
1025
+ offset: lineStart,
1026
+ limit: lineEnd && lineStart ? lineEnd - lineStart + 1 : undefined,
1027
+ });
1028
+ }
1029
+ catch {
1030
+ logEvent('thaddeus_at_mention_extracting_filename_error', {});
1031
+ }
1032
+ }));
1033
+ return results.filter(Boolean);
1034
+ }
1035
+ function processAgentMentions(input, agents) {
1036
+ const agentMentions = extractAgentMentions(input);
1037
+ if (agentMentions.length === 0)
1038
+ return [];
1039
+ const results = agentMentions.map(mention => {
1040
+ const agentType = mention.replace('agent-', '');
1041
+ const agentDef = agents.find(def => def.agentType === agentType);
1042
+ if (!agentDef) {
1043
+ logEvent('thaddeus_at_mention_agent_not_found', {});
1044
+ return null;
1045
+ }
1046
+ logEvent('thaddeus_at_mention_agent_success', {});
1047
+ return {
1048
+ type: 'agent_mention',
1049
+ agentType: agentDef.agentType,
1050
+ };
1051
+ });
1052
+ return results.filter((result) => result !== null);
1053
+ }
1054
+ async function processMcpResourceAttachments(input, toolUseContext) {
1055
+ const resourceMentions = extractMcpResourceMentions(input);
1056
+ if (resourceMentions.length === 0)
1057
+ return [];
1058
+ const mcpClients = toolUseContext.options.mcpClients || [];
1059
+ const results = await Promise.all(resourceMentions.map(async (mention) => {
1060
+ try {
1061
+ const [serverName, ...uriParts] = mention.split(':');
1062
+ const uri = uriParts.join(':'); // Rejoin in case URI contains colons
1063
+ if (!serverName || !uri) {
1064
+ logEvent('thaddeus_at_mention_mcp_resource_error', {});
1065
+ return null;
1066
+ }
1067
+ // Find the MCP client
1068
+ const client = mcpClients.find(c => c.name === serverName);
1069
+ if (!client || client.type !== 'connected') {
1070
+ logEvent('thaddeus_at_mention_mcp_resource_error', {});
1071
+ return null;
1072
+ }
1073
+ // Find the resource in available resources to get its metadata
1074
+ const serverResources = toolUseContext.options.mcpResources?.[serverName] || [];
1075
+ const resourceInfo = serverResources.find(r => r.uri === uri);
1076
+ if (!resourceInfo) {
1077
+ logEvent('thaddeus_at_mention_mcp_resource_error', {});
1078
+ return null;
1079
+ }
1080
+ try {
1081
+ const result = await client.client.readResource({
1082
+ uri,
1083
+ });
1084
+ logEvent('thaddeus_at_mention_mcp_resource_success', {});
1085
+ return {
1086
+ type: 'mcp_resource',
1087
+ server: serverName,
1088
+ uri,
1089
+ name: resourceInfo.name || uri,
1090
+ description: resourceInfo.description,
1091
+ content: result,
1092
+ };
1093
+ }
1094
+ catch (error) {
1095
+ logEvent('thaddeus_at_mention_mcp_resource_error', {});
1096
+ logError(error);
1097
+ return null;
1098
+ }
1099
+ }
1100
+ catch {
1101
+ logEvent('thaddeus_at_mention_mcp_resource_error', {});
1102
+ return null;
1103
+ }
1104
+ }));
1105
+ return results.filter((result) => result !== null);
1106
+ }
1107
+ export async function getChangedFiles(toolUseContext) {
1108
+ const filePaths = cacheKeys(toolUseContext.readFileState);
1109
+ if (filePaths.length === 0)
1110
+ return [];
1111
+ const appState = toolUseContext.getAppState();
1112
+ const results = await Promise.all(filePaths.map(async (filePath) => {
1113
+ const fileState = toolUseContext.readFileState.get(filePath);
1114
+ if (!fileState)
1115
+ return null;
1116
+ // TODO: Implement offset/limit support for changed files
1117
+ if (fileState.offset !== undefined || fileState.limit !== undefined) {
1118
+ return null;
1119
+ }
1120
+ const normalizedPath = expandPath(filePath);
1121
+ // Check if file has a deny rule configured
1122
+ if (isFileReadDenied(normalizedPath, appState.toolPermissionContext)) {
1123
+ return null;
1124
+ }
1125
+ try {
1126
+ const mtime = await getFileModificationTimeAsync(normalizedPath);
1127
+ if (mtime <= fileState.timestamp) {
1128
+ return null;
1129
+ }
1130
+ const fileInput = { file_path: normalizedPath };
1131
+ // Validate file path is valid
1132
+ const isValid = await FileReadTool.validateInput(fileInput, toolUseContext);
1133
+ if (!isValid.result) {
1134
+ return null;
1135
+ }
1136
+ const result = await FileReadTool.call(fileInput, toolUseContext);
1137
+ // Extract only the changed section
1138
+ if (result.data.type === 'text') {
1139
+ const snippet = getSnippetForTwoFileDiff(fileState.content, result.data.file.content);
1140
+ // File was touched but not modified
1141
+ if (snippet === '') {
1142
+ return null;
1143
+ }
1144
+ return {
1145
+ type: 'edited_text_file',
1146
+ filename: normalizedPath,
1147
+ snippet,
1148
+ };
1149
+ }
1150
+ // For non-text files (images), apply the same token limit logic as FileReadTool
1151
+ if (result.data.type === 'image') {
1152
+ try {
1153
+ const data = await readImageWithTokenBudget(normalizedPath);
1154
+ return {
1155
+ type: 'edited_image_file',
1156
+ filename: normalizedPath,
1157
+ content: data,
1158
+ };
1159
+ }
1160
+ catch (compressionError) {
1161
+ logError(compressionError);
1162
+ logEvent('thaddeus_watched_file_compression_failed', {
1163
+ file: normalizedPath,
1164
+ });
1165
+ return null;
1166
+ }
1167
+ }
1168
+ // notebook / pdf / parts — no diff representation; explicitly
1169
+ // null so the map callback has no implicit-undefined path.
1170
+ return null;
1171
+ }
1172
+ catch (err) {
1173
+ // Evict ONLY on ENOENT (file truly deleted). Transient stat
1174
+ // failures — atomic-save races (editor writes tmp→rename and
1175
+ // stat hits the gap), EACCES churn, network-FS hiccups — must
1176
+ // NOT evict, or the next Edit fails code-6 even though the
1177
+ // file still exists and the model just read it. VS Code
1178
+ // auto-save/format-on-save hits this race especially often.
1179
+ // See regression analysis on PR #18525.
1180
+ if (isENOENT(err)) {
1181
+ toolUseContext.readFileState.delete(filePath);
1182
+ }
1183
+ return null;
1184
+ }
1185
+ }));
1186
+ return results.filter(result => result != null);
1187
+ }
1188
+ /**
1189
+ * Processes paths that need nested memory attachments and checks for nested THADDEUS.md files
1190
+ * Uses nestedMemoryAttachmentTriggers field from ToolUseContext
1191
+ */
1192
+ async function getNestedMemoryAttachments(toolUseContext) {
1193
+ // Check triggers first — getAppState() waits for a React render cycle,
1194
+ // and the common case is an empty trigger set.
1195
+ if (!toolUseContext.nestedMemoryAttachmentTriggers ||
1196
+ toolUseContext.nestedMemoryAttachmentTriggers.size === 0) {
1197
+ return [];
1198
+ }
1199
+ const appState = toolUseContext.getAppState();
1200
+ const attachments = [];
1201
+ for (const filePath of toolUseContext.nestedMemoryAttachmentTriggers) {
1202
+ const nestedAttachments = await getNestedMemoryAttachmentsForFile(filePath, toolUseContext, appState);
1203
+ attachments.push(...nestedAttachments);
1204
+ }
1205
+ toolUseContext.nestedMemoryAttachmentTriggers.clear();
1206
+ return attachments;
1207
+ }
1208
+ async function getRelevantMemoryAttachments(input, agents, readFileState, recentTools, signal, alreadySurfaced) {
1209
+ // If an agent is @-mentioned, search only its memory dir (isolation).
1210
+ // Otherwise search the auto-memory dir.
1211
+ const memoryDirs = extractAgentMentions(input).flatMap(mention => {
1212
+ const agentType = mention.replace('agent-', '');
1213
+ const agentDef = agents.find(def => def.agentType === agentType);
1214
+ return agentDef?.memory
1215
+ ? [getAgentMemoryDir(agentType, agentDef.memory)]
1216
+ : [];
1217
+ });
1218
+ const dirs = memoryDirs.length > 0 ? memoryDirs : [getAutoMemPath()];
1219
+ const allResults = await Promise.all(dirs.map(dir => findRelevantMemories(input, dir, signal, recentTools, alreadySurfaced).catch(() => [])));
1220
+ // alreadySurfaced is filtered inside the selector so Sonnet spends its
1221
+ // 5-slot budget on fresh candidates; readFileState catches files the
1222
+ // model read via FileReadTool. The redundant alreadySurfaced check here
1223
+ // is a belt-and-suspenders guard (multi-dir results may re-introduce a
1224
+ // path the selector filtered in a different dir).
1225
+ const selected = allResults
1226
+ .flat()
1227
+ .filter(m => !readFileState.has(m.path) && !alreadySurfaced.has(m.path))
1228
+ .slice(0, 5);
1229
+ const memories = await readMemoriesForSurfacing(selected, signal);
1230
+ if (memories.length === 0) {
1231
+ return [];
1232
+ }
1233
+ return [{ type: 'relevant_memories', memories }];
1234
+ }
1235
+ /**
1236
+ * Scan messages for past relevant_memories attachments. Returns both the
1237
+ * set of surfaced paths (for selector de-dup) and cumulative byte count
1238
+ * (for session-total throttle). Scanning messages rather than tracking
1239
+ * in toolUseContext means compact naturally resets both — old attachments
1240
+ * are gone from the compacted transcript, so re-surfacing is valid again.
1241
+ */
1242
+ export function collectSurfacedMemories(messages) {
1243
+ const paths = new Set();
1244
+ let totalBytes = 0;
1245
+ for (const m of messages) {
1246
+ if (m.type === 'attachment' && m.attachment.type === 'relevant_memories') {
1247
+ for (const mem of m.attachment.memories) {
1248
+ paths.add(mem.path);
1249
+ totalBytes += mem.content.length;
1250
+ }
1251
+ }
1252
+ }
1253
+ return { paths, totalBytes };
1254
+ }
1255
+ /**
1256
+ * Reads a set of relevance-ranked memory files for injection as
1257
+ * <system-reminder> attachments. Enforces both MAX_MEMORY_LINES and
1258
+ * MAX_MEMORY_BYTES via readFileInRange's truncateOnByteLimit option.
1259
+ * Truncation surfaces partial
1260
+ * content with a note rather than dropping the file — findRelevantMemories
1261
+ * already picked this as most-relevant, so the frontmatter + opening context
1262
+ * is worth surfacing even if later lines are cut.
1263
+ *
1264
+ * Exported for direct testing without mocking the ranker + GB gates.
1265
+ */
1266
+ export async function readMemoriesForSurfacing(selected, signal) {
1267
+ const results = await Promise.all(selected.map(async ({ path: filePath, mtimeMs }) => {
1268
+ try {
1269
+ const result = await readFileInRange(filePath, 0, MAX_MEMORY_LINES, MAX_MEMORY_BYTES, signal, { truncateOnByteLimit: true });
1270
+ const truncated = result.totalLines > MAX_MEMORY_LINES || result.truncatedByBytes;
1271
+ const content = truncated
1272
+ ? result.content +
1273
+ `\n\n> This memory file was truncated (${result.truncatedByBytes ? `${MAX_MEMORY_BYTES} byte limit` : `first ${MAX_MEMORY_LINES} lines`}). Use the ${FILE_READ_TOOL_NAME} tool to view the complete file at: ${filePath}`
1274
+ : result.content;
1275
+ return {
1276
+ path: filePath,
1277
+ content,
1278
+ mtimeMs,
1279
+ header: memoryHeader(filePath, mtimeMs),
1280
+ limit: truncated ? result.lineCount : undefined,
1281
+ };
1282
+ }
1283
+ catch {
1284
+ return null;
1285
+ }
1286
+ }));
1287
+ return results.filter(r => r !== null);
1288
+ }
1289
+ /**
1290
+ * Header string for a relevant-memory block. Exported so messages.ts
1291
+ * can fall back for resumed sessions where the stored header is missing.
1292
+ */
1293
+ export function memoryHeader(path, mtimeMs) {
1294
+ const staleness = memoryFreshnessText(mtimeMs);
1295
+ return staleness
1296
+ ? `${staleness}\n\nMemory: ${path}:`
1297
+ : `Memory (saved ${memoryAge(mtimeMs)}): ${path}:`;
1298
+ }
1299
+ /**
1300
+ * Starts the relevant memory search as an async prefetch.
1301
+ * Extracts the last real user prompt from messages (skipping isMeta system
1302
+ * injections) and kicks off a non-blocking search. Returns a Disposable
1303
+ * handle with settlement tracking. Bound with `using` in query.ts.
1304
+ */
1305
+ export function startRelevantMemoryPrefetch(messages, toolUseContext) {
1306
+ if (!isAutoMemoryEnabled() ||
1307
+ !getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_moth_copse', false)) {
1308
+ return undefined;
1309
+ }
1310
+ const lastUserMessage = messages.findLast(m => m.type === 'user' && !m.isMeta);
1311
+ if (!lastUserMessage) {
1312
+ return undefined;
1313
+ }
1314
+ const input = getUserMessageText(lastUserMessage);
1315
+ // Single-word prompts lack enough context for meaningful term extraction
1316
+ if (!input || !/\s/.test(input.trim())) {
1317
+ return undefined;
1318
+ }
1319
+ const surfaced = collectSurfacedMemories(messages);
1320
+ if (surfaced.totalBytes >= RELEVANT_MEMORIES_CONFIG.MAX_SESSION_BYTES) {
1321
+ return undefined;
1322
+ }
1323
+ // Chained to the turn-level abort so user Escape cancels the sideQuery
1324
+ // immediately, not just on [Symbol.dispose] when queryLoop exits.
1325
+ const controller = createChildAbortController(toolUseContext.abortController);
1326
+ const firedAt = Date.now();
1327
+ const promise = getRelevantMemoryAttachments(input, toolUseContext.options.agentDefinitions.activeAgents, toolUseContext.readFileState, collectRecentSuccessfulTools(messages, lastUserMessage), controller.signal, surfaced.paths).catch(e => {
1328
+ if (!isAbortError(e)) {
1329
+ logError(e);
1330
+ }
1331
+ return [];
1332
+ });
1333
+ const handle = {
1334
+ promise,
1335
+ settledAt: null,
1336
+ consumedOnIteration: -1,
1337
+ [Symbol.dispose]() {
1338
+ controller.abort();
1339
+ logEvent('thaddeus_memdir_prefetch_collected', {
1340
+ hidden_by_first_iteration: handle.settledAt !== null && handle.consumedOnIteration === 0,
1341
+ consumed_on_iteration: handle.consumedOnIteration,
1342
+ latency_ms: (handle.settledAt ?? Date.now()) - firedAt,
1343
+ });
1344
+ },
1345
+ };
1346
+ void promise.finally(() => {
1347
+ handle.settledAt = Date.now();
1348
+ });
1349
+ return handle;
1350
+ }
1351
+ function isToolResultBlock(b) {
1352
+ return (typeof b === 'object' &&
1353
+ b !== null &&
1354
+ b.type === 'tool_result' &&
1355
+ typeof b.tool_use_id === 'string');
1356
+ }
1357
+ /**
1358
+ * Check whether a user message's content contains tool_result blocks.
1359
+ * This is more reliable than checking `toolUseResult === undefined` because
1360
+ * sub-agent tool result messages explicitly set `toolUseResult` to `undefined`
1361
+ * when `preserveToolUseResults` is false (the default for Explore agents).
1362
+ */
1363
+ function hasToolResultContent(content) {
1364
+ return Array.isArray(content) && content.some(isToolResultBlock);
1365
+ }
1366
+ /**
1367
+ * Tools that succeeded (and never errored) since the previous real turn
1368
+ * boundary. The memory selector uses this to suppress docs about tools
1369
+ * that are working — surfacing reference material for a tool the model
1370
+ * is already calling successfully is noise.
1371
+ *
1372
+ * Any error → tool excluded (model is struggling, docs stay available).
1373
+ * No result yet → also excluded (outcome unknown).
1374
+ *
1375
+ * tool_use lives in assistant content; tool_result in user content
1376
+ * (toolUseResult set, isMeta undefined). Both are within the scan window.
1377
+ * Backward scan sees results before uses so we collect both by id and
1378
+ * resolve after.
1379
+ */
1380
+ export function collectRecentSuccessfulTools(messages, lastUserMessage) {
1381
+ const useIdToName = new Map();
1382
+ const resultByUseId = new Map();
1383
+ for (let i = messages.length - 1; i >= 0; i--) {
1384
+ const m = messages[i];
1385
+ if (!m)
1386
+ continue;
1387
+ if (isHumanTurn(m) && m !== lastUserMessage)
1388
+ break;
1389
+ if (m.type === 'assistant' && typeof m.message.content !== 'string') {
1390
+ for (const block of m.message.content) {
1391
+ if (block.type === 'tool_use')
1392
+ useIdToName.set(block.id, block.name);
1393
+ }
1394
+ }
1395
+ else if (m.type === 'user' &&
1396
+ 'message' in m &&
1397
+ Array.isArray(m.message.content)) {
1398
+ for (const block of m.message.content) {
1399
+ if (isToolResultBlock(block)) {
1400
+ resultByUseId.set(block.tool_use_id, block.is_error === true);
1401
+ }
1402
+ }
1403
+ }
1404
+ }
1405
+ const failed = new Set();
1406
+ const succeeded = new Set();
1407
+ for (const [id, name] of useIdToName) {
1408
+ const errored = resultByUseId.get(id);
1409
+ if (errored === undefined)
1410
+ continue;
1411
+ if (errored) {
1412
+ failed.add(name);
1413
+ }
1414
+ else {
1415
+ succeeded.add(name);
1416
+ }
1417
+ }
1418
+ return [...succeeded].filter(t => !failed.has(t));
1419
+ }
1420
+ /**
1421
+ * Filters prefetched memory attachments to exclude memories the model already
1422
+ * has in context via FileRead/Write/Edit tool calls (any iteration this turn)
1423
+ * or a previous turn's memory surfacing — both tracked in the cumulative
1424
+ * readFileState. Survivors are then marked in readFileState so subsequent
1425
+ * turns won't re-surface them.
1426
+ *
1427
+ * The mark-after-filter ordering is load-bearing: readMemoriesForSurfacing
1428
+ * used to write to readFileState during the prefetch, which meant the filter
1429
+ * saw every prefetch-selected path as "already in context" and dropped them
1430
+ * all (self-referential filter). Deferring the write to here, after the
1431
+ * filter runs, breaks that cycle while still deduping against tool calls
1432
+ * from any iteration.
1433
+ */
1434
+ export function filterDuplicateMemoryAttachments(attachments, readFileState) {
1435
+ return attachments
1436
+ .map(attachment => {
1437
+ if (attachment.type !== 'relevant_memories')
1438
+ return attachment;
1439
+ const filtered = attachment.memories.filter(m => !readFileState.has(m.path));
1440
+ for (const m of filtered) {
1441
+ readFileState.set(m.path, {
1442
+ content: m.content,
1443
+ timestamp: m.mtimeMs,
1444
+ offset: undefined,
1445
+ limit: m.limit,
1446
+ });
1447
+ }
1448
+ return filtered.length > 0 ? { ...attachment, memories: filtered } : null;
1449
+ })
1450
+ .filter((a) => a !== null);
1451
+ }
1452
+ /**
1453
+ * Processes skill directories that were discovered during file operations.
1454
+ * Uses dynamicSkillDirTriggers field from ToolUseContext
1455
+ */
1456
+ async function getDynamicSkillAttachments(toolUseContext) {
1457
+ const attachments = [];
1458
+ if (toolUseContext.dynamicSkillDirTriggers &&
1459
+ toolUseContext.dynamicSkillDirTriggers.size > 0) {
1460
+ // Parallelize: readdir all skill dirs concurrently
1461
+ const perDirResults = await Promise.all(Array.from(toolUseContext.dynamicSkillDirTriggers).map(async (skillDir) => {
1462
+ try {
1463
+ const entries = await readdir(skillDir, { withFileTypes: true });
1464
+ const candidates = entries
1465
+ .filter(e => e.isDirectory() || e.isSymbolicLink())
1466
+ .map(e => e.name);
1467
+ // Parallelize: stat all SKILL.md candidates concurrently
1468
+ const checked = await Promise.all(candidates.map(async (name) => {
1469
+ try {
1470
+ await stat(resolve(skillDir, name, 'SKILL.md'));
1471
+ return name;
1472
+ }
1473
+ catch {
1474
+ return null; // SKILL.md doesn't exist, skip this entry
1475
+ }
1476
+ }));
1477
+ return {
1478
+ skillDir,
1479
+ skillNames: checked.filter((n) => n !== null),
1480
+ };
1481
+ }
1482
+ catch {
1483
+ // Ignore errors reading skill directories (e.g., directory doesn't exist)
1484
+ return { skillDir, skillNames: [] };
1485
+ }
1486
+ }));
1487
+ for (const { skillDir, skillNames } of perDirResults) {
1488
+ if (skillNames.length > 0) {
1489
+ attachments.push({
1490
+ type: 'dynamic_skill',
1491
+ skillDir,
1492
+ skillNames,
1493
+ displayPath: relative(getCwd(), skillDir),
1494
+ });
1495
+ }
1496
+ }
1497
+ toolUseContext.dynamicSkillDirTriggers.clear();
1498
+ }
1499
+ return attachments;
1500
+ }
1501
+ // Track which skills have been sent to avoid re-sending. Keyed by agentId
1502
+ // (empty string = main thread) so subagents get their own turn-0 listing —
1503
+ // without per-agent scoping, the main thread populating this Set would cause
1504
+ // every subagent's filterToBundledAndMcp result to dedup to empty.
1505
+ const sentSkillNames = new Map();
1506
+ // Called when the skill set genuinely changes (plugin reload, skill file
1507
+ // change on disk) so new skills get announced. NOT called on compact —
1508
+ // post-compact re-injection costs ~4K tokens/event for marginal benefit.
1509
+ export function resetSentSkillNames() {
1510
+ sentSkillNames.clear();
1511
+ suppressNext = false;
1512
+ }
1513
+ /**
1514
+ * Suppress the next skill-listing injection. Called by conversationRecovery
1515
+ * on --resume when a skill_listing attachment already exists in the
1516
+ * transcript.
1517
+ *
1518
+ * `sentSkillNames` is module-scope — process-local. Each `claude -p` spawn
1519
+ * starts with an empty Map, so without this every resume re-injects the
1520
+ * full ~600-token listing even though it's already in the conversation from
1521
+ * the prior process. Shows up on every --resume; particularly loud for
1522
+ * daemons that respawn frequently.
1523
+ *
1524
+ * Trade-off: skills added between sessions won't be announced until the
1525
+ * next non-resume session. Acceptable — skill_listing was never meant to
1526
+ * cover cross-process deltas, and the agent can still call them (they're
1527
+ * in the Skill tool's runtime registry regardless).
1528
+ */
1529
+ export function suppressNextSkillListing() {
1530
+ suppressNext = true;
1531
+ }
1532
+ let suppressNext = false;
1533
+ // When skill-search is enabled and the filtered (bundled + MCP) listing exceeds
1534
+ // this count, fall back to bundled-only. Protects MCP-heavy users (100+ servers)
1535
+ // from truncation while keeping the turn-0 guarantee for typical setups.
1536
+ const FILTERED_LISTING_MAX = 30;
1537
+ /**
1538
+ * Filter skills to bundled (Anthropic-curated) + MCP (user-connected) only.
1539
+ * Used when skill-search is enabled to resolve the turn-0 gap for subagents:
1540
+ * these sources are small, intent-signaled, and won't hit the truncation budget.
1541
+ * User/project/plugin skills (the long tail — 200+) go through discovery instead.
1542
+ *
1543
+ * Falls back to bundled-only if bundled+mcp exceeds FILTERED_LISTING_MAX.
1544
+ */
1545
+ export function filterToBundledAndMcp(commands) {
1546
+ const filtered = commands.filter(cmd => cmd.loadedFrom === 'bundled' || cmd.loadedFrom === 'mcp');
1547
+ if (filtered.length > FILTERED_LISTING_MAX) {
1548
+ return filtered.filter(cmd => cmd.loadedFrom === 'bundled');
1549
+ }
1550
+ return filtered;
1551
+ }
1552
+ async function getSkillListingAttachments(toolUseContext) {
1553
+ if (process.env.NODE_ENV === 'test') {
1554
+ return [];
1555
+ }
1556
+ // Skip skill listing for agents that don't have the Skill tool — they can't use skills directly.
1557
+ if (!toolUseContext.options.tools.some(t => toolMatchesName(t, SKILL_TOOL_NAME))) {
1558
+ return [];
1559
+ }
1560
+ const cwd = getProjectRoot();
1561
+ const localCommands = await getSkillToolCommands(cwd);
1562
+ const mcpSkills = getMcpSkillCommands(toolUseContext.getAppState().mcp.commands);
1563
+ let allCommands = mcpSkills.length > 0
1564
+ ? uniqBy([...localCommands, ...mcpSkills], 'name')
1565
+ : localCommands;
1566
+ // When skill search is active, filter to bundled + MCP instead of full
1567
+ // suppression. Resolves the turn-0 gap: main thread gets turn-0 discovery
1568
+ // via getTurnZeroSkillDiscovery (blocking), but subagents use the async
1569
+ // subagent_spawn signal (collected post-tools, visible turn 1). Bundled +
1570
+ // MCP are small and intent-signaled; user/project/plugin skills go through
1571
+ // discovery. feature() first for DCE — the property-access string leaks
1572
+ // otherwise even with ?. on null.
1573
+ if (feature('EXPERIMENTAL_SKILL_SEARCH') &&
1574
+ skillSearchModules?.featureCheck.isSkillSearchEnabled()) {
1575
+ allCommands = filterToBundledAndMcp(allCommands);
1576
+ }
1577
+ const agentKey = toolUseContext.agentId ?? '';
1578
+ let sent = sentSkillNames.get(agentKey);
1579
+ if (!sent) {
1580
+ sent = new Set();
1581
+ sentSkillNames.set(agentKey, sent);
1582
+ }
1583
+ // Resume path: prior process already injected a listing; it's in the
1584
+ // transcript. Mark everything current as sent so only post-resume deltas
1585
+ // (skills loaded later via /reload-plugins etc) get announced.
1586
+ if (suppressNext) {
1587
+ suppressNext = false;
1588
+ for (const cmd of allCommands) {
1589
+ sent.add(cmd.name);
1590
+ }
1591
+ return [];
1592
+ }
1593
+ // Find skills we haven't sent yet
1594
+ const newSkills = allCommands.filter(cmd => !sent.has(cmd.name));
1595
+ if (newSkills.length === 0) {
1596
+ return [];
1597
+ }
1598
+ // If no skills have been sent yet, this is the initial batch
1599
+ const isInitial = sent.size === 0;
1600
+ // Mark as sent
1601
+ for (const cmd of newSkills) {
1602
+ sent.add(cmd.name);
1603
+ }
1604
+ logForDebugging(`Sending ${newSkills.length} skills via attachment (${isInitial ? 'initial' : 'dynamic'}, ${sent.size} total sent)`);
1605
+ // Format within budget using existing logic
1606
+ const contextWindowTokens = getContextWindowForModel(toolUseContext.options.mainLoopModel, getSdkBetas());
1607
+ const content = formatCommandsWithinBudget(newSkills, contextWindowTokens);
1608
+ return [
1609
+ {
1610
+ type: 'skill_listing',
1611
+ content,
1612
+ skillCount: newSkills.length,
1613
+ isInitial,
1614
+ },
1615
+ ];
1616
+ }
1617
+ // getSkillDiscoveryAttachment moved to skillSearch/prefetch.ts as
1618
+ // getTurnZeroSkillDiscovery — keeps the 'skill_discovery' string literal inside
1619
+ // a feature-gated module so it doesn't leak into external builds.
1620
+ export function extractAtMentionedFiles(content) {
1621
+ // Extract filenames mentioned with @ symbol, including line range syntax: @file.txt#L10-20
1622
+ // Also supports quoted paths for files with spaces: @"my/file with spaces.txt"
1623
+ // Example: "foo bar @baz moo" would extract "baz"
1624
+ // Example: 'check @"my file.txt" please' would extract "my file.txt"
1625
+ // Two patterns: quoted paths and regular paths
1626
+ const quotedAtMentionRegex = /(^|\s)@"([^"]+)"/g;
1627
+ const regularAtMentionRegex = /(^|\s)@([^\s]+)\b/g;
1628
+ const quotedMatches = [];
1629
+ const regularMatches = [];
1630
+ // Extract quoted mentions first (skip agent mentions like @"code-reviewer (agent)")
1631
+ let match;
1632
+ while ((match = quotedAtMentionRegex.exec(content)) !== null) {
1633
+ if (match[2] && !match[2].endsWith(' (agent)')) {
1634
+ quotedMatches.push(match[2]); // The content inside quotes
1635
+ }
1636
+ }
1637
+ // Extract regular mentions
1638
+ const regularMatchArray = content.match(regularAtMentionRegex) || [];
1639
+ regularMatchArray.forEach(match => {
1640
+ const filename = match.slice(match.indexOf('@') + 1);
1641
+ // Don't include if it starts with a quote (already handled as quoted)
1642
+ if (!filename.startsWith('"')) {
1643
+ regularMatches.push(filename);
1644
+ }
1645
+ });
1646
+ // Combine and deduplicate
1647
+ return uniq([...quotedMatches, ...regularMatches]);
1648
+ }
1649
+ export function extractMcpResourceMentions(content) {
1650
+ // Extract MCP resources mentioned with @ symbol in format @server:uri
1651
+ // Example: "@server1:resource/path" would extract "server1:resource/path"
1652
+ const atMentionRegex = /(^|\s)@([^\s]+:[^\s]+)\b/g;
1653
+ const matches = content.match(atMentionRegex) || [];
1654
+ // Remove the prefix (everything before @) from each match
1655
+ return uniq(matches.map(match => match.slice(match.indexOf('@') + 1)));
1656
+ }
1657
+ export function extractAgentMentions(content) {
1658
+ // Extract agent mentions in two formats:
1659
+ // 1. @agent-<agent-type> (legacy/manual typing)
1660
+ // Example: "@agent-code-elegance-refiner" → "agent-code-elegance-refiner"
1661
+ // 2. @"<agent-type> (agent)" (from autocomplete selection)
1662
+ // Example: '@"code-reviewer (agent)"' → "code-reviewer"
1663
+ // Supports colons, dots, and at-signs for plugin-scoped agents like "@agent-asana:project-status-updater"
1664
+ const results = [];
1665
+ // Match quoted format: @"<type> (agent)"
1666
+ const quotedAgentRegex = /(^|\s)@"([\w:.@-]+) \(agent\)"/g;
1667
+ let match;
1668
+ while ((match = quotedAgentRegex.exec(content)) !== null) {
1669
+ if (match[2]) {
1670
+ results.push(match[2]);
1671
+ }
1672
+ }
1673
+ // Match unquoted format: @agent-<type>
1674
+ const unquotedAgentRegex = /(^|\s)@(agent-[\w:.@-]+)/g;
1675
+ const unquotedMatches = content.match(unquotedAgentRegex) || [];
1676
+ for (const m of unquotedMatches) {
1677
+ results.push(m.slice(m.indexOf('@') + 1));
1678
+ }
1679
+ return uniq(results);
1680
+ }
1681
+ export function parseAtMentionedFileLines(mention) {
1682
+ // Parse mentions like "file.txt#L10-20", "file.txt#heading", or just "file.txt"
1683
+ // Supports line ranges (#L10, #L10-20) and strips non-line-range fragments (#heading)
1684
+ const match = mention.match(/^([^#]+)(?:#L(\d+)(?:-(\d+))?)?(?:#[^#]*)?$/);
1685
+ if (!match) {
1686
+ return { filename: mention };
1687
+ }
1688
+ const [, filename, lineStartStr, lineEndStr] = match;
1689
+ const lineStart = lineStartStr ? parseInt(lineStartStr, 10) : undefined;
1690
+ const lineEnd = lineEndStr ? parseInt(lineEndStr, 10) : lineStart;
1691
+ return { filename: filename ?? mention, lineStart, lineEnd };
1692
+ }
1693
+ async function getDiagnosticAttachments(toolUseContext) {
1694
+ // Diagnostics are only useful if the agent has the Bash tool to act on them
1695
+ if (!toolUseContext.options.tools.some(t => toolMatchesName(t, BASH_TOOL_NAME))) {
1696
+ return [];
1697
+ }
1698
+ // Get new diagnostics from the tracker (IDE diagnostics via MCP)
1699
+ const newDiagnostics = await diagnosticTracker.getNewDiagnostics();
1700
+ if (newDiagnostics.length === 0) {
1701
+ return [];
1702
+ }
1703
+ return [
1704
+ {
1705
+ type: 'diagnostics',
1706
+ files: newDiagnostics,
1707
+ isNew: true,
1708
+ },
1709
+ ];
1710
+ }
1711
+ /**
1712
+ * Get LSP diagnostic attachments from passive LSP servers.
1713
+ * Follows the AsyncHookRegistry pattern for consistent async attachment delivery.
1714
+ */
1715
+ async function getLSPDiagnosticAttachments(toolUseContext) {
1716
+ // LSP diagnostics are only useful if the agent has the Bash tool to act on them
1717
+ if (!toolUseContext.options.tools.some(t => toolMatchesName(t, BASH_TOOL_NAME))) {
1718
+ return [];
1719
+ }
1720
+ logForDebugging('LSP Diagnostics: getLSPDiagnosticAttachments called');
1721
+ try {
1722
+ const diagnosticSets = checkForLSPDiagnostics();
1723
+ if (diagnosticSets.length === 0) {
1724
+ return [];
1725
+ }
1726
+ logForDebugging(`LSP Diagnostics: Found ${diagnosticSets.length} pending diagnostic set(s)`);
1727
+ // Convert each diagnostic set to an attachment
1728
+ const attachments = diagnosticSets.map(({ files }) => ({
1729
+ type: 'diagnostics',
1730
+ files,
1731
+ isNew: true,
1732
+ }));
1733
+ // Clear delivered diagnostics from registry to prevent memory leak
1734
+ // Follows same pattern as removeDeliveredAsyncHooks
1735
+ if (diagnosticSets.length > 0) {
1736
+ clearAllLSPDiagnostics();
1737
+ logForDebugging(`LSP Diagnostics: Cleared ${diagnosticSets.length} delivered diagnostic(s) from registry`);
1738
+ }
1739
+ logForDebugging(`LSP Diagnostics: Returning ${attachments.length} diagnostic attachment(s)`);
1740
+ return attachments;
1741
+ }
1742
+ catch (error) {
1743
+ const err = toError(error);
1744
+ logError(new Error(`Failed to get LSP diagnostic attachments: ${err.message}`));
1745
+ // Return empty array to allow other attachments to proceed
1746
+ return [];
1747
+ }
1748
+ }
1749
+ export async function* getAttachmentMessages(input, toolUseContext, ideSelection, queuedCommands, messages, querySource, options) {
1750
+ // TODO: Compute this upstream
1751
+ const attachments = await getAttachments(input, toolUseContext, ideSelection, queuedCommands, messages, querySource, options);
1752
+ if (attachments.length === 0) {
1753
+ return;
1754
+ }
1755
+ logEvent('thaddeus_attachments', {
1756
+ attachment_types: attachments.map(_ => _.type),
1757
+ });
1758
+ for (const attachment of attachments) {
1759
+ yield createAttachmentMessage(attachment);
1760
+ }
1761
+ }
1762
+ /**
1763
+ * Generates a file attachment by reading a file with proper validation and truncation.
1764
+ * This is the core file reading logic shared between @-mentioned files and post-compact restoration.
1765
+ *
1766
+ * @param filename The absolute path to the file to read
1767
+ * @param toolUseContext The tool use context for calling FileReadTool
1768
+ * @param options Optional configuration for file reading
1769
+ * @returns A new_file attachment or null if the file couldn't be read
1770
+ */
1771
+ /**
1772
+ * Check if a PDF file should be represented as a lightweight reference
1773
+ * instead of being inlined. Returns a PDFReferenceAttachment for large PDFs
1774
+ * (more than PDF_AT_MENTION_INLINE_THRESHOLD pages), or null otherwise.
1775
+ */
1776
+ export async function tryGetPDFReference(filename) {
1777
+ const ext = parse(filename).ext.toLowerCase();
1778
+ if (!isPDFExtension(ext)) {
1779
+ return null;
1780
+ }
1781
+ try {
1782
+ const [stats, pageCount] = await Promise.all([
1783
+ getFsImplementation().stat(filename),
1784
+ getPDFPageCount(filename),
1785
+ ]);
1786
+ // Use page count if available, otherwise fall back to size heuristic (~100KB per page)
1787
+ const effectivePageCount = pageCount ?? Math.ceil(stats.size / (100 * 1024));
1788
+ if (effectivePageCount > PDF_AT_MENTION_INLINE_THRESHOLD) {
1789
+ logEvent('thaddeus_pdf_reference_attachment', {
1790
+ pageCount: effectivePageCount,
1791
+ fileSize: stats.size,
1792
+ hadPdfinfo: pageCount !== null,
1793
+ });
1794
+ return {
1795
+ type: 'pdf_reference',
1796
+ filename,
1797
+ pageCount: effectivePageCount,
1798
+ fileSize: stats.size,
1799
+ displayPath: relative(getCwd(), filename),
1800
+ };
1801
+ }
1802
+ }
1803
+ catch {
1804
+ // If we can't stat the file, return null to proceed with normal reading
1805
+ }
1806
+ return null;
1807
+ }
1808
+ export async function generateFileAttachment(filename, toolUseContext, successEventName, errorEventName, mode, options) {
1809
+ const { offset, limit } = options ?? {};
1810
+ // Check if file has a deny rule configured
1811
+ const appState = toolUseContext.getAppState();
1812
+ if (isFileReadDenied(filename, appState.toolPermissionContext)) {
1813
+ return null;
1814
+ }
1815
+ // Check file size before attempting to read (skip for PDFs — they have their own size/page handling below)
1816
+ if (mode === 'at-mention' &&
1817
+ !isFileWithinReadSizeLimit(filename, getDefaultFileReadingLimits().maxSizeBytes)) {
1818
+ const ext = parse(filename).ext.toLowerCase();
1819
+ if (!isPDFExtension(ext)) {
1820
+ try {
1821
+ const stats = await getFsImplementation().stat(filename);
1822
+ logEvent('thaddeus_attachment_file_too_large', {
1823
+ size_bytes: stats.size,
1824
+ mode,
1825
+ });
1826
+ return null;
1827
+ }
1828
+ catch {
1829
+ // If we can't stat the file, proceed with normal reading (will fail later if file doesn't exist)
1830
+ }
1831
+ }
1832
+ }
1833
+ // For large PDFs on @ mention, return a lightweight reference instead of inlining
1834
+ if (mode === 'at-mention') {
1835
+ const pdfRef = await tryGetPDFReference(filename);
1836
+ if (pdfRef) {
1837
+ return pdfRef;
1838
+ }
1839
+ }
1840
+ // Check if file is already in context with latest version
1841
+ const existingFileState = toolUseContext.readFileState.get(filename);
1842
+ if (existingFileState && mode === 'at-mention') {
1843
+ try {
1844
+ // Check if the file has been modified since we last read it
1845
+ const mtimeMs = await getFileModificationTimeAsync(filename);
1846
+ // Handle timestamp format inconsistency:
1847
+ // - FileReadTool stores Date.now() (current time when read)
1848
+ // - FileEdit/WriteTools store mtimeMs (file modification time)
1849
+ //
1850
+ // If timestamp > mtimeMs, it was stored by FileReadTool using Date.now()
1851
+ // In this case, we should not use the optimization since we can't reliably
1852
+ // compare modification times. Only use optimization when timestamp <= mtimeMs,
1853
+ // indicating it was stored by FileEdit/WriteTool with actual mtimeMs.
1854
+ if (existingFileState.timestamp <= mtimeMs &&
1855
+ mtimeMs === existingFileState.timestamp) {
1856
+ // File hasn't been modified, return already_read_file attachment
1857
+ // This tells the system the file is already in context and doesn't need to be sent to API
1858
+ logEvent(successEventName, {});
1859
+ return {
1860
+ type: 'already_read_file',
1861
+ filename,
1862
+ displayPath: relative(getCwd(), filename),
1863
+ content: {
1864
+ type: 'text',
1865
+ file: {
1866
+ filePath: filename,
1867
+ content: existingFileState.content,
1868
+ numLines: countCharInString(existingFileState.content, '\n') + 1,
1869
+ startLine: offset ?? 1,
1870
+ totalLines: countCharInString(existingFileState.content, '\n') + 1,
1871
+ },
1872
+ },
1873
+ };
1874
+ }
1875
+ }
1876
+ catch {
1877
+ // If we can't stat the file, proceed with normal reading
1878
+ }
1879
+ }
1880
+ try {
1881
+ const fileInput = {
1882
+ file_path: filename,
1883
+ offset,
1884
+ limit,
1885
+ };
1886
+ async function readTruncatedFile() {
1887
+ if (mode === 'compact') {
1888
+ return {
1889
+ type: 'compact_file_reference',
1890
+ filename,
1891
+ displayPath: relative(getCwd(), filename),
1892
+ };
1893
+ }
1894
+ // Check deny rules before reading truncated file
1895
+ const appState = toolUseContext.getAppState();
1896
+ if (isFileReadDenied(filename, appState.toolPermissionContext)) {
1897
+ return null;
1898
+ }
1899
+ try {
1900
+ // Read only the first MAX_LINES_TO_READ lines for files that are too large
1901
+ const truncatedInput = {
1902
+ file_path: filename,
1903
+ offset: offset ?? 1,
1904
+ limit: MAX_LINES_TO_READ,
1905
+ };
1906
+ const result = await FileReadTool.call(truncatedInput, toolUseContext);
1907
+ logEvent(successEventName, {});
1908
+ return {
1909
+ type: 'file',
1910
+ filename,
1911
+ content: result.data,
1912
+ truncated: true,
1913
+ displayPath: relative(getCwd(), filename),
1914
+ };
1915
+ }
1916
+ catch {
1917
+ logEvent(errorEventName, {});
1918
+ return null;
1919
+ }
1920
+ }
1921
+ // Validate file path is valid
1922
+ const isValid = await FileReadTool.validateInput(fileInput, toolUseContext);
1923
+ if (!isValid.result) {
1924
+ return null;
1925
+ }
1926
+ try {
1927
+ const result = await FileReadTool.call(fileInput, toolUseContext);
1928
+ logEvent(successEventName, {});
1929
+ return {
1930
+ type: 'file',
1931
+ filename,
1932
+ content: result.data,
1933
+ displayPath: relative(getCwd(), filename),
1934
+ };
1935
+ }
1936
+ catch (error) {
1937
+ if (error instanceof MaxFileReadTokenExceededError ||
1938
+ error instanceof FileTooLargeError) {
1939
+ return await readTruncatedFile();
1940
+ }
1941
+ throw error;
1942
+ }
1943
+ }
1944
+ catch {
1945
+ logEvent(errorEventName, {});
1946
+ return null;
1947
+ }
1948
+ }
1949
+ export function createAttachmentMessage(attachment) {
1950
+ return {
1951
+ attachment,
1952
+ type: 'attachment',
1953
+ uuid: randomUUID(),
1954
+ timestamp: new Date().toISOString(),
1955
+ };
1956
+ }
1957
+ function getTodoReminderTurnCounts(messages) {
1958
+ let lastTodoWriteIndex = -1;
1959
+ let lastReminderIndex = -1;
1960
+ let assistantTurnsSinceWrite = 0;
1961
+ let assistantTurnsSinceReminder = 0;
1962
+ // Iterate backwards to find most recent events
1963
+ for (let i = messages.length - 1; i >= 0; i--) {
1964
+ const message = messages[i];
1965
+ if (message?.type === 'assistant') {
1966
+ if (isThinkingMessage(message)) {
1967
+ // Skip thinking messages
1968
+ continue;
1969
+ }
1970
+ // Check for TodoWrite usage BEFORE incrementing counter
1971
+ // (we don't want to count the TodoWrite message itself as "1 turn since write")
1972
+ if (lastTodoWriteIndex === -1 &&
1973
+ 'message' in message &&
1974
+ Array.isArray(message.message?.content) &&
1975
+ message.message.content.some(block => block.type === 'tool_use' && block.name === 'TodoWrite')) {
1976
+ lastTodoWriteIndex = i;
1977
+ }
1978
+ // Count assistant turns before finding events
1979
+ if (lastTodoWriteIndex === -1)
1980
+ assistantTurnsSinceWrite++;
1981
+ if (lastReminderIndex === -1)
1982
+ assistantTurnsSinceReminder++;
1983
+ }
1984
+ else if (lastReminderIndex === -1 &&
1985
+ message?.type === 'attachment' &&
1986
+ message.attachment.type === 'todo_reminder') {
1987
+ lastReminderIndex = i;
1988
+ }
1989
+ if (lastTodoWriteIndex !== -1 && lastReminderIndex !== -1) {
1990
+ break;
1991
+ }
1992
+ }
1993
+ return {
1994
+ turnsSinceLastTodoWrite: assistantTurnsSinceWrite,
1995
+ turnsSinceLastReminder: assistantTurnsSinceReminder,
1996
+ };
1997
+ }
1998
+ async function getTodoReminderAttachments(messages, toolUseContext) {
1999
+ // Skip if TodoWrite tool is not available
2000
+ if (!toolUseContext.options.tools.some(t => toolMatchesName(t, TODO_WRITE_TOOL_NAME))) {
2001
+ return [];
2002
+ }
2003
+ // When SendUserMessage is in the toolkit, it's the primary communication
2004
+ // channel and the model is always told to use it (#20467). TodoWrite
2005
+ // becomes a side channel — nudging the model about it conflicts with the
2006
+ // brief workflow. The tool itself stays available; this only gates the
2007
+ // "you haven't used it in a while" nag.
2008
+ if (BRIEF_TOOL_NAME &&
2009
+ toolUseContext.options.tools.some(t => toolMatchesName(t, BRIEF_TOOL_NAME))) {
2010
+ return [];
2011
+ }
2012
+ // Skip if no messages provided
2013
+ if (!messages || messages.length === 0) {
2014
+ return [];
2015
+ }
2016
+ const { turnsSinceLastTodoWrite, turnsSinceLastReminder } = getTodoReminderTurnCounts(messages);
2017
+ // Check if we should show a reminder
2018
+ if (turnsSinceLastTodoWrite >= TODO_REMINDER_CONFIG.TURNS_SINCE_WRITE &&
2019
+ turnsSinceLastReminder >= TODO_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS) {
2020
+ const todoKey = toolUseContext.agentId ?? getSessionId();
2021
+ const appState = toolUseContext.getAppState();
2022
+ const todos = appState.todos[todoKey] ?? [];
2023
+ return [
2024
+ {
2025
+ type: 'todo_reminder',
2026
+ content: todos,
2027
+ itemCount: todos.length,
2028
+ },
2029
+ ];
2030
+ }
2031
+ return [];
2032
+ }
2033
+ function getTaskReminderTurnCounts(messages) {
2034
+ let lastTaskManagementIndex = -1;
2035
+ let lastReminderIndex = -1;
2036
+ let assistantTurnsSinceTaskManagement = 0;
2037
+ let assistantTurnsSinceReminder = 0;
2038
+ // Iterate backwards to find most recent events
2039
+ for (let i = messages.length - 1; i >= 0; i--) {
2040
+ const message = messages[i];
2041
+ if (message?.type === 'assistant') {
2042
+ if (isThinkingMessage(message)) {
2043
+ // Skip thinking messages
2044
+ continue;
2045
+ }
2046
+ // Check for TaskCreate or TaskUpdate usage BEFORE incrementing counter
2047
+ if (lastTaskManagementIndex === -1 &&
2048
+ 'message' in message &&
2049
+ Array.isArray(message.message?.content) &&
2050
+ message.message.content.some(block => block.type === 'tool_use' &&
2051
+ (block.name === TASK_CREATE_TOOL_NAME ||
2052
+ block.name === TASK_UPDATE_TOOL_NAME))) {
2053
+ lastTaskManagementIndex = i;
2054
+ }
2055
+ // Count assistant turns before finding events
2056
+ if (lastTaskManagementIndex === -1)
2057
+ assistantTurnsSinceTaskManagement++;
2058
+ if (lastReminderIndex === -1)
2059
+ assistantTurnsSinceReminder++;
2060
+ }
2061
+ else if (lastReminderIndex === -1 &&
2062
+ message?.type === 'attachment' &&
2063
+ message.attachment.type === 'task_reminder') {
2064
+ lastReminderIndex = i;
2065
+ }
2066
+ if (lastTaskManagementIndex !== -1 && lastReminderIndex !== -1) {
2067
+ break;
2068
+ }
2069
+ }
2070
+ return {
2071
+ turnsSinceLastTaskManagement: assistantTurnsSinceTaskManagement,
2072
+ turnsSinceLastReminder: assistantTurnsSinceReminder,
2073
+ };
2074
+ }
2075
+ async function getTaskReminderAttachments(messages, toolUseContext) {
2076
+ if (!isTodoV2Enabled()) {
2077
+ return [];
2078
+ }
2079
+ // Skip for ant users
2080
+ if (process.env.USER_TYPE === 'ant') {
2081
+ return [];
2082
+ }
2083
+ // When SendUserMessage is in the toolkit, it's the primary communication
2084
+ // channel and the model is always told to use it (#20467). TaskUpdate
2085
+ // becomes a side channel — nudging the model about it conflicts with the
2086
+ // brief workflow. The tool itself stays available; this only gates the nag.
2087
+ if (BRIEF_TOOL_NAME &&
2088
+ toolUseContext.options.tools.some(t => toolMatchesName(t, BRIEF_TOOL_NAME))) {
2089
+ return [];
2090
+ }
2091
+ // Skip if TaskUpdate tool is not available
2092
+ if (!toolUseContext.options.tools.some(t => toolMatchesName(t, TASK_UPDATE_TOOL_NAME))) {
2093
+ return [];
2094
+ }
2095
+ // Skip if no messages provided
2096
+ if (!messages || messages.length === 0) {
2097
+ return [];
2098
+ }
2099
+ const { turnsSinceLastTaskManagement, turnsSinceLastReminder } = getTaskReminderTurnCounts(messages);
2100
+ // Check if we should show a reminder
2101
+ if (turnsSinceLastTaskManagement >= TODO_REMINDER_CONFIG.TURNS_SINCE_WRITE &&
2102
+ turnsSinceLastReminder >= TODO_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS) {
2103
+ const tasks = await listTasks(getTaskListId());
2104
+ return [
2105
+ {
2106
+ type: 'task_reminder',
2107
+ content: tasks,
2108
+ itemCount: tasks.length,
2109
+ },
2110
+ ];
2111
+ }
2112
+ return [];
2113
+ }
2114
+ /**
2115
+ * Get attachments for all unified tasks using the Task framework.
2116
+ * Replaces the old getBackgroundShellAttachments, getBackgroundRemoteSessionAttachments,
2117
+ * and getAsyncAgentAttachments functions.
2118
+ */
2119
+ async function getUnifiedTaskAttachments(toolUseContext) {
2120
+ const appState = toolUseContext.getAppState();
2121
+ const { attachments, updatedTaskOffsets, evictedTaskIds } = await generateTaskAttachments(appState);
2122
+ applyTaskOffsetsAndEvictions(toolUseContext.setAppState, updatedTaskOffsets, evictedTaskIds);
2123
+ // Convert TaskAttachment to Attachment format
2124
+ return attachments.map(taskAttachment => ({
2125
+ type: 'task_status',
2126
+ taskId: taskAttachment.taskId,
2127
+ taskType: taskAttachment.taskType,
2128
+ status: taskAttachment.status,
2129
+ description: taskAttachment.description,
2130
+ deltaSummary: taskAttachment.deltaSummary,
2131
+ outputFilePath: getTaskOutputPath(taskAttachment.taskId),
2132
+ }));
2133
+ }
2134
+ async function getAsyncHookResponseAttachments() {
2135
+ const responses = await checkForAsyncHookResponses();
2136
+ if (responses.length === 0) {
2137
+ return [];
2138
+ }
2139
+ logForDebugging(`Hooks: getAsyncHookResponseAttachments found ${responses.length} responses`);
2140
+ const attachments = responses.map(({ processId, response, hookName, hookEvent, toolName, pluginId, stdout, stderr, exitCode, }) => {
2141
+ logForDebugging(`Hooks: Creating attachment for ${processId} (${hookName}): ${jsonStringify(response)}`);
2142
+ return {
2143
+ type: 'async_hook_response',
2144
+ processId,
2145
+ hookName,
2146
+ hookEvent,
2147
+ toolName,
2148
+ response,
2149
+ stdout,
2150
+ stderr,
2151
+ exitCode,
2152
+ };
2153
+ });
2154
+ // Remove delivered hooks from registry to prevent re-processing
2155
+ if (responses.length > 0) {
2156
+ const processIds = responses.map(r => r.processId);
2157
+ removeDeliveredAsyncHooks(processIds);
2158
+ logForDebugging(`Hooks: Removed ${processIds.length} delivered hooks from registry`);
2159
+ }
2160
+ logForDebugging(`Hooks: getAsyncHookResponseAttachments found ${attachments.length} attachments`);
2161
+ return attachments;
2162
+ }
2163
+ /**
2164
+ * Get teammate mailbox attachments for agent swarm communication
2165
+ * Teammates are independent Claude Code sessions running in parallel (swarms),
2166
+ * not parent-child subagent relationships.
2167
+ *
2168
+ * This function checks two sources for messages:
2169
+ * 1. File-based mailbox (for messages that arrived between polls)
2170
+ * 2. AppState.inbox (for messages queued mid-turn by useInboxPoller)
2171
+ *
2172
+ * Messages from AppState.inbox are delivered mid-turn as attachments,
2173
+ * allowing teammates to receive messages without waiting for the turn to end.
2174
+ */
2175
+ async function getTeammateMailboxAttachments(toolUseContext) {
2176
+ if (!isAgentSwarmsEnabled()) {
2177
+ return [];
2178
+ }
2179
+ if (process.env.USER_TYPE !== 'ant') {
2180
+ return [];
2181
+ }
2182
+ // Get AppState early to check for team lead status
2183
+ const appState = toolUseContext.getAppState();
2184
+ // Use agent name from helper (checks AsyncLocalStorage, then dynamicTeamContext)
2185
+ const envAgentName = getAgentName();
2186
+ // Get team name (checks AsyncLocalStorage, dynamicTeamContext, then AppState)
2187
+ const teamName = getTeamName(appState.teamContext);
2188
+ // Check if we're the team lead (uses shared logic from swarm utils)
2189
+ const teamLeadStatus = isTeamLead(appState.teamContext);
2190
+ // Check if viewing a teammate's transcript (for in-process teammates)
2191
+ const viewedTeammate = getViewedTeammateTask(appState);
2192
+ // Resolve agent name based on who we're VIEWING:
2193
+ // - If viewing a teammate, use THEIR name (to read from their mailbox)
2194
+ // - Otherwise use env var if set, or leader's name if we're the team lead
2195
+ let agentName = viewedTeammate?.identity.agentName ?? envAgentName;
2196
+ if (!agentName && teamLeadStatus && appState.teamContext) {
2197
+ const leadAgentId = appState.teamContext.leadAgentId;
2198
+ // Look up the lead's name from agents map (not the UUID)
2199
+ agentName = appState.teamContext.teammates[leadAgentId]?.name || 'team-lead';
2200
+ }
2201
+ logForDebugging(`[SwarmMailbox] getTeammateMailboxAttachments called: envAgentName=${envAgentName}, isTeamLead=${teamLeadStatus}, resolved agentName=${agentName}, teamName=${teamName}`);
2202
+ // Only check inbox if running as an agent in a swarm or team lead
2203
+ if (!agentName) {
2204
+ logForDebugging(`[SwarmMailbox] Not checking inbox - not in a swarm or team lead`);
2205
+ return [];
2206
+ }
2207
+ logForDebugging(`[SwarmMailbox] Checking inbox for agent="${agentName}" team="${teamName || 'default'}"`);
2208
+ // Check mailbox for unread messages (routes to in-process or file-based)
2209
+ // Filter out structured protocol messages (permission requests/responses, shutdown
2210
+ // messages, etc.) — these must be left unread for useInboxPoller to route to their
2211
+ // proper handlers (workerPermissions queue, sandbox queue, etc.). Without filtering,
2212
+ // attachment generation races with InboxPoller: whichever reads first marks all
2213
+ // messages as read, and if attachments wins, protocol messages get bundled as raw
2214
+ // LLM context text instead of being routed to their UI handlers.
2215
+ const allUnreadMessages = await readUnreadMessages(agentName, teamName);
2216
+ const unreadMessages = allUnreadMessages.filter(m => !isStructuredProtocolMessage(m.text));
2217
+ logForDebugging(`[MailboxBridge] Found ${allUnreadMessages.length} unread message(s) for "${agentName}" (${allUnreadMessages.length - unreadMessages.length} structured protocol messages filtered out)`);
2218
+ // Also check AppState.inbox for pending messages (queued mid-turn by useInboxPoller)
2219
+ // IMPORTANT: appState.inbox contains messages FROM teammates TO the leader.
2220
+ // Only show these when viewing the leader's transcript (not a teammate's).
2221
+ // When viewing a teammate, their messages come from the file-based mailbox above.
2222
+ // In-process teammates share AppState with the leader — appState.inbox contains
2223
+ // the LEADER's queued messages, not the teammate's. Skip it to prevent leakage
2224
+ // (including self-echo from broadcasts). Teammates receive messages exclusively
2225
+ // through their file-based mailbox + waitForNextPromptOrShutdown.
2226
+ // Note: viewedTeammate was already computed above for agentName resolution
2227
+ const pendingInboxMessages = viewedTeammate || isInProcessTeammate()
2228
+ ? [] // Viewing teammate or running as in-process teammate - don't show leader's inbox
2229
+ : appState.inbox.messages.filter(m => m.status === 'pending');
2230
+ logForDebugging(`[SwarmMailbox] Found ${pendingInboxMessages.length} pending message(s) in AppState.inbox`);
2231
+ // Combine both sources of messages WITH DEDUPLICATION
2232
+ // The same message could exist in both file mailbox and AppState.inbox due to race conditions:
2233
+ // 1. getTeammateMailboxAttachments reads file -> finds message M
2234
+ // 2. InboxPoller reads same file -> queues M in AppState.inbox
2235
+ // 3. getTeammateMailboxAttachments reads AppState -> finds M again
2236
+ // We deduplicate using from+timestamp+text prefix as the key
2237
+ const seen = new Set();
2238
+ let allMessages = [];
2239
+ for (const m of [...unreadMessages, ...pendingInboxMessages]) {
2240
+ const key = `${m.from}|${m.timestamp}|${m.text.slice(0, 100)}`;
2241
+ if (!seen.has(key)) {
2242
+ seen.add(key);
2243
+ allMessages.push({
2244
+ from: m.from,
2245
+ text: m.text,
2246
+ timestamp: m.timestamp,
2247
+ color: m.color,
2248
+ summary: m.summary,
2249
+ });
2250
+ }
2251
+ }
2252
+ // Collapse multiple idle notifications per agent — keep only the latest.
2253
+ // Single pass to parse, then filter without re-parsing.
2254
+ const idleAgentByIndex = new Map();
2255
+ const latestIdleByAgent = new Map();
2256
+ for (let i = 0; i < allMessages.length; i++) {
2257
+ const idle = isIdleNotification(allMessages[i].text);
2258
+ if (idle) {
2259
+ idleAgentByIndex.set(i, idle.from);
2260
+ latestIdleByAgent.set(idle.from, i);
2261
+ }
2262
+ }
2263
+ if (idleAgentByIndex.size > latestIdleByAgent.size) {
2264
+ const beforeCount = allMessages.length;
2265
+ allMessages = allMessages.filter((_m, i) => {
2266
+ const agent = idleAgentByIndex.get(i);
2267
+ if (agent === undefined)
2268
+ return true;
2269
+ return latestIdleByAgent.get(agent) === i;
2270
+ });
2271
+ logForDebugging(`[SwarmMailbox] Collapsed ${beforeCount - allMessages.length} duplicate idle notification(s)`);
2272
+ }
2273
+ if (allMessages.length === 0) {
2274
+ logForDebugging(`[SwarmMailbox] No messages to deliver, returning empty`);
2275
+ return [];
2276
+ }
2277
+ logForDebugging(`[SwarmMailbox] Returning ${allMessages.length} message(s) as attachment for "${agentName}" (${unreadMessages.length} from file, ${pendingInboxMessages.length} from AppState, after dedup)`);
2278
+ // Build the attachment BEFORE marking messages as processed
2279
+ // This prevents message loss if any operation below fails
2280
+ const attachment = [
2281
+ {
2282
+ type: 'teammate_mailbox',
2283
+ messages: allMessages,
2284
+ },
2285
+ ];
2286
+ // Mark only non-structured mailbox messages as read after attachment is built.
2287
+ // Structured protocol messages stay unread for useInboxPoller to handle.
2288
+ if (unreadMessages.length > 0) {
2289
+ await markMessagesAsReadByPredicate(agentName, m => !isStructuredProtocolMessage(m.text), teamName);
2290
+ logForDebugging(`[MailboxBridge] marked ${unreadMessages.length} non-structured message(s) as read for agent="${agentName}" team="${teamName || 'default'}"`);
2291
+ }
2292
+ // Process shutdown_approved messages - remove teammates from team file
2293
+ // This mirrors what useInboxPoller does in interactive mode (lines 546-606)
2294
+ // In -p mode, useInboxPoller doesn't run, so we must handle this here
2295
+ if (teamLeadStatus && teamName) {
2296
+ for (const m of allMessages) {
2297
+ const shutdownApproval = isShutdownApproved(m.text);
2298
+ if (shutdownApproval) {
2299
+ const teammateToRemove = shutdownApproval.from;
2300
+ logForDebugging(`[SwarmMailbox] Processing shutdown_approved from ${teammateToRemove}`);
2301
+ // Find the teammate ID by name
2302
+ const teammateId = appState.teamContext?.teammates
2303
+ ? Object.entries(appState.teamContext.teammates).find(([, t]) => t.name === teammateToRemove)?.[0]
2304
+ : undefined;
2305
+ if (teammateId) {
2306
+ // Remove from team file
2307
+ removeTeammateFromTeamFile(teamName, {
2308
+ agentId: teammateId,
2309
+ name: teammateToRemove,
2310
+ });
2311
+ logForDebugging(`[SwarmMailbox] Removed ${teammateToRemove} from team file`);
2312
+ // Unassign tasks owned by this teammate
2313
+ await unassignTeammateTasks(teamName, teammateId, teammateToRemove, 'shutdown');
2314
+ // Remove from teamContext in AppState
2315
+ toolUseContext.setAppState(prev => {
2316
+ if (!prev.teamContext?.teammates)
2317
+ return prev;
2318
+ if (!(teammateId in prev.teamContext.teammates))
2319
+ return prev;
2320
+ const { [teammateId]: _, ...remainingTeammates } = prev.teamContext.teammates;
2321
+ return {
2322
+ ...prev,
2323
+ teamContext: {
2324
+ ...prev.teamContext,
2325
+ teammates: remainingTeammates,
2326
+ },
2327
+ };
2328
+ });
2329
+ }
2330
+ }
2331
+ }
2332
+ }
2333
+ // Mark AppState inbox messages as processed LAST, after attachment is built
2334
+ // This ensures messages aren't lost if earlier operations fail
2335
+ if (pendingInboxMessages.length > 0) {
2336
+ const pendingIds = new Set(pendingInboxMessages.map(m => m.id));
2337
+ toolUseContext.setAppState(prev => ({
2338
+ ...prev,
2339
+ inbox: {
2340
+ messages: prev.inbox.messages.map(m => pendingIds.has(m.id) ? { ...m, status: 'processed' } : m),
2341
+ },
2342
+ }));
2343
+ }
2344
+ return attachment;
2345
+ }
2346
+ /**
2347
+ * Get team context attachment for teammates in a swarm.
2348
+ * Only injected on the first turn to provide team coordination instructions.
2349
+ */
2350
+ function getTeamContextAttachment(messages) {
2351
+ const teamName = getTeamName();
2352
+ const agentId = getAgentId();
2353
+ const agentName = getAgentName();
2354
+ // Only inject for teammates (not team lead or non-team sessions)
2355
+ if (!teamName || !agentId) {
2356
+ return [];
2357
+ }
2358
+ // Only inject on first turn - check if there are no assistant messages yet
2359
+ const hasAssistantMessage = messages.some(m => m.type === 'assistant');
2360
+ if (hasAssistantMessage) {
2361
+ return [];
2362
+ }
2363
+ const configDir = getClaudeConfigHomeDir();
2364
+ const teamConfigPath = `${configDir}/teams/${teamName}/config.json`;
2365
+ const taskListPath = `${configDir}/tasks/${teamName}/`;
2366
+ return [
2367
+ {
2368
+ type: 'team_context',
2369
+ agentId,
2370
+ agentName: agentName || agentId,
2371
+ teamName,
2372
+ teamConfigPath,
2373
+ taskListPath,
2374
+ },
2375
+ ];
2376
+ }
2377
+ function getTokenUsageAttachment(messages, model) {
2378
+ if (!isEnvTruthy(process.env.THADDEUS_ENABLE_TOKEN_USAGE_ATTACHMENT)) {
2379
+ return [];
2380
+ }
2381
+ const contextWindow = getEffectiveContextWindowSize(model);
2382
+ const usedTokens = tokenCountFromLastAPIResponse(messages);
2383
+ return [
2384
+ {
2385
+ type: 'token_usage',
2386
+ used: usedTokens,
2387
+ total: contextWindow,
2388
+ remaining: contextWindow - usedTokens,
2389
+ },
2390
+ ];
2391
+ }
2392
+ function getOutputTokenUsageAttachment() {
2393
+ if (feature('TOKEN_BUDGET')) {
2394
+ const budget = getCurrentTurnTokenBudget();
2395
+ if (budget === null || budget <= 0) {
2396
+ return [];
2397
+ }
2398
+ return [
2399
+ {
2400
+ type: 'output_token_usage',
2401
+ turn: getTurnOutputTokens(),
2402
+ session: getTotalOutputTokens(),
2403
+ budget,
2404
+ },
2405
+ ];
2406
+ }
2407
+ return [];
2408
+ }
2409
+ function getMaxBudgetUsdAttachment(maxBudgetUsd) {
2410
+ if (maxBudgetUsd === undefined) {
2411
+ return [];
2412
+ }
2413
+ const usedCost = getTotalCostUSD();
2414
+ const remainingBudget = maxBudgetUsd - usedCost;
2415
+ return [
2416
+ {
2417
+ type: 'budget_usd',
2418
+ used: usedCost,
2419
+ total: maxBudgetUsd,
2420
+ remaining: remainingBudget,
2421
+ },
2422
+ ];
2423
+ }
2424
+ /**
2425
+ * Count human turns since plan mode exit (plan_mode_exit attachment).
2426
+ * Returns 0 if no plan_mode_exit attachment found.
2427
+ *
2428
+ * tool_result messages are type:'user' without isMeta, so filter by
2429
+ * toolUseResult to avoid counting them — otherwise the 10-turn reminder
2430
+ * interval fires every ~10 tool calls instead of ~10 human turns.
2431
+ */
2432
+ export function getVerifyPlanReminderTurnCount(messages) {
2433
+ let turnCount = 0;
2434
+ for (let i = messages.length - 1; i >= 0; i--) {
2435
+ const message = messages[i];
2436
+ if (message && isHumanTurn(message)) {
2437
+ turnCount++;
2438
+ }
2439
+ // Stop counting at plan_mode_exit attachment (marks when implementation started)
2440
+ if (message?.type === 'attachment' &&
2441
+ message.attachment.type === 'plan_mode_exit') {
2442
+ return turnCount;
2443
+ }
2444
+ }
2445
+ // No plan_mode_exit found
2446
+ return 0;
2447
+ }
2448
+ /**
2449
+ * Get verify plan reminder attachment if the model hasn't called VerifyPlanExecution yet.
2450
+ */
2451
+ async function getVerifyPlanReminderAttachment(messages, toolUseContext) {
2452
+ if (process.env.USER_TYPE !== 'ant' ||
2453
+ !isEnvTruthy(process.env.THADDEUS_VERIFY_PLAN)) {
2454
+ return [];
2455
+ }
2456
+ const appState = toolUseContext.getAppState();
2457
+ const pending = appState.pendingPlanVerification;
2458
+ // Only remind if plan exists and verification not started or completed
2459
+ if (!pending ||
2460
+ pending.verificationStarted ||
2461
+ pending.verificationCompleted) {
2462
+ return [];
2463
+ }
2464
+ // Only remind every N turns
2465
+ if (messages && messages.length > 0) {
2466
+ const turnCount = getVerifyPlanReminderTurnCount(messages);
2467
+ if (turnCount === 0 ||
2468
+ turnCount % VERIFY_PLAN_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS !== 0) {
2469
+ return [];
2470
+ }
2471
+ }
2472
+ return [{ type: 'verify_plan_reminder' }];
2473
+ }
2474
+ export function getCompactionReminderAttachment(messages, model) {
2475
+ if (!getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_marble_fox', false)) {
2476
+ return [];
2477
+ }
2478
+ if (!isAutoCompactEnabled()) {
2479
+ return [];
2480
+ }
2481
+ const contextWindow = getContextWindowForModel(model, getSdkBetas());
2482
+ if (contextWindow < 1_000_000) {
2483
+ return [];
2484
+ }
2485
+ const effectiveWindow = getEffectiveContextWindowSize(model);
2486
+ const usedTokens = tokenCountWithEstimation(messages);
2487
+ if (usedTokens < effectiveWindow * 0.25) {
2488
+ return [];
2489
+ }
2490
+ return [{ type: 'compaction_reminder' }];
2491
+ }
2492
+ /**
2493
+ * Context-efficiency nudge. Injected after every N tokens of growth without
2494
+ * a snip. Pacing is handled entirely by shouldNudgeForSnips — the 10k
2495
+ * interval resets on prior nudges, snip markers, snip boundaries, and
2496
+ * compact boundaries.
2497
+ */
2498
+ export function getContextEfficiencyAttachment(messages) {
2499
+ if (!feature('HISTORY_SNIP')) {
2500
+ return [];
2501
+ }
2502
+ // Gate must match SnipTool.isEnabled() — don't nudge toward a tool that
2503
+ // isn't in the tool list. Lazy require keeps this file snip-string-free.
2504
+ const { isSnipRuntimeEnabled, shouldNudgeForSnips } =
2505
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2506
+ require('../services/compact/snipCompact.js');
2507
+ if (!isSnipRuntimeEnabled()) {
2508
+ return [];
2509
+ }
2510
+ if (!shouldNudgeForSnips(messages)) {
2511
+ return [];
2512
+ }
2513
+ return [{ type: 'context_efficiency' }];
2514
+ }
2515
+ function isFileReadDenied(filePath, toolPermissionContext) {
2516
+ const denyRule = matchingRuleForInput(filePath, toolPermissionContext, 'read', 'deny');
2517
+ return denyRule !== null;
2518
+ }