thaddeus 1.0.18 → 1.0.27

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 (2084) 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 +950 -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/SandboxViolationExpandedView.tsx +3 -0
  436. package/src/components/ScrollKeybindingHandler.js +982 -0
  437. package/src/components/SearchBox.js +56 -0
  438. package/src/components/SentryErrorBoundary.js +16 -0
  439. package/src/components/SessionBackgroundHint.js +105 -0
  440. package/src/components/SessionPreview.js +200 -0
  441. package/src/components/Settings/Config.js +1626 -0
  442. package/src/components/Settings/Settings.js +131 -0
  443. package/src/components/Settings/Status.js +230 -0
  444. package/src/components/Settings/Usage.js +341 -0
  445. package/src/components/ShowInIDEPrompt.js +152 -0
  446. package/src/components/SkillImprovementSurvey.js +130 -0
  447. package/src/components/Spinner/FlashingChar.js +52 -0
  448. package/src/components/Spinner/GlimmerMessage.js +329 -0
  449. package/src/components/Spinner/ShimmerChar.js +23 -0
  450. package/src/components/Spinner/SpinnerAnimationRow.js +170 -0
  451. package/src/components/Spinner/SpinnerGlyph.js +70 -0
  452. package/src/components/Spinner/TeammateSpinnerLine.js +171 -0
  453. package/src/components/Spinner/TeammateSpinnerTree.js +269 -0
  454. package/src/components/Spinner/index.js +9 -0
  455. package/src/components/Spinner/teammateSelectHint.js +1 -0
  456. package/src/components/Spinner/useShimmerAnimation.js +22 -0
  457. package/src/components/Spinner/useStalledAnimation.js +63 -0
  458. package/src/components/Spinner/utils.js +78 -0
  459. package/src/components/Spinner.js +474 -0
  460. package/src/components/Stats.js +1000 -0
  461. package/src/components/StatusLine.js +286 -0
  462. package/src/components/StatusNotices.js +50 -0
  463. package/src/components/StructuredDiff/Fallback.js +336 -0
  464. package/src/components/StructuredDiff/colorDiff.js +37 -0
  465. package/src/components/StructuredDiff.js +153 -0
  466. package/src/components/StructuredDiffList.js +9 -0
  467. package/src/components/TagTabs.js +101 -0
  468. package/src/components/TaskListV2.js +333 -0
  469. package/src/components/TeammateViewHeader.js +88 -0
  470. package/src/components/TeleportError.js +191 -0
  471. package/src/components/TeleportProgress.js +131 -0
  472. package/src/components/TeleportRepoMismatchDialog.js +98 -0
  473. package/src/components/TeleportResumeWrapper.js +158 -0
  474. package/src/components/TeleportStash.js +82 -0
  475. package/src/components/TextInput.js +108 -0
  476. package/src/components/ThaddeusHint/PluginHintMenu.js +37 -0
  477. package/src/components/ThemePicker.js +331 -0
  478. package/src/components/ThinkingToggle.js +154 -0
  479. package/src/components/TokenWarning.js +171 -0
  480. package/src/components/ToolUseLoader.js +35 -0
  481. package/src/components/TrustDialog/TrustDialog.js +301 -0
  482. package/src/components/TrustDialog/utils.js +199 -0
  483. package/src/components/UndercoverAutoCallout.js +5 -0
  484. package/src/components/ValidationErrorsList.js +147 -0
  485. package/src/components/VimTextInput.js +136 -0
  486. package/src/components/VirtualMessageList.js +893 -0
  487. package/src/components/WorkflowMultiselectDialog.js +118 -0
  488. package/src/components/WorktreeExitDialog.js +220 -0
  489. package/src/components/agents/AgentDetail.js +227 -0
  490. package/src/components/agents/AgentEditor.js +147 -0
  491. package/src/components/agents/AgentNavigationFooter.js +22 -0
  492. package/src/components/agents/AgentsList.js +436 -0
  493. package/src/components/agents/AgentsMenu.js +849 -0
  494. package/src/components/agents/ColorPicker.js +110 -0
  495. package/src/components/agents/ModelSelector.js +63 -0
  496. package/src/components/agents/SnapshotUpdateDialog.js +14 -0
  497. package/src/components/agents/ToolSelector.js +557 -0
  498. package/src/components/agents/agentFileUtils.js +179 -0
  499. package/src/components/agents/generateAgent.js +161 -0
  500. package/src/components/agents/new-agent-creation/CreateAgentWizard.js +89 -0
  501. package/src/components/agents/new-agent-creation/wizard-steps/ColorStep.js +81 -0
  502. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStep.js +387 -0
  503. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStepWrapper.js +63 -0
  504. package/src/components/agents/new-agent-creation/wizard-steps/DescriptionStep.js +126 -0
  505. package/src/components/agents/new-agent-creation/wizard-steps/GenerateStep.js +118 -0
  506. package/src/components/agents/new-agent-creation/wizard-steps/LocationStep.js +80 -0
  507. package/src/components/agents/new-agent-creation/wizard-steps/MemoryStep.js +108 -0
  508. package/src/components/agents/new-agent-creation/wizard-steps/MethodStep.js +80 -0
  509. package/src/components/agents/new-agent-creation/wizard-steps/ModelStep.js +49 -0
  510. package/src/components/agents/new-agent-creation/wizard-steps/PromptStep.js +131 -0
  511. package/src/components/agents/new-agent-creation/wizard-steps/ToolsStep.js +52 -0
  512. package/src/components/agents/new-agent-creation/wizard-steps/TypeStep.js +100 -0
  513. package/src/components/agents/types.js +4 -0
  514. package/src/components/agents/utils.js +14 -0
  515. package/src/components/agents/validateAgent.js +79 -0
  516. package/src/components/design-system/Byline.js +72 -0
  517. package/src/components/design-system/Dialog.js +117 -0
  518. package/src/components/design-system/Divider.js +110 -0
  519. package/src/components/design-system/FuzzyPicker.js +191 -0
  520. package/src/components/design-system/KeyboardShortcutHint.js +68 -0
  521. package/src/components/design-system/ListItem.js +184 -0
  522. package/src/components/design-system/LoadingState.js +69 -0
  523. package/src/components/design-system/Pane.js +69 -0
  524. package/src/components/design-system/ProgressBar.js +63 -0
  525. package/src/components/design-system/Ratchet.js +71 -0
  526. package/src/components/design-system/StatusIcon.js +70 -0
  527. package/src/components/design-system/Tabs.js +269 -0
  528. package/src/components/design-system/ThemeProvider.js +137 -0
  529. package/src/components/design-system/ThemedBox.js +126 -0
  530. package/src/components/design-system/ThemedText.js +60 -0
  531. package/src/components/design-system/color.js +22 -0
  532. package/src/components/diff/DiffDetailView.js +285 -0
  533. package/src/components/diff/DiffDialog.js +387 -0
  534. package/src/components/diff/DiffFileList.js +292 -0
  535. package/src/components/grove/Grove.js +483 -0
  536. package/src/components/hooks/HooksConfigMenu.js +583 -0
  537. package/src/components/hooks/PromptDialog.js +82 -0
  538. package/src/components/hooks/SelectEventMode.js +118 -0
  539. package/src/components/hooks/SelectHookMode.js +101 -0
  540. package/src/components/hooks/SelectMatcherMode.js +131 -0
  541. package/src/components/hooks/ViewHookMode.js +204 -0
  542. package/src/components/mcp/CapabilitiesSection.js +56 -0
  543. package/src/components/mcp/ElicitationDialog.js +945 -0
  544. package/src/components/mcp/MCPAgentServerMenu.js +95 -0
  545. package/src/components/mcp/MCPListPanel.js +505 -0
  546. package/src/components/mcp/MCPReconnect.js +168 -0
  547. package/src/components/mcp/MCPRemoteServerMenu.js +460 -0
  548. package/src/components/mcp/MCPSettings.js +414 -0
  549. package/src/components/mcp/MCPStdioServerMenu.js +95 -0
  550. package/src/components/mcp/MCPToolDetailView.js +219 -0
  551. package/src/components/mcp/MCPToolListView.js +137 -0
  552. package/src/components/mcp/McpParsingWarnings.js +212 -0
  553. package/src/components/mcp/index.js +8 -0
  554. package/src/components/mcp/utils/reconnectHelpers.js +35 -0
  555. package/src/components/memory/MemoryFileSelector.js +454 -0
  556. package/src/components/memory/MemoryUpdateNotification.js +43 -0
  557. package/src/components/messageActions.js +418 -0
  558. package/src/components/messages/AdvisorMessage.js +152 -0
  559. package/src/components/messages/AssistantRedactedThinkingMessage.js +28 -0
  560. package/src/components/messages/AssistantTextMessage.js +287 -0
  561. package/src/components/messages/AssistantThinkingMessage.js +70 -0
  562. package/src/components/messages/AssistantToolUseMessage.js +324 -0
  563. package/src/components/messages/AttachmentMessage.js +418 -0
  564. package/src/components/messages/CollapsedReadSearchContent.js +363 -0
  565. package/src/components/messages/CompactBoundaryMessage.js +19 -0
  566. package/src/components/messages/GroupedToolUseContent.js +37 -0
  567. package/src/components/messages/HighlightedThinkingText.js +165 -0
  568. package/src/components/messages/HookProgressMessage.js +111 -0
  569. package/src/components/messages/PlanApprovalMessage.js +213 -0
  570. package/src/components/messages/RateLimitMessage.js +149 -0
  571. package/src/components/messages/ShutdownMessage.js +124 -0
  572. package/src/components/messages/SnipBoundaryMessage.js +7 -0
  573. package/src/components/messages/SystemAPIErrorMessage.js +136 -0
  574. package/src/components/messages/SystemTextMessage.js +842 -0
  575. package/src/components/messages/TaskAssignmentMessage.js +72 -0
  576. package/src/components/messages/UserAgentNotificationMessage.js +78 -0
  577. package/src/components/messages/UserBashInputMessage.js +52 -0
  578. package/src/components/messages/UserBashOutputMessage.js +55 -0
  579. package/src/components/messages/UserChannelMessage.js +130 -0
  580. package/src/components/messages/UserCommandMessage.js +107 -0
  581. package/src/components/messages/UserCrossSessionMessage.js +11 -0
  582. package/src/components/messages/UserForkBoilerplateMessage.js +11 -0
  583. package/src/components/messages/UserGitHubWebhookMessage.js +12 -0
  584. package/src/components/messages/UserImageMessage.js +54 -0
  585. package/src/components/messages/UserLocalCommandOutputMessage.js +170 -0
  586. package/src/components/messages/UserMemoryInputMessage.js +73 -0
  587. package/src/components/messages/UserPlanMessage.js +38 -0
  588. package/src/components/messages/UserPromptMessage.js +63 -0
  589. package/src/components/messages/UserResourceUpdateMessage.js +102 -0
  590. package/src/components/messages/UserTeammateMessage.js +156 -0
  591. package/src/components/messages/UserTextMessage.js +270 -0
  592. package/src/components/messages/UserToolResultMessage/RejectedPlanMessage.js +28 -0
  593. package/src/components/messages/UserToolResultMessage/RejectedToolUseMessage.js +17 -0
  594. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.js +17 -0
  595. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.js +92 -0
  596. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.js +74 -0
  597. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.js +84 -0
  598. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.js +58 -0
  599. package/src/components/messages/UserToolResultMessage/utils.js +43 -0
  600. package/src/components/messages/nullRenderingAttachments.js +58 -0
  601. package/src/components/messages/teamMemCollapsed.js +142 -0
  602. package/src/components/messages/teamMemSaved.js +16 -0
  603. package/src/components/permissions/AskUserQuestionPermissionRequest/AskUserQuestionPermissionRequest.js +659 -0
  604. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewBox.js +219 -0
  605. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewQuestionView.js +227 -0
  606. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionNavigationBar.js +175 -0
  607. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionView.js +444 -0
  608. package/src/components/permissions/AskUserQuestionPermissionRequest/SubmitQuestionsView.js +137 -0
  609. package/src/components/permissions/AskUserQuestionPermissionRequest/use-multiple-choice-state.js +100 -0
  610. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.js +404 -0
  611. package/src/components/permissions/BashPermissionRequest/bashToolUseOptions.js +110 -0
  612. package/src/components/permissions/ComputerUseApproval/ComputerUseApproval.js +449 -0
  613. package/src/components/permissions/EnterPlanModePermissionRequest/EnterPlanModePermissionRequest.js +126 -0
  614. package/src/components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js +653 -0
  615. package/src/components/permissions/FallbackPermissionRequest.js +349 -0
  616. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.js +185 -0
  617. package/src/components/permissions/FilePermissionDialog/FilePermissionDialog.js +108 -0
  618. package/src/components/permissions/FilePermissionDialog/ideDiffConfig.js +13 -0
  619. package/src/components/permissions/FilePermissionDialog/permissionOptions.js +137 -0
  620. package/src/components/permissions/FilePermissionDialog/useFilePermissionDialog.js +131 -0
  621. package/src/components/permissions/FilePermissionDialog/usePermissionHandler.js +86 -0
  622. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.js +164 -0
  623. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.js +79 -0
  624. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +113 -0
  625. package/src/components/permissions/MonitorPermissionRequest/MonitorPermissionRequest.js +7 -0
  626. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditPermissionRequest.js +164 -0
  627. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditToolDiff.js +218 -0
  628. package/src/components/permissions/PermissionDecisionDebugInfo.js +467 -0
  629. package/src/components/permissions/PermissionDialog.js +55 -0
  630. package/src/components/permissions/PermissionExplanation.js +269 -0
  631. package/src/components/permissions/PermissionPrompt.js +316 -0
  632. package/src/components/permissions/PermissionRequest.js +159 -0
  633. package/src/components/permissions/PermissionRequestTitle.js +58 -0
  634. package/src/components/permissions/PermissionRuleExplanation.js +110 -0
  635. package/src/components/permissions/PowerShellPermissionRequest/PowerShellPermissionRequest.js +178 -0
  636. package/src/components/permissions/PowerShellPermissionRequest/powershellToolUseOptions.js +73 -0
  637. package/src/components/permissions/ReviewArtifactPermissionRequest/ReviewArtifactPermissionRequest.js +7 -0
  638. package/src/components/permissions/SandboxPermissionRequest.js +162 -0
  639. package/src/components/permissions/SedEditPermissionRequest/SedEditPermissionRequest.js +228 -0
  640. package/src/components/permissions/SkillPermissionRequest/SkillPermissionRequest.js +385 -0
  641. package/src/components/permissions/WebFetchPermissionRequest/WebFetchPermissionRequest.js +259 -0
  642. package/src/components/permissions/WorkerBadge.js +44 -0
  643. package/src/components/permissions/WorkerPendingPermission.js +107 -0
  644. package/src/components/permissions/hooks.js +163 -0
  645. package/src/components/permissions/rules/AddPermissionRules.js +171 -0
  646. package/src/components/permissions/rules/AddWorkspaceDirectory.js +335 -0
  647. package/src/components/permissions/rules/PermissionRuleDescription.js +78 -0
  648. package/src/components/permissions/rules/PermissionRuleInput.js +136 -0
  649. package/src/components/permissions/rules/PermissionRuleList.js +1190 -0
  650. package/src/components/permissions/rules/RecentDenialsTab.js +205 -0
  651. package/src/components/permissions/rules/RemoveWorkspaceDirectory.js +103 -0
  652. package/src/components/permissions/rules/WorkspaceTab.js +133 -0
  653. package/src/components/permissions/shellPermissionHelpers.js +112 -0
  654. package/src/components/permissions/useShellPermissionFeedback.js +108 -0
  655. package/src/components/permissions/utils.js +14 -0
  656. package/src/components/sandbox/SandboxConfigTab.js +48 -0
  657. package/src/components/sandbox/SandboxDependenciesTab.js +123 -0
  658. package/src/components/sandbox/SandboxDoctorSection.js +47 -0
  659. package/src/components/sandbox/SandboxOverridesTab.js +193 -0
  660. package/src/components/sandbox/SandboxSettings.js +297 -0
  661. package/src/components/shell/ExpandShellOutputContext.js +33 -0
  662. package/src/components/shell/OutputLine.js +110 -0
  663. package/src/components/shell/ShellProgressMessage.js +144 -0
  664. package/src/components/shell/ShellTimeDisplay.js +72 -0
  665. package/src/components/skills/SkillsMenu.js +239 -0
  666. package/src/components/tasks/AsyncAgentDetailDialog.js +235 -0
  667. package/src/components/tasks/BackgroundTask.js +364 -0
  668. package/src/components/tasks/BackgroundTaskStatus.js +419 -0
  669. package/src/components/tasks/BackgroundTasksDialog.js +494 -0
  670. package/src/components/tasks/DreamDetailDialog.js +251 -0
  671. package/src/components/tasks/InProcessTeammateDetailDialog.js +275 -0
  672. package/src/components/tasks/MonitorMcpDetailDialog.js +7 -0
  673. package/src/components/tasks/RemoteSessionDetailDialog.js +868 -0
  674. package/src/components/tasks/RemoteSessionProgress.js +249 -0
  675. package/src/components/tasks/ShellDetailDialog.js +403 -0
  676. package/src/components/tasks/ShellProgress.js +77 -0
  677. package/src/components/tasks/WorkflowDetailDialog.js +7 -0
  678. package/src/components/tasks/renderToolActivity.js +29 -0
  679. package/src/components/tasks/taskStatusUtils.js +94 -0
  680. package/src/components/teams/TeamStatus.js +77 -0
  681. package/src/components/teams/TeamsDialog.js +673 -0
  682. package/src/components/ui/OrderedList.js +66 -0
  683. package/src/components/ui/OrderedListItem.js +41 -0
  684. package/src/components/ui/TreeSelect.js +300 -0
  685. package/src/components/wizard/WizardDialogLayout.js +48 -0
  686. package/src/components/wizard/WizardNavigationFooter.js +11 -0
  687. package/src/components/wizard/WizardProvider.js +217 -0
  688. package/src/components/wizard/index.js +4 -0
  689. package/src/components/wizard/useWizard.js +9 -0
  690. package/src/constants/apiLimits.js +81 -0
  691. package/src/constants/betas.js +45 -0
  692. package/src/constants/common.js +29 -0
  693. package/src/constants/cyberRiskInstruction.js +23 -0
  694. package/src/constants/errorIds.js +14 -0
  695. package/src/constants/figures.js +38 -0
  696. package/src/constants/files.js +150 -0
  697. package/src/constants/github-app.js +139 -0
  698. package/src/constants/identity.js +112 -0
  699. package/src/constants/keys.js +10 -0
  700. package/src/constants/messages.js +1 -0
  701. package/src/constants/oauth.js +175 -0
  702. package/src/constants/outputStyles.js +162 -0
  703. package/src/constants/product.js +54 -0
  704. package/src/constants/prompts.js +994 -0
  705. package/src/constants/spinnerVerbs.js +98 -0
  706. package/src/constants/system.js +77 -0
  707. package/src/constants/systemPromptSections.js +39 -0
  708. package/src/constants/toolLimits.js +50 -0
  709. package/src/constants/tools.js +103 -0
  710. package/src/constants/turnCompletionVerbs.js +12 -0
  711. package/src/constants/xml.js +73 -0
  712. package/src/context/QueuedMessageContext.js +51 -0
  713. package/src/context/fpsMetrics.js +22 -0
  714. package/src/context/mailbox.js +35 -0
  715. package/src/context/modalContext.js +34 -0
  716. package/src/context/notifications.js +199 -0
  717. package/src/context/overlayContext.js +149 -0
  718. package/src/context/promptOverlayContext.js +118 -0
  719. package/src/context/stats.js +207 -0
  720. package/src/context/voice.js +74 -0
  721. package/src/context.js +146 -0
  722. package/src/coordinator/coordinatorMode.js +345 -0
  723. package/src/coordinator/workerAgent.js +24 -0
  724. package/src/cost-tracker.js +208 -0
  725. package/src/costHook.js +17 -0
  726. package/src/daemon/main.js +19 -0
  727. package/src/dialogLaunchers.js +77 -0
  728. package/src/entrypoints/agentSdkTypes.js +202 -0
  729. package/src/entrypoints/cli.js +226 -0
  730. package/src/entrypoints/init.js +265 -0
  731. package/src/entrypoints/mcp.js +141 -0
  732. package/src/entrypoints/sandboxTypes.js +112 -0
  733. package/src/entrypoints/sdk/controlSchemas.js +452 -0
  734. package/src/entrypoints/sdk/controlTypes.js +1 -0
  735. package/src/entrypoints/sdk/coreSchemas.js +1331 -0
  736. package/src/entrypoints/sdk/coreTypes.generated.js +3 -0
  737. package/src/entrypoints/sdk/coreTypes.js +49 -0
  738. package/src/entrypoints/sdk/runtimeTypes.js +1 -0
  739. package/src/entrypoints/sdk/sdkUtilityTypes.js +1 -0
  740. package/src/entrypoints/sdk/settingsTypes.generated.js +1 -0
  741. package/src/entrypoints/sdk/toolTypes.js +1 -0
  742. package/src/environment-runner/main.js +8 -0
  743. package/src/history.js +386 -0
  744. package/src/hooks/fileSuggestions.js +635 -0
  745. package/src/hooks/notifs/useAntOrgWarningNotification.js +5 -0
  746. package/src/hooks/notifs/useAutoModeUnavailableNotification.js +47 -0
  747. package/src/hooks/notifs/useCanSwitchToExistingSubscription.js +58 -0
  748. package/src/hooks/notifs/useDeprecationWarningNotification.js +43 -0
  749. package/src/hooks/notifs/useFastModeNotification.js +164 -0
  750. package/src/hooks/notifs/useIDEStatusIndicator.js +174 -0
  751. package/src/hooks/notifs/useInstallMessages.js +27 -0
  752. package/src/hooks/notifs/useLspInitializationNotification.js +144 -0
  753. package/src/hooks/notifs/useMcpConnectivityStatus.js +81 -0
  754. package/src/hooks/notifs/useModelMigrationNotifications.js +53 -0
  755. package/src/hooks/notifs/useNpmDeprecationNotification.js +25 -0
  756. package/src/hooks/notifs/usePluginAutoupdateNotification.js +83 -0
  757. package/src/hooks/notifs/usePluginInstallationStatus.js +128 -0
  758. package/src/hooks/notifs/useRateLimitWarningNotification.js +119 -0
  759. package/src/hooks/notifs/useSettingsErrors.js +64 -0
  760. package/src/hooks/notifs/useStartupNotification.js +33 -0
  761. package/src/hooks/notifs/useTeammateShutdownNotification.js +64 -0
  762. package/src/hooks/renderPlaceholder.js +26 -0
  763. package/src/hooks/toolPermission/PermissionContext.js +211 -0
  764. package/src/hooks/toolPermission/handlers/coordinatorHandler.js +44 -0
  765. package/src/hooks/toolPermission/handlers/interactiveHandler.js +397 -0
  766. package/src/hooks/toolPermission/handlers/swarmWorkerHandler.js +108 -0
  767. package/src/hooks/toolPermission/permissionLogging.js +145 -0
  768. package/src/hooks/unifiedSuggestions.js +130 -0
  769. package/src/hooks/useAfterFirstRender.js +12 -0
  770. package/src/hooks/useApiKeyVerification.js +63 -0
  771. package/src/hooks/useArrowKeyHistory.js +203 -0
  772. package/src/hooks/useAssistantHistory.js +193 -0
  773. package/src/hooks/useAwaySummary.js +105 -0
  774. package/src/hooks/useBackgroundTaskNavigation.js +204 -0
  775. package/src/hooks/useBlink.js +28 -0
  776. package/src/hooks/useCanUseTool.js +193 -0
  777. package/src/hooks/useCancelRequest.js +195 -0
  778. package/src/hooks/useChromeExtensionNotification.js +50 -0
  779. package/src/hooks/useClipboardImageHint.js +59 -0
  780. package/src/hooks/useCommandKeybindings.js +87 -0
  781. package/src/hooks/useCommandQueue.js +10 -0
  782. package/src/hooks/useCopyOnSelect.js +88 -0
  783. package/src/hooks/useDeferredHookMessages.js +43 -0
  784. package/src/hooks/useDiffData.js +69 -0
  785. package/src/hooks/useDiffInIDE.js +252 -0
  786. package/src/hooks/useDirectConnect.js +150 -0
  787. package/src/hooks/useDoublePress.js +44 -0
  788. package/src/hooks/useDynamicConfig.js +17 -0
  789. package/src/hooks/useElapsedTime.js +25 -0
  790. package/src/hooks/useExitOnCtrlCD.js +57 -0
  791. package/src/hooks/useExitOnCtrlCDWithKeybindings.js +17 -0
  792. package/src/hooks/useFileHistorySnapshotInit.js +14 -0
  793. package/src/hooks/useGlobalKeybindings.js +213 -0
  794. package/src/hooks/useHistorySearch.js +241 -0
  795. package/src/hooks/useIDEIntegration.js +56 -0
  796. package/src/hooks/useIdeAtMentioned.js +51 -0
  797. package/src/hooks/useIdeConnectionStatus.js +21 -0
  798. package/src/hooks/useIdeLogging.js +29 -0
  799. package/src/hooks/useIdeSelection.js +106 -0
  800. package/src/hooks/useInboxPoller.js +709 -0
  801. package/src/hooks/useInputBuffer.js +73 -0
  802. package/src/hooks/useIssueFlagBanner.js +115 -0
  803. package/src/hooks/useLogMessages.js +98 -0
  804. package/src/hooks/useLspPluginRecommendation.js +176 -0
  805. package/src/hooks/useMailboxBridge.js +15 -0
  806. package/src/hooks/useMainLoopModel.js +25 -0
  807. package/src/hooks/useManagePlugins.js +261 -0
  808. package/src/hooks/useMemoryUsage.js +28 -0
  809. package/src/hooks/useMergedClients.js +11 -0
  810. package/src/hooks/useMergedCommands.js +10 -0
  811. package/src/hooks/useMergedTools.js +32 -0
  812. package/src/hooks/useMinDisplayTime.js +26 -0
  813. package/src/hooks/useNotifyAfterTimeout.js +51 -0
  814. package/src/hooks/useOfficialMarketplaceNotification.js +47 -0
  815. package/src/hooks/usePasteHandler.js +195 -0
  816. package/src/hooks/usePluginRecommendationBase.js +101 -0
  817. package/src/hooks/usePrStatus.js +91 -0
  818. package/src/hooks/usePromptSuggestion.js +128 -0
  819. package/src/hooks/usePromptsFromClaudeInChrome.js +66 -0
  820. package/src/hooks/useQueueProcessor.js +46 -0
  821. package/src/hooks/useRemoteSession.js +431 -0
  822. package/src/hooks/useReplBridge.js +715 -0
  823. package/src/hooks/useSSHSession.js +167 -0
  824. package/src/hooks/useScheduledTasks.js +104 -0
  825. package/src/hooks/useSearchInput.js +302 -0
  826. package/src/hooks/useSessionBackgrounding.js +132 -0
  827. package/src/hooks/useSettings.js +10 -0
  828. package/src/hooks/useSettingsChange.js +13 -0
  829. package/src/hooks/useSkillImprovementSurvey.js +69 -0
  830. package/src/hooks/useSkillsChange.js +51 -0
  831. package/src/hooks/useSwarmInitialization.js +67 -0
  832. package/src/hooks/useSwarmPermissionPoller.js +215 -0
  833. package/src/hooks/useTaskListWatcher.js +157 -0
  834. package/src/hooks/useTasksV2.js +220 -0
  835. package/src/hooks/useTeammateViewAutoExit.js +55 -0
  836. package/src/hooks/useTeleportResume.js +81 -0
  837. package/src/hooks/useTerminalSize.js +9 -0
  838. package/src/hooks/useTextInput.js +397 -0
  839. package/src/hooks/useThaddeusHintRecommendation.js +117 -0
  840. package/src/hooks/useTimeout.js +10 -0
  841. package/src/hooks/useTurnDiffs.js +160 -0
  842. package/src/hooks/useTypeahead.js +1250 -0
  843. package/src/hooks/useUpdateNotification.js +21 -0
  844. package/src/hooks/useVimInput.js +232 -0
  845. package/src/hooks/useVirtualScroll.js +627 -0
  846. package/src/hooks/useVoice.js +952 -0
  847. package/src/hooks/useVoiceEnabled.js +21 -0
  848. package/src/hooks/useVoiceIntegration.js +629 -0
  849. package/src/infrastructure/audit.js +210 -0
  850. package/src/infrastructure/guardrails.js +513 -0
  851. package/src/infrastructure/index.js +11 -0
  852. package/src/ink/Ansi.js +269 -0
  853. package/src/ink/bidi.js +117 -0
  854. package/src/ink/clearTerminal.js +58 -0
  855. package/src/ink/colorize.js +198 -0
  856. package/src/ink/components/AlternateScreen.js +74 -0
  857. package/src/ink/components/App.js +562 -0
  858. package/src/ink/components/AppContext.js +11 -0
  859. package/src/ink/components/Box.js +155 -0
  860. package/src/ink/components/Button.js +166 -0
  861. package/src/ink/components/ClockContext.js +108 -0
  862. package/src/ink/components/CursorDeclarationContext.js +3 -0
  863. package/src/ink/components/ErrorOverview.js +50 -0
  864. package/src/ink/components/Link.js +34 -0
  865. package/src/ink/components/Newline.js +30 -0
  866. package/src/ink/components/NoSelect.js +57 -0
  867. package/src/ink/components/RawAnsi.js +46 -0
  868. package/src/ink/components/ScrollBox.js +171 -0
  869. package/src/ink/components/Spacer.js +20 -0
  870. package/src/ink/components/StdinContext.js +16 -0
  871. package/src/ink/components/TerminalFocusContext.js +45 -0
  872. package/src/ink/components/TerminalSizeContext.js +3 -0
  873. package/src/ink/components/Text.js +195 -0
  874. package/src/ink/constants.js +2 -0
  875. package/src/ink/dom.js +298 -0
  876. package/src/ink/events/click-event.js +36 -0
  877. package/src/ink/events/dispatcher.js +172 -0
  878. package/src/ink/events/emitter.js +31 -0
  879. package/src/ink/events/event-handlers.js +30 -0
  880. package/src/ink/events/event.js +9 -0
  881. package/src/ink/events/focus-event.js +16 -0
  882. package/src/ink/events/input-event.js +161 -0
  883. package/src/ink/events/keyboard-event.js +46 -0
  884. package/src/ink/events/terminal-event.js +78 -0
  885. package/src/ink/events/terminal-focus-event.js +15 -0
  886. package/src/ink/focus.js +158 -0
  887. package/src/ink/frame.js +30 -0
  888. package/src/ink/get-max-width.js +23 -0
  889. package/src/ink/hit-test.js +113 -0
  890. package/src/ink/hooks/use-animation-frame.js +48 -0
  891. package/src/ink/hooks/use-app.js +7 -0
  892. package/src/ink/hooks/use-declared-cursor.js +60 -0
  893. package/src/ink/hooks/use-input.js +70 -0
  894. package/src/ink/hooks/use-interval.js +54 -0
  895. package/src/ink/hooks/use-search-highlight.js +32 -0
  896. package/src/ink/hooks/use-selection.js +60 -0
  897. package/src/ink/hooks/use-stdin.js +7 -0
  898. package/src/ink/hooks/use-tab-status.js +57 -0
  899. package/src/ink/hooks/use-terminal-focus.js +15 -0
  900. package/src/ink/hooks/use-terminal-title.js +29 -0
  901. package/src/ink/hooks/use-terminal-viewport.js +77 -0
  902. package/src/ink/ink.js +1645 -0
  903. package/src/ink/instances.js +7 -0
  904. package/src/ink/layout/engine.js +4 -0
  905. package/src/ink/layout/geometry.js +61 -0
  906. package/src/ink/layout/node.js +62 -0
  907. package/src/ink/layout/yoga.js +237 -0
  908. package/src/ink/line-width-cache.js +19 -0
  909. package/src/ink/log-update.js +583 -0
  910. package/src/ink/measure-element.js +8 -0
  911. package/src/ink/measure-text.js +35 -0
  912. package/src/ink/node-cache.js +30 -0
  913. package/src/ink/optimizer.js +81 -0
  914. package/src/ink/output.js +556 -0
  915. package/src/ink/parse-keypress.js +695 -0
  916. package/src/ink/reconciler.js +384 -0
  917. package/src/ink/render-border.js +134 -0
  918. package/src/ink/render-node-to-output.js +1216 -0
  919. package/src/ink/render-to-screen.js +171 -0
  920. package/src/ink/renderer.js +129 -0
  921. package/src/ink/root.js +80 -0
  922. package/src/ink/screen.js +1132 -0
  923. package/src/ink/searchHighlight.js +78 -0
  924. package/src/ink/selection.js +792 -0
  925. package/src/ink/squash-text-nodes.js +56 -0
  926. package/src/ink/stringWidth.js +200 -0
  927. package/src/ink/styles.js +299 -0
  928. package/src/ink/supports-hyperlinks.js +40 -0
  929. package/src/ink/tabstops.js +39 -0
  930. package/src/ink/terminal-focus-state.js +35 -0
  931. package/src/ink/terminal-querier.js +173 -0
  932. package/src/ink/terminal.js +208 -0
  933. package/src/ink/termio/ansi.js +70 -0
  934. package/src/ink/termio/csi.js +260 -0
  935. package/src/ink/termio/dec.js +53 -0
  936. package/src/ink/termio/esc.js +55 -0
  937. package/src/ink/termio/osc.js +432 -0
  938. package/src/ink/termio/parser.js +356 -0
  939. package/src/ink/termio/sgr.js +292 -0
  940. package/src/ink/termio/tokenize.js +264 -0
  941. package/src/ink/termio/types.js +55 -0
  942. package/src/ink/termio.js +24 -0
  943. package/src/ink/useTerminalNotification.js +57 -0
  944. package/src/ink/warn.js +10 -0
  945. package/src/ink/widest-line.js +14 -0
  946. package/src/ink/wrap-text.js +54 -0
  947. package/src/ink/wrapAnsi.js +6 -0
  948. package/src/ink.js +50 -0
  949. package/src/integrations/credentialStore.js +176 -0
  950. package/src/integrations/index.js +5 -0
  951. package/src/integrations/integrationManager.js +180 -0
  952. package/src/integrations/providers/BaseProvider.js +180 -0
  953. package/src/integrations/providers/GitHubProvider.js +217 -0
  954. package/src/integrations/providers/GmailProvider.js +204 -0
  955. package/src/integrations/providers/GoogleCalendarProvider.js +113 -0
  956. package/src/integrations/providers/HubSpotProvider.js +159 -0
  957. package/src/integrations/providers/JiraProvider.js +216 -0
  958. package/src/integrations/providers/NotionProvider.js +221 -0
  959. package/src/integrations/providers/QuickBooksProvider.js +176 -0
  960. package/src/integrations/providers/SlackProvider.js +174 -0
  961. package/src/integrations/providers/StripeProvider.js +206 -0
  962. package/src/integrations/providers/TwilioProvider.js +239 -0
  963. package/src/integrations/providers/_template.js +112 -0
  964. package/src/integrations/types.js +7 -0
  965. package/src/interactiveHelpers.js +308 -0
  966. package/src/jobs/classifier.js +6 -0
  967. package/src/keybindings/KeybindingContext.js +184 -0
  968. package/src/keybindings/KeybindingProviderSetup.js +259 -0
  969. package/src/keybindings/defaultBindings.js +333 -0
  970. package/src/keybindings/loadUserBindings.js +393 -0
  971. package/src/keybindings/match.js +111 -0
  972. package/src/keybindings/parser.js +184 -0
  973. package/src/keybindings/reservedShortcuts.js +109 -0
  974. package/src/keybindings/resolver.js +182 -0
  975. package/src/keybindings/schema.js +205 -0
  976. package/src/keybindings/shortcutFormat.js +48 -0
  977. package/src/keybindings/template.js +40 -0
  978. package/src/keybindings/useKeybinding.js +161 -0
  979. package/src/keybindings/useShortcutDisplay.js +43 -0
  980. package/src/keybindings/validate.js +395 -0
  981. package/src/main.js +4128 -0
  982. package/src/memdir/findRelevantMemories.js +99 -0
  983. package/src/memdir/memdir.js +406 -0
  984. package/src/memdir/memoryAge.js +52 -0
  985. package/src/memdir/memoryScan.js +65 -0
  986. package/src/memdir/memoryShapeTelemetry.js +8 -0
  987. package/src/memdir/memoryTypes.js +260 -0
  988. package/src/memdir/paths.js +235 -0
  989. package/src/memdir/teamMemPaths.js +261 -0
  990. package/src/memdir/teamMemPrompts.js +82 -0
  991. package/src/migrations/migrateAutoUpdatesToSettings.js +47 -0
  992. package/src/migrations/migrateBypassPermissionsAcceptedToSettings.js +32 -0
  993. package/src/migrations/migrateEnableAllProjectMcpServersToSettings.js +83 -0
  994. package/src/migrations/migrateFennecToOpus.js +39 -0
  995. package/src/migrations/migrateLegacyOpusToCurrent.js +44 -0
  996. package/src/migrations/migrateOpusToOpus1m.js +31 -0
  997. package/src/migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.js +23 -0
  998. package/src/migrations/migrateSonnet1mToSonnet45.js +38 -0
  999. package/src/migrations/migrateSonnet45ToSonnet46.js +48 -0
  1000. package/src/migrations/resetAutoModeOptInForDefaultOffer.js +47 -0
  1001. package/src/migrations/resetProToOpusDefault.js +46 -0
  1002. package/src/moreright/useMoreRight.js +13 -0
  1003. package/src/native-ts/color-diff/index.js +819 -0
  1004. package/src/native-ts/file-index/index.js +328 -0
  1005. package/src/native-ts/yoga-layout/enums.js +101 -0
  1006. package/src/native-ts/yoga-layout/index.js +2113 -0
  1007. package/src/outputStyles/loadOutputStylesDir.js +71 -0
  1008. package/src/plugins/builtinPlugins.js +132 -0
  1009. package/src/plugins/bundled/index.js +22 -0
  1010. package/src/proactive/index.js +138 -0
  1011. package/src/proactive/useProactive.js +82 -0
  1012. package/src/projectOnboardingState.js +61 -0
  1013. package/src/query/config.js +17 -0
  1014. package/src/query/deps.js +12 -0
  1015. package/src/query/stopHooks.js +332 -0
  1016. package/src/query/tokenBudget.js +49 -0
  1017. package/src/query.js +1264 -0
  1018. package/src/remote/RemoteSessionManager.js +172 -0
  1019. package/src/remote/SessionsWebSocket.js +308 -0
  1020. package/src/remote/remotePermissionBridge.js +70 -0
  1021. package/src/remote/sdkMessageAdapter.js +227 -0
  1022. package/src/replLauncher.js +7 -0
  1023. package/src/schemas/hooks.js +174 -0
  1024. package/src/screens/Doctor.js +580 -0
  1025. package/src/screens/REPL.js +4500 -0
  1026. package/src/screens/ResumeConversation.js +339 -0
  1027. package/src/self-hosted-runner/main.js +8 -0
  1028. package/src/server/backends/dangerousBackend.js +8 -0
  1029. package/src/server/connectHeadless.js +6 -0
  1030. package/src/server/createDirectConnectSession.js +62 -0
  1031. package/src/server/directConnectManager.js +153 -0
  1032. package/src/server/lockfile.js +11 -0
  1033. package/src/server/parseConnectUrl.js +20 -0
  1034. package/src/server/server.js +12 -0
  1035. package/src/server/serverBanner.js +9 -0
  1036. package/src/server/serverLog.js +11 -0
  1037. package/src/server/sessionManager.js +19 -0
  1038. package/src/server/types.js +7 -0
  1039. package/src/services/AgentSummary/agentSummary.js +147 -0
  1040. package/src/services/MagicDocs/magicDocs.js +193 -0
  1041. package/src/services/MagicDocs/prompts.js +110 -0
  1042. package/src/services/PromptSuggestion/promptSuggestion.js +402 -0
  1043. package/src/services/PromptSuggestion/speculation.js +643 -0
  1044. package/src/services/SessionMemory/prompts.js +254 -0
  1045. package/src/services/SessionMemory/sessionMemory.js +358 -0
  1046. package/src/services/SessionMemory/sessionMemoryUtils.js +157 -0
  1047. package/src/services/analytics/config.js +27 -0
  1048. package/src/services/analytics/datadog.js +26 -0
  1049. package/src/services/analytics/firstPartyEventLogger.js +65 -0
  1050. package/src/services/analytics/firstPartyEventLoggingExporter.js +595 -0
  1051. package/src/services/analytics/growthbook.js +103 -0
  1052. package/src/services/analytics/index.js +91 -0
  1053. package/src/services/analytics/metadata.js +696 -0
  1054. package/src/services/analytics/sink.js +19 -0
  1055. package/src/services/analytics/sinkKillswitch.js +19 -0
  1056. package/src/services/api/adminRequests.js +57 -0
  1057. package/src/services/api/bootstrap.js +118 -0
  1058. package/src/services/api/claude.js +2466 -0
  1059. package/src/services/api/client.js +335 -0
  1060. package/src/services/api/dumpPrompts.js +174 -0
  1061. package/src/services/api/emptyUsage.js +20 -0
  1062. package/src/services/api/errorUtils.js +203 -0
  1063. package/src/services/api/errors.js +926 -0
  1064. package/src/services/api/filesApi.js +523 -0
  1065. package/src/services/api/firstTokenDate.js +49 -0
  1066. package/src/services/api/grove.js +44 -0
  1067. package/src/services/api/logging.js +484 -0
  1068. package/src/services/api/metricsOptOut.js +15 -0
  1069. package/src/services/api/overageCreditGrant.js +123 -0
  1070. package/src/services/api/promptCacheBreakDetection.js +510 -0
  1071. package/src/services/api/referral.js +219 -0
  1072. package/src/services/api/sessionIngress.js +358 -0
  1073. package/src/services/api/ultrareviewQuota.js +29 -0
  1074. package/src/services/api/usage.js +31 -0
  1075. package/src/services/api/withRetry.js +587 -0
  1076. package/src/services/api/xai/anthropic-shim.js +885 -0
  1077. package/src/services/api/xai/brightDataSearch.js +161 -0
  1078. package/src/services/api/xai/thaddeus-engine.js +605 -0
  1079. package/src/services/api/xai/xai-client.js +276 -0
  1080. package/src/services/autoDream/autoDream.js +244 -0
  1081. package/src/services/autoDream/config.js +17 -0
  1082. package/src/services/autoDream/consolidationLock.js +122 -0
  1083. package/src/services/autoDream/consolidationPrompt.js +55 -0
  1084. package/src/services/awaySummary.js +61 -0
  1085. package/src/services/claudeAiLimits.js +331 -0
  1086. package/src/services/claudeAiLimitsHook.js +15 -0
  1087. package/src/services/compact/apiMicrocompact.js +97 -0
  1088. package/src/services/compact/autoCompact.js +234 -0
  1089. package/src/services/compact/cachedMCConfig.js +5 -0
  1090. package/src/services/compact/compact.js +1256 -0
  1091. package/src/services/compact/compactWarningHook.js +12 -0
  1092. package/src/services/compact/compactWarningState.js +15 -0
  1093. package/src/services/compact/grouping.js +58 -0
  1094. package/src/services/compact/microCompact.js +414 -0
  1095. package/src/services/compact/postCompactCleanup.js +70 -0
  1096. package/src/services/compact/prompt.js +325 -0
  1097. package/src/services/compact/reactiveCompact.js +20 -0
  1098. package/src/services/compact/sessionMemoryCompact.js +467 -0
  1099. package/src/services/compact/snipCompact.js +23 -0
  1100. package/src/services/compact/snipProjection.js +11 -0
  1101. package/src/services/compact/timeBasedMCConfig.js +11 -0
  1102. package/src/services/contextCollapse/index.js +33 -0
  1103. package/src/services/contextCollapse/operations.js +5 -0
  1104. package/src/services/contextCollapse/persist.js +5 -0
  1105. package/src/services/diagnosticTracking.js +282 -0
  1106. package/src/services/elevenlabsTTS.js +245 -0
  1107. package/src/services/extractMemories/extractMemories.js +442 -0
  1108. package/src/services/extractMemories/prompts.js +129 -0
  1109. package/src/services/internalLogging.js +68 -0
  1110. package/src/services/lsp/LSPClient.js +306 -0
  1111. package/src/services/lsp/LSPDiagnosticRegistry.js +277 -0
  1112. package/src/services/lsp/LSPServerInstance.js +388 -0
  1113. package/src/services/lsp/LSPServerManager.js +305 -0
  1114. package/src/services/lsp/config.js +57 -0
  1115. package/src/services/lsp/manager.js +246 -0
  1116. package/src/services/lsp/passiveFeedback.js +226 -0
  1117. package/src/services/mcp/InProcessTransport.js +54 -0
  1118. package/src/services/mcp/MCPConnectionManager.js +50 -0
  1119. package/src/services/mcp/SdkControlTransport.js +115 -0
  1120. package/src/services/mcp/auth.js +1882 -0
  1121. package/src/services/mcp/channelAllowlist.js +57 -0
  1122. package/src/services/mcp/channelNotification.js +235 -0
  1123. package/src/services/mcp/channelPermissions.js +192 -0
  1124. package/src/services/mcp/claudeai.js +123 -0
  1125. package/src/services/mcp/client.js +2478 -0
  1126. package/src/services/mcp/config.js +1271 -0
  1127. package/src/services/mcp/elicitationHandler.js +192 -0
  1128. package/src/services/mcp/envExpansion.js +30 -0
  1129. package/src/services/mcp/headersHelper.js +93 -0
  1130. package/src/services/mcp/mcpStringUtils.js +85 -0
  1131. package/src/services/mcp/normalization.js +21 -0
  1132. package/src/services/mcp/oauthPort.js +69 -0
  1133. package/src/services/mcp/officialRegistry.js +20 -0
  1134. package/src/services/mcp/types.js +94 -0
  1135. package/src/services/mcp/useManageMCPConnections.js +818 -0
  1136. package/src/services/mcp/utils.js +433 -0
  1137. package/src/services/mcp/vscodeSdkMcp.js +69 -0
  1138. package/src/services/mcp/xaa.js +342 -0
  1139. package/src/services/mcp/xaaIdpLogin.js +377 -0
  1140. package/src/services/mcpServerApproval.js +30 -0
  1141. package/src/services/mockRateLimits.js +666 -0
  1142. package/src/services/notifier.js +114 -0
  1143. package/src/services/oauth/auth-code-listener.js +165 -0
  1144. package/src/services/oauth/client.js +397 -0
  1145. package/src/services/oauth/crypto.js +19 -0
  1146. package/src/services/oauth/getOauthProfile.js +48 -0
  1147. package/src/services/oauth/index.js +133 -0
  1148. package/src/services/plugins/PluginInstallationManager.js +139 -0
  1149. package/src/services/plugins/pluginCliCommands.js +230 -0
  1150. package/src/services/plugins/pluginOperations.js +826 -0
  1151. package/src/services/policyLimits/index.js +547 -0
  1152. package/src/services/policyLimits/types.js +9 -0
  1153. package/src/services/preventSleep.js +143 -0
  1154. package/src/services/rateLimitMessages.js +271 -0
  1155. package/src/services/rateLimitMocking.js +91 -0
  1156. package/src/services/remoteManagedSettings/index.js +534 -0
  1157. package/src/services/remoteManagedSettings/securityCheck.js +60 -0
  1158. package/src/services/remoteManagedSettings/syncCache.js +90 -0
  1159. package/src/services/remoteManagedSettings/syncCacheState.js +89 -0
  1160. package/src/services/remoteManagedSettings/types.js +12 -0
  1161. package/src/services/sessionTranscript/sessionTranscript.js +5 -0
  1162. package/src/services/settingsSync/index.js +478 -0
  1163. package/src/services/settingsSync/types.js +35 -0
  1164. package/src/services/skillSearch/featureCheck.js +8 -0
  1165. package/src/services/skillSearch/localSearch.js +5 -0
  1166. package/src/services/skillSearch/prefetch.js +8 -0
  1167. package/src/services/skillSearch/remoteSkillLoader.js +8 -0
  1168. package/src/services/skillSearch/remoteSkillState.js +11 -0
  1169. package/src/services/skillSearch/signals.js +3 -0
  1170. package/src/services/skillSearch/telemetry.js +8 -0
  1171. package/src/services/teamMemorySync/index.js +976 -0
  1172. package/src/services/teamMemorySync/secretScanner.js +275 -0
  1173. package/src/services/teamMemorySync/teamMemSecretGuard.js +33 -0
  1174. package/src/services/teamMemorySync/types.js +47 -0
  1175. package/src/services/teamMemorySync/watcher.js +326 -0
  1176. package/src/services/thaddeusAuth.js +485 -0
  1177. package/src/services/thaddeusAuthTypes.js +9 -0
  1178. package/src/services/thaddeusLoginFlow.js +236 -0
  1179. package/src/services/tips/tipHistory.js +17 -0
  1180. package/src/services/tips/tipRegistry.js +593 -0
  1181. package/src/services/tips/tipScheduler.js +40 -0
  1182. package/src/services/tokenEstimation.js +365 -0
  1183. package/src/services/toolUseSummary/toolUseSummaryGenerator.js +87 -0
  1184. package/src/services/tools/StreamingToolExecutor.js +413 -0
  1185. package/src/services/tools/toolExecution.js +1309 -0
  1186. package/src/services/tools/toolHooks.js +454 -0
  1187. package/src/services/tools/toolOrchestration.js +110 -0
  1188. package/src/services/vcr.js +291 -0
  1189. package/src/services/voice.js +392 -0
  1190. package/src/services/voiceKeyterms.js +94 -0
  1191. package/src/services/voiceStreamSTT.js +405 -0
  1192. package/src/setup.js +310 -0
  1193. package/src/skills/bundled/batch.js +114 -0
  1194. package/src/skills/bundled/claudeApi.js +145 -0
  1195. package/src/skills/bundled/claudeApiContent.js +71 -0
  1196. package/src/skills/bundled/claudeInChrome.js +27 -0
  1197. package/src/skills/bundled/debug.js +99 -0
  1198. package/src/skills/bundled/dream.js +49 -0
  1199. package/src/skills/bundled/emailSetup.js +196 -0
  1200. package/src/skills/bundled/hunter.js +28 -0
  1201. package/src/skills/bundled/index.js +80 -0
  1202. package/src/skills/bundled/keybindings.js +292 -0
  1203. package/src/skills/bundled/loop.js +81 -0
  1204. package/src/skills/bundled/loremIpsum.js +264 -0
  1205. package/src/skills/bundled/reactor.js +31 -0
  1206. package/src/skills/bundled/remember.js +73 -0
  1207. package/src/skills/bundled/runSkillGenerator.js +12 -0
  1208. package/src/skills/bundled/scheduleRemoteAgents.js +373 -0
  1209. package/src/skills/bundled/simplify.js +66 -0
  1210. package/src/skills/bundled/skillify.js +182 -0
  1211. package/src/skills/bundled/stuck.js +69 -0
  1212. package/src/skills/bundled/updateConfig.js +463 -0
  1213. package/src/skills/bundled/verify.js +23 -0
  1214. package/src/skills/bundled/verifyContent.js +10 -0
  1215. package/src/skills/bundledSkills.js +159 -0
  1216. package/src/skills/loadSkillsDir.js +736 -0
  1217. package/src/skills/mcpSkillBuilders.js +10 -0
  1218. package/src/skills/mcpSkills.js +5 -0
  1219. package/src/state/AppState.js +182 -0
  1220. package/src/state/AppStateStore.js +117 -0
  1221. package/src/state/onChangeAppState.js +132 -0
  1222. package/src/state/selectors.js +51 -0
  1223. package/src/state/store.js +21 -0
  1224. package/src/state/teammateViewHelpers.js +124 -0
  1225. package/src/stubs/ant-chrome-mcp/index.js +4 -0
  1226. package/src/stubs/ant-computer-use-input/index.js +2 -0
  1227. package/src/stubs/ant-computer-use-mcp/index.js +7 -0
  1228. package/src/stubs/ant-computer-use-mcp/sentinelApps.js +2 -0
  1229. package/src/stubs/ant-computer-use-mcp/types.js +3 -0
  1230. package/src/stubs/ant-computer-use-swift/index.js +1 -0
  1231. package/src/stubs/anthropic-sandbox/index.js +34 -0
  1232. package/src/tasks/DreamTask/DreamTask.js +99 -0
  1233. package/src/tasks/InProcessTeammateTask/InProcessTeammateTask.js +116 -0
  1234. package/src/tasks/InProcessTeammateTask/types.js +35 -0
  1235. package/src/tasks/LocalAgentTask/LocalAgentTask.js +507 -0
  1236. package/src/tasks/LocalMainSessionTask.js +338 -0
  1237. package/src/tasks/LocalShellTask/LocalShellTask.js +475 -0
  1238. package/src/tasks/LocalShellTask/guards.js +9 -0
  1239. package/src/tasks/LocalShellTask/killShellTasks.js +59 -0
  1240. package/src/tasks/LocalWorkflowTask/LocalWorkflowTask.js +7 -0
  1241. package/src/tasks/MonitorMcpTask/MonitorMcpTask.js +20 -0
  1242. package/src/tasks/RemoteAgentTask/RemoteAgentTask.js +742 -0
  1243. package/src/tasks/pillLabel.js +69 -0
  1244. package/src/tasks/stopTask.js +67 -0
  1245. package/src/tasks/types.js +18 -0
  1246. package/src/tasks.js +37 -0
  1247. package/src/tools/AIEmployeesTool/AIEmployeesTool.js +674 -0
  1248. package/src/tools/AIEmployeesTool/constants.js +1 -0
  1249. package/src/tools/AIEmployeesTool/prompt.js +56 -0
  1250. package/src/tools/AgentTool/AgentTool.js +1221 -0
  1251. package/src/tools/AgentTool/UI.js +593 -0
  1252. package/src/tools/AgentTool/agentColorManager.js +43 -0
  1253. package/src/tools/AgentTool/agentDisplay.js +72 -0
  1254. package/src/tools/AgentTool/agentMemory.js +125 -0
  1255. package/src/tools/AgentTool/agentMemorySnapshot.js +136 -0
  1256. package/src/tools/AgentTool/agentToolUtils.js +456 -0
  1257. package/src/tools/AgentTool/built-in/exploreAgent.js +76 -0
  1258. package/src/tools/AgentTool/built-in/generalPurposeAgent.js +28 -0
  1259. package/src/tools/AgentTool/built-in/planAgent.js +87 -0
  1260. package/src/tools/AgentTool/built-in/statuslineSetup.js +140 -0
  1261. package/src/tools/AgentTool/built-in/thaddeusGuideAgent.js +174 -0
  1262. package/src/tools/AgentTool/built-in/verificationAgent.js +146 -0
  1263. package/src/tools/AgentTool/builtInAgents.js +56 -0
  1264. package/src/tools/AgentTool/constants.js +11 -0
  1265. package/src/tools/AgentTool/forkSubagent.js +177 -0
  1266. package/src/tools/AgentTool/loadAgentsDir.js +497 -0
  1267. package/src/tools/AgentTool/prompt.js +260 -0
  1268. package/src/tools/AgentTool/resumeAgent.js +182 -0
  1269. package/src/tools/AgentTool/runAgent.js +627 -0
  1270. package/src/tools/AppointmentsTool/AppointmentsTool.js +628 -0
  1271. package/src/tools/AppointmentsTool/constants.js +1 -0
  1272. package/src/tools/AppointmentsTool/prompt.js +15 -0
  1273. package/src/tools/AskUserQuestionTool/AskUserQuestionTool.js +238 -0
  1274. package/src/tools/AskUserQuestionTool/prompt.js +38 -0
  1275. package/src/tools/BashTool/BashTool.js +1009 -0
  1276. package/src/tools/BashTool/BashToolResultMessage.js +169 -0
  1277. package/src/tools/BashTool/UI.js +134 -0
  1278. package/src/tools/BashTool/bashCommandHelpers.js +184 -0
  1279. package/src/tools/BashTool/bashPermissions.js +2023 -0
  1280. package/src/tools/BashTool/bashSecurity.js +2267 -0
  1281. package/src/tools/BashTool/commandSemantics.js +105 -0
  1282. package/src/tools/BashTool/commentLabel.js +14 -0
  1283. package/src/tools/BashTool/destructiveCommandWarning.js +88 -0
  1284. package/src/tools/BashTool/modeValidation.js +86 -0
  1285. package/src/tools/BashTool/pathValidation.js +1079 -0
  1286. package/src/tools/BashTool/prompt.js +333 -0
  1287. package/src/tools/BashTool/readOnlyValidation.js +1794 -0
  1288. package/src/tools/BashTool/sedEditParser.js +282 -0
  1289. package/src/tools/BashTool/sedValidation.js +580 -0
  1290. package/src/tools/BashTool/shouldUseSandbox.js +125 -0
  1291. package/src/tools/BashTool/toolName.js +2 -0
  1292. package/src/tools/BashTool/utils.js +180 -0
  1293. package/src/tools/BriefTool/BriefTool.js +173 -0
  1294. package/src/tools/BriefTool/UI.js +67 -0
  1295. package/src/tools/BriefTool/attachments.js +86 -0
  1296. package/src/tools/BriefTool/prompt.js +19 -0
  1297. package/src/tools/BriefTool/upload.js +136 -0
  1298. package/src/tools/CalendarTool/CalendarTool.js +498 -0
  1299. package/src/tools/CalendarTool/constants.js +1 -0
  1300. package/src/tools/CalendarTool/prompt.js +11 -0
  1301. package/src/tools/ConfigTool/ConfigTool.js +398 -0
  1302. package/src/tools/ConfigTool/UI.js +25 -0
  1303. package/src/tools/ConfigTool/constants.js +1 -0
  1304. package/src/tools/ConfigTool/prompt.js +82 -0
  1305. package/src/tools/ConfigTool/supportedSettings.js +180 -0
  1306. package/src/tools/ContactsTool/ContactsTool.js +648 -0
  1307. package/src/tools/ContactsTool/constants.js +1 -0
  1308. package/src/tools/ContactsTool/prompt.js +15 -0
  1309. package/src/tools/CtxInspectTool/CtxInspectTool.js +44 -0
  1310. package/src/tools/DiscoverSkillsTool/prompt.js +4 -0
  1311. package/src/tools/EmailReadTool/index.js +410 -0
  1312. package/src/tools/EmailSendTool/index.js +178 -0
  1313. package/src/tools/EnterPlanModeTool/EnterPlanModeTool.js +98 -0
  1314. package/src/tools/EnterPlanModeTool/UI.js +14 -0
  1315. package/src/tools/EnterPlanModeTool/constants.js +1 -0
  1316. package/src/tools/EnterPlanModeTool/prompt.js +164 -0
  1317. package/src/tools/EnterWorktreeTool/EnterWorktreeTool.js +104 -0
  1318. package/src/tools/EnterWorktreeTool/UI.js +9 -0
  1319. package/src/tools/EnterWorktreeTool/constants.js +1 -0
  1320. package/src/tools/EnterWorktreeTool/prompt.js +30 -0
  1321. package/src/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js +383 -0
  1322. package/src/tools/ExitPlanModeTool/UI.js +32 -0
  1323. package/src/tools/ExitPlanModeTool/constants.js +2 -0
  1324. package/src/tools/ExitPlanModeTool/prompt.js +27 -0
  1325. package/src/tools/ExitWorktreeTool/ExitWorktreeTool.js +257 -0
  1326. package/src/tools/ExitWorktreeTool/UI.js +10 -0
  1327. package/src/tools/ExitWorktreeTool/constants.js +1 -0
  1328. package/src/tools/ExitWorktreeTool/prompt.js +32 -0
  1329. package/src/tools/FileEditTool/FileEditTool.js +480 -0
  1330. package/src/tools/FileEditTool/UI.js +202 -0
  1331. package/src/tools/FileEditTool/constants.js +7 -0
  1332. package/src/tools/FileEditTool/prompt.js +24 -0
  1333. package/src/tools/FileEditTool/types.js +50 -0
  1334. package/src/tools/FileEditTool/utils.js +579 -0
  1335. package/src/tools/FileReadTool/FileReadTool.js +889 -0
  1336. package/src/tools/FileReadTool/UI.js +126 -0
  1337. package/src/tools/FileReadTool/imageProcessor.js +46 -0
  1338. package/src/tools/FileReadTool/limits.js +70 -0
  1339. package/src/tools/FileReadTool/prompt.js +31 -0
  1340. package/src/tools/FileWriteTool/FileWriteTool.js +341 -0
  1341. package/src/tools/FileWriteTool/UI.js +339 -0
  1342. package/src/tools/FileWriteTool/prompt.js +15 -0
  1343. package/src/tools/GlobTool/GlobTool.js +161 -0
  1344. package/src/tools/GlobTool/UI.js +40 -0
  1345. package/src/tools/GlobTool/prompt.js +6 -0
  1346. package/src/tools/GrepTool/GrepTool.js +439 -0
  1347. package/src/tools/GrepTool/UI.js +155 -0
  1348. package/src/tools/GrepTool/prompt.js +16 -0
  1349. package/src/tools/IntegrationsTool/IntegrationsTool.js +217 -0
  1350. package/src/tools/IntegrationsTool/constants.js +1 -0
  1351. package/src/tools/IntegrationsTool/prompt.js +41 -0
  1352. package/src/tools/InteractionsTool/InteractionsTool.js +525 -0
  1353. package/src/tools/InteractionsTool/constants.js +1 -0
  1354. package/src/tools/InteractionsTool/prompt.js +14 -0
  1355. package/src/tools/InvoicesTool/InvoicesTool.js +581 -0
  1356. package/src/tools/InvoicesTool/constants.js +1 -0
  1357. package/src/tools/InvoicesTool/prompt.js +15 -0
  1358. package/src/tools/LSPTool/LSPTool.js +660 -0
  1359. package/src/tools/LSPTool/UI.js +205 -0
  1360. package/src/tools/LSPTool/formatters.js +445 -0
  1361. package/src/tools/LSPTool/prompt.js +20 -0
  1362. package/src/tools/LSPTool/schemas.js +197 -0
  1363. package/src/tools/LSPTool/symbolContext.js +75 -0
  1364. package/src/tools/LeadScorerTool/LeadScorerTool.js +509 -0
  1365. package/src/tools/LeadScorerTool/constants.js +1 -0
  1366. package/src/tools/LeadScorerTool/prompt.js +11 -0
  1367. package/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +100 -0
  1368. package/src/tools/ListMcpResourcesTool/UI.js +17 -0
  1369. package/src/tools/ListMcpResourcesTool/prompt.js +18 -0
  1370. package/src/tools/ListPeersTool/ListPeersTool.js +45 -0
  1371. package/src/tools/MCPTool/MCPTool.js +60 -0
  1372. package/src/tools/MCPTool/UI.js +343 -0
  1373. package/src/tools/MCPTool/classifyForCollapse.js +597 -0
  1374. package/src/tools/MCPTool/prompt.js +3 -0
  1375. package/src/tools/McpAuthTool/McpAuthTool.js +162 -0
  1376. package/src/tools/MonitorTool/MonitorTool.js +55 -0
  1377. package/src/tools/NotebookEditTool/NotebookEditTool.js +421 -0
  1378. package/src/tools/NotebookEditTool/UI.js +41 -0
  1379. package/src/tools/NotebookEditTool/constants.js +2 -0
  1380. package/src/tools/NotebookEditTool/prompt.js +2 -0
  1381. package/src/tools/OverflowTestTool/OverflowTestTool.js +51 -0
  1382. package/src/tools/PhoneBridgeTool/PhoneBridgeTool.js +301 -0
  1383. package/src/tools/PhoneBridgeTool/constants.js +1 -0
  1384. package/src/tools/PhoneBridgeTool/prompt.js +26 -0
  1385. package/src/tools/PowerShellTool/PowerShellTool.js +900 -0
  1386. package/src/tools/PowerShellTool/UI.js +58 -0
  1387. package/src/tools/PowerShellTool/clmTypes.js +207 -0
  1388. package/src/tools/PowerShellTool/commandSemantics.js +115 -0
  1389. package/src/tools/PowerShellTool/commonParameters.js +27 -0
  1390. package/src/tools/PowerShellTool/destructiveCommandWarning.js +92 -0
  1391. package/src/tools/PowerShellTool/gitSafety.js +185 -0
  1392. package/src/tools/PowerShellTool/modeValidation.js +357 -0
  1393. package/src/tools/PowerShellTool/pathValidation.js +1712 -0
  1394. package/src/tools/PowerShellTool/powershellPermissions.js +1351 -0
  1395. package/src/tools/PowerShellTool/powershellSecurity.js +942 -0
  1396. package/src/tools/PowerShellTool/prompt.js +132 -0
  1397. package/src/tools/PowerShellTool/readOnlyValidation.js +1633 -0
  1398. package/src/tools/PowerShellTool/toolName.js +2 -0
  1399. package/src/tools/PushNotificationTool/PushNotificationTool.js +35 -0
  1400. package/src/tools/REPLTool/REPLTool.js +44 -0
  1401. package/src/tools/REPLTool/constants.js +43 -0
  1402. package/src/tools/REPLTool/primitiveTools.js +36 -0
  1403. package/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +112 -0
  1404. package/src/tools/ReadMcpResourceTool/UI.js +24 -0
  1405. package/src/tools/ReadMcpResourceTool/prompt.js +15 -0
  1406. package/src/tools/RemoteTriggerTool/RemoteTriggerTool.js +142 -0
  1407. package/src/tools/RemoteTriggerTool/UI.js +12 -0
  1408. package/src/tools/RemoteTriggerTool/prompt.js +12 -0
  1409. package/src/tools/ReviewArtifactTool/ReviewArtifactTool.js +51 -0
  1410. package/src/tools/ScheduleCronTool/CronCreateTool.js +120 -0
  1411. package/src/tools/ScheduleCronTool/CronDeleteTool.js +74 -0
  1412. package/src/tools/ScheduleCronTool/CronListTool.js +77 -0
  1413. package/src/tools/ScheduleCronTool/UI.js +29 -0
  1414. package/src/tools/ScheduleCronTool/prompt.js +115 -0
  1415. package/src/tools/SendMessageTool/SendMessageTool.js +673 -0
  1416. package/src/tools/SendMessageTool/UI.js +24 -0
  1417. package/src/tools/SendMessageTool/constants.js +1 -0
  1418. package/src/tools/SendMessageTool/prompt.js +47 -0
  1419. package/src/tools/SendUserFileTool/SendUserFileTool.js +35 -0
  1420. package/src/tools/SendUserFileTool/prompt.js +5 -0
  1421. package/src/tools/SkillTool/SkillTool.js +825 -0
  1422. package/src/tools/SkillTool/UI.js +61 -0
  1423. package/src/tools/SkillTool/constants.js +1 -0
  1424. package/src/tools/SkillTool/prompt.js +184 -0
  1425. package/src/tools/SleepTool/SleepTool.js +42 -0
  1426. package/src/tools/SleepTool/prompt.js +14 -0
  1427. package/src/tools/SnipTool/SnipTool.js +47 -0
  1428. package/src/tools/SnipTool/prompt.js +5 -0
  1429. package/src/tools/SubscribePRTool/SubscribePRTool.js +49 -0
  1430. package/src/tools/SuggestBackgroundPRTool/SuggestBackgroundPRTool.js +44 -0
  1431. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.js +138 -0
  1432. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.ts +1 -1
  1433. package/src/tools/TaskCreateTool/TaskCreateTool.js +104 -0
  1434. package/src/tools/TaskCreateTool/constants.js +1 -0
  1435. package/src/tools/TaskCreateTool/prompt.js +52 -0
  1436. package/src/tools/TaskGetTool/TaskGetTool.js +106 -0
  1437. package/src/tools/TaskGetTool/constants.js +1 -0
  1438. package/src/tools/TaskGetTool/prompt.js +23 -0
  1439. package/src/tools/TaskListTool/TaskListTool.js +89 -0
  1440. package/src/tools/TaskListTool/constants.js +1 -0
  1441. package/src/tools/TaskListTool/prompt.js +44 -0
  1442. package/src/tools/TaskOutputTool/TaskOutputTool.js +536 -0
  1443. package/src/tools/TaskOutputTool/constants.js +1 -0
  1444. package/src/tools/TaskStopTool/TaskStopTool.js +110 -0
  1445. package/src/tools/TaskStopTool/UI.js +31 -0
  1446. package/src/tools/TaskStopTool/prompt.js +7 -0
  1447. package/src/tools/TaskUpdateTool/TaskUpdateTool.js +301 -0
  1448. package/src/tools/TaskUpdateTool/constants.js +1 -0
  1449. package/src/tools/TaskUpdateTool/prompt.js +76 -0
  1450. package/src/tools/TeamCreateTool/TeamCreateTool.js +177 -0
  1451. package/src/tools/TeamCreateTool/UI.js +4 -0
  1452. package/src/tools/TeamCreateTool/constants.js +1 -0
  1453. package/src/tools/TeamCreateTool/prompt.js +113 -0
  1454. package/src/tools/TeamDeleteTool/TeamDeleteTool.js +102 -0
  1455. package/src/tools/TeamDeleteTool/UI.js +13 -0
  1456. package/src/tools/TeamDeleteTool/constants.js +1 -0
  1457. package/src/tools/TeamDeleteTool/prompt.js +16 -0
  1458. package/src/tools/TerminalCaptureTool/TerminalCaptureTool.js +47 -0
  1459. package/src/tools/TerminalCaptureTool/prompt.js +11 -0
  1460. package/src/tools/TodoWriteTool/TodoWriteTool.js +99 -0
  1461. package/src/tools/TodoWriteTool/constants.js +1 -0
  1462. package/src/tools/TodoWriteTool/prompt.js +181 -0
  1463. package/src/tools/ToolSearchTool/ToolSearchTool.js +357 -0
  1464. package/src/tools/ToolSearchTool/constants.js +1 -0
  1465. package/src/tools/ToolSearchTool/prompt.js +97 -0
  1466. package/src/tools/TungstenTool/TungstenLiveMonitor.js +7 -0
  1467. package/src/tools/TungstenTool/TungstenTool.js +3 -0
  1468. package/src/tools/VerifyPlanExecutionTool/VerifyPlanExecutionTool.js +45 -0
  1469. package/src/tools/VerifyPlanExecutionTool/constants.js +2 -0
  1470. package/src/tools/WebBrowserTool/WebBrowserPanel.js +5 -0
  1471. package/src/tools/WebBrowserTool/WebBrowserTool.js +58 -0
  1472. package/src/tools/WebFetchTool/UI.js +31 -0
  1473. package/src/tools/WebFetchTool/WebFetchTool.js +246 -0
  1474. package/src/tools/WebFetchTool/preapproved.js +154 -0
  1475. package/src/tools/WebFetchTool/prompt.js +39 -0
  1476. package/src/tools/WebFetchTool/utils.js +368 -0
  1477. package/src/tools/WebSearchTool/UI.js +67 -0
  1478. package/src/tools/WebSearchTool/WebSearchTool.js +396 -0
  1479. package/src/tools/WebSearchTool/prompt.js +32 -0
  1480. package/src/tools/WorkflowTool/WorkflowPermissionRequest.js +7 -0
  1481. package/src/tools/WorkflowTool/WorkflowTool.js +51 -0
  1482. package/src/tools/WorkflowTool/bundled/index.js +5 -0
  1483. package/src/tools/WorkflowTool/constants.js +1 -0
  1484. package/src/tools/WorkflowTool/createWorkflowCommand.js +5 -0
  1485. package/src/tools/shared/gitOperationTracking.js +220 -0
  1486. package/src/tools/shared/spawnMultiAgent.js +805 -0
  1487. package/src/tools/testing/TestingPermissionTool.js +72 -0
  1488. package/src/tools/utils.js +24 -0
  1489. package/src/tools.js +365 -0
  1490. package/src/types/command.js +8 -0
  1491. package/src/types/connectorText.js +3 -0
  1492. package/src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.js +673 -0
  1493. package/src/types/generated/events_mono/common/v1/auth.js +49 -0
  1494. package/src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.js +147 -0
  1495. package/src/types/generated/google/protobuf/timestamp.js +38 -0
  1496. package/src/types/hooks.js +153 -0
  1497. package/src/types/ids.js +27 -0
  1498. package/src/types/logs.js +11 -0
  1499. package/src/types/permissions.js +25 -0
  1500. package/src/types/plugin.js +72 -0
  1501. package/src/types/textInputTypes.js +20 -0
  1502. package/src/upstreamproxy/relay.js +346 -0
  1503. package/src/upstreamproxy/upstreamproxy.js +234 -0
  1504. package/src/utils/CircularBuffer.js +75 -0
  1505. package/src/utils/Cursor.js +1229 -0
  1506. package/src/utils/QueryGuard.js +115 -0
  1507. package/src/utils/Shell.js +374 -0
  1508. package/src/utils/ShellCommand.js +336 -0
  1509. package/src/utils/abortController.js +74 -0
  1510. package/src/utils/activityManager.js +127 -0
  1511. package/src/utils/advisor.js +77 -0
  1512. package/src/utils/agentContext.js +91 -0
  1513. package/src/utils/agentId.js +83 -0
  1514. package/src/utils/agentSwarmsEnabled.js +37 -0
  1515. package/src/utils/agenticSessionSearch.js +255 -0
  1516. package/src/utils/analyzeContext.js +846 -0
  1517. package/src/utils/ansiToPng.js +259 -0
  1518. package/src/utils/ansiToSvg.js +207 -0
  1519. package/src/utils/api.js +555 -0
  1520. package/src/utils/apiPreconnect.js +62 -0
  1521. package/src/utils/appleTerminalBackup.js +95 -0
  1522. package/src/utils/argumentSubstitution.js +114 -0
  1523. package/src/utils/array.js +12 -0
  1524. package/src/utils/asciicast.js +200 -0
  1525. package/src/utils/attachments.js +2518 -0
  1526. package/src/utils/attribution.js +308 -0
  1527. package/src/utils/auth.js +1598 -0
  1528. package/src/utils/authFileDescriptor.js +152 -0
  1529. package/src/utils/authPortable.js +14 -0
  1530. package/src/utils/autoModeDenials.js +15 -0
  1531. package/src/utils/autoRunIssue.js +113 -0
  1532. package/src/utils/autoUpdater.js +457 -0
  1533. package/src/utils/aws.js +44 -0
  1534. package/src/utils/awsAuthStatusManager.js +66 -0
  1535. package/src/utils/background/remote/preconditions.js +175 -0
  1536. package/src/utils/background/remote/remoteSession.js +53 -0
  1537. package/src/utils/backgroundHousekeeping.js +64 -0
  1538. package/src/utils/bash/ParsedCommand.js +241 -0
  1539. package/src/utils/bash/ShellSnapshot.js +489 -0
  1540. package/src/utils/bash/ast.js +2590 -0
  1541. package/src/utils/bash/bashParser.js +4355 -0
  1542. package/src/utils/bash/bashPipeCommand.js +249 -0
  1543. package/src/utils/bash/commands.js +1131 -0
  1544. package/src/utils/bash/heredoc.js +647 -0
  1545. package/src/utils/bash/parser.js +195 -0
  1546. package/src/utils/bash/prefix.js +154 -0
  1547. package/src/utils/bash/registry.js +23 -0
  1548. package/src/utils/bash/shellCompletion.js +196 -0
  1549. package/src/utils/bash/shellPrefix.js +25 -0
  1550. package/src/utils/bash/shellQuote.js +253 -0
  1551. package/src/utils/bash/shellQuoting.js +106 -0
  1552. package/src/utils/bash/specs/alias.js +11 -0
  1553. package/src/utils/bash/specs/index.js +16 -0
  1554. package/src/utils/bash/specs/nohup.js +10 -0
  1555. package/src/utils/bash/specs/pyright.js +88 -0
  1556. package/src/utils/bash/specs/sleep.js +10 -0
  1557. package/src/utils/bash/specs/srun.js +28 -0
  1558. package/src/utils/bash/specs/time.js +10 -0
  1559. package/src/utils/bash/specs/timeout.js +17 -0
  1560. package/src/utils/bash/treeSitterAnalysis.js +407 -0
  1561. package/src/utils/betas.js +331 -0
  1562. package/src/utils/billing.js +54 -0
  1563. package/src/utils/binaryCheck.js +40 -0
  1564. package/src/utils/browser.js +58 -0
  1565. package/src/utils/bufferedWriter.js +77 -0
  1566. package/src/utils/bundledMode.js +19 -0
  1567. package/src/utils/businessDb.js +390 -0
  1568. package/src/utils/caCerts.js +91 -0
  1569. package/src/utils/caCertsConfig.js +77 -0
  1570. package/src/utils/cachePaths.js +28 -0
  1571. package/src/utils/classifierApprovals.js +66 -0
  1572. package/src/utils/classifierApprovalsHook.js +10 -0
  1573. package/src/utils/claudeDesktop.js +108 -0
  1574. package/src/utils/claudeInChrome/chromeNativeHost.js +416 -0
  1575. package/src/utils/claudeInChrome/common.js +466 -0
  1576. package/src/utils/claudeInChrome/mcpServer.js +237 -0
  1577. package/src/utils/claudeInChrome/prompt.js +79 -0
  1578. package/src/utils/claudeInChrome/setup.js +304 -0
  1579. package/src/utils/claudeInChrome/setupPortable.js +172 -0
  1580. package/src/utils/claudeInChrome/toolRendering.js +235 -0
  1581. package/src/utils/claudemd.js +1052 -0
  1582. package/src/utils/cleanup.js +514 -0
  1583. package/src/utils/cleanupRegistry.js +22 -0
  1584. package/src/utils/cliArgs.js +53 -0
  1585. package/src/utils/cliHighlight.js +45 -0
  1586. package/src/utils/codeIndexing.js +149 -0
  1587. package/src/utils/collapseBackgroundBashNotifications.js +70 -0
  1588. package/src/utils/collapseHookSummaries.js +48 -0
  1589. package/src/utils/collapseReadSearch.js +869 -0
  1590. package/src/utils/collapseTeammateShutdowns.js +44 -0
  1591. package/src/utils/combinedAbortSignal.js +40 -0
  1592. package/src/utils/commandLifecycle.js +7 -0
  1593. package/src/utils/commitAttribution.js +718 -0
  1594. package/src/utils/completionCache.js +138 -0
  1595. package/src/utils/computerUse/appNames.js +170 -0
  1596. package/src/utils/computerUse/cleanup.js +65 -0
  1597. package/src/utils/computerUse/common.js +56 -0
  1598. package/src/utils/computerUse/computerUseLock.js +183 -0
  1599. package/src/utils/computerUse/drainRunLoop.js +71 -0
  1600. package/src/utils/computerUse/escHotkey.js +53 -0
  1601. package/src/utils/computerUse/executor.js +480 -0
  1602. package/src/utils/computerUse/gates.js +55 -0
  1603. package/src/utils/computerUse/hostAdapter.js +62 -0
  1604. package/src/utils/computerUse/inputLoader.js +25 -0
  1605. package/src/utils/computerUse/mcpServer.js +84 -0
  1606. package/src/utils/computerUse/setup.js +42 -0
  1607. package/src/utils/computerUse/swiftLoader.js +18 -0
  1608. package/src/utils/computerUse/toolRendering.js +101 -0
  1609. package/src/utils/computerUse/wrapper.js +317 -0
  1610. package/src/utils/concurrentSessions.js +179 -0
  1611. package/src/utils/config.js +1078 -0
  1612. package/src/utils/configConstants.js +18 -0
  1613. package/src/utils/contentArray.js +45 -0
  1614. package/src/utils/context.js +185 -0
  1615. package/src/utils/contextAnalysis.js +171 -0
  1616. package/src/utils/contextSuggestions.js +158 -0
  1617. package/src/utils/controlMessageCompat.js +31 -0
  1618. package/src/utils/conversationRecovery.js +434 -0
  1619. package/src/utils/cron.js +260 -0
  1620. package/src/utils/cronJitterConfig.js +62 -0
  1621. package/src/utils/cronScheduler.js +388 -0
  1622. package/src/utils/cronTasks.js +328 -0
  1623. package/src/utils/cronTasksLock.js +159 -0
  1624. package/src/utils/crossProjectResume.js +46 -0
  1625. package/src/utils/crypto.js +13 -0
  1626. package/src/utils/cwd.js +29 -0
  1627. package/src/utils/debug.js +220 -0
  1628. package/src/utils/debugFilter.js +125 -0
  1629. package/src/utils/deepLink/banner.js +103 -0
  1630. package/src/utils/deepLink/parseDeepLink.js +138 -0
  1631. package/src/utils/deepLink/protocolHandler.js +119 -0
  1632. package/src/utils/deepLink/registerProtocol.js +291 -0
  1633. package/src/utils/deepLink/terminalLauncher.js +455 -0
  1634. package/src/utils/deepLink/terminalPreference.js +51 -0
  1635. package/src/utils/desktopDeepLink.js +208 -0
  1636. package/src/utils/detectRepository.js +157 -0
  1637. package/src/utils/diagLogs.js +74 -0
  1638. package/src/utils/diff.js +108 -0
  1639. package/src/utils/directMemberMessage.js +34 -0
  1640. package/src/utils/displayTags.js +46 -0
  1641. package/src/utils/doctorContextWarnings.js +179 -0
  1642. package/src/utils/doctorDiagnostic.js +494 -0
  1643. package/src/utils/dxt/helpers.js +64 -0
  1644. package/src/utils/dxt/zip.js +167 -0
  1645. package/src/utils/earlyInput.js +166 -0
  1646. package/src/utils/editor.js +163 -0
  1647. package/src/utils/effort.js +271 -0
  1648. package/src/utils/embeddedTools.js +26 -0
  1649. package/src/utils/employeeChat.js +271 -0
  1650. package/src/utils/employeeDb.js +326 -0
  1651. package/src/utils/env.js +358 -0
  1652. package/src/utils/envDynamic.js +130 -0
  1653. package/src/utils/envUtils.js +161 -0
  1654. package/src/utils/envValidation.js +26 -0
  1655. package/src/utils/errorLogSink.js +196 -0
  1656. package/src/utils/errors.js +207 -0
  1657. package/src/utils/exampleCommands.js +165 -0
  1658. package/src/utils/execFileNoThrow.js +93 -0
  1659. package/src/utils/execFileNoThrowPortable.js +49 -0
  1660. package/src/utils/execSyncWrapper.js +6 -0
  1661. package/src/utils/exportRenderer.js +71 -0
  1662. package/src/utils/extraUsage.js +19 -0
  1663. package/src/utils/fastMode.js +393 -0
  1664. package/src/utils/file.js +467 -0
  1665. package/src/utils/fileHistory.js +851 -0
  1666. package/src/utils/fileOperationAnalytics.js +45 -0
  1667. package/src/utils/filePersistence/filePersistence.js +212 -0
  1668. package/src/utils/filePersistence/outputsScanner.js +104 -0
  1669. package/src/utils/filePersistence/types.js +4 -0
  1670. package/src/utils/fileRead.js +81 -0
  1671. package/src/utils/fileReadCache.js +78 -0
  1672. package/src/utils/fileStateCache.js +99 -0
  1673. package/src/utils/findExecutable.js +13 -0
  1674. package/src/utils/fingerprint.js +58 -0
  1675. package/src/utils/forkedAgent.js +410 -0
  1676. package/src/utils/format.js +238 -0
  1677. package/src/utils/formatBriefTimestamp.js +72 -0
  1678. package/src/utils/fpsTracker.js +34 -0
  1679. package/src/utils/frontmatterParser.js +260 -0
  1680. package/src/utils/fsOperations.js +555 -0
  1681. package/src/utils/fullscreen.js +194 -0
  1682. package/src/utils/generatedFiles.js +122 -0
  1683. package/src/utils/generators.js +67 -0
  1684. package/src/utils/genericProcessUtils.js +155 -0
  1685. package/src/utils/getWorktreePaths.js +56 -0
  1686. package/src/utils/getWorktreePathsPortable.js +23 -0
  1687. package/src/utils/ghPrStatus.js +71 -0
  1688. package/src/utils/git/gitConfigParser.js +226 -0
  1689. package/src/utils/git/gitFilesystem.js +606 -0
  1690. package/src/utils/git/gitignore.js +84 -0
  1691. package/src/utils/git.js +725 -0
  1692. package/src/utils/gitDiff.js +395 -0
  1693. package/src/utils/gitSettings.js +18 -0
  1694. package/src/utils/github/ghAuthStatus.js +23 -0
  1695. package/src/utils/githubRepoPathMapping.js +135 -0
  1696. package/src/utils/glob.js +90 -0
  1697. package/src/utils/gracefulShutdown.js +447 -0
  1698. package/src/utils/groupToolUses.js +126 -0
  1699. package/src/utils/handlePromptSubmit.js +398 -0
  1700. package/src/utils/hash.js +44 -0
  1701. package/src/utils/headlessProfiler.js +147 -0
  1702. package/src/utils/heapDumpService.js +201 -0
  1703. package/src/utils/heatmap.js +151 -0
  1704. package/src/utils/highlightMatch.js +29 -0
  1705. package/src/utils/hooks/AsyncHookRegistry.js +187 -0
  1706. package/src/utils/hooks/apiQueryHookHelper.js +77 -0
  1707. package/src/utils/hooks/execAgentHook.js +257 -0
  1708. package/src/utils/hooks/execHttpHook.js +184 -0
  1709. package/src/utils/hooks/execPromptHook.js +171 -0
  1710. package/src/utils/hooks/fileChangedWatcher.js +161 -0
  1711. package/src/utils/hooks/hookEvents.js +111 -0
  1712. package/src/utils/hooks/hookHelpers.js +60 -0
  1713. package/src/utils/hooks/hooksConfigManager.js +323 -0
  1714. package/src/utils/hooks/hooksConfigSnapshot.js +114 -0
  1715. package/src/utils/hooks/hooksSettings.js +204 -0
  1716. package/src/utils/hooks/postSamplingHooks.js +39 -0
  1717. package/src/utils/hooks/registerFrontmatterHooks.js +47 -0
  1718. package/src/utils/hooks/registerSkillHooks.js +40 -0
  1719. package/src/utils/hooks/sessionHooks.js +252 -0
  1720. package/src/utils/hooks/skillImprovement.js +211 -0
  1721. package/src/utils/hooks/ssrfGuard.js +258 -0
  1722. package/src/utils/hooks.js +3668 -0
  1723. package/src/utils/horizontalScroll.js +108 -0
  1724. package/src/utils/http.js +120 -0
  1725. package/src/utils/hyperlink.js +28 -0
  1726. package/src/utils/iTermBackup.js +48 -0
  1727. package/src/utils/ide.js +1195 -0
  1728. package/src/utils/idePathConversion.js +66 -0
  1729. package/src/utils/idleTimeout.js +44 -0
  1730. package/src/utils/imagePaste.js +343 -0
  1731. package/src/utils/imageResizer.js +664 -0
  1732. package/src/utils/imageStore.js +150 -0
  1733. package/src/utils/imageValidation.js +92 -0
  1734. package/src/utils/immediateCommand.js +12 -0
  1735. package/src/utils/inProcessTeammateHelpers.js +71 -0
  1736. package/src/utils/ink.js +20 -0
  1737. package/src/utils/intl.js +83 -0
  1738. package/src/utils/jetbrains.js +152 -0
  1739. package/src/utils/json.js +231 -0
  1740. package/src/utils/jsonRead.js +14 -0
  1741. package/src/utils/keyboardShortcuts.js +11 -0
  1742. package/src/utils/lazySchema.js +8 -0
  1743. package/src/utils/listSessionsImpl.js +332 -0
  1744. package/src/utils/localInstaller.js +130 -0
  1745. package/src/utils/lockfile.js +30 -0
  1746. package/src/utils/log.js +280 -0
  1747. package/src/utils/logoV2Utils.js +256 -0
  1748. package/src/utils/mailbox.js +50 -0
  1749. package/src/utils/managedEnv.js +160 -0
  1750. package/src/utils/managedEnvConstants.js +185 -0
  1751. package/src/utils/markdown.js +315 -0
  1752. package/src/utils/markdownConfigLoader.js +480 -0
  1753. package/src/utils/mcp/dateTimeParser.js +102 -0
  1754. package/src/utils/mcp/elicitationValidation.js +259 -0
  1755. package/src/utils/mcpInstructionsDelta.js +97 -0
  1756. package/src/utils/mcpOutputStorage.js +159 -0
  1757. package/src/utils/mcpValidation.js +165 -0
  1758. package/src/utils/mcpWebSocketTransport.js +180 -0
  1759. package/src/utils/memoize.js +205 -0
  1760. package/src/utils/memory/types.js +9 -0
  1761. package/src/utils/memory/versions.js +7 -0
  1762. package/src/utils/memoryFileDetection.js +245 -0
  1763. package/src/utils/messagePredicates.js +6 -0
  1764. package/src/utils/messageQueueManager.js +430 -0
  1765. package/src/utils/messages/mappers.js +240 -0
  1766. package/src/utils/messages/systemInit.js +72 -0
  1767. package/src/utils/messages.js +4286 -0
  1768. package/src/utils/model/agent.js +128 -0
  1769. package/src/utils/model/aliases.js +21 -0
  1770. package/src/utils/model/antModels.js +25 -0
  1771. package/src/utils/model/bedrock.js +220 -0
  1772. package/src/utils/model/check1mAccess.js +64 -0
  1773. package/src/utils/model/configs.js +86 -0
  1774. package/src/utils/model/contextWindowUpgradeCheck.js +41 -0
  1775. package/src/utils/model/deprecation.js +72 -0
  1776. package/src/utils/model/model.js +533 -0
  1777. package/src/utils/model/modelAllowlist.js +148 -0
  1778. package/src/utils/model/modelCapabilities.js +105 -0
  1779. package/src/utils/model/modelOptions.js +450 -0
  1780. package/src/utils/model/modelStrings.js +144 -0
  1781. package/src/utils/model/modelSupportOverrides.js +40 -0
  1782. package/src/utils/model/providers.js +35 -0
  1783. package/src/utils/model/validateModel.js +131 -0
  1784. package/src/utils/modelCost.js +160 -0
  1785. package/src/utils/modifiers.js +39 -0
  1786. package/src/utils/mtls.js +132 -0
  1787. package/src/utils/nativeInstaller/download.js +370 -0
  1788. package/src/utils/nativeInstaller/index.js +8 -0
  1789. package/src/utils/nativeInstaller/installer.js +1395 -0
  1790. package/src/utils/nativeInstaller/packageManagers.js +258 -0
  1791. package/src/utils/nativeInstaller/pidLock.js +347 -0
  1792. package/src/utils/notebook.js +176 -0
  1793. package/src/utils/objectGroupBy.js +15 -0
  1794. package/src/utils/pasteStore.js +93 -0
  1795. package/src/utils/path.js +140 -0
  1796. package/src/utils/pdf.js +236 -0
  1797. package/src/utils/pdfUtils.js +61 -0
  1798. package/src/utils/peerAddress.js +20 -0
  1799. package/src/utils/permissions/PermissionMode.js +95 -0
  1800. package/src/utils/permissions/PermissionPromptToolResultSchema.js +85 -0
  1801. package/src/utils/permissions/PermissionResult.js +11 -0
  1802. package/src/utils/permissions/PermissionRule.js +19 -0
  1803. package/src/utils/permissions/PermissionUpdate.js +268 -0
  1804. package/src/utils/permissions/PermissionUpdateSchema.js +61 -0
  1805. package/src/utils/permissions/autoModeState.js +31 -0
  1806. package/src/utils/permissions/bashClassifier.js +30 -0
  1807. package/src/utils/permissions/bypassPermissionsKillswitch.js +115 -0
  1808. package/src/utils/permissions/classifierDecision.js +86 -0
  1809. package/src/utils/permissions/classifierShared.js +28 -0
  1810. package/src/utils/permissions/dangerousPatterns.js +78 -0
  1811. package/src/utils/permissions/denialTracking.js +34 -0
  1812. package/src/utils/permissions/filesystem.js +1411 -0
  1813. package/src/utils/permissions/getNextPermissionMode.js +74 -0
  1814. package/src/utils/permissions/pathValidation.js +351 -0
  1815. package/src/utils/permissions/permissionExplainer.js +188 -0
  1816. package/src/utils/permissions/permissionRuleParser.js +175 -0
  1817. package/src/utils/permissions/permissionSetup.js +1162 -0
  1818. package/src/utils/permissions/permissions.js +1063 -0
  1819. package/src/utils/permissions/permissionsLoader.js +217 -0
  1820. package/src/utils/permissions/shadowedRuleDetection.js +149 -0
  1821. package/src/utils/permissions/shellRuleMatching.js +174 -0
  1822. package/src/utils/permissions/yoloClassifier.js +1193 -0
  1823. package/src/utils/planModeV2.js +75 -0
  1824. package/src/utils/plans.js +334 -0
  1825. package/src/utils/platform.js +122 -0
  1826. package/src/utils/plugins/addDirPluginSettings.js +53 -0
  1827. package/src/utils/plugins/cacheUtils.js +174 -0
  1828. package/src/utils/plugins/dependencyResolver.js +244 -0
  1829. package/src/utils/plugins/fetchTelemetry.js +108 -0
  1830. package/src/utils/plugins/gitAvailability.js +65 -0
  1831. package/src/utils/plugins/headlessPluginInstall.js +136 -0
  1832. package/src/utils/plugins/hintRecommendation.js +136 -0
  1833. package/src/utils/plugins/installCounts.js +221 -0
  1834. package/src/utils/plugins/installedPluginsManager.js +1003 -0
  1835. package/src/utils/plugins/loadPluginAgents.js +219 -0
  1836. package/src/utils/plugins/loadPluginCommands.js +595 -0
  1837. package/src/utils/plugins/loadPluginHooks.js +239 -0
  1838. package/src/utils/plugins/loadPluginOutputStyles.js +112 -0
  1839. package/src/utils/plugins/lspPluginIntegration.js +293 -0
  1840. package/src/utils/plugins/lspRecommendation.js +278 -0
  1841. package/src/utils/plugins/managedPlugins.js +26 -0
  1842. package/src/utils/plugins/marketplaceHelpers.js +470 -0
  1843. package/src/utils/plugins/marketplaceManager.js +1939 -0
  1844. package/src/utils/plugins/mcpPluginIntegration.js +465 -0
  1845. package/src/utils/plugins/mcpbHandler.js +708 -0
  1846. package/src/utils/plugins/officialMarketplace.js +19 -0
  1847. package/src/utils/plugins/officialMarketplaceGcs.js +202 -0
  1848. package/src/utils/plugins/officialMarketplaceStartupCheck.js +344 -0
  1849. package/src/utils/plugins/orphanedPluginFilter.js +96 -0
  1850. package/src/utils/plugins/parseMarketplaceInput.js +143 -0
  1851. package/src/utils/plugins/performStartupChecks.js +66 -0
  1852. package/src/utils/plugins/pluginAutoupdate.js +210 -0
  1853. package/src/utils/plugins/pluginBlocklist.js +93 -0
  1854. package/src/utils/plugins/pluginDirectories.js +170 -0
  1855. package/src/utils/plugins/pluginFlagging.js +173 -0
  1856. package/src/utils/plugins/pluginIdentifier.js +78 -0
  1857. package/src/utils/plugins/pluginInstallationHelpers.js +400 -0
  1858. package/src/utils/plugins/pluginLoader.js +2426 -0
  1859. package/src/utils/plugins/pluginOptionsStorage.js +311 -0
  1860. package/src/utils/plugins/pluginPolicy.js +18 -0
  1861. package/src/utils/plugins/pluginStartupCheck.js +261 -0
  1862. package/src/utils/plugins/pluginVersioning.js +128 -0
  1863. package/src/utils/plugins/reconciler.js +181 -0
  1864. package/src/utils/plugins/refresh.js +162 -0
  1865. package/src/utils/plugins/schemas.js +1283 -0
  1866. package/src/utils/plugins/validatePlugin.js +765 -0
  1867. package/src/utils/plugins/walkPluginMarkdown.js +49 -0
  1868. package/src/utils/plugins/zipCache.js +346 -0
  1869. package/src/utils/plugins/zipCacheAdapters.js +133 -0
  1870. package/src/utils/powershell/dangerousCmdlets.js +174 -0
  1871. package/src/utils/powershell/parser.js +1357 -0
  1872. package/src/utils/powershell/staticPrefix.js +277 -0
  1873. package/src/utils/preflightChecks.js +147 -0
  1874. package/src/utils/privacyLevel.js +49 -0
  1875. package/src/utils/process.js +56 -0
  1876. package/src/utils/processUserInput/processBashCommand.js +118 -0
  1877. package/src/utils/processUserInput/processSlashCommand.js +845 -0
  1878. package/src/utils/processUserInput/processTextPrompt.js +68 -0
  1879. package/src/utils/processUserInput/processUserInput.js +344 -0
  1880. package/src/utils/profilerBase.js +32 -0
  1881. package/src/utils/promptCategory.js +39 -0
  1882. package/src/utils/promptEditor.js +151 -0
  1883. package/src/utils/promptShellExecution.js +117 -0
  1884. package/src/utils/protectedNamespace.js +4 -0
  1885. package/src/utils/proxy.js +345 -0
  1886. package/src/utils/queryContext.js +110 -0
  1887. package/src/utils/queryHelpers.js +436 -0
  1888. package/src/utils/queryProfiler.js +242 -0
  1889. package/src/utils/queueProcessor.js +70 -0
  1890. package/src/utils/readEditContext.js +176 -0
  1891. package/src/utils/readFileInRange.js +278 -0
  1892. package/src/utils/releaseNotes.js +307 -0
  1893. package/src/utils/renderOptions.js +67 -0
  1894. package/src/utils/ripgrep.js +521 -0
  1895. package/src/utils/sandbox/sandbox-adapter.js +750 -0
  1896. package/src/utils/sandbox/sandbox-ui-utils.js +11 -0
  1897. package/src/utils/sanitization.js +72 -0
  1898. package/src/utils/screenshotClipboard.js +89 -0
  1899. package/src/utils/sdkEventQueue.js +49 -0
  1900. package/src/utils/secureStorage/fallbackStorage.js +59 -0
  1901. package/src/utils/secureStorage/index.js +13 -0
  1902. package/src/utils/secureStorage/keychainPrefetch.js +91 -0
  1903. package/src/utils/secureStorage/macOsKeychainHelpers.js +91 -0
  1904. package/src/utils/secureStorage/macOsKeychainStorage.js +192 -0
  1905. package/src/utils/secureStorage/plainTextStorage.js +81 -0
  1906. package/src/utils/semanticBoolean.js +23 -0
  1907. package/src/utils/semanticNumber.js +34 -0
  1908. package/src/utils/semver.js +51 -0
  1909. package/src/utils/sequential.js +43 -0
  1910. package/src/utils/sessionActivity.js +120 -0
  1911. package/src/utils/sessionEnvVars.js +18 -0
  1912. package/src/utils/sessionEnvironment.js +131 -0
  1913. package/src/utils/sessionFileAccessHooks.js +205 -0
  1914. package/src/utils/sessionIngressAuth.js +113 -0
  1915. package/src/utils/sessionRestore.js +357 -0
  1916. package/src/utils/sessionStart.js +165 -0
  1917. package/src/utils/sessionState.js +76 -0
  1918. package/src/utils/sessionStorage.js +4162 -0
  1919. package/src/utils/sessionStoragePortable.js +665 -0
  1920. package/src/utils/sessionTitle.js +120 -0
  1921. package/src/utils/sessionUrl.js +50 -0
  1922. package/src/utils/set.js +50 -0
  1923. package/src/utils/settings/allErrors.js +29 -0
  1924. package/src/utils/settings/applySettingsChange.js +65 -0
  1925. package/src/utils/settings/changeDetector.js +409 -0
  1926. package/src/utils/settings/constants.js +166 -0
  1927. package/src/utils/settings/internalWrites.js +33 -0
  1928. package/src/utils/settings/managedPath.js +29 -0
  1929. package/src/utils/settings/mdm/constants.js +62 -0
  1930. package/src/utils/settings/mdm/rawRead.js +97 -0
  1931. package/src/utils/settings/mdm/settings.js +254 -0
  1932. package/src/utils/settings/permissionValidation.js +224 -0
  1933. package/src/utils/settings/pluginOnlyPolicy.js +53 -0
  1934. package/src/utils/settings/schemaOutput.js +7 -0
  1935. package/src/utils/settings/settings.js +791 -0
  1936. package/src/utils/settings/settingsCache.js +47 -0
  1937. package/src/utils/settings/toolValidationConfig.js +76 -0
  1938. package/src/utils/settings/types.js +846 -0
  1939. package/src/utils/settings/validateEditTool.js +34 -0
  1940. package/src/utils/settings/validation.js +192 -0
  1941. package/src/utils/settings/validationTips.js +111 -0
  1942. package/src/utils/shell/bashProvider.js +202 -0
  1943. package/src/utils/shell/outputLimits.js +7 -0
  1944. package/src/utils/shell/powershellDetection.js +96 -0
  1945. package/src/utils/shell/powershellProvider.js +104 -0
  1946. package/src/utils/shell/prefix.js +246 -0
  1947. package/src/utils/shell/readOnlyCommandValidation.js +1776 -0
  1948. package/src/utils/shell/resolveDefaultShell.js +13 -0
  1949. package/src/utils/shell/shellProvider.js +2 -0
  1950. package/src/utils/shell/shellToolUtils.js +21 -0
  1951. package/src/utils/shell/specPrefix.js +198 -0
  1952. package/src/utils/shellConfig.js +136 -0
  1953. package/src/utils/sideQuery.js +134 -0
  1954. package/src/utils/sideQuestion.js +121 -0
  1955. package/src/utils/signal.js +34 -0
  1956. package/src/utils/sinks.js +15 -0
  1957. package/src/utils/skills/skillChangeDetector.js +264 -0
  1958. package/src/utils/slashCommandParsing.js +46 -0
  1959. package/src/utils/sleep.js +72 -0
  1960. package/src/utils/sliceAnsi.js +74 -0
  1961. package/src/utils/slowOperations.js +216 -0
  1962. package/src/utils/standaloneAgent.js +20 -0
  1963. package/src/utils/startupProfiler.js +149 -0
  1964. package/src/utils/staticRender.js +104 -0
  1965. package/src/utils/stats.js +802 -0
  1966. package/src/utils/statsCache.js +330 -0
  1967. package/src/utils/status.js +359 -0
  1968. package/src/utils/statusNoticeDefinitions.js +123 -0
  1969. package/src/utils/statusNoticeHelpers.js +15 -0
  1970. package/src/utils/stream.js +73 -0
  1971. package/src/utils/streamJsonStdoutGuard.js +107 -0
  1972. package/src/utils/streamlinedTransform.js +162 -0
  1973. package/src/utils/stringUtils.js +202 -0
  1974. package/src/utils/subprocessEnv.js +87 -0
  1975. package/src/utils/suggestions/commandSuggestions.js +458 -0
  1976. package/src/utils/suggestions/directoryCompletion.js +191 -0
  1977. package/src/utils/suggestions/shellHistoryCompletion.js +95 -0
  1978. package/src/utils/suggestions/skillUsageTracking.js +50 -0
  1979. package/src/utils/suggestions/slackChannelSuggestions.js +169 -0
  1980. package/src/utils/swarm/It2SetupPrompt.js +386 -0
  1981. package/src/utils/swarm/backends/ITermBackend.js +276 -0
  1982. package/src/utils/swarm/backends/InProcessBackend.js +237 -0
  1983. package/src/utils/swarm/backends/PaneBackendExecutor.js +250 -0
  1984. package/src/utils/swarm/backends/TmuxBackend.js +574 -0
  1985. package/src/utils/swarm/backends/detection.js +112 -0
  1986. package/src/utils/swarm/backends/it2Setup.js +185 -0
  1987. package/src/utils/swarm/backends/registry.js +369 -0
  1988. package/src/utils/swarm/backends/teammateModeSnapshot.js +68 -0
  1989. package/src/utils/swarm/backends/types.js +9 -0
  1990. package/src/utils/swarm/constants.js +29 -0
  1991. package/src/utils/swarm/inProcessRunner.js +1021 -0
  1992. package/src/utils/swarm/leaderPermissionBridge.js +31 -0
  1993. package/src/utils/swarm/permissionSync.js +667 -0
  1994. package/src/utils/swarm/reconnection.js +82 -0
  1995. package/src/utils/swarm/spawnInProcess.js +218 -0
  1996. package/src/utils/swarm/spawnUtils.js +123 -0
  1997. package/src/utils/swarm/teamHelpers.js +484 -0
  1998. package/src/utils/swarm/teammateInit.js +87 -0
  1999. package/src/utils/swarm/teammateLayoutManager.js +82 -0
  2000. package/src/utils/swarm/teammateModel.js +9 -0
  2001. package/src/utils/swarm/teammatePromptAddendum.js +17 -0
  2002. package/src/utils/systemDirectories.js +51 -0
  2003. package/src/utils/systemPrompt.js +88 -0
  2004. package/src/utils/systemPromptType.js +9 -0
  2005. package/src/utils/systemTheme.js +108 -0
  2006. package/src/utils/taggedId.js +49 -0
  2007. package/src/utils/task/TaskOutput.js +320 -0
  2008. package/src/utils/task/diskOutput.js +387 -0
  2009. package/src/utils/task/framework.js +236 -0
  2010. package/src/utils/task/outputFormatting.js +24 -0
  2011. package/src/utils/task/sdkProgress.js +24 -0
  2012. package/src/utils/taskSummary.js +3 -0
  2013. package/src/utils/tasks.js +672 -0
  2014. package/src/utils/teamDiscovery.js +48 -0
  2015. package/src/utils/teamMemoryOps.js +67 -0
  2016. package/src/utils/teammate.js +237 -0
  2017. package/src/utils/teammateContext.js +56 -0
  2018. package/src/utils/teammateMailbox.js +793 -0
  2019. package/src/utils/telemetry/betaSessionTracing.js +25 -0
  2020. package/src/utils/telemetry/bigqueryExporter.js +17 -0
  2021. package/src/utils/telemetry/events.js +7 -0
  2022. package/src/utils/telemetry/instrumentation.js +16 -0
  2023. package/src/utils/telemetry/logger.js +25 -0
  2024. package/src/utils/telemetry/perfettoTracing.js +882 -0
  2025. package/src/utils/telemetry/pluginTelemetry.js +76 -0
  2026. package/src/utils/telemetry/sessionTracing.js +62 -0
  2027. package/src/utils/telemetry/skillLoadedEvent.js +4 -0
  2028. package/src/utils/telemetryAttributes.js +56 -0
  2029. package/src/utils/teleport/api.js +299 -0
  2030. package/src/utils/teleport/environmentSelection.js +55 -0
  2031. package/src/utils/teleport/environments.js +84 -0
  2032. package/src/utils/teleport/gitBundle.js +192 -0
  2033. package/src/utils/teleport.js +1047 -0
  2034. package/src/utils/tempfile.js +26 -0
  2035. package/src/utils/terminal.js +105 -0
  2036. package/src/utils/terminalPanel.js +155 -0
  2037. package/src/utils/textHighlighting.js +113 -0
  2038. package/src/utils/thaddeusHints.js +142 -0
  2039. package/src/utils/theme.js +525 -0
  2040. package/src/utils/thinking.js +130 -0
  2041. package/src/utils/timeouts.js +35 -0
  2042. package/src/utils/tmuxSocket.js +373 -0
  2043. package/src/utils/todo/types.js +9 -0
  2044. package/src/utils/tokenBudget.js +62 -0
  2045. package/src/utils/tokens.js +223 -0
  2046. package/src/utils/toolErrors.js +101 -0
  2047. package/src/utils/toolPool.js +61 -0
  2048. package/src/utils/toolResultStorage.js +768 -0
  2049. package/src/utils/toolSchemaCache.js +7 -0
  2050. package/src/utils/toolSearch.js +551 -0
  2051. package/src/utils/transcriptSearch.js +200 -0
  2052. package/src/utils/treeify.js +111 -0
  2053. package/src/utils/truncate.js +164 -0
  2054. package/src/utils/udsClient.js +5 -0
  2055. package/src/utils/udsMessaging.js +23 -0
  2056. package/src/utils/ultraplan/ccrSession.js +264 -0
  2057. package/src/utils/ultraplan/keyword.js +122 -0
  2058. package/src/utils/unaryLogging.js +16 -0
  2059. package/src/utils/undercover.js +89 -0
  2060. package/src/utils/user.js +137 -0
  2061. package/src/utils/userAgent.js +9 -0
  2062. package/src/utils/userPromptKeywords.js +21 -0
  2063. package/src/utils/uuid.js +22 -0
  2064. package/src/utils/warningHandler.js +97 -0
  2065. package/src/utils/which.js +75 -0
  2066. package/src/utils/windowsPaths.js +146 -0
  2067. package/src/utils/withResolvers.js +13 -0
  2068. package/src/utils/words.js +793 -0
  2069. package/src/utils/workforceIntent.js +192 -0
  2070. package/src/utils/workloadContext.js +42 -0
  2071. package/src/utils/worktree.js +1142 -0
  2072. package/src/utils/worktreeModeEnabled.js +11 -0
  2073. package/src/utils/xdg.js +52 -0
  2074. package/src/utils/xml.js +15 -0
  2075. package/src/utils/yaml.js +14 -0
  2076. package/src/utils/zodToJsonSchema.js +19 -0
  2077. package/src/vim/motions.js +73 -0
  2078. package/src/vim/operators.js +401 -0
  2079. package/src/vim/textObjects.js +153 -0
  2080. package/src/vim/transitions.js +340 -0
  2081. package/src/vim/types.js +93 -0
  2082. package/src/voice/voiceModeEnabled.js +20 -0
  2083. package/thaddeus-terminal.ts +401 -3
  2084. package/thaddeus.command +1 -1
@@ -0,0 +1,2466 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { getAPIProvider, isFirstPartyAnthropicBaseUrl, } from 'src/utils/model/providers.js';
3
+ import { getAttributionHeader, getCLISyspromptPrefix, } from '../../constants/system.js';
4
+ import { getEmptyToolPermissionContext, toolMatchesName, } from '../../Tool.js';
5
+ import { isConnectorTextBlock, } from '../../types/connectorText.js';
6
+ import { logAPIPrefix, splitSysPromptPrefix, toolToAPISchema, } from '../../utils/api.js';
7
+ import { getOauthAccountInfo } from '../../utils/auth.js';
8
+ import { getBedrockExtraBodyParamsBetas, getMergedBetas, getModelBetas, } from '../../utils/betas.js';
9
+ import { getOrCreateUserID } from '../../utils/config.js';
10
+ import { CAPPED_DEFAULT_MAX_TOKENS, getModelMaxOutputTokens, getSonnet1mExpTreatmentEnabled, } from '../../utils/context.js';
11
+ import { resolveAppliedEffort } from '../../utils/effort.js';
12
+ import { isEnvTruthy } from '../../utils/envUtils.js';
13
+ import { errorMessage } from '../../utils/errors.js';
14
+ import { computeFingerprintFromMessages } from '../../utils/fingerprint.js';
15
+ import { captureAPIRequest, logError } from '../../utils/log.js';
16
+ import { createAssistantAPIErrorMessage, createUserMessage, ensureToolResultPairing, normalizeContentFromAPI, normalizeMessagesForAPI, stripAdvisorBlocks, stripCallerFieldFromAssistantMessage, stripToolReferenceBlocksFromUserMessage, } from '../../utils/messages.js';
17
+ import { getDefaultOpusModel, getDefaultSonnetModel, getSmallFastModel, isNonCustomOpusModel, } from '../../utils/model/model.js';
18
+ import { asSystemPrompt, } from '../../utils/systemPromptType.js';
19
+ import { tokenCountFromLastAPIResponse } from '../../utils/tokens.js';
20
+ import { getDynamicConfig_BLOCKS_ON_INIT } from '../analytics/growthbook.js';
21
+ import { currentLimits, extractQuotaStatusFromError, extractQuotaStatusFromHeaders, } from '../claudeAiLimits.js';
22
+ import { getAPIContextManagement } from '../compact/apiMicrocompact.js';
23
+ /* eslint-disable @typescript-eslint/no-require-imports */
24
+ const autoModeStateModule = feature('TRANSCRIPT_CLASSIFIER')
25
+ ? require('../../utils/permissions/autoModeState.js')
26
+ : null;
27
+ import { feature } from 'bun:bundle';
28
+ import { APIConnectionTimeoutError, APIError, APIUserAbortError, } from '@anthropic-ai/sdk/error';
29
+ import { getAfkModeHeaderLatched, getCacheEditingHeaderLatched, getFastModeHeaderLatched, getLastApiCompletionTimestamp, getPromptCache1hAllowlist, getPromptCache1hEligible, getSessionId, getThinkingClearLatched, setAfkModeHeaderLatched, setCacheEditingHeaderLatched, setFastModeHeaderLatched, setLastMainRequestId, setPromptCache1hAllowlist, setPromptCache1hEligible, setThinkingClearLatched, } from 'src/bootstrap/state.js';
30
+ import { AFK_MODE_BETA_HEADER, CONTEXT_1M_BETA_HEADER, CONTEXT_MANAGEMENT_BETA_HEADER, EFFORT_BETA_HEADER, FAST_MODE_BETA_HEADER, PROMPT_CACHING_SCOPE_BETA_HEADER, REDACT_THINKING_BETA_HEADER, STRUCTURED_OUTPUTS_BETA_HEADER, TASK_BUDGETS_BETA_HEADER, } from 'src/constants/betas.js';
31
+ import { addToTotalSessionCost } from 'src/cost-tracker.js';
32
+ import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js';
33
+ import { ADVISOR_TOOL_INSTRUCTIONS, getExperimentAdvisorModels, isAdvisorEnabled, isValidAdvisorModel, modelSupportsAdvisor, } from 'src/utils/advisor.js';
34
+ import { getAgentContext } from 'src/utils/agentContext.js';
35
+ import { isClaudeAISubscriber } from 'src/utils/auth.js';
36
+ import { getToolSearchBetaHeader, modelSupportsStructuredOutputs, shouldIncludeFirstPartyOnlyBetas, shouldUseGlobalCacheScope, } from 'src/utils/betas.js';
37
+ import { CLAUDE_IN_CHROME_MCP_SERVER_NAME } from 'src/utils/claudeInChrome/common.js';
38
+ import { CHROME_TOOL_SEARCH_INSTRUCTIONS } from 'src/utils/claudeInChrome/prompt.js';
39
+ import { getMaxThinkingTokensForModel } from 'src/utils/context.js';
40
+ import { logForDebugging } from 'src/utils/debug.js';
41
+ import { logForDiagnosticsNoPII } from 'src/utils/diagLogs.js';
42
+ import { modelSupportsEffort } from 'src/utils/effort.js';
43
+ import { isFastModeAvailable, isFastModeCooldown, isFastModeEnabled, isFastModeSupportedByModel, } from 'src/utils/fastMode.js';
44
+ import { returnValue } from 'src/utils/generators.js';
45
+ import { headlessProfilerCheckpoint } from 'src/utils/headlessProfiler.js';
46
+ import { isMcpInstructionsDeltaEnabled } from 'src/utils/mcpInstructionsDelta.js';
47
+ import { calculateUSDCost } from 'src/utils/modelCost.js';
48
+ import { endQueryProfile, queryCheckpoint } from 'src/utils/queryProfiler.js';
49
+ import { modelSupportsAdaptiveThinking, modelSupportsThinking, } from 'src/utils/thinking.js';
50
+ import { extractDiscoveredToolNames, isDeferredToolsDeltaEnabled, isToolSearchEnabled, } from 'src/utils/toolSearch.js';
51
+ import { API_MAX_MEDIA_PER_REQUEST } from '../../constants/apiLimits.js';
52
+ import { ADVISOR_BETA_HEADER } from '../../constants/betas.js';
53
+ import { formatDeferredToolLine, isDeferredTool, TOOL_SEARCH_TOOL_NAME, } from '../../tools/ToolSearchTool/prompt.js';
54
+ import { count } from '../../utils/array.js';
55
+ import { insertBlockAfterToolResults } from '../../utils/contentArray.js';
56
+ import { validateBoundedIntEnvVar } from '../../utils/envValidation.js';
57
+ import { safeParseJSON } from '../../utils/json.js';
58
+ import { getInferenceProfileBackingModel } from '../../utils/model/bedrock.js';
59
+ import { normalizeModelStringForAPI, parseUserSpecifiedModel, } from '../../utils/model/model.js';
60
+ import { startSessionActivity, stopSessionActivity, } from '../../utils/sessionActivity.js';
61
+ import { jsonStringify } from '../../utils/slowOperations.js';
62
+ import { isBetaTracingEnabled, startLLMRequestSpan, } from '../../utils/telemetry/sessionTracing.js';
63
+ /* eslint-enable @typescript-eslint/no-require-imports */
64
+ import { logEvent, } from '../analytics/index.js';
65
+ import { consumePendingCacheEdits, getPinnedCacheEdits, markToolsSentToAPIState, pinCacheEdits, } from '../compact/microCompact.js';
66
+ import { getInitializationStatus } from '../lsp/manager.js';
67
+ import { isToolFromMcpServer } from '../mcp/utils.js';
68
+ import { withStreamingVCR, withVCR } from '../vcr.js';
69
+ import { CLIENT_REQUEST_ID_HEADER, getAnthropicClient } from './client.js';
70
+ import { API_ERROR_MESSAGE_PREFIX, CUSTOM_OFF_SWITCH_MESSAGE, getAssistantMessageFromError, getErrorMessageIfRefusal, } from './errors.js';
71
+ import { EMPTY_USAGE, logAPIError, logAPIQuery, logAPISuccessAndDuration, } from './logging.js';
72
+ import { CACHE_TTL_1HOUR_MS, checkResponseForCacheBreak, recordPromptState, } from './promptCacheBreakDetection.js';
73
+ import { CannotRetryError, FallbackTriggeredError, is529Error, withRetry, } from './withRetry.js';
74
+ /**
75
+ * Assemble the extra body parameters for the API request, based on the
76
+ * THADDEUS_EXTRA_BODY environment variable if present and on any beta
77
+ * headers (primarily for Bedrock requests).
78
+ *
79
+ * @param betaHeaders - An array of beta headers to include in the request.
80
+ * @returns A JSON object representing the extra body parameters.
81
+ */
82
+ export function getExtraBodyParams(betaHeaders) {
83
+ // Parse user's extra body parameters first
84
+ const extraBodyStr = process.env.THADDEUS_EXTRA_BODY;
85
+ let result = {};
86
+ if (extraBodyStr) {
87
+ try {
88
+ // Parse as JSON, which can be null, boolean, number, string, array or object
89
+ const parsed = safeParseJSON(extraBodyStr);
90
+ // We expect an object with key-value pairs to spread into API parameters
91
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
92
+ // Shallow clone — safeParseJSON is LRU-cached and returns the same
93
+ // object reference for the same string. Mutating `result` below
94
+ // would poison the cache, causing stale values to persist.
95
+ result = { ...parsed };
96
+ }
97
+ else {
98
+ logForDebugging(`THADDEUS_EXTRA_BODY env var must be a JSON object, but was given ${extraBodyStr}`, { level: 'error' });
99
+ }
100
+ }
101
+ catch (error) {
102
+ logForDebugging(`Error parsing THADDEUS_EXTRA_BODY: ${errorMessage(error)}`, { level: 'error' });
103
+ }
104
+ }
105
+ // Anti-distillation: send fake_tools opt-in for 1P CLI only
106
+ if (feature('ANTI_DISTILLATION_CC')
107
+ ? process.env.THADDEUS_ENTRYPOINT === 'cli' &&
108
+ shouldIncludeFirstPartyOnlyBetas() &&
109
+ getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_anti_distill_fake_tool_injection', false)
110
+ : false) {
111
+ result.anti_distillation = ['fake_tools'];
112
+ }
113
+ // Handle beta headers if provided
114
+ if (betaHeaders && betaHeaders.length > 0) {
115
+ if (result.anthropic_beta && Array.isArray(result.anthropic_beta)) {
116
+ // Add to existing array, avoiding duplicates
117
+ const existingHeaders = result.anthropic_beta;
118
+ const newHeaders = betaHeaders.filter(header => !existingHeaders.includes(header));
119
+ result.anthropic_beta = [...existingHeaders, ...newHeaders];
120
+ }
121
+ else {
122
+ // Create new array with the beta headers
123
+ result.anthropic_beta = betaHeaders;
124
+ }
125
+ }
126
+ return result;
127
+ }
128
+ export function getPromptCachingEnabled(model) {
129
+ // Global disable takes precedence
130
+ if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING))
131
+ return false;
132
+ // Check if we should disable for small/fast model
133
+ if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING_HAIKU)) {
134
+ const smallFastModel = getSmallFastModel();
135
+ if (model === smallFastModel)
136
+ return false;
137
+ }
138
+ // Check if we should disable for default Sonnet
139
+ if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING_SONNET)) {
140
+ const defaultSonnet = getDefaultSonnetModel();
141
+ if (model === defaultSonnet)
142
+ return false;
143
+ }
144
+ // Check if we should disable for default Opus
145
+ if (isEnvTruthy(process.env.DISABLE_PROMPT_CACHING_OPUS)) {
146
+ const defaultOpus = getDefaultOpusModel();
147
+ if (model === defaultOpus)
148
+ return false;
149
+ }
150
+ return true;
151
+ }
152
+ export function getCacheControl({ scope, querySource, } = {}) {
153
+ return {
154
+ type: 'ephemeral',
155
+ ...(should1hCacheTTL(querySource) && { ttl: '1h' }),
156
+ ...(scope === 'global' && { scope }),
157
+ };
158
+ }
159
+ /**
160
+ * Determines if 1h TTL should be used for prompt caching.
161
+ *
162
+ * Only applied when:
163
+ * 1. User is eligible (ant or subscriber within rate limits)
164
+ * 2. The query source matches a pattern in the GrowthBook allowlist
165
+ *
166
+ * GrowthBook config shape: { allowlist: string[] }
167
+ * Patterns support trailing '*' for prefix matching.
168
+ * Examples:
169
+ * - { allowlist: ["repl_main_thread*", "sdk"] } — main thread + SDK only
170
+ * - { allowlist: ["repl_main_thread*", "sdk", "agent:*"] } — also subagents
171
+ * - { allowlist: ["*"] } — all sources
172
+ *
173
+ * The allowlist is cached in STATE for session stability — prevents mixed
174
+ * TTLs when GrowthBook's disk cache updates mid-request.
175
+ */
176
+ function should1hCacheTTL(querySource) {
177
+ // 3P Bedrock users get 1h TTL when opted in via env var — they manage their own billing
178
+ // No GrowthBook gating needed since 3P users don't have GrowthBook configured
179
+ if (getAPIProvider() === 'bedrock' &&
180
+ isEnvTruthy(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK)) {
181
+ return true;
182
+ }
183
+ // Latch eligibility in bootstrap state for session stability — prevents
184
+ // mid-session overage flips from changing the cache_control TTL, which
185
+ // would bust the server-side prompt cache (~20K tokens per flip).
186
+ let userEligible = getPromptCache1hEligible();
187
+ if (userEligible === null) {
188
+ userEligible =
189
+ process.env.USER_TYPE === 'ant' ||
190
+ (isClaudeAISubscriber() && !currentLimits.isUsingOverage);
191
+ setPromptCache1hEligible(userEligible);
192
+ }
193
+ if (!userEligible)
194
+ return false;
195
+ // Cache allowlist in bootstrap state for session stability — prevents mixed
196
+ // TTLs when GrowthBook's disk cache updates mid-request
197
+ let allowlist = getPromptCache1hAllowlist();
198
+ if (allowlist === null) {
199
+ const config = getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_prompt_cache_1h_config', {});
200
+ allowlist = config.allowlist ?? [];
201
+ setPromptCache1hAllowlist(allowlist);
202
+ }
203
+ return (querySource !== undefined &&
204
+ allowlist.some(pattern => pattern.endsWith('*')
205
+ ? querySource.startsWith(pattern.slice(0, -1))
206
+ : querySource === pattern));
207
+ }
208
+ /**
209
+ * Configure effort parameters for API request.
210
+ *
211
+ */
212
+ function configureEffortParams(effortValue, outputConfig, extraBodyParams, betas, model) {
213
+ if (!modelSupportsEffort(model) || 'effort' in outputConfig) {
214
+ return;
215
+ }
216
+ if (effortValue === undefined) {
217
+ betas.push(EFFORT_BETA_HEADER);
218
+ }
219
+ else if (typeof effortValue === 'string') {
220
+ // Send string effort level as is
221
+ outputConfig.effort = effortValue;
222
+ betas.push(EFFORT_BETA_HEADER);
223
+ }
224
+ else if (process.env.USER_TYPE === 'ant') {
225
+ // Numeric effort override - ant-only (uses anthropic_internal)
226
+ const existingInternal = extraBodyParams.anthropic_internal || {};
227
+ extraBodyParams.anthropic_internal = {
228
+ ...existingInternal,
229
+ effort_override: effortValue,
230
+ };
231
+ }
232
+ }
233
+ export function configureTaskBudgetParams(taskBudget, outputConfig, betas) {
234
+ if (!taskBudget ||
235
+ 'task_budget' in outputConfig ||
236
+ !shouldIncludeFirstPartyOnlyBetas()) {
237
+ return;
238
+ }
239
+ outputConfig.task_budget = {
240
+ type: 'tokens',
241
+ total: taskBudget.total,
242
+ ...(taskBudget.remaining !== undefined && {
243
+ remaining: taskBudget.remaining,
244
+ }),
245
+ };
246
+ if (!betas.includes(TASK_BUDGETS_BETA_HEADER)) {
247
+ betas.push(TASK_BUDGETS_BETA_HEADER);
248
+ }
249
+ }
250
+ export function getAPIMetadata() {
251
+ // https://docs.google.com/document/d/1dURO9ycXXQCBS0V4Vhl4poDBRgkelFc5t2BNPoEgH5Q/edit?tab=t.0#heading=h.5g7nec5b09w5
252
+ let extra = {};
253
+ const extraStr = process.env.THADDEUS_EXTRA_METADATA;
254
+ if (extraStr) {
255
+ const parsed = safeParseJSON(extraStr, false);
256
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
257
+ extra = parsed;
258
+ }
259
+ else {
260
+ logForDebugging(`THADDEUS_EXTRA_METADATA env var must be a JSON object, but was given ${extraStr}`, { level: 'error' });
261
+ }
262
+ }
263
+ return {
264
+ user_id: jsonStringify({
265
+ ...extra,
266
+ device_id: getOrCreateUserID(),
267
+ // Only include OAuth account UUID when actively using OAuth authentication
268
+ account_uuid: getOauthAccountInfo()?.accountUuid ?? '',
269
+ session_id: getSessionId(),
270
+ }),
271
+ };
272
+ }
273
+ export async function verifyApiKey(apiKey, isNonInteractiveSession) {
274
+ // Skip API verification if running in print mode (isNonInteractiveSession)
275
+ if (isNonInteractiveSession) {
276
+ return true;
277
+ }
278
+ try {
279
+ // WARNING: if you change this to use a non-Haiku model, this request will fail in 1P unless it uses getCLISyspromptPrefix.
280
+ const model = getSmallFastModel();
281
+ const betas = getModelBetas(model);
282
+ return await returnValue(withRetry(() => getAnthropicClient({
283
+ apiKey,
284
+ maxRetries: 3,
285
+ model,
286
+ source: 'verify_api_key',
287
+ }), async (anthropic) => {
288
+ const messages = [{ role: 'user', content: 'test' }];
289
+ // biome-ignore lint/plugin: API key verification is intentionally a minimal direct call
290
+ await anthropic.beta.messages.create({
291
+ model,
292
+ max_tokens: 1,
293
+ messages,
294
+ temperature: 1,
295
+ ...(betas.length > 0 && { betas }),
296
+ metadata: getAPIMetadata(),
297
+ ...getExtraBodyParams(),
298
+ });
299
+ return true;
300
+ }, { maxRetries: 2, model, thinkingConfig: { type: 'disabled' } }));
301
+ }
302
+ catch (errorFromRetry) {
303
+ let error = errorFromRetry;
304
+ if (errorFromRetry instanceof CannotRetryError) {
305
+ error = errorFromRetry.originalError;
306
+ }
307
+ logError(error);
308
+ // Check for authentication error
309
+ if (error instanceof Error &&
310
+ error.message.includes('{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}')) {
311
+ return false;
312
+ }
313
+ throw error;
314
+ }
315
+ }
316
+ export function userMessageToMessageParam(message, addCache = false, enablePromptCaching, querySource) {
317
+ if (addCache) {
318
+ if (typeof message.message.content === 'string') {
319
+ return {
320
+ role: 'user',
321
+ content: [
322
+ {
323
+ type: 'text',
324
+ text: message.message.content,
325
+ ...(enablePromptCaching && {
326
+ cache_control: getCacheControl({ querySource }),
327
+ }),
328
+ },
329
+ ],
330
+ };
331
+ }
332
+ else {
333
+ return {
334
+ role: 'user',
335
+ content: message.message.content.map((_, i) => ({
336
+ ..._,
337
+ ...(i === message.message.content.length - 1
338
+ ? enablePromptCaching
339
+ ? { cache_control: getCacheControl({ querySource }) }
340
+ : {}
341
+ : {}),
342
+ })),
343
+ };
344
+ }
345
+ }
346
+ // Clone array content to prevent in-place mutations (e.g., insertCacheEditsBlock's
347
+ // splice) from contaminating the original message. Without cloning, multiple calls
348
+ // to addCacheBreakpoints share the same array and each splices in duplicate cache_edits.
349
+ return {
350
+ role: 'user',
351
+ content: Array.isArray(message.message.content)
352
+ ? [...message.message.content]
353
+ : message.message.content,
354
+ };
355
+ }
356
+ export function assistantMessageToMessageParam(message, addCache = false, enablePromptCaching, querySource) {
357
+ if (addCache) {
358
+ if (typeof message.message.content === 'string') {
359
+ return {
360
+ role: 'assistant',
361
+ content: [
362
+ {
363
+ type: 'text',
364
+ text: message.message.content,
365
+ ...(enablePromptCaching && {
366
+ cache_control: getCacheControl({ querySource }),
367
+ }),
368
+ },
369
+ ],
370
+ };
371
+ }
372
+ else {
373
+ return {
374
+ role: 'assistant',
375
+ content: message.message.content.map((_, i) => ({
376
+ ..._,
377
+ ...(i === message.message.content.length - 1 &&
378
+ _.type !== 'thinking' &&
379
+ _.type !== 'redacted_thinking' &&
380
+ (feature('CONNECTOR_TEXT') ? !isConnectorTextBlock(_) : true)
381
+ ? enablePromptCaching
382
+ ? { cache_control: getCacheControl({ querySource }) }
383
+ : {}
384
+ : {}),
385
+ })),
386
+ };
387
+ }
388
+ }
389
+ return {
390
+ role: 'assistant',
391
+ content: message.message.content,
392
+ };
393
+ }
394
+ export async function queryModelWithoutStreaming({ messages, systemPrompt, thinkingConfig, tools, signal, options, }) {
395
+ // Store the assistant message but continue consuming the generator to ensure
396
+ // logAPISuccessAndDuration gets called (which happens after all yields)
397
+ let assistantMessage;
398
+ for await (const message of withStreamingVCR(messages, async function* () {
399
+ yield* queryModel(messages, systemPrompt, thinkingConfig, tools, signal, options);
400
+ })) {
401
+ if (message.type === 'assistant') {
402
+ assistantMessage = message;
403
+ }
404
+ }
405
+ if (!assistantMessage) {
406
+ // If the signal was aborted, throw APIUserAbortError instead of a generic error
407
+ // This allows callers to handle abort scenarios gracefully
408
+ if (signal.aborted) {
409
+ throw new APIUserAbortError();
410
+ }
411
+ throw new Error('No assistant message found');
412
+ }
413
+ return assistantMessage;
414
+ }
415
+ export async function* queryModelWithStreaming({ messages, systemPrompt, thinkingConfig, tools, signal, options, }) {
416
+ return yield* withStreamingVCR(messages, async function* () {
417
+ yield* queryModel(messages, systemPrompt, thinkingConfig, tools, signal, options);
418
+ });
419
+ }
420
+ /**
421
+ * Determines if an LSP tool should be deferred (tool appears with defer_loading: true)
422
+ * because LSP initialization is not yet complete.
423
+ */
424
+ function shouldDeferLspTool(tool) {
425
+ if (!('isLsp' in tool) || !tool.isLsp) {
426
+ return false;
427
+ }
428
+ const status = getInitializationStatus();
429
+ // Defer when pending or not started
430
+ return status.status === 'pending' || status.status === 'not-started';
431
+ }
432
+ /**
433
+ * Per-attempt timeout for non-streaming fallback requests, in milliseconds.
434
+ * Reads API_TIMEOUT_MS when set so slow backends and the streaming path
435
+ * share the same ceiling.
436
+ *
437
+ * Remote sessions default to 120s to stay under CCR's container idle-kill
438
+ * (~5min) so a hung fallback to a wedged backend surfaces a clean
439
+ * APIConnectionTimeoutError instead of stalling past SIGKILL.
440
+ *
441
+ * Otherwise defaults to 300s — long enough for slow backends without
442
+ * approaching the API's 10-minute non-streaming boundary.
443
+ */
444
+ function getNonstreamingFallbackTimeoutMs() {
445
+ const override = parseInt(process.env.API_TIMEOUT_MS || '', 10);
446
+ if (override)
447
+ return override;
448
+ return isEnvTruthy(process.env.THADDEUS_REMOTE) ? 120_000 : 300_000;
449
+ }
450
+ /**
451
+ * Helper generator for non-streaming API requests.
452
+ * Encapsulates the common pattern of creating a withRetry generator,
453
+ * iterating to yield system messages, and returning the final BetaMessage.
454
+ */
455
+ export async function* executeNonStreamingRequest(clientOptions, retryOptions, paramsFromContext, onAttempt, captureRequest,
456
+ /**
457
+ * Request ID of the failed streaming attempt this fallback is recovering
458
+ * from. Emitted in thaddeus_nonstreaming_fallback_error for funnel correlation.
459
+ */
460
+ originatingRequestId) {
461
+ const fallbackTimeoutMs = getNonstreamingFallbackTimeoutMs();
462
+ const generator = withRetry(() => getAnthropicClient({
463
+ maxRetries: 0,
464
+ model: clientOptions.model,
465
+ fetchOverride: clientOptions.fetchOverride,
466
+ source: clientOptions.source,
467
+ }), async (anthropic, attempt, context) => {
468
+ const start = Date.now();
469
+ const retryParams = paramsFromContext(context);
470
+ captureRequest(retryParams);
471
+ onAttempt(attempt, start, retryParams.max_tokens);
472
+ const adjustedParams = adjustParamsForNonStreaming(retryParams, MAX_NON_STREAMING_TOKENS);
473
+ try {
474
+ // biome-ignore lint/plugin: non-streaming API call
475
+ return await anthropic.beta.messages.create({
476
+ ...adjustedParams,
477
+ model: normalizeModelStringForAPI(adjustedParams.model),
478
+ }, {
479
+ signal: retryOptions.signal,
480
+ timeout: fallbackTimeoutMs,
481
+ });
482
+ }
483
+ catch (err) {
484
+ // User aborts are not errors — re-throw immediately without logging
485
+ if (err instanceof APIUserAbortError)
486
+ throw err;
487
+ // Instrumentation: record when the non-streaming request errors (including
488
+ // timeouts). Lets us distinguish "fallback hung past container kill"
489
+ // (no event) from "fallback hit the bounded timeout" (this event).
490
+ logForDiagnosticsNoPII('error', 'cli_nonstreaming_fallback_error');
491
+ logEvent('thaddeus_nonstreaming_fallback_error', {
492
+ model: clientOptions.model,
493
+ error: err instanceof Error
494
+ ? err.name
495
+ : 'unknown',
496
+ attempt,
497
+ timeout_ms: fallbackTimeoutMs,
498
+ request_id: (originatingRequestId ??
499
+ 'unknown'),
500
+ });
501
+ throw err;
502
+ }
503
+ }, {
504
+ model: retryOptions.model,
505
+ fallbackModel: retryOptions.fallbackModel,
506
+ thinkingConfig: retryOptions.thinkingConfig,
507
+ ...(isFastModeEnabled() && { fastMode: retryOptions.fastMode }),
508
+ signal: retryOptions.signal,
509
+ initialConsecutive529Errors: retryOptions.initialConsecutive529Errors,
510
+ querySource: retryOptions.querySource,
511
+ });
512
+ let e;
513
+ do {
514
+ e = await generator.next();
515
+ if (!e.done && e.value.type === 'system') {
516
+ yield e.value;
517
+ }
518
+ } while (!e.done);
519
+ return e.value;
520
+ }
521
+ /**
522
+ * Extracts the request ID from the most recent assistant message in the
523
+ * conversation. Used to link consecutive API requests in analytics so we can
524
+ * join them for cache-hit-rate analysis and incremental token tracking.
525
+ *
526
+ * Deriving this from the message array (rather than global state) ensures each
527
+ * query chain (main thread, subagent, teammate) tracks its own request chain
528
+ * independently, and rollback/undo naturally updates the value.
529
+ */
530
+ function getPreviousRequestIdFromMessages(messages) {
531
+ for (let i = messages.length - 1; i >= 0; i--) {
532
+ const msg = messages[i];
533
+ if (msg.type === 'assistant' && msg.requestId) {
534
+ return msg.requestId;
535
+ }
536
+ }
537
+ return undefined;
538
+ }
539
+ function isMedia(block) {
540
+ return block.type === 'image' || block.type === 'document';
541
+ }
542
+ function isToolResult(block) {
543
+ return block.type === 'tool_result';
544
+ }
545
+ /**
546
+ * Ensures messages contain at most `limit` media items (images + documents).
547
+ * Strips oldest media first to preserve the most recent.
548
+ */
549
+ export function stripExcessMediaItems(messages, limit) {
550
+ let toRemove = 0;
551
+ for (const msg of messages) {
552
+ if (!Array.isArray(msg.message.content))
553
+ continue;
554
+ for (const block of msg.message.content) {
555
+ if (isMedia(block))
556
+ toRemove++;
557
+ if (isToolResult(block) && Array.isArray(block.content)) {
558
+ for (const nested of block.content) {
559
+ if (isMedia(nested))
560
+ toRemove++;
561
+ }
562
+ }
563
+ }
564
+ }
565
+ toRemove -= limit;
566
+ if (toRemove <= 0)
567
+ return messages;
568
+ return messages.map(msg => {
569
+ if (toRemove <= 0)
570
+ return msg;
571
+ const content = msg.message.content;
572
+ if (!Array.isArray(content))
573
+ return msg;
574
+ const before = toRemove;
575
+ const stripped = content
576
+ .map(block => {
577
+ if (toRemove <= 0 ||
578
+ !isToolResult(block) ||
579
+ !Array.isArray(block.content))
580
+ return block;
581
+ const filtered = block.content.filter(n => {
582
+ if (toRemove > 0 && isMedia(n)) {
583
+ toRemove--;
584
+ return false;
585
+ }
586
+ return true;
587
+ });
588
+ return filtered.length === block.content.length
589
+ ? block
590
+ : { ...block, content: filtered };
591
+ })
592
+ .filter(block => {
593
+ if (toRemove > 0 && isMedia(block)) {
594
+ toRemove--;
595
+ return false;
596
+ }
597
+ return true;
598
+ });
599
+ return before === toRemove
600
+ ? msg
601
+ : {
602
+ ...msg,
603
+ message: { ...msg.message, content: stripped },
604
+ };
605
+ });
606
+ }
607
+ async function* queryModel(messages, systemPrompt, thinkingConfig, tools, signal, options) {
608
+ // Check cheap conditions first — the off-switch await blocks on GrowthBook
609
+ // init (~10ms). For non-Opus models (haiku, sonnet) this skips the await
610
+ // entirely. Subscribers don't hit this path at all.
611
+ if (!isClaudeAISubscriber() &&
612
+ isNonCustomOpusModel(options.model) &&
613
+ (await getDynamicConfig_BLOCKS_ON_INIT('thaddeus-off-switch', {
614
+ activated: false,
615
+ })).activated) {
616
+ logEvent('thaddeus_off_switch_query', {});
617
+ yield getAssistantMessageFromError(new Error(CUSTOM_OFF_SWITCH_MESSAGE), options.model);
618
+ return;
619
+ }
620
+ // Derive previous request ID from the last assistant message in this query chain.
621
+ // This is scoped per message array (main thread, subagent, teammate each have their own),
622
+ // so concurrent agents don't clobber each other's request chain tracking.
623
+ // Also naturally handles rollback/undo since removed messages won't be in the array.
624
+ const previousRequestId = getPreviousRequestIdFromMessages(messages);
625
+ const resolvedModel = getAPIProvider() === 'bedrock' &&
626
+ options.model.includes('application-inference-profile')
627
+ ? ((await getInferenceProfileBackingModel(options.model)) ??
628
+ options.model)
629
+ : options.model;
630
+ queryCheckpoint('query_tool_schema_build_start');
631
+ const isAgenticQuery = options.querySource.startsWith('repl_main_thread') ||
632
+ options.querySource.startsWith('agent:') ||
633
+ options.querySource === 'sdk' ||
634
+ options.querySource === 'hook_agent' ||
635
+ options.querySource === 'verification_agent';
636
+ const betas = getMergedBetas(options.model, { isAgenticQuery });
637
+ // Always send the advisor beta header when advisor is enabled, so
638
+ // non-agentic queries (compact, side_question, extract_memories, etc.)
639
+ // can parse advisor server_tool_use blocks already in the conversation history.
640
+ if (isAdvisorEnabled()) {
641
+ betas.push(ADVISOR_BETA_HEADER);
642
+ }
643
+ let advisorModel;
644
+ if (isAgenticQuery && isAdvisorEnabled()) {
645
+ let advisorOption = options.advisorModel;
646
+ const advisorExperiment = getExperimentAdvisorModels();
647
+ if (advisorExperiment !== undefined) {
648
+ if (normalizeModelStringForAPI(advisorExperiment.baseModel) ===
649
+ normalizeModelStringForAPI(options.model)) {
650
+ // Override the advisor model if the base model matches. We
651
+ // should only have experiment models if the user cannot
652
+ // configure it themselves.
653
+ advisorOption = advisorExperiment.advisorModel;
654
+ }
655
+ }
656
+ if (advisorOption) {
657
+ const normalizedAdvisorModel = normalizeModelStringForAPI(parseUserSpecifiedModel(advisorOption));
658
+ if (!modelSupportsAdvisor(options.model)) {
659
+ logForDebugging(`[AdvisorTool] Skipping advisor - base model ${options.model} does not support advisor`);
660
+ }
661
+ else if (!isValidAdvisorModel(normalizedAdvisorModel)) {
662
+ logForDebugging(`[AdvisorTool] Skipping advisor - ${normalizedAdvisorModel} is not a valid advisor model`);
663
+ }
664
+ else {
665
+ advisorModel = normalizedAdvisorModel;
666
+ logForDebugging(`[AdvisorTool] Server-side tool enabled with ${advisorModel} as the advisor model`);
667
+ }
668
+ }
669
+ }
670
+ // Check if tool search is enabled (checks mode, model support, and threshold for auto mode)
671
+ // This is async because it may need to calculate MCP tool description sizes for TstAuto mode
672
+ let useToolSearch = await isToolSearchEnabled(options.model, tools, options.getToolPermissionContext, options.agents, 'query');
673
+ // Precompute once — isDeferredTool does 2 GrowthBook lookups per call
674
+ const deferredToolNames = new Set();
675
+ if (useToolSearch) {
676
+ for (const t of tools) {
677
+ if (isDeferredTool(t))
678
+ deferredToolNames.add(t.name);
679
+ }
680
+ }
681
+ // Even if tool search mode is enabled, skip if there are no deferred tools
682
+ // AND no MCP servers are still connecting. When servers are pending, keep
683
+ // ToolSearch available so the model can discover tools after they connect.
684
+ if (useToolSearch &&
685
+ deferredToolNames.size === 0 &&
686
+ !options.hasPendingMcpServers) {
687
+ logForDebugging('Tool search disabled: no deferred tools available to search');
688
+ useToolSearch = false;
689
+ }
690
+ // Filter out ToolSearchTool if tool search is not enabled for this model
691
+ // ToolSearchTool returns tool_reference blocks which unsupported models can't handle
692
+ let filteredTools;
693
+ if (useToolSearch) {
694
+ // Dynamic tool loading: Only include deferred tools that have been discovered
695
+ // via tool_reference blocks in the message history. This eliminates the need
696
+ // to predeclare all deferred tools upfront and removes limits on tool quantity.
697
+ const discoveredToolNames = extractDiscoveredToolNames(messages);
698
+ filteredTools = tools.filter(tool => {
699
+ // Always include non-deferred tools
700
+ if (!deferredToolNames.has(tool.name))
701
+ return true;
702
+ // Always include ToolSearchTool (so it can discover more tools)
703
+ if (toolMatchesName(tool, TOOL_SEARCH_TOOL_NAME))
704
+ return true;
705
+ // Only include deferred tools that have been discovered
706
+ return discoveredToolNames.has(tool.name);
707
+ });
708
+ }
709
+ else {
710
+ filteredTools = tools.filter(t => !toolMatchesName(t, TOOL_SEARCH_TOOL_NAME));
711
+ }
712
+ // Add tool search beta header if enabled - required for defer_loading to be accepted
713
+ // Header differs by provider: 1P/Foundry use advanced-tool-use, Vertex/Bedrock use tool-search-tool
714
+ // For Bedrock, this header must go in extraBodyParams, not the betas array
715
+ const toolSearchHeader = useToolSearch ? getToolSearchBetaHeader() : null;
716
+ if (toolSearchHeader && getAPIProvider() !== 'bedrock') {
717
+ if (!betas.includes(toolSearchHeader)) {
718
+ betas.push(toolSearchHeader);
719
+ }
720
+ }
721
+ // Determine if cached microcompact is enabled for this model.
722
+ // Computed once here (in async context) and captured by paramsFromContext.
723
+ // The beta header is also captured here to avoid a top-level import of the
724
+ // ant-only CACHE_EDITING_BETA_HEADER constant.
725
+ let cachedMCEnabled = false;
726
+ let cacheEditingBetaHeader = '';
727
+ if (feature('CACHED_MICROCOMPACT')) {
728
+ const { isCachedMicrocompactEnabled, isModelSupportedForCacheEditing, getCachedMCConfig, } = await import('../compact/cachedMicrocompact.js');
729
+ const betas = await import('src/constants/betas.js');
730
+ cacheEditingBetaHeader = betas.CACHE_EDITING_BETA_HEADER;
731
+ const featureEnabled = isCachedMicrocompactEnabled();
732
+ const modelSupported = isModelSupportedForCacheEditing(options.model);
733
+ cachedMCEnabled = featureEnabled && modelSupported;
734
+ const config = getCachedMCConfig();
735
+ logForDebugging(`Cached MC gate: enabled=${featureEnabled} modelSupported=${modelSupported} model=${options.model} supportedModels=${jsonStringify(config.supportedModels)}`);
736
+ }
737
+ const useGlobalCacheFeature = shouldUseGlobalCacheScope();
738
+ const willDefer = (t) => useToolSearch && (deferredToolNames.has(t.name) || shouldDeferLspTool(t));
739
+ // MCP tools are per-user → dynamic tool section → can't globally cache.
740
+ // Only gate when an MCP tool will actually render (not defer_loading).
741
+ const needsToolBasedCacheMarker = useGlobalCacheFeature &&
742
+ filteredTools.some(t => t.isMcp === true && !willDefer(t));
743
+ // Ensure prompt_caching_scope beta header is present when global cache is enabled.
744
+ if (useGlobalCacheFeature &&
745
+ !betas.includes(PROMPT_CACHING_SCOPE_BETA_HEADER)) {
746
+ betas.push(PROMPT_CACHING_SCOPE_BETA_HEADER);
747
+ }
748
+ // Determine global cache strategy for logging
749
+ const globalCacheStrategy = useGlobalCacheFeature
750
+ ? needsToolBasedCacheMarker
751
+ ? 'none'
752
+ : 'system_prompt'
753
+ : 'none';
754
+ // Build tool schemas, adding defer_loading for MCP tools when tool search is enabled
755
+ // Note: We pass the full `tools` list (not filteredTools) to toolToAPISchema so that
756
+ // ToolSearchTool's prompt can list ALL available MCP tools. The filtering only affects
757
+ // which tools are actually sent to the API, not what the model sees in tool descriptions.
758
+ const toolSchemas = await Promise.all(filteredTools.map(tool => toolToAPISchema(tool, {
759
+ getToolPermissionContext: options.getToolPermissionContext,
760
+ tools,
761
+ agents: options.agents,
762
+ allowedAgentTypes: options.allowedAgentTypes,
763
+ model: options.model,
764
+ deferLoading: willDefer(tool),
765
+ })));
766
+ if (useToolSearch) {
767
+ const includedDeferredTools = count(filteredTools, t => deferredToolNames.has(t.name));
768
+ logForDebugging(`Dynamic tool loading: ${includedDeferredTools}/${deferredToolNames.size} deferred tools included`);
769
+ }
770
+ queryCheckpoint('query_tool_schema_build_end');
771
+ // Normalize messages before building system prompt (needed for fingerprinting)
772
+ // Instrumentation: Track message count before normalization
773
+ logEvent('thaddeus_api_before_normalize', {
774
+ preNormalizedMessageCount: messages.length,
775
+ });
776
+ queryCheckpoint('query_message_normalization_start');
777
+ let messagesForAPI = normalizeMessagesForAPI(messages, filteredTools);
778
+ queryCheckpoint('query_message_normalization_end');
779
+ // Model-specific post-processing: strip tool-search-specific fields if the
780
+ // selected model doesn't support tool search.
781
+ //
782
+ // Why is this needed in addition to normalizeMessagesForAPI?
783
+ // - normalizeMessagesForAPI uses isToolSearchEnabledNoModelCheck() because it's
784
+ // called from ~20 places (analytics, feedback, sharing, etc.), many of which
785
+ // don't have model context. Adding model to its signature would be a large refactor.
786
+ // - This post-processing uses the model-aware isToolSearchEnabled() check
787
+ // - This handles mid-conversation model switching (e.g., Sonnet → Haiku) where
788
+ // stale tool-search fields from the previous model would cause 400 errors
789
+ //
790
+ // Note: For assistant messages, normalizeMessagesForAPI already normalized the
791
+ // tool inputs, so stripCallerFieldFromAssistantMessage only needs to remove the
792
+ // 'caller' field (not re-normalize inputs).
793
+ if (!useToolSearch) {
794
+ messagesForAPI = messagesForAPI.map(msg => {
795
+ switch (msg.type) {
796
+ case 'user':
797
+ // Strip tool_reference blocks from tool_result content
798
+ return stripToolReferenceBlocksFromUserMessage(msg);
799
+ case 'assistant':
800
+ // Strip 'caller' field from tool_use blocks
801
+ return stripCallerFieldFromAssistantMessage(msg);
802
+ default:
803
+ return msg;
804
+ }
805
+ });
806
+ }
807
+ // Repair tool_use/tool_result pairing mismatches that can occur when resuming
808
+ // remote/teleport sessions. Inserts synthetic error tool_results for orphaned
809
+ // tool_uses and strips orphaned tool_results referencing non-existent tool_uses.
810
+ messagesForAPI = ensureToolResultPairing(messagesForAPI);
811
+ // Strip advisor blocks — the API rejects them without the beta header.
812
+ if (!betas.includes(ADVISOR_BETA_HEADER)) {
813
+ messagesForAPI = stripAdvisorBlocks(messagesForAPI);
814
+ }
815
+ // Strip excess media items before making the API call.
816
+ // The API rejects requests with >100 media items but returns a confusing error.
817
+ // Rather than erroring (which is hard to recover from in Cowork/CCD), we
818
+ // silently drop the oldest media items to stay within the limit.
819
+ messagesForAPI = stripExcessMediaItems(messagesForAPI, API_MAX_MEDIA_PER_REQUEST);
820
+ // Instrumentation: Track message count after normalization
821
+ logEvent('thaddeus_api_after_normalize', {
822
+ postNormalizedMessageCount: messagesForAPI.length,
823
+ });
824
+ // Compute fingerprint from first user message for attribution.
825
+ // Must run BEFORE injecting synthetic messages (e.g. deferred tool names)
826
+ // so the fingerprint reflects the actual user input.
827
+ const fingerprint = computeFingerprintFromMessages(messagesForAPI);
828
+ // When the delta attachment is enabled, deferred tools are announced
829
+ // via persisted deferred_tools_delta attachments instead of this
830
+ // ephemeral prepend (which busts cache whenever the pool changes).
831
+ if (useToolSearch && !isDeferredToolsDeltaEnabled()) {
832
+ const deferredToolList = tools
833
+ .filter(t => deferredToolNames.has(t.name))
834
+ .map(formatDeferredToolLine)
835
+ .sort()
836
+ .join('\n');
837
+ if (deferredToolList) {
838
+ messagesForAPI = [
839
+ createUserMessage({
840
+ content: `<available-deferred-tools>\n${deferredToolList}\n</available-deferred-tools>`,
841
+ isMeta: true,
842
+ }),
843
+ ...messagesForAPI,
844
+ ];
845
+ }
846
+ }
847
+ // Chrome tool-search instructions: when the delta attachment is enabled,
848
+ // these are carried as a client-side block in mcp_instructions_delta
849
+ // (attachments.ts) instead of here. This per-request sys-prompt append
850
+ // busts the prompt cache when chrome connects late.
851
+ const hasChromeTools = filteredTools.some(t => isToolFromMcpServer(t.name, CLAUDE_IN_CHROME_MCP_SERVER_NAME));
852
+ const injectChromeHere = useToolSearch && hasChromeTools && !isMcpInstructionsDeltaEnabled();
853
+ // filter(Boolean) works by converting each element to a boolean - empty strings become false and are filtered out.
854
+ systemPrompt = asSystemPrompt([
855
+ getAttributionHeader(fingerprint),
856
+ getCLISyspromptPrefix({
857
+ isNonInteractive: options.isNonInteractiveSession,
858
+ hasAppendSystemPrompt: options.hasAppendSystemPrompt,
859
+ }),
860
+ ...systemPrompt,
861
+ ...(advisorModel ? [ADVISOR_TOOL_INSTRUCTIONS] : []),
862
+ ...(injectChromeHere ? [CHROME_TOOL_SEARCH_INSTRUCTIONS] : []),
863
+ ].filter(Boolean));
864
+ // Prepend system prompt block for easy API identification
865
+ logAPIPrefix(systemPrompt);
866
+ const enablePromptCaching = options.enablePromptCaching ?? getPromptCachingEnabled(options.model);
867
+ const system = buildSystemPromptBlocks(systemPrompt, enablePromptCaching, {
868
+ skipGlobalCacheForSystemPrompt: needsToolBasedCacheMarker,
869
+ querySource: options.querySource,
870
+ });
871
+ const useBetas = betas.length > 0;
872
+ // Build minimal context for detailed tracing (when beta tracing is enabled)
873
+ // Note: The actual new_context message extraction is done in sessionTracing.ts using
874
+ // hash-based tracking per querySource (agent) from the messagesForAPI array
875
+ const extraToolSchemas = [...(options.extraToolSchemas ?? [])];
876
+ if (advisorModel) {
877
+ // Server tools must be in the tools array by API contract. Appended after
878
+ // toolSchemas (which carries the cache_control marker) so toggling /advisor
879
+ // only churns the small suffix, not the cached prefix.
880
+ extraToolSchemas.push({
881
+ type: 'advisor_20260301',
882
+ name: 'advisor',
883
+ model: advisorModel,
884
+ });
885
+ }
886
+ const allTools = [...toolSchemas, ...extraToolSchemas];
887
+ const isFastMode = isFastModeEnabled() &&
888
+ isFastModeAvailable() &&
889
+ !isFastModeCooldown() &&
890
+ isFastModeSupportedByModel(options.model) &&
891
+ !!options.fastMode;
892
+ // Sticky-on latches for dynamic beta headers. Each header, once first
893
+ // sent, keeps being sent for the rest of the session so mid-session
894
+ // toggles don't change the server-side cache key and bust ~50-70K tokens.
895
+ // Latches are cleared on /clear and /compact via clearBetaHeaderLatches().
896
+ // Per-call gates (isAgenticQuery, querySource===repl_main_thread) stay
897
+ // per-call so non-agentic queries keep their own stable header set.
898
+ let afkHeaderLatched = getAfkModeHeaderLatched() === true;
899
+ if (feature('TRANSCRIPT_CLASSIFIER')) {
900
+ if (!afkHeaderLatched &&
901
+ isAgenticQuery &&
902
+ shouldIncludeFirstPartyOnlyBetas() &&
903
+ (autoModeStateModule?.isAutoModeActive() ?? false)) {
904
+ afkHeaderLatched = true;
905
+ setAfkModeHeaderLatched(true);
906
+ }
907
+ }
908
+ let fastModeHeaderLatched = getFastModeHeaderLatched() === true;
909
+ if (!fastModeHeaderLatched && isFastMode) {
910
+ fastModeHeaderLatched = true;
911
+ setFastModeHeaderLatched(true);
912
+ }
913
+ let cacheEditingHeaderLatched = getCacheEditingHeaderLatched() === true;
914
+ if (feature('CACHED_MICROCOMPACT')) {
915
+ if (!cacheEditingHeaderLatched &&
916
+ cachedMCEnabled &&
917
+ getAPIProvider() === 'firstParty' &&
918
+ options.querySource === 'repl_main_thread') {
919
+ cacheEditingHeaderLatched = true;
920
+ setCacheEditingHeaderLatched(true);
921
+ }
922
+ }
923
+ // Only latch from agentic queries so a classifier call doesn't flip the
924
+ // main thread's context_management mid-turn.
925
+ let thinkingClearLatched = getThinkingClearLatched() === true;
926
+ if (!thinkingClearLatched && isAgenticQuery) {
927
+ const lastCompletion = getLastApiCompletionTimestamp();
928
+ if (lastCompletion !== null &&
929
+ Date.now() - lastCompletion > CACHE_TTL_1HOUR_MS) {
930
+ thinkingClearLatched = true;
931
+ setThinkingClearLatched(true);
932
+ }
933
+ }
934
+ const effort = resolveAppliedEffort(options.model, options.effortValue);
935
+ if (feature('PROMPT_CACHE_BREAK_DETECTION')) {
936
+ // Exclude defer_loading tools from the hash -- the API strips them from the
937
+ // prompt, so they never affect the actual cache key. Including them creates
938
+ // false-positive "tool schemas changed" breaks when tools are discovered or
939
+ // MCP servers reconnect.
940
+ const toolsForCacheDetection = allTools.filter(t => !('defer_loading' in t && t.defer_loading));
941
+ // Capture everything that could affect the server-side cache key.
942
+ // Pass latched header values (not live state) so break detection
943
+ // reflects what we actually send, not what the user toggled.
944
+ recordPromptState({
945
+ system,
946
+ toolSchemas: toolsForCacheDetection,
947
+ querySource: options.querySource,
948
+ model: options.model,
949
+ agentId: options.agentId,
950
+ fastMode: fastModeHeaderLatched,
951
+ globalCacheStrategy,
952
+ betas,
953
+ autoModeActive: afkHeaderLatched,
954
+ isUsingOverage: currentLimits.isUsingOverage ?? false,
955
+ cachedMCEnabled: cacheEditingHeaderLatched,
956
+ effortValue: effort,
957
+ extraBodyParams: getExtraBodyParams(),
958
+ });
959
+ }
960
+ const newContext = isBetaTracingEnabled()
961
+ ? {
962
+ systemPrompt: systemPrompt.join('\n\n'),
963
+ querySource: options.querySource,
964
+ tools: jsonStringify(allTools),
965
+ }
966
+ : undefined;
967
+ // Capture the span so we can pass it to endLLMRequestSpan later
968
+ // This ensures responses are matched to the correct request when multiple requests run in parallel
969
+ const llmSpan = startLLMRequestSpan(options.model, newContext, messagesForAPI, isFastMode);
970
+ const startIncludingRetries = Date.now();
971
+ let start = Date.now();
972
+ let attemptNumber = 0;
973
+ const attemptStartTimes = [];
974
+ let stream = undefined;
975
+ let streamRequestId = undefined;
976
+ let clientRequestId = undefined;
977
+ // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins -- Response is available in Node 18+ and is used by the SDK
978
+ let streamResponse = undefined;
979
+ // Release all stream resources to prevent native memory leaks.
980
+ // The Response object holds native TLS/socket buffers that live outside the
981
+ // V8 heap (observed on the Node.js/npm path; see GH #32920), so we must
982
+ // explicitly cancel and release it regardless of how the generator exits.
983
+ function releaseStreamResources() {
984
+ cleanupStream(stream);
985
+ stream = undefined;
986
+ if (streamResponse) {
987
+ streamResponse.body?.cancel().catch(() => { });
988
+ streamResponse = undefined;
989
+ }
990
+ }
991
+ // Consume pending cache edits ONCE before paramsFromContext is defined.
992
+ // paramsFromContext is called multiple times (logging, retries), so consuming
993
+ // inside it would cause the first call to steal edits from subsequent calls.
994
+ const consumedCacheEdits = cachedMCEnabled ? consumePendingCacheEdits() : null;
995
+ const consumedPinnedEdits = cachedMCEnabled ? getPinnedCacheEdits() : [];
996
+ // Capture the betas sent in the last API request, including the ones that
997
+ // were dynamically added, so we can log and send it to telemetry.
998
+ let lastRequestBetas;
999
+ const paramsFromContext = (retryContext) => {
1000
+ const betasParams = [...betas];
1001
+ // Append 1M beta dynamically for the Sonnet 1M experiment.
1002
+ if (!betasParams.includes(CONTEXT_1M_BETA_HEADER) &&
1003
+ getSonnet1mExpTreatmentEnabled(retryContext.model)) {
1004
+ betasParams.push(CONTEXT_1M_BETA_HEADER);
1005
+ }
1006
+ // For Bedrock, include both model-based betas and dynamically-added tool search header
1007
+ const bedrockBetas = getAPIProvider() === 'bedrock'
1008
+ ? [
1009
+ ...getBedrockExtraBodyParamsBetas(retryContext.model),
1010
+ ...(toolSearchHeader ? [toolSearchHeader] : []),
1011
+ ]
1012
+ : [];
1013
+ const extraBodyParams = getExtraBodyParams(bedrockBetas);
1014
+ const outputConfig = {
1015
+ ...(extraBodyParams.output_config ?? {}),
1016
+ };
1017
+ configureEffortParams(effort, outputConfig, extraBodyParams, betasParams, options.model);
1018
+ configureTaskBudgetParams(options.taskBudget, outputConfig, betasParams);
1019
+ // Merge outputFormat into extraBodyParams.output_config alongside effort
1020
+ // Requires structured-outputs beta header per SDK (see parse() in messages.mjs)
1021
+ if (options.outputFormat && !('format' in outputConfig)) {
1022
+ outputConfig.format = options.outputFormat;
1023
+ // Add beta header if not already present and provider supports it
1024
+ if (modelSupportsStructuredOutputs(options.model) &&
1025
+ !betasParams.includes(STRUCTURED_OUTPUTS_BETA_HEADER)) {
1026
+ betasParams.push(STRUCTURED_OUTPUTS_BETA_HEADER);
1027
+ }
1028
+ }
1029
+ // Retry context gets preference because it tries to course correct if we exceed the context window limit
1030
+ const maxOutputTokens = retryContext?.maxTokensOverride ||
1031
+ options.maxOutputTokensOverride ||
1032
+ getMaxOutputTokensForModel(options.model);
1033
+ const hasThinking = thinkingConfig.type !== 'disabled' &&
1034
+ !isEnvTruthy(process.env.THADDEUS_DISABLE_THINKING);
1035
+ let thinking = undefined;
1036
+ // IMPORTANT: Do not change the adaptive-vs-budget thinking selection below
1037
+ // without notifying the model launch DRI and research. This is a sensitive
1038
+ // setting that can greatly affect model quality and bashing.
1039
+ if (hasThinking && modelSupportsThinking(options.model)) {
1040
+ if (!isEnvTruthy(process.env.THADDEUS_DISABLE_ADAPTIVE_THINKING) &&
1041
+ modelSupportsAdaptiveThinking(options.model)) {
1042
+ // For models that support adaptive thinking, always use adaptive
1043
+ // thinking without a budget.
1044
+ thinking = {
1045
+ type: 'adaptive',
1046
+ };
1047
+ }
1048
+ else {
1049
+ // For models that do not support adaptive thinking, use the default
1050
+ // thinking budget unless explicitly specified.
1051
+ let thinkingBudget = getMaxThinkingTokensForModel(options.model);
1052
+ if (thinkingConfig.type === 'enabled' &&
1053
+ thinkingConfig.budgetTokens !== undefined) {
1054
+ thinkingBudget = thinkingConfig.budgetTokens;
1055
+ }
1056
+ thinkingBudget = Math.min(maxOutputTokens - 1, thinkingBudget);
1057
+ thinking = {
1058
+ budget_tokens: thinkingBudget,
1059
+ type: 'enabled',
1060
+ };
1061
+ }
1062
+ }
1063
+ // Get API context management strategies if enabled
1064
+ const contextManagement = getAPIContextManagement({
1065
+ hasThinking,
1066
+ isRedactThinkingActive: betasParams.includes(REDACT_THINKING_BETA_HEADER),
1067
+ clearAllThinking: thinkingClearLatched,
1068
+ });
1069
+ const enablePromptCaching = options.enablePromptCaching ?? getPromptCachingEnabled(retryContext.model);
1070
+ // Fast mode: header is latched session-stable (cache-safe), but
1071
+ // `speed='fast'` stays dynamic so cooldown still suppresses the actual
1072
+ // fast-mode request without changing the cache key.
1073
+ let speed;
1074
+ const isFastModeForRetry = isFastModeEnabled() &&
1075
+ isFastModeAvailable() &&
1076
+ !isFastModeCooldown() &&
1077
+ isFastModeSupportedByModel(options.model) &&
1078
+ !!retryContext.fastMode;
1079
+ if (isFastModeForRetry) {
1080
+ speed = 'fast';
1081
+ }
1082
+ if (fastModeHeaderLatched && !betasParams.includes(FAST_MODE_BETA_HEADER)) {
1083
+ betasParams.push(FAST_MODE_BETA_HEADER);
1084
+ }
1085
+ // AFK mode beta: latched once auto mode is first activated. Still gated
1086
+ // by isAgenticQuery per-call so classifiers/compaction don't get it.
1087
+ if (feature('TRANSCRIPT_CLASSIFIER')) {
1088
+ if (afkHeaderLatched &&
1089
+ shouldIncludeFirstPartyOnlyBetas() &&
1090
+ isAgenticQuery &&
1091
+ !betasParams.includes(AFK_MODE_BETA_HEADER)) {
1092
+ betasParams.push(AFK_MODE_BETA_HEADER);
1093
+ }
1094
+ }
1095
+ // Cache editing beta: header is latched session-stable; useCachedMC
1096
+ // (controls cache_edits body behavior) stays live so edits stop when
1097
+ // the feature disables but the header doesn't flip.
1098
+ const useCachedMC = cachedMCEnabled &&
1099
+ getAPIProvider() === 'firstParty' &&
1100
+ options.querySource === 'repl_main_thread';
1101
+ if (cacheEditingHeaderLatched &&
1102
+ getAPIProvider() === 'firstParty' &&
1103
+ options.querySource === 'repl_main_thread' &&
1104
+ !betasParams.includes(cacheEditingBetaHeader)) {
1105
+ betasParams.push(cacheEditingBetaHeader);
1106
+ logForDebugging('Cache editing beta header enabled for cached microcompact');
1107
+ }
1108
+ // Only send temperature when thinking is disabled — the API requires
1109
+ // temperature: 1 when thinking is enabled, which is already the default.
1110
+ const temperature = !hasThinking
1111
+ ? (options.temperatureOverride ?? 1)
1112
+ : undefined;
1113
+ lastRequestBetas = betasParams;
1114
+ return {
1115
+ model: normalizeModelStringForAPI(options.model),
1116
+ messages: addCacheBreakpoints(messagesForAPI, enablePromptCaching, options.querySource, useCachedMC, consumedCacheEdits, consumedPinnedEdits, options.skipCacheWrite),
1117
+ system,
1118
+ tools: allTools,
1119
+ tool_choice: options.toolChoice,
1120
+ ...(useBetas && { betas: betasParams }),
1121
+ metadata: getAPIMetadata(),
1122
+ max_tokens: maxOutputTokens,
1123
+ thinking,
1124
+ ...(temperature !== undefined && { temperature }),
1125
+ ...(contextManagement &&
1126
+ useBetas &&
1127
+ betasParams.includes(CONTEXT_MANAGEMENT_BETA_HEADER) && {
1128
+ context_management: contextManagement,
1129
+ }),
1130
+ ...extraBodyParams,
1131
+ ...(Object.keys(outputConfig).length > 0 && {
1132
+ output_config: outputConfig,
1133
+ }),
1134
+ ...(speed !== undefined && { speed }),
1135
+ };
1136
+ };
1137
+ // Compute log scalars synchronously so the fire-and-forget .then() closure
1138
+ // captures only primitives instead of paramsFromContext's full closure scope
1139
+ // (messagesForAPI, system, allTools, betas — the entire request-building
1140
+ // context), which would otherwise be pinned until the promise resolves.
1141
+ {
1142
+ const queryParams = paramsFromContext({
1143
+ model: options.model,
1144
+ thinkingConfig,
1145
+ });
1146
+ const logMessagesLength = queryParams.messages.length;
1147
+ const logBetas = useBetas ? (queryParams.betas ?? []) : [];
1148
+ const logThinkingType = queryParams.thinking?.type ?? 'disabled';
1149
+ const logEffortValue = queryParams.output_config?.effort;
1150
+ void options.getToolPermissionContext().then(permissionContext => {
1151
+ logAPIQuery({
1152
+ model: options.model,
1153
+ messagesLength: logMessagesLength,
1154
+ temperature: options.temperatureOverride ?? 1,
1155
+ betas: logBetas,
1156
+ permissionMode: permissionContext.mode,
1157
+ querySource: options.querySource,
1158
+ queryTracking: options.queryTracking,
1159
+ thinkingType: logThinkingType,
1160
+ effortValue: logEffortValue,
1161
+ fastMode: isFastMode,
1162
+ previousRequestId,
1163
+ });
1164
+ });
1165
+ }
1166
+ const newMessages = [];
1167
+ let ttftMs = 0;
1168
+ let partialMessage = undefined;
1169
+ const contentBlocks = [];
1170
+ let usage = EMPTY_USAGE;
1171
+ let costUSD = 0;
1172
+ let stopReason = null;
1173
+ let didFallBackToNonStreaming = false;
1174
+ let fallbackMessage;
1175
+ let maxOutputTokens = 0;
1176
+ let responseHeaders = undefined;
1177
+ let research = undefined;
1178
+ let isFastModeRequest = isFastMode; // Keep separate state as it may change if falling back
1179
+ let isAdvisorInProgress = false;
1180
+ try {
1181
+ queryCheckpoint('query_client_creation_start');
1182
+ const generator = withRetry(() => getAnthropicClient({
1183
+ maxRetries: 0, // Disabled auto-retry in favor of manual implementation
1184
+ model: options.model,
1185
+ fetchOverride: options.fetchOverride,
1186
+ source: options.querySource,
1187
+ }), async (anthropic, attempt, context) => {
1188
+ attemptNumber = attempt;
1189
+ isFastModeRequest = context.fastMode ?? false;
1190
+ start = Date.now();
1191
+ attemptStartTimes.push(start);
1192
+ // Client has been created by withRetry's getClient() call. This fires
1193
+ // once per attempt; on retries the client is usually cached (withRetry
1194
+ // only calls getClient() again after auth errors), so the delta from
1195
+ // client_creation_start is meaningful on attempt 1.
1196
+ queryCheckpoint('query_client_creation_end');
1197
+ const params = paramsFromContext(context);
1198
+ captureAPIRequest(params, options.querySource); // Capture for bug reports
1199
+ maxOutputTokens = params.max_tokens;
1200
+ // Fire immediately before the fetch is dispatched. .withResponse() below
1201
+ // awaits until response headers arrive, so this MUST be before the await
1202
+ // or the "Network TTFB" phase measurement is wrong.
1203
+ queryCheckpoint('query_api_request_sent');
1204
+ if (!options.agentId) {
1205
+ headlessProfilerCheckpoint('api_request_sent');
1206
+ }
1207
+ // Generate and track client request ID so timeouts (which return no
1208
+ // server request ID) can still be correlated with server logs.
1209
+ // First-party only — 3P providers don't log it (inc-4029 class).
1210
+ clientRequestId =
1211
+ getAPIProvider() === 'firstParty' && isFirstPartyAnthropicBaseUrl()
1212
+ ? randomUUID()
1213
+ : undefined;
1214
+ // Use raw stream instead of BetaMessageStream to avoid O(n²) partial JSON parsing
1215
+ // BetaMessageStream calls partialParse() on every input_json_delta, which we don't need
1216
+ // since we handle tool input accumulation ourselves
1217
+ // biome-ignore lint/plugin: main conversation loop handles attribution separately
1218
+ const result = await anthropic.beta.messages
1219
+ .create({ ...params, stream: true }, {
1220
+ signal,
1221
+ ...(clientRequestId && {
1222
+ headers: { [CLIENT_REQUEST_ID_HEADER]: clientRequestId },
1223
+ }),
1224
+ })
1225
+ .withResponse();
1226
+ queryCheckpoint('query_response_headers_received');
1227
+ streamRequestId = result.request_id;
1228
+ streamResponse = result.response;
1229
+ return result.data;
1230
+ }, {
1231
+ model: options.model,
1232
+ fallbackModel: options.fallbackModel,
1233
+ thinkingConfig,
1234
+ ...(isFastModeEnabled() ? { fastMode: isFastMode } : false),
1235
+ signal,
1236
+ querySource: options.querySource,
1237
+ });
1238
+ let e;
1239
+ do {
1240
+ e = await generator.next();
1241
+ // yield API error messages (the stream has a 'controller' property, error messages don't)
1242
+ if (!('controller' in e.value)) {
1243
+ yield e.value;
1244
+ }
1245
+ } while (!e.done);
1246
+ stream = e.value;
1247
+ // reset state
1248
+ newMessages.length = 0;
1249
+ ttftMs = 0;
1250
+ partialMessage = undefined;
1251
+ contentBlocks.length = 0;
1252
+ usage = EMPTY_USAGE;
1253
+ stopReason = null;
1254
+ isAdvisorInProgress = false;
1255
+ // Streaming idle timeout watchdog: abort the stream if no chunks arrive
1256
+ // for STREAM_IDLE_TIMEOUT_MS. Unlike the stall detection below (which only
1257
+ // fires when the *next* chunk arrives), this uses setTimeout to actively
1258
+ // kill hung streams. Without this, a silently dropped connection can hang
1259
+ // the session indefinitely since the SDK's request timeout only covers the
1260
+ // initial fetch(), not the streaming body.
1261
+ const streamWatchdogEnabled = isEnvTruthy(process.env.CLAUDE_ENABLE_STREAM_WATCHDOG);
1262
+ const STREAM_IDLE_TIMEOUT_MS = parseInt(process.env.CLAUDE_STREAM_IDLE_TIMEOUT_MS || '', 10) || 90_000;
1263
+ const STREAM_IDLE_WARNING_MS = STREAM_IDLE_TIMEOUT_MS / 2;
1264
+ let streamIdleAborted = false;
1265
+ // performance.now() snapshot when watchdog fires, for measuring abort propagation delay
1266
+ let streamWatchdogFiredAt = null;
1267
+ let streamIdleWarningTimer = null;
1268
+ let streamIdleTimer = null;
1269
+ function clearStreamIdleTimers() {
1270
+ if (streamIdleWarningTimer !== null) {
1271
+ clearTimeout(streamIdleWarningTimer);
1272
+ streamIdleWarningTimer = null;
1273
+ }
1274
+ if (streamIdleTimer !== null) {
1275
+ clearTimeout(streamIdleTimer);
1276
+ streamIdleTimer = null;
1277
+ }
1278
+ }
1279
+ function resetStreamIdleTimer() {
1280
+ clearStreamIdleTimers();
1281
+ if (!streamWatchdogEnabled) {
1282
+ return;
1283
+ }
1284
+ streamIdleWarningTimer = setTimeout(warnMs => {
1285
+ logForDebugging(`Streaming idle warning: no chunks received for ${warnMs / 1000}s`, { level: 'warn' });
1286
+ logForDiagnosticsNoPII('warn', 'cli_streaming_idle_warning');
1287
+ }, STREAM_IDLE_WARNING_MS, STREAM_IDLE_WARNING_MS);
1288
+ streamIdleTimer = setTimeout(() => {
1289
+ streamIdleAborted = true;
1290
+ streamWatchdogFiredAt = performance.now();
1291
+ logForDebugging(`Streaming idle timeout: no chunks received for ${STREAM_IDLE_TIMEOUT_MS / 1000}s, aborting stream`, { level: 'error' });
1292
+ logForDiagnosticsNoPII('error', 'cli_streaming_idle_timeout');
1293
+ logEvent('thaddeus_streaming_idle_timeout', {
1294
+ model: options.model,
1295
+ request_id: (streamRequestId ??
1296
+ 'unknown'),
1297
+ timeout_ms: STREAM_IDLE_TIMEOUT_MS,
1298
+ });
1299
+ releaseStreamResources();
1300
+ }, STREAM_IDLE_TIMEOUT_MS);
1301
+ }
1302
+ resetStreamIdleTimer();
1303
+ startSessionActivity('api_call');
1304
+ try {
1305
+ // stream in and accumulate state
1306
+ let isFirstChunk = true;
1307
+ let lastEventTime = null; // Set after first chunk to avoid measuring TTFB as a stall
1308
+ const STALL_THRESHOLD_MS = 30_000; // 30 seconds
1309
+ let totalStallTime = 0;
1310
+ let stallCount = 0;
1311
+ for await (const part of stream) {
1312
+ resetStreamIdleTimer();
1313
+ const now = Date.now();
1314
+ // Detect and log streaming stalls (only after first event to avoid counting TTFB)
1315
+ if (lastEventTime !== null) {
1316
+ const timeSinceLastEvent = now - lastEventTime;
1317
+ if (timeSinceLastEvent > STALL_THRESHOLD_MS) {
1318
+ stallCount++;
1319
+ totalStallTime += timeSinceLastEvent;
1320
+ logForDebugging(`Streaming stall detected: ${(timeSinceLastEvent / 1000).toFixed(1)}s gap between events (stall #${stallCount})`, { level: 'warn' });
1321
+ logEvent('thaddeus_streaming_stall', {
1322
+ stall_duration_ms: timeSinceLastEvent,
1323
+ stall_count: stallCount,
1324
+ total_stall_time_ms: totalStallTime,
1325
+ event_type: part.type,
1326
+ model: options.model,
1327
+ request_id: (streamRequestId ??
1328
+ 'unknown'),
1329
+ });
1330
+ }
1331
+ }
1332
+ lastEventTime = now;
1333
+ if (isFirstChunk) {
1334
+ logForDebugging('Stream started - received first chunk');
1335
+ queryCheckpoint('query_first_chunk_received');
1336
+ if (!options.agentId) {
1337
+ headlessProfilerCheckpoint('first_chunk');
1338
+ }
1339
+ endQueryProfile();
1340
+ isFirstChunk = false;
1341
+ }
1342
+ switch (part.type) {
1343
+ case 'message_start': {
1344
+ partialMessage = part.message;
1345
+ ttftMs = Date.now() - start;
1346
+ usage = updateUsage(usage, part.message?.usage);
1347
+ // Capture research from message_start if available (internal only).
1348
+ // Always overwrite with the latest value.
1349
+ if (process.env.USER_TYPE === 'ant' &&
1350
+ 'research' in part.message) {
1351
+ research = part.message
1352
+ .research;
1353
+ }
1354
+ break;
1355
+ }
1356
+ case 'content_block_start':
1357
+ switch (part.content_block.type) {
1358
+ case 'tool_use':
1359
+ contentBlocks[part.index] = {
1360
+ ...part.content_block,
1361
+ input: '',
1362
+ };
1363
+ break;
1364
+ case 'server_tool_use':
1365
+ contentBlocks[part.index] = {
1366
+ ...part.content_block,
1367
+ input: '',
1368
+ };
1369
+ if (part.content_block.name === 'advisor') {
1370
+ isAdvisorInProgress = true;
1371
+ logForDebugging(`[AdvisorTool] Advisor tool called`);
1372
+ logEvent('thaddeus_advisor_tool_call', {
1373
+ model: options.model,
1374
+ advisor_model: (advisorModel ??
1375
+ 'unknown'),
1376
+ });
1377
+ }
1378
+ break;
1379
+ case 'text':
1380
+ contentBlocks[part.index] = {
1381
+ ...part.content_block,
1382
+ // awkwardly, the sdk sometimes returns text as part of a
1383
+ // content_block_start message, then returns the same text
1384
+ // again in a content_block_delta message. we ignore it here
1385
+ // since there doesn't seem to be a way to detect when a
1386
+ // content_block_delta message duplicates the text.
1387
+ text: '',
1388
+ };
1389
+ break;
1390
+ case 'thinking':
1391
+ contentBlocks[part.index] = {
1392
+ ...part.content_block,
1393
+ // also awkward
1394
+ thinking: '',
1395
+ // initialize signature to ensure field exists even if signature_delta never arrives
1396
+ signature: '',
1397
+ };
1398
+ break;
1399
+ default:
1400
+ // even more awkwardly, the sdk mutates the contents of text blocks
1401
+ // as it works. we want the blocks to be immutable, so that we can
1402
+ // accumulate state ourselves.
1403
+ contentBlocks[part.index] = { ...part.content_block };
1404
+ if (part.content_block.type === 'advisor_tool_result') {
1405
+ isAdvisorInProgress = false;
1406
+ logForDebugging(`[AdvisorTool] Advisor tool result received`);
1407
+ }
1408
+ break;
1409
+ }
1410
+ break;
1411
+ case 'content_block_delta': {
1412
+ const contentBlock = contentBlocks[part.index];
1413
+ const delta = part.delta;
1414
+ if (!contentBlock) {
1415
+ logEvent('thaddeus_streaming_error', {
1416
+ error_type: 'content_block_not_found_delta',
1417
+ part_type: part.type,
1418
+ part_index: part.index,
1419
+ });
1420
+ throw new RangeError('Content block not found');
1421
+ }
1422
+ if (feature('CONNECTOR_TEXT') &&
1423
+ delta.type === 'connector_text_delta') {
1424
+ if (contentBlock.type !== 'connector_text') {
1425
+ logEvent('thaddeus_streaming_error', {
1426
+ error_type: 'content_block_type_mismatch_connector_text',
1427
+ expected_type: 'connector_text',
1428
+ actual_type: contentBlock.type,
1429
+ });
1430
+ throw new Error('Content block is not a connector_text block');
1431
+ }
1432
+ contentBlock.connector_text += delta.connector_text;
1433
+ }
1434
+ else {
1435
+ switch (delta.type) {
1436
+ case 'citations_delta':
1437
+ // TODO: handle citations
1438
+ break;
1439
+ case 'input_json_delta':
1440
+ if (contentBlock.type !== 'tool_use' &&
1441
+ contentBlock.type !== 'server_tool_use') {
1442
+ logEvent('thaddeus_streaming_error', {
1443
+ error_type: 'content_block_type_mismatch_input_json',
1444
+ expected_type: 'tool_use',
1445
+ actual_type: contentBlock.type,
1446
+ });
1447
+ throw new Error('Content block is not a input_json block');
1448
+ }
1449
+ if (typeof contentBlock.input !== 'string') {
1450
+ logEvent('thaddeus_streaming_error', {
1451
+ error_type: 'content_block_input_not_string',
1452
+ input_type: typeof contentBlock.input,
1453
+ });
1454
+ throw new Error('Content block input is not a string');
1455
+ }
1456
+ contentBlock.input += delta.partial_json;
1457
+ break;
1458
+ case 'text_delta':
1459
+ if (contentBlock.type !== 'text') {
1460
+ logEvent('thaddeus_streaming_error', {
1461
+ error_type: 'content_block_type_mismatch_text',
1462
+ expected_type: 'text',
1463
+ actual_type: contentBlock.type,
1464
+ });
1465
+ throw new Error('Content block is not a text block');
1466
+ }
1467
+ // Decode HTML entities from xAI/Grok responses (&#39; → ', &amp; → &, etc.)
1468
+ contentBlock.text += delta.text.includes('&')
1469
+ ? delta.text
1470
+ .replace(/&amp;/g, '&')
1471
+ .replace(/&lt;/g, '<')
1472
+ .replace(/&gt;/g, '>')
1473
+ .replace(/&quot;/g, '"')
1474
+ .replace(/&apos;/g, "'")
1475
+ .replace(/&nbsp;/g, ' ')
1476
+ .replace(/&#(\d+);/g, (_m, code) => String.fromCharCode(parseInt(code, 10)))
1477
+ .replace(/&#x([0-9a-fA-F]+);/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16)))
1478
+ : delta.text;
1479
+ break;
1480
+ case 'signature_delta':
1481
+ if (feature('CONNECTOR_TEXT') &&
1482
+ contentBlock.type === 'connector_text') {
1483
+ contentBlock.signature = delta.signature;
1484
+ break;
1485
+ }
1486
+ if (contentBlock.type !== 'thinking') {
1487
+ logEvent('thaddeus_streaming_error', {
1488
+ error_type: 'content_block_type_mismatch_thinking_signature',
1489
+ expected_type: 'thinking',
1490
+ actual_type: contentBlock.type,
1491
+ });
1492
+ throw new Error('Content block is not a thinking block');
1493
+ }
1494
+ contentBlock.signature = delta.signature;
1495
+ break;
1496
+ case 'thinking_delta':
1497
+ if (contentBlock.type !== 'thinking') {
1498
+ logEvent('thaddeus_streaming_error', {
1499
+ error_type: 'content_block_type_mismatch_thinking_delta',
1500
+ expected_type: 'thinking',
1501
+ actual_type: contentBlock.type,
1502
+ });
1503
+ throw new Error('Content block is not a thinking block');
1504
+ }
1505
+ contentBlock.thinking += delta.thinking;
1506
+ break;
1507
+ }
1508
+ }
1509
+ // Capture research from content_block_delta if available (internal only).
1510
+ // Always overwrite with the latest value.
1511
+ if (process.env.USER_TYPE === 'ant' && 'research' in part) {
1512
+ research = part.research;
1513
+ }
1514
+ break;
1515
+ }
1516
+ case 'content_block_stop': {
1517
+ const contentBlock = contentBlocks[part.index];
1518
+ if (!contentBlock) {
1519
+ logEvent('thaddeus_streaming_error', {
1520
+ error_type: 'content_block_not_found_stop',
1521
+ part_type: part.type,
1522
+ part_index: part.index,
1523
+ });
1524
+ throw new RangeError('Content block not found');
1525
+ }
1526
+ if (!partialMessage) {
1527
+ logEvent('thaddeus_streaming_error', {
1528
+ error_type: 'partial_message_not_found',
1529
+ part_type: part.type,
1530
+ });
1531
+ throw new Error('Message not found');
1532
+ }
1533
+ const m = {
1534
+ message: {
1535
+ ...partialMessage,
1536
+ content: normalizeContentFromAPI([contentBlock], tools, options.agentId),
1537
+ },
1538
+ requestId: streamRequestId ?? undefined,
1539
+ type: 'assistant',
1540
+ uuid: randomUUID(),
1541
+ timestamp: new Date().toISOString(),
1542
+ ...(process.env.USER_TYPE === 'ant' &&
1543
+ research !== undefined && { research }),
1544
+ ...(advisorModel && { advisorModel }),
1545
+ };
1546
+ newMessages.push(m);
1547
+ yield m;
1548
+ break;
1549
+ }
1550
+ case 'message_delta': {
1551
+ usage = updateUsage(usage, part.usage);
1552
+ // Capture research from message_delta if available (internal only).
1553
+ // Always overwrite with the latest value. Also write back to
1554
+ // already-yielded messages since message_delta arrives after
1555
+ // content_block_stop.
1556
+ if (process.env.USER_TYPE === 'ant' &&
1557
+ 'research' in part) {
1558
+ research = part.research;
1559
+ for (const msg of newMessages) {
1560
+ msg.research = research;
1561
+ }
1562
+ }
1563
+ // Write final usage and stop_reason back to the last yielded
1564
+ // message. Messages are created at content_block_stop from
1565
+ // partialMessage, which was set at message_start before any tokens
1566
+ // were generated (output_tokens: 0, stop_reason: null).
1567
+ // message_delta arrives after content_block_stop with the real
1568
+ // values.
1569
+ //
1570
+ // IMPORTANT: Use direct property mutation, not object replacement.
1571
+ // The transcript write queue holds a reference to message.message
1572
+ // and serializes it lazily (100ms flush interval). Object
1573
+ // replacement ({ ...lastMsg.message, usage }) would disconnect
1574
+ // the queued reference; direct mutation ensures the transcript
1575
+ // captures the final values.
1576
+ stopReason = part.delta.stop_reason;
1577
+ const lastMsg = newMessages.at(-1);
1578
+ if (lastMsg) {
1579
+ lastMsg.message.usage = usage;
1580
+ lastMsg.message.stop_reason = stopReason;
1581
+ }
1582
+ // Update cost
1583
+ const costUSDForPart = calculateUSDCost(resolvedModel, usage);
1584
+ costUSD += addToTotalSessionCost(costUSDForPart, usage, options.model);
1585
+ const refusalMessage = getErrorMessageIfRefusal(part.delta.stop_reason, options.model);
1586
+ if (refusalMessage) {
1587
+ yield refusalMessage;
1588
+ }
1589
+ if (stopReason === 'max_tokens') {
1590
+ logEvent('thaddeus_max_tokens_reached', {
1591
+ max_tokens: maxOutputTokens,
1592
+ });
1593
+ yield createAssistantAPIErrorMessage({
1594
+ content: `${API_ERROR_MESSAGE_PREFIX}: The response exceeded the ${maxOutputTokens} output token maximum. To configure this behavior, set the THADDEUS_MAX_OUTPUT_TOKENS environment variable.`,
1595
+ apiError: 'max_output_tokens',
1596
+ error: 'max_output_tokens',
1597
+ });
1598
+ }
1599
+ if (stopReason === 'model_context_window_exceeded') {
1600
+ logEvent('thaddeus_context_window_exceeded', {
1601
+ max_tokens: maxOutputTokens,
1602
+ output_tokens: usage.output_tokens,
1603
+ });
1604
+ // Reuse the max_output_tokens recovery path — from the model's
1605
+ // perspective, both mean "response was cut off, continue from
1606
+ // where you left off."
1607
+ yield createAssistantAPIErrorMessage({
1608
+ content: `${API_ERROR_MESSAGE_PREFIX}: The model has reached its context window limit.`,
1609
+ apiError: 'max_output_tokens',
1610
+ error: 'max_output_tokens',
1611
+ });
1612
+ }
1613
+ break;
1614
+ }
1615
+ case 'message_stop':
1616
+ break;
1617
+ }
1618
+ yield {
1619
+ type: 'stream_event',
1620
+ event: part,
1621
+ ...(part.type === 'message_start' ? { ttftMs } : undefined),
1622
+ };
1623
+ }
1624
+ // Clear the idle timeout watchdog now that the stream loop has exited
1625
+ clearStreamIdleTimers();
1626
+ // If the stream was aborted by our idle timeout watchdog, fall back to
1627
+ // non-streaming retry rather than treating it as a completed stream.
1628
+ if (streamIdleAborted) {
1629
+ // Instrumentation: proves the for-await exited after the watchdog fired
1630
+ // (vs. hung forever). exit_delay_ms measures abort propagation latency:
1631
+ // 0-10ms = abort worked; >>1000ms = something else woke the loop.
1632
+ const exitDelayMs = streamWatchdogFiredAt !== null
1633
+ ? Math.round(performance.now() - streamWatchdogFiredAt)
1634
+ : -1;
1635
+ logForDiagnosticsNoPII('info', 'cli_stream_loop_exited_after_watchdog_clean');
1636
+ logEvent('thaddeus_stream_loop_exited_after_watchdog', {
1637
+ request_id: (streamRequestId ??
1638
+ 'unknown'),
1639
+ exit_delay_ms: exitDelayMs,
1640
+ exit_path: 'clean',
1641
+ model: options.model,
1642
+ });
1643
+ // Prevent double-emit: this throw lands in the catch block below,
1644
+ // whose exit_path='error' probe guards on streamWatchdogFiredAt.
1645
+ streamWatchdogFiredAt = null;
1646
+ throw new Error('Stream idle timeout - no chunks received');
1647
+ }
1648
+ // Detect when the stream completed without producing any assistant messages.
1649
+ // This covers two proxy failure modes:
1650
+ // 1. No events at all (!partialMessage): proxy returned 200 with non-SSE body
1651
+ // 2. Partial events (partialMessage set but no content blocks completed AND
1652
+ // no stop_reason received): proxy returned message_start but stream ended
1653
+ // before content_block_stop and before message_delta with stop_reason
1654
+ // BetaMessageStream had the first check in _endRequest() but the raw Stream
1655
+ // does not - without it the generator silently returns no assistant messages,
1656
+ // causing "Execution error" in -p mode.
1657
+ // Note: We must check stopReason to avoid false positives. For example, with
1658
+ // structured output (--json-schema), the model calls a StructuredOutput tool
1659
+ // on turn 1, then on turn 2 responds with end_turn and no content blocks.
1660
+ // That's a legitimate empty response, not an incomplete stream.
1661
+ if (!partialMessage || (newMessages.length === 0 && !stopReason)) {
1662
+ logForDebugging(!partialMessage
1663
+ ? 'Stream completed without receiving message_start event - triggering non-streaming fallback'
1664
+ : 'Stream completed with message_start but no content blocks completed - triggering non-streaming fallback', { level: 'error' });
1665
+ logEvent('thaddeus_stream_no_events', {
1666
+ model: options.model,
1667
+ request_id: (streamRequestId ??
1668
+ 'unknown'),
1669
+ });
1670
+ throw new Error('Stream ended without receiving any events');
1671
+ }
1672
+ // Log summary if any stalls occurred during streaming
1673
+ if (stallCount > 0) {
1674
+ logForDebugging(`Streaming completed with ${stallCount} stall(s), total stall time: ${(totalStallTime / 1000).toFixed(1)}s`, { level: 'warn' });
1675
+ logEvent('thaddeus_streaming_stall_summary', {
1676
+ stall_count: stallCount,
1677
+ total_stall_time_ms: totalStallTime,
1678
+ model: options.model,
1679
+ request_id: (streamRequestId ??
1680
+ 'unknown'),
1681
+ });
1682
+ }
1683
+ // Check if the cache actually broke based on response tokens
1684
+ if (feature('PROMPT_CACHE_BREAK_DETECTION')) {
1685
+ void checkResponseForCacheBreak(options.querySource, usage.cache_read_input_tokens, usage.cache_creation_input_tokens, messages, options.agentId, streamRequestId);
1686
+ }
1687
+ // Process fallback percentage header and quota status if available
1688
+ // streamResponse is set when the stream is created in the withRetry callback above
1689
+ // TypeScript's control flow analysis can't track that streamResponse is set in the callback
1690
+ // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
1691
+ const resp = streamResponse;
1692
+ if (resp) {
1693
+ extractQuotaStatusFromHeaders(resp.headers);
1694
+ // Store headers for gateway detection
1695
+ responseHeaders = resp.headers;
1696
+ }
1697
+ }
1698
+ catch (streamingError) {
1699
+ // Clear the idle timeout watchdog on error path too
1700
+ clearStreamIdleTimers();
1701
+ // Instrumentation: if the watchdog had already fired and the for-await
1702
+ // threw (rather than exiting cleanly), record that the loop DID exit and
1703
+ // how long after the watchdog. Distinguishes true hangs from error exits.
1704
+ if (streamIdleAborted && streamWatchdogFiredAt !== null) {
1705
+ const exitDelayMs = Math.round(performance.now() - streamWatchdogFiredAt);
1706
+ logForDiagnosticsNoPII('info', 'cli_stream_loop_exited_after_watchdog_error');
1707
+ logEvent('thaddeus_stream_loop_exited_after_watchdog', {
1708
+ request_id: (streamRequestId ??
1709
+ 'unknown'),
1710
+ exit_delay_ms: exitDelayMs,
1711
+ exit_path: 'error',
1712
+ error_name: streamingError instanceof Error
1713
+ ? streamingError.name
1714
+ : 'unknown',
1715
+ model: options.model,
1716
+ });
1717
+ }
1718
+ if (streamingError instanceof APIUserAbortError) {
1719
+ // Check if the abort signal was triggered by the user (ESC key)
1720
+ // If the signal is aborted, it's a user-initiated abort
1721
+ // If not, it's likely a timeout from the SDK
1722
+ if (signal.aborted) {
1723
+ // This is a real user abort (ESC key was pressed)
1724
+ logForDebugging(`Streaming aborted by user: ${errorMessage(streamingError)}`);
1725
+ if (isAdvisorInProgress) {
1726
+ logEvent('thaddeus_advisor_tool_interrupted', {
1727
+ model: options.model,
1728
+ advisor_model: (advisorModel ??
1729
+ 'unknown'),
1730
+ });
1731
+ }
1732
+ throw streamingError;
1733
+ }
1734
+ else {
1735
+ // The SDK threw APIUserAbortError but our signal wasn't aborted
1736
+ // This means it's a timeout from the SDK's internal timeout
1737
+ logForDebugging(`Streaming timeout (SDK abort): ${streamingError.message}`, { level: 'error' });
1738
+ // Throw a more specific error for timeout
1739
+ throw new APIConnectionTimeoutError({ message: 'Request timed out' });
1740
+ }
1741
+ }
1742
+ // When the flag is enabled, skip the non-streaming fallback and let the
1743
+ // error propagate to withRetry. The mid-stream fallback causes double tool
1744
+ // execution when streaming tool execution is active: the partial stream
1745
+ // starts a tool, then the non-streaming retry produces the same tool_use
1746
+ // and runs it again. See inc-4258.
1747
+ const disableFallback = isEnvTruthy(process.env.THADDEUS_DISABLE_NONSTREAMING_FALLBACK) ||
1748
+ getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_disable_streaming_to_non_streaming_fallback', false);
1749
+ if (disableFallback) {
1750
+ logForDebugging(`Error streaming (non-streaming fallback disabled): ${errorMessage(streamingError)}`, { level: 'error' });
1751
+ logEvent('thaddeus_streaming_fallback_to_non_streaming', {
1752
+ model: options.model,
1753
+ error: streamingError instanceof Error
1754
+ ? streamingError.name
1755
+ : String(streamingError),
1756
+ attemptNumber,
1757
+ maxOutputTokens,
1758
+ thinkingType: thinkingConfig.type,
1759
+ fallback_disabled: true,
1760
+ request_id: (streamRequestId ??
1761
+ 'unknown'),
1762
+ fallback_cause: (streamIdleAborted
1763
+ ? 'watchdog'
1764
+ : 'other'),
1765
+ });
1766
+ throw streamingError;
1767
+ }
1768
+ logForDebugging(`Error streaming, falling back to non-streaming mode: ${errorMessage(streamingError)}`, { level: 'error' });
1769
+ didFallBackToNonStreaming = true;
1770
+ if (options.onStreamingFallback) {
1771
+ options.onStreamingFallback();
1772
+ }
1773
+ logEvent('thaddeus_streaming_fallback_to_non_streaming', {
1774
+ model: options.model,
1775
+ error: streamingError instanceof Error
1776
+ ? streamingError.name
1777
+ : String(streamingError),
1778
+ attemptNumber,
1779
+ maxOutputTokens,
1780
+ thinkingType: thinkingConfig.type,
1781
+ fallback_disabled: false,
1782
+ request_id: (streamRequestId ??
1783
+ 'unknown'),
1784
+ fallback_cause: (streamIdleAborted
1785
+ ? 'watchdog'
1786
+ : 'other'),
1787
+ });
1788
+ // Fall back to non-streaming mode with retries.
1789
+ // If the streaming failure was itself a 529, count it toward the
1790
+ // consecutive-529 budget so total 529s-before-model-fallback is the
1791
+ // same whether the overload was hit in streaming or non-streaming mode.
1792
+ // This is a speculative fix for https://github.com/anthropics/claude-code/issues/1513
1793
+ // Instrumentation: proves executeNonStreamingRequest was entered (vs. the
1794
+ // fallback event firing but the call itself hanging at dispatch).
1795
+ logForDiagnosticsNoPII('info', 'cli_nonstreaming_fallback_started');
1796
+ logEvent('thaddeus_nonstreaming_fallback_started', {
1797
+ request_id: (streamRequestId ??
1798
+ 'unknown'),
1799
+ model: options.model,
1800
+ fallback_cause: (streamIdleAborted
1801
+ ? 'watchdog'
1802
+ : 'other'),
1803
+ });
1804
+ const result = yield* executeNonStreamingRequest({ model: options.model, source: options.querySource }, {
1805
+ model: options.model,
1806
+ fallbackModel: options.fallbackModel,
1807
+ thinkingConfig,
1808
+ ...(isFastModeEnabled() && { fastMode: isFastMode }),
1809
+ signal,
1810
+ initialConsecutive529Errors: is529Error(streamingError) ? 1 : 0,
1811
+ querySource: options.querySource,
1812
+ }, paramsFromContext, (attempt, _startTime, tokens) => {
1813
+ attemptNumber = attempt;
1814
+ maxOutputTokens = tokens;
1815
+ }, params => captureAPIRequest(params, options.querySource), streamRequestId);
1816
+ const m = {
1817
+ message: {
1818
+ ...result,
1819
+ content: normalizeContentFromAPI(result.content, tools, options.agentId),
1820
+ },
1821
+ requestId: streamRequestId ?? undefined,
1822
+ type: 'assistant',
1823
+ uuid: randomUUID(),
1824
+ timestamp: new Date().toISOString(),
1825
+ ...(process.env.USER_TYPE === 'ant' &&
1826
+ research !== undefined && {
1827
+ research,
1828
+ }),
1829
+ ...(advisorModel && {
1830
+ advisorModel,
1831
+ }),
1832
+ };
1833
+ newMessages.push(m);
1834
+ fallbackMessage = m;
1835
+ yield m;
1836
+ }
1837
+ finally {
1838
+ clearStreamIdleTimers();
1839
+ }
1840
+ }
1841
+ catch (errorFromRetry) {
1842
+ // FallbackTriggeredError must propagate to query.ts, which performs the
1843
+ // actual model switch. Swallowing it here would turn the fallback into a
1844
+ // no-op — the user would just see "Model fallback triggered: X -> Y" as
1845
+ // an error message with no actual retry on the fallback model.
1846
+ if (errorFromRetry instanceof FallbackTriggeredError) {
1847
+ throw errorFromRetry;
1848
+ }
1849
+ // Check if this is a 404 error during stream creation that should trigger
1850
+ // non-streaming fallback. This handles gateways that return 404 for streaming
1851
+ // endpoints but work fine with non-streaming. Before v2.1.8, BetaMessageStream
1852
+ // threw 404s during iteration (caught by inner catch with fallback), but now
1853
+ // with raw streams, 404s are thrown during creation (caught here).
1854
+ const is404StreamCreationError = !didFallBackToNonStreaming &&
1855
+ errorFromRetry instanceof CannotRetryError &&
1856
+ errorFromRetry.originalError instanceof APIError &&
1857
+ errorFromRetry.originalError.status === 404;
1858
+ if (is404StreamCreationError) {
1859
+ // 404 is thrown at .withResponse() before streamRequestId is assigned,
1860
+ // and CannotRetryError means every retry failed — so grab the failed
1861
+ // request's ID from the error header instead.
1862
+ const failedRequestId = errorFromRetry.originalError.requestID ?? 'unknown';
1863
+ logForDebugging('Streaming endpoint returned 404, falling back to non-streaming mode', { level: 'warn' });
1864
+ didFallBackToNonStreaming = true;
1865
+ if (options.onStreamingFallback) {
1866
+ options.onStreamingFallback();
1867
+ }
1868
+ logEvent('thaddeus_streaming_fallback_to_non_streaming', {
1869
+ model: options.model,
1870
+ error: '404_stream_creation',
1871
+ attemptNumber,
1872
+ maxOutputTokens,
1873
+ thinkingType: thinkingConfig.type,
1874
+ request_id: failedRequestId,
1875
+ fallback_cause: '404_stream_creation',
1876
+ });
1877
+ try {
1878
+ // Fall back to non-streaming mode
1879
+ const result = yield* executeNonStreamingRequest({ model: options.model, source: options.querySource }, {
1880
+ model: options.model,
1881
+ fallbackModel: options.fallbackModel,
1882
+ thinkingConfig,
1883
+ ...(isFastModeEnabled() && { fastMode: isFastMode }),
1884
+ signal,
1885
+ }, paramsFromContext, (attempt, _startTime, tokens) => {
1886
+ attemptNumber = attempt;
1887
+ maxOutputTokens = tokens;
1888
+ }, params => captureAPIRequest(params, options.querySource), failedRequestId);
1889
+ const m = {
1890
+ message: {
1891
+ ...result,
1892
+ content: normalizeContentFromAPI(result.content, tools, options.agentId),
1893
+ },
1894
+ requestId: streamRequestId ?? undefined,
1895
+ type: 'assistant',
1896
+ uuid: randomUUID(),
1897
+ timestamp: new Date().toISOString(),
1898
+ ...(process.env.USER_TYPE === 'ant' &&
1899
+ research !== undefined && { research }),
1900
+ ...(advisorModel && { advisorModel }),
1901
+ };
1902
+ newMessages.push(m);
1903
+ fallbackMessage = m;
1904
+ yield m;
1905
+ // Continue to success logging below
1906
+ }
1907
+ catch (fallbackError) {
1908
+ // Propagate model-fallback signal to query.ts (see comment above).
1909
+ if (fallbackError instanceof FallbackTriggeredError) {
1910
+ throw fallbackError;
1911
+ }
1912
+ // Fallback also failed, handle as normal error
1913
+ logForDebugging(`Non-streaming fallback also failed: ${errorMessage(fallbackError)}`, { level: 'error' });
1914
+ let error = fallbackError;
1915
+ let errorModel = options.model;
1916
+ if (fallbackError instanceof CannotRetryError) {
1917
+ error = fallbackError.originalError;
1918
+ errorModel = fallbackError.retryContext.model;
1919
+ }
1920
+ if (error instanceof APIError) {
1921
+ extractQuotaStatusFromError(error);
1922
+ }
1923
+ const requestId = streamRequestId ||
1924
+ (error instanceof APIError ? error.requestID : undefined) ||
1925
+ (error instanceof APIError
1926
+ ? error.error?.request_id
1927
+ : undefined);
1928
+ logAPIError({
1929
+ error,
1930
+ model: errorModel,
1931
+ messageCount: messagesForAPI.length,
1932
+ messageTokens: tokenCountFromLastAPIResponse(messagesForAPI),
1933
+ durationMs: Date.now() - start,
1934
+ durationMsIncludingRetries: Date.now() - startIncludingRetries,
1935
+ attempt: attemptNumber,
1936
+ requestId,
1937
+ clientRequestId,
1938
+ didFallBackToNonStreaming,
1939
+ queryTracking: options.queryTracking,
1940
+ querySource: options.querySource,
1941
+ llmSpan,
1942
+ fastMode: isFastModeRequest,
1943
+ previousRequestId,
1944
+ });
1945
+ if (error instanceof APIUserAbortError) {
1946
+ releaseStreamResources();
1947
+ return;
1948
+ }
1949
+ yield getAssistantMessageFromError(error, errorModel, {
1950
+ messages,
1951
+ messagesForAPI,
1952
+ });
1953
+ releaseStreamResources();
1954
+ return;
1955
+ }
1956
+ }
1957
+ else {
1958
+ // Original error handling for non-404 errors
1959
+ logForDebugging(`Error in API request: ${errorMessage(errorFromRetry)}`, {
1960
+ level: 'error',
1961
+ });
1962
+ let error = errorFromRetry;
1963
+ let errorModel = options.model;
1964
+ if (errorFromRetry instanceof CannotRetryError) {
1965
+ error = errorFromRetry.originalError;
1966
+ errorModel = errorFromRetry.retryContext.model;
1967
+ }
1968
+ // Extract quota status from error headers if it's a rate limit error
1969
+ if (error instanceof APIError) {
1970
+ extractQuotaStatusFromError(error);
1971
+ }
1972
+ // Extract requestId from stream, error header, or error body
1973
+ const requestId = streamRequestId ||
1974
+ (error instanceof APIError ? error.requestID : undefined) ||
1975
+ (error instanceof APIError
1976
+ ? error.error?.request_id
1977
+ : undefined);
1978
+ logAPIError({
1979
+ error,
1980
+ model: errorModel,
1981
+ messageCount: messagesForAPI.length,
1982
+ messageTokens: tokenCountFromLastAPIResponse(messagesForAPI),
1983
+ durationMs: Date.now() - start,
1984
+ durationMsIncludingRetries: Date.now() - startIncludingRetries,
1985
+ attempt: attemptNumber,
1986
+ requestId,
1987
+ clientRequestId,
1988
+ didFallBackToNonStreaming,
1989
+ queryTracking: options.queryTracking,
1990
+ querySource: options.querySource,
1991
+ llmSpan,
1992
+ fastMode: isFastModeRequest,
1993
+ previousRequestId,
1994
+ });
1995
+ // Don't yield an assistant error message for user aborts
1996
+ // The interruption message is handled in query.ts
1997
+ if (error instanceof APIUserAbortError) {
1998
+ releaseStreamResources();
1999
+ return;
2000
+ }
2001
+ yield getAssistantMessageFromError(error, errorModel, {
2002
+ messages,
2003
+ messagesForAPI,
2004
+ });
2005
+ releaseStreamResources();
2006
+ return;
2007
+ }
2008
+ }
2009
+ finally {
2010
+ stopSessionActivity('api_call');
2011
+ // Must be in the finally block: if the generator is terminated early
2012
+ // via .return() (e.g. consumer breaks out of for-await-of, or query.ts
2013
+ // encounters an abort), code after the try/finally never executes.
2014
+ // Without this, the Response object's native TLS/socket buffers leak
2015
+ // until the generator itself is GC'd (see GH #32920).
2016
+ releaseStreamResources();
2017
+ // Non-streaming fallback cost: the streaming path tracks cost in the
2018
+ // message_delta handler before any yield. Fallback pushes to newMessages
2019
+ // then yields, so tracking must be here to survive .return() at the yield.
2020
+ if (fallbackMessage) {
2021
+ const fallbackUsage = fallbackMessage.message.usage;
2022
+ usage = updateUsage(EMPTY_USAGE, fallbackUsage);
2023
+ stopReason = fallbackMessage.message.stop_reason;
2024
+ const fallbackCost = calculateUSDCost(resolvedModel, fallbackUsage);
2025
+ costUSD += addToTotalSessionCost(fallbackCost, fallbackUsage, options.model);
2026
+ }
2027
+ }
2028
+ // Mark all registered tools as sent to API so they become eligible for deletion
2029
+ if (feature('CACHED_MICROCOMPACT') && cachedMCEnabled) {
2030
+ markToolsSentToAPIState();
2031
+ }
2032
+ // Track the last requestId for the main conversation chain so shutdown
2033
+ // can send a cache eviction hint to inference. Exclude backgrounded
2034
+ // sessions (Ctrl+B) which share the repl_main_thread querySource but
2035
+ // run inside an agent context — they are independent conversation chains
2036
+ // whose cache should not be evicted when the foreground session clears.
2037
+ if (streamRequestId &&
2038
+ !getAgentContext() &&
2039
+ (options.querySource.startsWith('repl_main_thread') ||
2040
+ options.querySource === 'sdk')) {
2041
+ setLastMainRequestId(streamRequestId);
2042
+ }
2043
+ // Precompute scalars so the fire-and-forget .then() closure doesn't pin the
2044
+ // full messagesForAPI array (the entire conversation up to the context window
2045
+ // limit) until getToolPermissionContext() resolves.
2046
+ const logMessageCount = messagesForAPI.length;
2047
+ const logMessageTokens = tokenCountFromLastAPIResponse(messagesForAPI);
2048
+ void options.getToolPermissionContext().then(permissionContext => {
2049
+ logAPISuccessAndDuration({
2050
+ model: newMessages[0]?.message.model ?? partialMessage?.model ?? options.model,
2051
+ preNormalizedModel: options.model,
2052
+ usage,
2053
+ start,
2054
+ startIncludingRetries,
2055
+ attempt: attemptNumber,
2056
+ messageCount: logMessageCount,
2057
+ messageTokens: logMessageTokens,
2058
+ requestId: streamRequestId ?? null,
2059
+ stopReason,
2060
+ ttftMs,
2061
+ didFallBackToNonStreaming,
2062
+ querySource: options.querySource,
2063
+ headers: responseHeaders,
2064
+ costUSD,
2065
+ queryTracking: options.queryTracking,
2066
+ permissionMode: permissionContext.mode,
2067
+ // Pass newMessages for beta tracing - extraction happens in logging.ts
2068
+ // only when beta tracing is enabled
2069
+ newMessages,
2070
+ llmSpan,
2071
+ globalCacheStrategy,
2072
+ requestSetupMs: start - startIncludingRetries,
2073
+ attemptStartTimes,
2074
+ fastMode: isFastModeRequest,
2075
+ previousRequestId,
2076
+ betas: lastRequestBetas,
2077
+ });
2078
+ });
2079
+ // Defensive: also release on normal completion (no-op if finally already ran).
2080
+ releaseStreamResources();
2081
+ }
2082
+ /**
2083
+ * Cleans up stream resources to prevent memory leaks.
2084
+ * @internal Exported for testing
2085
+ */
2086
+ export function cleanupStream(stream) {
2087
+ if (!stream) {
2088
+ return;
2089
+ }
2090
+ try {
2091
+ // Abort the stream via its controller if not already aborted
2092
+ if (!stream.controller.signal.aborted) {
2093
+ stream.controller.abort();
2094
+ }
2095
+ }
2096
+ catch {
2097
+ // Ignore - stream may already be closed
2098
+ }
2099
+ }
2100
+ /**
2101
+ * Updates usage statistics with new values from streaming API events.
2102
+ * Note: The streaming API provides cumulative usage totals, not incremental deltas.
2103
+ * Each event contains the complete usage up to that point in the stream.
2104
+ *
2105
+ * Input-related tokens (input_tokens, cache_creation_input_tokens, cache_read_input_tokens)
2106
+ * are typically set in message_start and remain constant. message_delta events may send
2107
+ * explicit 0 values for these fields, which should not overwrite the values from message_start.
2108
+ * We only update these fields if they have a non-null, non-zero value.
2109
+ */
2110
+ export function updateUsage(usage, partUsage) {
2111
+ if (!partUsage) {
2112
+ return { ...usage };
2113
+ }
2114
+ return {
2115
+ input_tokens: partUsage.input_tokens !== null && partUsage.input_tokens > 0
2116
+ ? partUsage.input_tokens
2117
+ : usage.input_tokens,
2118
+ cache_creation_input_tokens: partUsage.cache_creation_input_tokens !== null &&
2119
+ partUsage.cache_creation_input_tokens > 0
2120
+ ? partUsage.cache_creation_input_tokens
2121
+ : usage.cache_creation_input_tokens,
2122
+ cache_read_input_tokens: partUsage.cache_read_input_tokens !== null &&
2123
+ partUsage.cache_read_input_tokens > 0
2124
+ ? partUsage.cache_read_input_tokens
2125
+ : usage.cache_read_input_tokens,
2126
+ output_tokens: partUsage.output_tokens ?? usage.output_tokens,
2127
+ server_tool_use: {
2128
+ web_search_requests: partUsage.server_tool_use?.web_search_requests ??
2129
+ usage.server_tool_use.web_search_requests,
2130
+ web_fetch_requests: partUsage.server_tool_use?.web_fetch_requests ??
2131
+ usage.server_tool_use.web_fetch_requests,
2132
+ },
2133
+ service_tier: usage.service_tier,
2134
+ cache_creation: {
2135
+ // SDK type BetaMessageDeltaUsage is missing cache_creation, but it's real!
2136
+ ephemeral_1h_input_tokens: partUsage.cache_creation?.ephemeral_1h_input_tokens ??
2137
+ usage.cache_creation.ephemeral_1h_input_tokens,
2138
+ ephemeral_5m_input_tokens: partUsage.cache_creation?.ephemeral_5m_input_tokens ??
2139
+ usage.cache_creation.ephemeral_5m_input_tokens,
2140
+ },
2141
+ // cache_deleted_input_tokens: returned by the API when cache editing
2142
+ // deletes KV cache content, but not in SDK types. Kept off NonNullableUsage
2143
+ // so the string is eliminated from external builds by dead code elimination.
2144
+ // Uses the same > 0 guard as other token fields to prevent message_delta
2145
+ // from overwriting the real value with 0.
2146
+ ...(feature('CACHED_MICROCOMPACT')
2147
+ ? {
2148
+ cache_deleted_input_tokens: partUsage
2149
+ .cache_deleted_input_tokens != null &&
2150
+ partUsage
2151
+ .cache_deleted_input_tokens > 0
2152
+ ? partUsage
2153
+ .cache_deleted_input_tokens
2154
+ : (usage
2155
+ .cache_deleted_input_tokens ?? 0),
2156
+ }
2157
+ : {}),
2158
+ inference_geo: usage.inference_geo,
2159
+ iterations: partUsage.iterations ?? usage.iterations,
2160
+ speed: partUsage.speed ?? usage.speed,
2161
+ };
2162
+ }
2163
+ /**
2164
+ * Accumulates usage from one message into a total usage object.
2165
+ * Used to track cumulative usage across multiple assistant turns.
2166
+ */
2167
+ export function accumulateUsage(totalUsage, messageUsage) {
2168
+ return {
2169
+ input_tokens: totalUsage.input_tokens + messageUsage.input_tokens,
2170
+ cache_creation_input_tokens: totalUsage.cache_creation_input_tokens +
2171
+ messageUsage.cache_creation_input_tokens,
2172
+ cache_read_input_tokens: totalUsage.cache_read_input_tokens + messageUsage.cache_read_input_tokens,
2173
+ output_tokens: totalUsage.output_tokens + messageUsage.output_tokens,
2174
+ server_tool_use: {
2175
+ web_search_requests: totalUsage.server_tool_use.web_search_requests +
2176
+ messageUsage.server_tool_use.web_search_requests,
2177
+ web_fetch_requests: totalUsage.server_tool_use.web_fetch_requests +
2178
+ messageUsage.server_tool_use.web_fetch_requests,
2179
+ },
2180
+ service_tier: messageUsage.service_tier, // Use the most recent service tier
2181
+ cache_creation: {
2182
+ ephemeral_1h_input_tokens: totalUsage.cache_creation.ephemeral_1h_input_tokens +
2183
+ messageUsage.cache_creation.ephemeral_1h_input_tokens,
2184
+ ephemeral_5m_input_tokens: totalUsage.cache_creation.ephemeral_5m_input_tokens +
2185
+ messageUsage.cache_creation.ephemeral_5m_input_tokens,
2186
+ },
2187
+ // See comment in updateUsage — field is not on NonNullableUsage to keep
2188
+ // the string out of external builds.
2189
+ ...(feature('CACHED_MICROCOMPACT')
2190
+ ? {
2191
+ cache_deleted_input_tokens: (totalUsage
2192
+ .cache_deleted_input_tokens ?? 0) +
2193
+ (messageUsage.cache_deleted_input_tokens ?? 0),
2194
+ }
2195
+ : {}),
2196
+ inference_geo: messageUsage.inference_geo, // Use the most recent
2197
+ iterations: messageUsage.iterations, // Use the most recent
2198
+ speed: messageUsage.speed, // Use the most recent
2199
+ };
2200
+ }
2201
+ function isToolResultBlock(block) {
2202
+ return (block !== null &&
2203
+ typeof block === 'object' &&
2204
+ 'type' in block &&
2205
+ block.type === 'tool_result' &&
2206
+ 'tool_use_id' in block);
2207
+ }
2208
+ // Exported for testing cache_reference placement constraints
2209
+ export function addCacheBreakpoints(messages, enablePromptCaching, querySource, useCachedMC = false, newCacheEdits, pinnedEdits, skipCacheWrite = false) {
2210
+ logEvent('thaddeus_api_cache_breakpoints', {
2211
+ totalMessageCount: messages.length,
2212
+ cachingEnabled: enablePromptCaching,
2213
+ skipCacheWrite,
2214
+ });
2215
+ // Exactly one message-level cache_control marker per request. Mycro's
2216
+ // turn-to-turn eviction (page_manager/index.rs: Index::insert) frees
2217
+ // local-attention KV pages at any cached prefix position NOT in
2218
+ // cache_store_int_token_boundaries. With two markers the second-to-last
2219
+ // position is protected and its locals survive an extra turn even though
2220
+ // nothing will ever resume from there — with one marker they're freed
2221
+ // immediately. For fire-and-forget forks (skipCacheWrite) we shift the
2222
+ // marker to the second-to-last message: that's the last shared-prefix
2223
+ // point, so the write is a no-op merge on mycro (entry already exists)
2224
+ // and the fork doesn't leave its own tail in the KVCC. Dense pages are
2225
+ // refcounted and survive via the new hash either way.
2226
+ const markerIndex = skipCacheWrite ? messages.length - 2 : messages.length - 1;
2227
+ const result = messages.map((msg, index) => {
2228
+ const addCache = index === markerIndex;
2229
+ if (msg.type === 'user') {
2230
+ return userMessageToMessageParam(msg, addCache, enablePromptCaching, querySource);
2231
+ }
2232
+ return assistantMessageToMessageParam(msg, addCache, enablePromptCaching, querySource);
2233
+ });
2234
+ if (!useCachedMC) {
2235
+ return result;
2236
+ }
2237
+ // Track all cache_references being deleted to prevent duplicates across blocks.
2238
+ const seenDeleteRefs = new Set();
2239
+ // Helper to deduplicate a cache_edits block against already-seen deletions
2240
+ const deduplicateEdits = (block) => {
2241
+ const uniqueEdits = block.edits.filter(edit => {
2242
+ if (seenDeleteRefs.has(edit.cache_reference)) {
2243
+ return false;
2244
+ }
2245
+ seenDeleteRefs.add(edit.cache_reference);
2246
+ return true;
2247
+ });
2248
+ return { ...block, edits: uniqueEdits };
2249
+ };
2250
+ // Re-insert all previously-pinned cache_edits at their original positions
2251
+ for (const pinned of pinnedEdits ?? []) {
2252
+ const msg = result[pinned.userMessageIndex];
2253
+ if (msg && msg.role === 'user') {
2254
+ if (!Array.isArray(msg.content)) {
2255
+ msg.content = [{ type: 'text', text: msg.content }];
2256
+ }
2257
+ const dedupedBlock = deduplicateEdits(pinned.block);
2258
+ if (dedupedBlock.edits.length > 0) {
2259
+ insertBlockAfterToolResults(msg.content, dedupedBlock);
2260
+ }
2261
+ }
2262
+ }
2263
+ // Insert new cache_edits into the last user message and pin them
2264
+ if (newCacheEdits && result.length > 0) {
2265
+ const dedupedNewEdits = deduplicateEdits(newCacheEdits);
2266
+ if (dedupedNewEdits.edits.length > 0) {
2267
+ for (let i = result.length - 1; i >= 0; i--) {
2268
+ const msg = result[i];
2269
+ if (msg && msg.role === 'user') {
2270
+ if (!Array.isArray(msg.content)) {
2271
+ msg.content = [{ type: 'text', text: msg.content }];
2272
+ }
2273
+ insertBlockAfterToolResults(msg.content, dedupedNewEdits);
2274
+ // Pin so this block is re-sent at the same position in future calls
2275
+ pinCacheEdits(i, newCacheEdits);
2276
+ logForDebugging(`Added cache_edits block with ${dedupedNewEdits.edits.length} deletion(s) to message[${i}]: ${dedupedNewEdits.edits.map(e => e.cache_reference).join(', ')}`);
2277
+ break;
2278
+ }
2279
+ }
2280
+ }
2281
+ }
2282
+ // Add cache_reference to tool_result blocks that are within the cached prefix.
2283
+ // Must be done AFTER cache_edits insertion since that modifies content arrays.
2284
+ if (enablePromptCaching) {
2285
+ // Find the last message containing a cache_control marker
2286
+ let lastCCMsg = -1;
2287
+ for (let i = 0; i < result.length; i++) {
2288
+ const msg = result[i];
2289
+ if (Array.isArray(msg.content)) {
2290
+ for (const block of msg.content) {
2291
+ if (block && typeof block === 'object' && 'cache_control' in block) {
2292
+ lastCCMsg = i;
2293
+ }
2294
+ }
2295
+ }
2296
+ }
2297
+ // Add cache_reference to tool_result blocks that are strictly before
2298
+ // the last cache_control marker. The API requires cache_reference to
2299
+ // appear "before or on" the last cache_control — we use strict "before"
2300
+ // to avoid edge cases where cache_edits splicing shifts block indices.
2301
+ //
2302
+ // Create new objects instead of mutating in-place to avoid contaminating
2303
+ // blocks reused by secondary queries that use models without cache_editing support.
2304
+ if (lastCCMsg >= 0) {
2305
+ for (let i = 0; i < lastCCMsg; i++) {
2306
+ const msg = result[i];
2307
+ if (msg.role !== 'user' || !Array.isArray(msg.content)) {
2308
+ continue;
2309
+ }
2310
+ let cloned = false;
2311
+ for (let j = 0; j < msg.content.length; j++) {
2312
+ const block = msg.content[j];
2313
+ if (block && isToolResultBlock(block)) {
2314
+ if (!cloned) {
2315
+ msg.content = [...msg.content];
2316
+ cloned = true;
2317
+ }
2318
+ msg.content[j] = Object.assign({}, block, {
2319
+ cache_reference: block.tool_use_id,
2320
+ });
2321
+ }
2322
+ }
2323
+ }
2324
+ }
2325
+ }
2326
+ return result;
2327
+ }
2328
+ export function buildSystemPromptBlocks(systemPrompt, enablePromptCaching, options) {
2329
+ // IMPORTANT: Do not add any more blocks for caching or you will get a 400
2330
+ return splitSysPromptPrefix(systemPrompt, {
2331
+ skipGlobalCacheForSystemPrompt: options?.skipGlobalCacheForSystemPrompt,
2332
+ }).map(block => {
2333
+ return {
2334
+ type: 'text',
2335
+ text: block.text,
2336
+ ...(enablePromptCaching &&
2337
+ block.cacheScope !== null && {
2338
+ cache_control: getCacheControl({
2339
+ scope: block.cacheScope,
2340
+ querySource: options?.querySource,
2341
+ }),
2342
+ }),
2343
+ };
2344
+ });
2345
+ }
2346
+ export async function queryHaiku({ systemPrompt = asSystemPrompt([]), userPrompt, outputFormat, signal, options, }) {
2347
+ const result = await withVCR([
2348
+ createUserMessage({
2349
+ content: systemPrompt.map(text => ({ type: 'text', text })),
2350
+ }),
2351
+ createUserMessage({
2352
+ content: userPrompt,
2353
+ }),
2354
+ ], async () => {
2355
+ const messages = [
2356
+ createUserMessage({
2357
+ content: userPrompt,
2358
+ }),
2359
+ ];
2360
+ const result = await queryModelWithoutStreaming({
2361
+ messages,
2362
+ systemPrompt,
2363
+ thinkingConfig: { type: 'disabled' },
2364
+ tools: [],
2365
+ signal,
2366
+ options: {
2367
+ ...options,
2368
+ model: getSmallFastModel(),
2369
+ enablePromptCaching: options.enablePromptCaching ?? false,
2370
+ outputFormat,
2371
+ async getToolPermissionContext() {
2372
+ return getEmptyToolPermissionContext();
2373
+ },
2374
+ },
2375
+ });
2376
+ return [result];
2377
+ });
2378
+ // We don't use streaming for Haiku so this is safe
2379
+ return result[0];
2380
+ }
2381
+ /**
2382
+ * Query a specific model through the Thaddeus infrastructure.
2383
+ * This goes through the full query pipeline including proper authentication,
2384
+ * betas, and headers - unlike direct API calls.
2385
+ */
2386
+ export async function queryWithModel({ systemPrompt = asSystemPrompt([]), userPrompt, outputFormat, signal, options, }) {
2387
+ const result = await withVCR([
2388
+ createUserMessage({
2389
+ content: systemPrompt.map(text => ({ type: 'text', text })),
2390
+ }),
2391
+ createUserMessage({
2392
+ content: userPrompt,
2393
+ }),
2394
+ ], async () => {
2395
+ const messages = [
2396
+ createUserMessage({
2397
+ content: userPrompt,
2398
+ }),
2399
+ ];
2400
+ const result = await queryModelWithoutStreaming({
2401
+ messages,
2402
+ systemPrompt,
2403
+ thinkingConfig: { type: 'disabled' },
2404
+ tools: [],
2405
+ signal,
2406
+ options: {
2407
+ ...options,
2408
+ enablePromptCaching: options.enablePromptCaching ?? false,
2409
+ outputFormat,
2410
+ async getToolPermissionContext() {
2411
+ return getEmptyToolPermissionContext();
2412
+ },
2413
+ },
2414
+ });
2415
+ return [result];
2416
+ });
2417
+ return result[0];
2418
+ }
2419
+ // Non-streaming requests have a 10min max per the docs:
2420
+ // https://platform.claude.com/docs/en/api/errors#long-requests
2421
+ // The SDK's 21333-token cap is derived from 10min × 128k tokens/hour, but we
2422
+ // bypass it by setting a client-level timeout, so we can cap higher.
2423
+ export const MAX_NON_STREAMING_TOKENS = 64_000;
2424
+ /**
2425
+ * Adjusts thinking budget when max_tokens is capped for non-streaming fallback.
2426
+ * Ensures the API constraint: max_tokens > thinking.budget_tokens
2427
+ *
2428
+ * @param params - The parameters that will be sent to the API
2429
+ * @param maxTokensCap - The maximum allowed tokens (MAX_NON_STREAMING_TOKENS)
2430
+ * @returns Adjusted parameters with thinking budget capped if needed
2431
+ */
2432
+ export function adjustParamsForNonStreaming(params, maxTokensCap) {
2433
+ const cappedMaxTokens = Math.min(params.max_tokens, maxTokensCap);
2434
+ // Adjust thinking budget if it would exceed capped max_tokens
2435
+ // to maintain the constraint: max_tokens > thinking.budget_tokens
2436
+ const adjustedParams = { ...params };
2437
+ if (adjustedParams.thinking?.type === 'enabled' &&
2438
+ adjustedParams.thinking.budget_tokens) {
2439
+ adjustedParams.thinking = {
2440
+ ...adjustedParams.thinking,
2441
+ budget_tokens: Math.min(adjustedParams.thinking.budget_tokens, cappedMaxTokens - 1),
2442
+ };
2443
+ }
2444
+ return {
2445
+ ...adjustedParams,
2446
+ max_tokens: cappedMaxTokens,
2447
+ };
2448
+ }
2449
+ function isMaxTokensCapEnabled() {
2450
+ // 3P default: false (not validated on Bedrock/Vertex)
2451
+ return getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_otk_slot_v1', false);
2452
+ }
2453
+ export function getMaxOutputTokensForModel(model) {
2454
+ const maxOutputTokens = getModelMaxOutputTokens(model);
2455
+ // Slot-reservation cap: drop default to 8k for all models. BQ p99 output
2456
+ // = 4,911 tokens; 32k/64k defaults over-reserve 8-16× slot capacity.
2457
+ // Requests hitting the cap get one clean retry at 64k (query.ts
2458
+ // max_output_tokens_escalate). Math.min keeps models with lower native
2459
+ // defaults (e.g. claude-3-opus at 4k) at their native value. Applied
2460
+ // before the env-var override so THADDEUS_MAX_OUTPUT_TOKENS still wins.
2461
+ const defaultTokens = isMaxTokensCapEnabled()
2462
+ ? Math.min(maxOutputTokens.default, CAPPED_DEFAULT_MAX_TOKENS)
2463
+ : maxOutputTokens.default;
2464
+ const result = validateBoundedIntEnvVar('THADDEUS_MAX_OUTPUT_TOKENS', process.env.THADDEUS_MAX_OUTPUT_TOKENS, defaultTokens, maxOutputTokens.upperLimit);
2465
+ return result.effective;
2466
+ }