thaddeus 1.0.26 → 1.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2082) hide show
  1. package/package.json +14 -5
  2. package/src/QueryEngine.js +926 -0
  3. package/src/Task.js +49 -0
  4. package/src/Tool.js +61 -0
  5. package/src/assistant/gate.js +5 -0
  6. package/src/assistant/index.js +106 -0
  7. package/src/assistant/sessionHistory.js +145 -0
  8. package/src/bootstrap/state.js +1163 -0
  9. package/src/bridge/bridgeApi.js +304 -0
  10. package/src/bridge/bridgeConfig.js +39 -0
  11. package/src/bridge/bridgeDebug.js +73 -0
  12. package/src/bridge/bridgeEnabled.js +185 -0
  13. package/src/bridge/bridgeMain.js +2289 -0
  14. package/src/bridge/bridgeMessaging.js +353 -0
  15. package/src/bridge/bridgePermissionCallbacks.js +10 -0
  16. package/src/bridge/bridgePointer.js +175 -0
  17. package/src/bridge/bridgeStatusUtil.js +105 -0
  18. package/src/bridge/bridgeUI.js +411 -0
  19. package/src/bridge/capacityWake.js +35 -0
  20. package/src/bridge/codeSessionApi.js +111 -0
  21. package/src/bridge/createSession.js +273 -0
  22. package/src/bridge/debugUtils.js +115 -0
  23. package/src/bridge/envLessBridgeConfig.js +120 -0
  24. package/src/bridge/flushGate.js +65 -0
  25. package/src/bridge/inboundAttachments.js +152 -0
  26. package/src/bridge/inboundMessages.js +63 -0
  27. package/src/bridge/initReplBridge.js +431 -0
  28. package/src/bridge/jwtUtils.js +185 -0
  29. package/src/bridge/peerSessions.js +5 -0
  30. package/src/bridge/pollConfig.js +85 -0
  31. package/src/bridge/pollConfigDefaults.js +62 -0
  32. package/src/bridge/remoteBridgeCore.js +712 -0
  33. package/src/bridge/replBridge.js +1719 -0
  34. package/src/bridge/replBridgeHandle.js +30 -0
  35. package/src/bridge/replBridgeTransport.js +236 -0
  36. package/src/bridge/sessionIdCompat.js +56 -0
  37. package/src/bridge/sessionRunner.js +421 -0
  38. package/src/bridge/trustedDevice.js +170 -0
  39. package/src/bridge/types.js +9 -0
  40. package/src/bridge/webhookSanitizer.js +6 -0
  41. package/src/bridge/workSecret.js +99 -0
  42. package/src/buddy/CompanionSprite.js +348 -0
  43. package/src/buddy/companion.js +107 -0
  44. package/src/buddy/prompt.js +33 -0
  45. package/src/buddy/sprites.js +488 -0
  46. package/src/buddy/types.js +90 -0
  47. package/src/buddy/useBuddyNotification.js +85 -0
  48. package/src/cli/bg.js +17 -0
  49. package/src/cli/exit.js +30 -0
  50. package/src/cli/handlers/agents.js +55 -0
  51. package/src/cli/handlers/auth.js +249 -0
  52. package/src/cli/handlers/autoMode.js +128 -0
  53. package/src/cli/handlers/mcp.js +335 -0
  54. package/src/cli/handlers/plugins.js +634 -0
  55. package/src/cli/handlers/templateJobs.js +19 -0
  56. package/src/cli/handlers/util.js +76 -0
  57. package/src/cli/ndjsonSafeStringify.js +27 -0
  58. package/src/cli/print.js +4294 -0
  59. package/src/cli/remoteIO.js +208 -0
  60. package/src/cli/structuredIO.js +644 -0
  61. package/src/cli/transports/HybridTransport.js +233 -0
  62. package/src/cli/transports/SSETransport.js +538 -0
  63. package/src/cli/transports/SerialBatchEventUploader.js +224 -0
  64. package/src/cli/transports/WebSocketTransport.js +613 -0
  65. package/src/cli/transports/WorkerStateUploader.js +88 -0
  66. package/src/cli/transports/ccrClient.js +711 -0
  67. package/src/cli/transports/transportUtils.js +39 -0
  68. package/src/cli/update.js +314 -0
  69. package/src/commandCenter/launch.js +39 -0
  70. package/src/commandCenter/phoneApi.js +168 -0
  71. package/src/commandCenter/phoneStore.js +159 -0
  72. package/src/commandCenter/reactorBus.js +130 -0
  73. package/src/commandCenter/server.js +288 -0
  74. package/src/commandCenter/server.ts +42 -7
  75. package/src/commandCenter/tunnel.js +199 -0
  76. package/src/commands/add-dir/add-dir.js +121 -0
  77. package/src/commands/add-dir/index.js +8 -0
  78. package/src/commands/add-dir/validation.js +76 -0
  79. package/src/commands/advisor.js +88 -0
  80. package/src/commands/agents/agents.js +10 -0
  81. package/src/commands/agents/index.js +7 -0
  82. package/src/commands/agents-platform/index.js +2 -0
  83. package/src/commands/assistant/index.js +86 -0
  84. package/src/commands/backup/index.js +31 -0
  85. package/src/commands/branch/branch.js +205 -0
  86. package/src/commands/branch/index.js +11 -0
  87. package/src/commands/bridge/bridge.js +513 -0
  88. package/src/commands/bridge/index.js +22 -0
  89. package/src/commands/bridge-kick.js +179 -0
  90. package/src/commands/brief.js +89 -0
  91. package/src/commands/btw/btw.js +235 -0
  92. package/src/commands/btw/index.js +9 -0
  93. package/src/commands/buddy/buddy.js +100 -0
  94. package/src/commands/buddy/index.js +11 -0
  95. package/src/commands/chrome/chrome.js +291 -0
  96. package/src/commands/chrome/index.js +10 -0
  97. package/src/commands/clear/caches.js +116 -0
  98. package/src/commands/clear/clear.js +5 -0
  99. package/src/commands/clear/conversation.js +189 -0
  100. package/src/commands/clear/index.js +9 -0
  101. package/src/commands/color/color.js +58 -0
  102. package/src/commands/color/index.js +9 -0
  103. package/src/commands/commit-push-pr.js +137 -0
  104. package/src/commands/commit.js +80 -0
  105. package/src/commands/compact/compact.js +194 -0
  106. package/src/commands/compact/index.js +11 -0
  107. package/src/commands/config/config.js +6 -0
  108. package/src/commands/config/index.js +8 -0
  109. package/src/commands/context/context-noninteractive.js +219 -0
  110. package/src/commands/context/context.js +45 -0
  111. package/src/commands/context/index.js +21 -0
  112. package/src/commands/coordinator.js +34 -0
  113. package/src/commands/copy/copy.js +366 -0
  114. package/src/commands/copy/index.js +7 -0
  115. package/src/commands/cost/cost.js +21 -0
  116. package/src/commands/cost/index.js +16 -0
  117. package/src/commands/createMovedToPluginCommand.js +33 -0
  118. package/src/commands/desktop/desktop.js +6 -0
  119. package/src/commands/desktop/index.js +22 -0
  120. package/src/commands/diff/diff.js +6 -0
  121. package/src/commands/diff/index.js +6 -0
  122. package/src/commands/doctor/doctor.js +6 -0
  123. package/src/commands/doctor/index.js +9 -0
  124. package/src/commands/effort/effort.js +166 -0
  125. package/src/commands/effort/index.js +11 -0
  126. package/src/commands/exit/exit.js +32 -0
  127. package/src/commands/exit/index.js +9 -0
  128. package/src/commands/export/export.js +87 -0
  129. package/src/commands/export/index.js +8 -0
  130. package/src/commands/extra-usage/extra-usage-core.js +99 -0
  131. package/src/commands/extra-usage/extra-usage-noninteractive.js +13 -0
  132. package/src/commands/extra-usage/extra-usage.js +15 -0
  133. package/src/commands/extra-usage/index.js +29 -0
  134. package/src/commands/fast/fast.js +276 -0
  135. package/src/commands/fast/index.js +19 -0
  136. package/src/commands/feedback/feedback.js +11 -0
  137. package/src/commands/feedback/index.js +20 -0
  138. package/src/commands/files/files.js +11 -0
  139. package/src/commands/files/index.js +9 -0
  140. package/src/commands/force-snip.js +19 -0
  141. package/src/commands/fork/index.js +67 -0
  142. package/src/commands/heapdump/heapdump.js +14 -0
  143. package/src/commands/heapdump/index.js +9 -0
  144. package/src/commands/help/help.js +6 -0
  145. package/src/commands/help/index.js +7 -0
  146. package/src/commands/hooks/hooks.js +12 -0
  147. package/src/commands/hooks/index.js +8 -0
  148. package/src/commands/ide/ide.js +615 -0
  149. package/src/commands/ide/index.js +8 -0
  150. package/src/commands/init-verifiers.js +258 -0
  151. package/src/commands/init.js +248 -0
  152. package/src/commands/insights.js +2554 -0
  153. package/src/commands/install-github-app/ApiKeyStep.js +230 -0
  154. package/src/commands/install-github-app/CheckExistingSecretStep.js +194 -0
  155. package/src/commands/install-github-app/CheckGitHubStep.js +16 -0
  156. package/src/commands/install-github-app/ChooseRepoStep.js +211 -0
  157. package/src/commands/install-github-app/CreatingStep.js +53 -0
  158. package/src/commands/install-github-app/ErrorStep.js +84 -0
  159. package/src/commands/install-github-app/ExistingWorkflowStep.js +105 -0
  160. package/src/commands/install-github-app/InstallAppStep.js +97 -0
  161. package/src/commands/install-github-app/OAuthFlowStep.js +190 -0
  162. package/src/commands/install-github-app/SuccessStep.js +94 -0
  163. package/src/commands/install-github-app/WarningsStep.js +71 -0
  164. package/src/commands/install-github-app/index.js +10 -0
  165. package/src/commands/install-github-app/install-github-app.js +593 -0
  166. package/src/commands/install-github-app/setupGitHubActions.js +227 -0
  167. package/src/commands/install-slack-app/index.js +9 -0
  168. package/src/commands/install-slack-app/install-slack-app.js +25 -0
  169. package/src/commands/install.js +198 -0
  170. package/src/commands/keybindings/index.js +10 -0
  171. package/src/commands/keybindings/keybindings.js +47 -0
  172. package/src/commands/login/index.js +21 -0
  173. package/src/commands/login/login.js +135 -0
  174. package/src/commands/logout/index.js +11 -0
  175. package/src/commands/logout/logout.js +75 -0
  176. package/src/commands/mcp/addCommand.js +183 -0
  177. package/src/commands/mcp/index.js +9 -0
  178. package/src/commands/mcp/mcp.js +78 -0
  179. package/src/commands/mcp/xaaIdpCommand.js +193 -0
  180. package/src/commands/memories/index.js +9 -0
  181. package/src/commands/memories/index.ts +12 -0
  182. package/src/commands/memories/memories.tsx +949 -0
  183. package/src/commands/memory/index.js +7 -0
  184. package/src/commands/memory/memory.js +71 -0
  185. package/src/commands/mobile/index.js +9 -0
  186. package/src/commands/mobile/mobile.js +279 -0
  187. package/src/commands/model/index.js +14 -0
  188. package/src/commands/model/model.js +284 -0
  189. package/src/commands/output-style/index.js +8 -0
  190. package/src/commands/output-style/output-style.js +6 -0
  191. package/src/commands/passes/index.js +17 -0
  192. package/src/commands/passes/passes.js +23 -0
  193. package/src/commands/peers/index.js +68 -0
  194. package/src/commands/permissions/index.js +8 -0
  195. package/src/commands/permissions/permissions.js +9 -0
  196. package/src/commands/plan/index.js +8 -0
  197. package/src/commands/plan/plan.js +116 -0
  198. package/src/commands/plugin/AddMarketplace.js +96 -0
  199. package/src/commands/plugin/BrowseMarketplace.js +582 -0
  200. package/src/commands/plugin/DiscoverPlugins.js +613 -0
  201. package/src/commands/plugin/ManageMarketplaces.js +583 -0
  202. package/src/commands/plugin/ManagePlugins.js +1783 -0
  203. package/src/commands/plugin/PluginErrors.js +124 -0
  204. package/src/commands/plugin/PluginOptionsDialog.js +367 -0
  205. package/src/commands/plugin/PluginOptionsFlow.js +97 -0
  206. package/src/commands/plugin/PluginSettings.js +1041 -0
  207. package/src/commands/plugin/PluginTrustWarning.js +35 -0
  208. package/src/commands/plugin/UnifiedInstalledCell.js +616 -0
  209. package/src/commands/plugin/ValidatePlugin.js +96 -0
  210. package/src/commands/plugin/index.js +10 -0
  211. package/src/commands/plugin/parseArgs.js +71 -0
  212. package/src/commands/plugin/plugin.js +6 -0
  213. package/src/commands/plugin/pluginDetailsHelpers.js +95 -0
  214. package/src/commands/plugin/usePagination.js +89 -0
  215. package/src/commands/pr_comments/index.js +49 -0
  216. package/src/commands/privacy-settings/index.js +11 -0
  217. package/src/commands/privacy-settings/privacy-settings.js +55 -0
  218. package/src/commands/proactive.js +29 -0
  219. package/src/commands/rate-limit-options/index.js +15 -0
  220. package/src/commands/rate-limit-options/rate-limit-options.js +213 -0
  221. package/src/commands/release-notes/index.js +8 -0
  222. package/src/commands/release-notes/release-notes.js +38 -0
  223. package/src/commands/reload-plugins/index.js +11 -0
  224. package/src/commands/reload-plugins/reload-plugins.js +52 -0
  225. package/src/commands/remote-env/index.js +12 -0
  226. package/src/commands/remote-env/remote-env.js +6 -0
  227. package/src/commands/remote-setup/api.js +155 -0
  228. package/src/commands/remote-setup/index.js +15 -0
  229. package/src/commands/remote-setup/remote-setup.js +150 -0
  230. package/src/commands/remoteControlServer/index.js +58 -0
  231. package/src/commands/rename/generateSessionName.js +58 -0
  232. package/src/commands/rename/index.js +9 -0
  233. package/src/commands/rename/rename.js +52 -0
  234. package/src/commands/resume/index.js +9 -0
  235. package/src/commands/resume/resume.js +239 -0
  236. package/src/commands/review/UltrareviewOverageDialog.js +97 -0
  237. package/src/commands/review/reviewRemote.js +259 -0
  238. package/src/commands/review/ultrareviewCommand.js +58 -0
  239. package/src/commands/review/ultrareviewEnabled.js +10 -0
  240. package/src/commands/review.js +53 -0
  241. package/src/commands/rewind/index.js +10 -0
  242. package/src/commands/rewind/rewind.js +7 -0
  243. package/src/commands/sandbox-toggle/index.js +41 -0
  244. package/src/commands/sandbox-toggle/sandbox-toggle.js +73 -0
  245. package/src/commands/security-review.js +231 -0
  246. package/src/commands/session/index.js +13 -0
  247. package/src/commands/session/session.js +143 -0
  248. package/src/commands/skills/index.js +7 -0
  249. package/src/commands/skills/skills.js +6 -0
  250. package/src/commands/speak.js +21 -0
  251. package/src/commands/start-business.js +1575 -0
  252. package/src/commands/start-business.ts +1581 -0
  253. package/src/commands/stats/index.js +7 -0
  254. package/src/commands/stats/stats.js +6 -0
  255. package/src/commands/status/index.js +8 -0
  256. package/src/commands/status/status.js +6 -0
  257. package/src/commands/statusline.js +22 -0
  258. package/src/commands/stickers/index.js +8 -0
  259. package/src/commands/stickers/stickers.js +14 -0
  260. package/src/commands/subscribe-pr.js +131 -0
  261. package/src/commands/tag/index.js +9 -0
  262. package/src/commands/tag/tag.js +215 -0
  263. package/src/commands/tasks/index.js +8 -0
  264. package/src/commands/tasks/tasks.js +6 -0
  265. package/src/commands/terminalSetup/index.js +18 -0
  266. package/src/commands/terminalSetup/terminalSetup.js +491 -0
  267. package/src/commands/thaddeus-usage/index.js +17 -0
  268. package/src/commands/theme/index.js +7 -0
  269. package/src/commands/theme/theme.js +51 -0
  270. package/src/commands/thinkback/index.js +9 -0
  271. package/src/commands/thinkback/thinkback.js +528 -0
  272. package/src/commands/thinkback-play/index.js +13 -0
  273. package/src/commands/thinkback-play/thinkback-play.js +34 -0
  274. package/src/commands/torch.js +122 -0
  275. package/src/commands/ultraplan.js +416 -0
  276. package/src/commands/upgrade/index.js +12 -0
  277. package/src/commands/upgrade/upgrade.js +38 -0
  278. package/src/commands/usage/index.js +7 -0
  279. package/src/commands/usage/usage.js +6 -0
  280. package/src/commands/version.js +17 -0
  281. package/src/commands/vim/index.js +8 -0
  282. package/src/commands/vim/vim.js +25 -0
  283. package/src/commands/voice/index.js +13 -0
  284. package/src/commands/voice/voice.js +44 -0
  285. package/src/commands/workflows/index.js +123 -0
  286. package/src/commands.js +614 -0
  287. package/src/commands.ts +4 -0
  288. package/src/components/AgentProgressLine.js +112 -0
  289. package/src/components/AntModelSwitchCallout.js +8 -0
  290. package/src/components/App.js +46 -0
  291. package/src/components/ApproveApiKey.js +125 -0
  292. package/src/components/AutoModeOptInDialog.js +140 -0
  293. package/src/components/AutoUpdater.js +156 -0
  294. package/src/components/AutoUpdaterWrapper.js +78 -0
  295. package/src/components/AwsAuthStatusBox.js +88 -0
  296. package/src/components/BaseTextInput.js +105 -0
  297. package/src/components/BashModeProgress.js +49 -0
  298. package/src/components/BridgeDialog.js +415 -0
  299. package/src/components/BypassPermissionsModeDialog.js +87 -0
  300. package/src/components/ChannelDowngradeDialog.js +101 -0
  301. package/src/components/ClaudeInChromeOnboarding.js +126 -0
  302. package/src/components/ClaudeMdExternalIncludesDialog.js +137 -0
  303. package/src/components/ClickableImageRef.js +65 -0
  304. package/src/components/CompactSummary.js +120 -0
  305. package/src/components/ConfigurableShortcutHint.js +35 -0
  306. package/src/components/ConsoleOAuthFlow.js +554 -0
  307. package/src/components/ContextSuggestions.js +44 -0
  308. package/src/components/ContextVisualization.js +482 -0
  309. package/src/components/CoordinatorAgentStatus.js +261 -0
  310. package/src/components/CostThresholdDialog.js +49 -0
  311. package/src/components/CtrlOToExpand.js +50 -0
  312. package/src/components/CustomSelect/SelectMulti.js +150 -0
  313. package/src/components/CustomSelect/index.js +2 -0
  314. package/src/components/CustomSelect/option-map.js +32 -0
  315. package/src/components/CustomSelect/select-input-option.js +426 -0
  316. package/src/components/CustomSelect/select-option.js +24 -0
  317. package/src/components/CustomSelect/select.js +518 -0
  318. package/src/components/CustomSelect/use-multi-select-state.js +214 -0
  319. package/src/components/CustomSelect/use-select-input.js +170 -0
  320. package/src/components/CustomSelect/use-select-navigation.js +366 -0
  321. package/src/components/CustomSelect/use-select-state.js +22 -0
  322. package/src/components/DesktopHandoff.js +195 -0
  323. package/src/components/DesktopUpsell/DesktopUpsellStartup.js +174 -0
  324. package/src/components/DevBar.js +51 -0
  325. package/src/components/DevChannelsDialog.js +104 -0
  326. package/src/components/DiagnosticsDisplay.js +91 -0
  327. package/src/components/EffortCallout.js +264 -0
  328. package/src/components/EffortIndicator.js +28 -0
  329. package/src/components/ExitFlow.js +41 -0
  330. package/src/components/ExportDialog.js +101 -0
  331. package/src/components/FallbackToolUseErrorMessage.js +116 -0
  332. package/src/components/FallbackToolUseRejectedMessage.js +17 -0
  333. package/src/components/FastIcon.js +43 -0
  334. package/src/components/Feedback.js +369 -0
  335. package/src/components/FeedbackSurvey/FeedbackSurvey.js +151 -0
  336. package/src/components/FeedbackSurvey/FeedbackSurveyView.js +104 -0
  337. package/src/components/FeedbackSurvey/TranscriptSharePrompt.js +84 -0
  338. package/src/components/FeedbackSurvey/submitTranscriptShare.js +10 -0
  339. package/src/components/FeedbackSurvey/useDebouncedDigitInput.js +51 -0
  340. package/src/components/FeedbackSurvey/useFeedbackSurvey.js +258 -0
  341. package/src/components/FeedbackSurvey/useFrustrationDetection.js +8 -0
  342. package/src/components/FeedbackSurvey/useMemorySurvey.js +191 -0
  343. package/src/components/FeedbackSurvey/usePostCompactSurvey.js +202 -0
  344. package/src/components/FeedbackSurvey/useSurveyState.js +80 -0
  345. package/src/components/FileEditToolDiff.js +167 -0
  346. package/src/components/FileEditToolUpdatedMessage.js +112 -0
  347. package/src/components/FileEditToolUseRejectedMessage.js +158 -0
  348. package/src/components/FilePathLink.js +35 -0
  349. package/src/components/FullscreenLayout.js +578 -0
  350. package/src/components/GlobalSearchDialog.js +340 -0
  351. package/src/components/HelpV2/Commands.js +66 -0
  352. package/src/components/HelpV2/General.js +25 -0
  353. package/src/components/HelpV2/HelpV2.js +186 -0
  354. package/src/components/HighlightedCode/Fallback.js +193 -0
  355. package/src/components/HighlightedCode.js +185 -0
  356. package/src/components/HistorySearchDialog.js +93 -0
  357. package/src/components/IdeAutoConnectDialog.js +154 -0
  358. package/src/components/IdeOnboardingDialog.js +175 -0
  359. package/src/components/IdeStatusIndicator.js +50 -0
  360. package/src/components/IdleReturnDialog.js +117 -0
  361. package/src/components/InterruptedByUser.js +16 -0
  362. package/src/components/InvalidConfigDialog.js +135 -0
  363. package/src/components/InvalidSettingsDialog.js +85 -0
  364. package/src/components/KeybindingWarnings.js +55 -0
  365. package/src/components/LanguagePicker.js +84 -0
  366. package/src/components/LogSelector.js +1579 -0
  367. package/src/components/LogoV2/AnimatedAsterisk.js +43 -0
  368. package/src/components/LogoV2/AnimatedClawd.js +64 -0
  369. package/src/components/LogoV2/ChannelsNotice.js +262 -0
  370. package/src/components/LogoV2/Clawd.js +33 -0
  371. package/src/components/LogoV2/CondensedLogo.js +160 -0
  372. package/src/components/LogoV2/EmergencyTip.js +48 -0
  373. package/src/components/LogoV2/Feed.js +85 -0
  374. package/src/components/LogoV2/FeedColumn.js +55 -0
  375. package/src/components/LogoV2/GuestPassesUpsell.js +71 -0
  376. package/src/components/LogoV2/LogoV2.js +565 -0
  377. package/src/components/LogoV2/Opus1mMergeNotice.js +57 -0
  378. package/src/components/LogoV2/OverageCreditUpsell.js +161 -0
  379. package/src/components/LogoV2/VoiceModeNotice.js +71 -0
  380. package/src/components/LogoV2/WelcomeV2.js +14 -0
  381. package/src/components/LogoV2/feedConfigs.js +79 -0
  382. package/src/components/LspRecommendation/LspRecommendationMenu.js +46 -0
  383. package/src/components/MCPServerApprovalDialog.js +114 -0
  384. package/src/components/MCPServerDesktopImportDialog.js +206 -0
  385. package/src/components/MCPServerDialogCopy.js +16 -0
  386. package/src/components/MCPServerMultiselectDialog.js +134 -0
  387. package/src/components/ManagedSettingsSecurityDialog/ManagedSettingsSecurityDialog.js +150 -0
  388. package/src/components/ManagedSettingsSecurityDialog/utils.js +105 -0
  389. package/src/components/Markdown.js +233 -0
  390. package/src/components/MarkdownTable.js +280 -0
  391. package/src/components/MemoryUsageIndicator.js +28 -0
  392. package/src/components/Message.js +564 -0
  393. package/src/components/MessageModel.js +37 -0
  394. package/src/components/MessageResponse.js +73 -0
  395. package/src/components/MessageRow.js +346 -0
  396. package/src/components/MessageSelector.js +744 -0
  397. package/src/components/MessageTimestamp.js +58 -0
  398. package/src/components/Messages.js +645 -0
  399. package/src/components/ModelPicker.js +452 -0
  400. package/src/components/NativeAutoUpdater.js +152 -0
  401. package/src/components/NotebookEditToolUseRejectedMessage.js +84 -0
  402. package/src/components/OffscreenFreeze.js +35 -0
  403. package/src/components/Onboarding.js +174 -0
  404. package/src/components/OutputStylePicker.js +103 -0
  405. package/src/components/PackageManagerAutoUpdater.js +99 -0
  406. package/src/components/Passes/Passes.js +114 -0
  407. package/src/components/PrBadge.js +91 -0
  408. package/src/components/PressEnterToContinue.js +16 -0
  409. package/src/components/PromptInput/HistorySearchInput.js +45 -0
  410. package/src/components/PromptInput/IssueFlagBanner.js +8 -0
  411. package/src/components/PromptInput/Notifications.js +220 -0
  412. package/src/components/PromptInput/PromptInput.js +2014 -0
  413. package/src/components/PromptInput/PromptInputFooter.js +85 -0
  414. package/src/components/PromptInput/PromptInputFooterLeftSide.js +408 -0
  415. package/src/components/PromptInput/PromptInputFooterSuggestions.js +281 -0
  416. package/src/components/PromptInput/PromptInputHelpMenu.js +380 -0
  417. package/src/components/PromptInput/PromptInputModeIndicator.js +73 -0
  418. package/src/components/PromptInput/PromptInputQueuedCommands.js +105 -0
  419. package/src/components/PromptInput/PromptInputStashNotice.js +21 -0
  420. package/src/components/PromptInput/SandboxPromptFooterHint.js +66 -0
  421. package/src/components/PromptInput/ShimmeredInput.js +133 -0
  422. package/src/components/PromptInput/VoiceIndicator.js +137 -0
  423. package/src/components/PromptInput/inputModes.js +24 -0
  424. package/src/components/PromptInput/inputPaste.js +62 -0
  425. package/src/components/PromptInput/useMaybeTruncateInput.js +33 -0
  426. package/src/components/PromptInput/usePromptInputPlaceholder.js +53 -0
  427. package/src/components/PromptInput/useShowFastIconHint.js +23 -0
  428. package/src/components/PromptInput/useSwarmBanner.js +112 -0
  429. package/src/components/PromptInput/utils.js +50 -0
  430. package/src/components/QuickOpenDialog.js +244 -0
  431. package/src/components/RemoteCallout.js +53 -0
  432. package/src/components/RemoteEnvironmentDialog.js +346 -0
  433. package/src/components/ResumeTask.js +173 -0
  434. package/src/components/SandboxViolationExpandedView.js +106 -0
  435. package/src/components/ScrollKeybindingHandler.js +982 -0
  436. package/src/components/SearchBox.js +56 -0
  437. package/src/components/SentryErrorBoundary.js +16 -0
  438. package/src/components/SessionBackgroundHint.js +105 -0
  439. package/src/components/SessionPreview.js +200 -0
  440. package/src/components/Settings/Config.js +1626 -0
  441. package/src/components/Settings/Settings.js +131 -0
  442. package/src/components/Settings/Status.js +230 -0
  443. package/src/components/Settings/Usage.js +341 -0
  444. package/src/components/ShowInIDEPrompt.js +152 -0
  445. package/src/components/SkillImprovementSurvey.js +130 -0
  446. package/src/components/Spinner/FlashingChar.js +52 -0
  447. package/src/components/Spinner/GlimmerMessage.js +329 -0
  448. package/src/components/Spinner/ShimmerChar.js +23 -0
  449. package/src/components/Spinner/SpinnerAnimationRow.js +170 -0
  450. package/src/components/Spinner/SpinnerGlyph.js +70 -0
  451. package/src/components/Spinner/TeammateSpinnerLine.js +171 -0
  452. package/src/components/Spinner/TeammateSpinnerTree.js +269 -0
  453. package/src/components/Spinner/index.js +9 -0
  454. package/src/components/Spinner/teammateSelectHint.js +1 -0
  455. package/src/components/Spinner/useShimmerAnimation.js +22 -0
  456. package/src/components/Spinner/useStalledAnimation.js +63 -0
  457. package/src/components/Spinner/utils.js +78 -0
  458. package/src/components/Spinner.js +474 -0
  459. package/src/components/Stats.js +1000 -0
  460. package/src/components/StatusLine.js +286 -0
  461. package/src/components/StatusNotices.js +50 -0
  462. package/src/components/StructuredDiff/Fallback.js +336 -0
  463. package/src/components/StructuredDiff/colorDiff.js +37 -0
  464. package/src/components/StructuredDiff.js +153 -0
  465. package/src/components/StructuredDiffList.js +9 -0
  466. package/src/components/TagTabs.js +101 -0
  467. package/src/components/TaskListV2.js +333 -0
  468. package/src/components/TeammateViewHeader.js +88 -0
  469. package/src/components/TeleportError.js +191 -0
  470. package/src/components/TeleportProgress.js +131 -0
  471. package/src/components/TeleportRepoMismatchDialog.js +98 -0
  472. package/src/components/TeleportResumeWrapper.js +158 -0
  473. package/src/components/TeleportStash.js +82 -0
  474. package/src/components/TextInput.js +108 -0
  475. package/src/components/ThaddeusHint/PluginHintMenu.js +37 -0
  476. package/src/components/ThemePicker.js +331 -0
  477. package/src/components/ThinkingToggle.js +154 -0
  478. package/src/components/TokenWarning.js +171 -0
  479. package/src/components/ToolUseLoader.js +35 -0
  480. package/src/components/TrustDialog/TrustDialog.js +301 -0
  481. package/src/components/TrustDialog/utils.js +199 -0
  482. package/src/components/UndercoverAutoCallout.js +5 -0
  483. package/src/components/ValidationErrorsList.js +147 -0
  484. package/src/components/VimTextInput.js +136 -0
  485. package/src/components/VirtualMessageList.js +893 -0
  486. package/src/components/WorkflowMultiselectDialog.js +118 -0
  487. package/src/components/WorktreeExitDialog.js +220 -0
  488. package/src/components/agents/AgentDetail.js +227 -0
  489. package/src/components/agents/AgentEditor.js +147 -0
  490. package/src/components/agents/AgentNavigationFooter.js +22 -0
  491. package/src/components/agents/AgentsList.js +436 -0
  492. package/src/components/agents/AgentsMenu.js +849 -0
  493. package/src/components/agents/ColorPicker.js +110 -0
  494. package/src/components/agents/ModelSelector.js +63 -0
  495. package/src/components/agents/SnapshotUpdateDialog.js +14 -0
  496. package/src/components/agents/ToolSelector.js +557 -0
  497. package/src/components/agents/agentFileUtils.js +179 -0
  498. package/src/components/agents/generateAgent.js +161 -0
  499. package/src/components/agents/new-agent-creation/CreateAgentWizard.js +89 -0
  500. package/src/components/agents/new-agent-creation/wizard-steps/ColorStep.js +81 -0
  501. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStep.js +387 -0
  502. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStepWrapper.js +63 -0
  503. package/src/components/agents/new-agent-creation/wizard-steps/DescriptionStep.js +126 -0
  504. package/src/components/agents/new-agent-creation/wizard-steps/GenerateStep.js +118 -0
  505. package/src/components/agents/new-agent-creation/wizard-steps/LocationStep.js +80 -0
  506. package/src/components/agents/new-agent-creation/wizard-steps/MemoryStep.js +108 -0
  507. package/src/components/agents/new-agent-creation/wizard-steps/MethodStep.js +80 -0
  508. package/src/components/agents/new-agent-creation/wizard-steps/ModelStep.js +49 -0
  509. package/src/components/agents/new-agent-creation/wizard-steps/PromptStep.js +131 -0
  510. package/src/components/agents/new-agent-creation/wizard-steps/ToolsStep.js +52 -0
  511. package/src/components/agents/new-agent-creation/wizard-steps/TypeStep.js +100 -0
  512. package/src/components/agents/types.js +4 -0
  513. package/src/components/agents/utils.js +14 -0
  514. package/src/components/agents/validateAgent.js +79 -0
  515. package/src/components/design-system/Byline.js +72 -0
  516. package/src/components/design-system/Dialog.js +117 -0
  517. package/src/components/design-system/Divider.js +110 -0
  518. package/src/components/design-system/FuzzyPicker.js +191 -0
  519. package/src/components/design-system/KeyboardShortcutHint.js +68 -0
  520. package/src/components/design-system/ListItem.js +184 -0
  521. package/src/components/design-system/LoadingState.js +69 -0
  522. package/src/components/design-system/Pane.js +69 -0
  523. package/src/components/design-system/ProgressBar.js +63 -0
  524. package/src/components/design-system/Ratchet.js +71 -0
  525. package/src/components/design-system/StatusIcon.js +70 -0
  526. package/src/components/design-system/Tabs.js +269 -0
  527. package/src/components/design-system/ThemeProvider.js +137 -0
  528. package/src/components/design-system/ThemedBox.js +126 -0
  529. package/src/components/design-system/ThemedText.js +60 -0
  530. package/src/components/design-system/color.js +22 -0
  531. package/src/components/diff/DiffDetailView.js +285 -0
  532. package/src/components/diff/DiffDialog.js +387 -0
  533. package/src/components/diff/DiffFileList.js +292 -0
  534. package/src/components/grove/Grove.js +483 -0
  535. package/src/components/hooks/HooksConfigMenu.js +583 -0
  536. package/src/components/hooks/PromptDialog.js +82 -0
  537. package/src/components/hooks/SelectEventMode.js +118 -0
  538. package/src/components/hooks/SelectHookMode.js +101 -0
  539. package/src/components/hooks/SelectMatcherMode.js +131 -0
  540. package/src/components/hooks/ViewHookMode.js +204 -0
  541. package/src/components/mcp/CapabilitiesSection.js +56 -0
  542. package/src/components/mcp/ElicitationDialog.js +945 -0
  543. package/src/components/mcp/MCPAgentServerMenu.js +95 -0
  544. package/src/components/mcp/MCPListPanel.js +505 -0
  545. package/src/components/mcp/MCPReconnect.js +168 -0
  546. package/src/components/mcp/MCPRemoteServerMenu.js +460 -0
  547. package/src/components/mcp/MCPSettings.js +414 -0
  548. package/src/components/mcp/MCPStdioServerMenu.js +95 -0
  549. package/src/components/mcp/MCPToolDetailView.js +219 -0
  550. package/src/components/mcp/MCPToolListView.js +137 -0
  551. package/src/components/mcp/McpParsingWarnings.js +212 -0
  552. package/src/components/mcp/index.js +8 -0
  553. package/src/components/mcp/utils/reconnectHelpers.js +35 -0
  554. package/src/components/memory/MemoryFileSelector.js +454 -0
  555. package/src/components/memory/MemoryUpdateNotification.js +43 -0
  556. package/src/components/messageActions.js +418 -0
  557. package/src/components/messages/AdvisorMessage.js +152 -0
  558. package/src/components/messages/AssistantRedactedThinkingMessage.js +28 -0
  559. package/src/components/messages/AssistantTextMessage.js +287 -0
  560. package/src/components/messages/AssistantThinkingMessage.js +70 -0
  561. package/src/components/messages/AssistantToolUseMessage.js +324 -0
  562. package/src/components/messages/AttachmentMessage.js +418 -0
  563. package/src/components/messages/CollapsedReadSearchContent.js +363 -0
  564. package/src/components/messages/CompactBoundaryMessage.js +19 -0
  565. package/src/components/messages/GroupedToolUseContent.js +37 -0
  566. package/src/components/messages/HighlightedThinkingText.js +165 -0
  567. package/src/components/messages/HookProgressMessage.js +111 -0
  568. package/src/components/messages/PlanApprovalMessage.js +213 -0
  569. package/src/components/messages/RateLimitMessage.js +149 -0
  570. package/src/components/messages/ShutdownMessage.js +124 -0
  571. package/src/components/messages/SnipBoundaryMessage.js +7 -0
  572. package/src/components/messages/SystemAPIErrorMessage.js +136 -0
  573. package/src/components/messages/SystemTextMessage.js +842 -0
  574. package/src/components/messages/TaskAssignmentMessage.js +72 -0
  575. package/src/components/messages/UserAgentNotificationMessage.js +78 -0
  576. package/src/components/messages/UserBashInputMessage.js +52 -0
  577. package/src/components/messages/UserBashOutputMessage.js +55 -0
  578. package/src/components/messages/UserChannelMessage.js +130 -0
  579. package/src/components/messages/UserCommandMessage.js +107 -0
  580. package/src/components/messages/UserCrossSessionMessage.js +11 -0
  581. package/src/components/messages/UserForkBoilerplateMessage.js +11 -0
  582. package/src/components/messages/UserGitHubWebhookMessage.js +12 -0
  583. package/src/components/messages/UserImageMessage.js +54 -0
  584. package/src/components/messages/UserLocalCommandOutputMessage.js +170 -0
  585. package/src/components/messages/UserMemoryInputMessage.js +73 -0
  586. package/src/components/messages/UserPlanMessage.js +38 -0
  587. package/src/components/messages/UserPromptMessage.js +63 -0
  588. package/src/components/messages/UserResourceUpdateMessage.js +102 -0
  589. package/src/components/messages/UserTeammateMessage.js +156 -0
  590. package/src/components/messages/UserTextMessage.js +270 -0
  591. package/src/components/messages/UserToolResultMessage/RejectedPlanMessage.js +28 -0
  592. package/src/components/messages/UserToolResultMessage/RejectedToolUseMessage.js +17 -0
  593. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.js +17 -0
  594. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.js +92 -0
  595. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.js +74 -0
  596. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.js +84 -0
  597. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.js +58 -0
  598. package/src/components/messages/UserToolResultMessage/utils.js +43 -0
  599. package/src/components/messages/nullRenderingAttachments.js +58 -0
  600. package/src/components/messages/teamMemCollapsed.js +142 -0
  601. package/src/components/messages/teamMemSaved.js +16 -0
  602. package/src/components/permissions/AskUserQuestionPermissionRequest/AskUserQuestionPermissionRequest.js +659 -0
  603. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewBox.js +219 -0
  604. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewQuestionView.js +227 -0
  605. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionNavigationBar.js +175 -0
  606. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionView.js +444 -0
  607. package/src/components/permissions/AskUserQuestionPermissionRequest/SubmitQuestionsView.js +137 -0
  608. package/src/components/permissions/AskUserQuestionPermissionRequest/use-multiple-choice-state.js +100 -0
  609. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.js +404 -0
  610. package/src/components/permissions/BashPermissionRequest/bashToolUseOptions.js +110 -0
  611. package/src/components/permissions/ComputerUseApproval/ComputerUseApproval.js +449 -0
  612. package/src/components/permissions/EnterPlanModePermissionRequest/EnterPlanModePermissionRequest.js +126 -0
  613. package/src/components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js +653 -0
  614. package/src/components/permissions/FallbackPermissionRequest.js +349 -0
  615. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.js +185 -0
  616. package/src/components/permissions/FilePermissionDialog/FilePermissionDialog.js +108 -0
  617. package/src/components/permissions/FilePermissionDialog/ideDiffConfig.js +13 -0
  618. package/src/components/permissions/FilePermissionDialog/permissionOptions.js +137 -0
  619. package/src/components/permissions/FilePermissionDialog/useFilePermissionDialog.js +131 -0
  620. package/src/components/permissions/FilePermissionDialog/usePermissionHandler.js +86 -0
  621. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.js +164 -0
  622. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.js +79 -0
  623. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +113 -0
  624. package/src/components/permissions/MonitorPermissionRequest/MonitorPermissionRequest.js +7 -0
  625. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditPermissionRequest.js +164 -0
  626. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditToolDiff.js +218 -0
  627. package/src/components/permissions/PermissionDecisionDebugInfo.js +467 -0
  628. package/src/components/permissions/PermissionDialog.js +55 -0
  629. package/src/components/permissions/PermissionExplanation.js +269 -0
  630. package/src/components/permissions/PermissionPrompt.js +316 -0
  631. package/src/components/permissions/PermissionRequest.js +159 -0
  632. package/src/components/permissions/PermissionRequestTitle.js +58 -0
  633. package/src/components/permissions/PermissionRuleExplanation.js +110 -0
  634. package/src/components/permissions/PowerShellPermissionRequest/PowerShellPermissionRequest.js +178 -0
  635. package/src/components/permissions/PowerShellPermissionRequest/powershellToolUseOptions.js +73 -0
  636. package/src/components/permissions/ReviewArtifactPermissionRequest/ReviewArtifactPermissionRequest.js +7 -0
  637. package/src/components/permissions/SandboxPermissionRequest.js +162 -0
  638. package/src/components/permissions/SedEditPermissionRequest/SedEditPermissionRequest.js +228 -0
  639. package/src/components/permissions/SkillPermissionRequest/SkillPermissionRequest.js +385 -0
  640. package/src/components/permissions/WebFetchPermissionRequest/WebFetchPermissionRequest.js +259 -0
  641. package/src/components/permissions/WorkerBadge.js +44 -0
  642. package/src/components/permissions/WorkerPendingPermission.js +107 -0
  643. package/src/components/permissions/hooks.js +163 -0
  644. package/src/components/permissions/rules/AddPermissionRules.js +171 -0
  645. package/src/components/permissions/rules/AddWorkspaceDirectory.js +335 -0
  646. package/src/components/permissions/rules/PermissionRuleDescription.js +78 -0
  647. package/src/components/permissions/rules/PermissionRuleInput.js +136 -0
  648. package/src/components/permissions/rules/PermissionRuleList.js +1190 -0
  649. package/src/components/permissions/rules/RecentDenialsTab.js +205 -0
  650. package/src/components/permissions/rules/RemoveWorkspaceDirectory.js +103 -0
  651. package/src/components/permissions/rules/WorkspaceTab.js +133 -0
  652. package/src/components/permissions/shellPermissionHelpers.js +112 -0
  653. package/src/components/permissions/useShellPermissionFeedback.js +108 -0
  654. package/src/components/permissions/utils.js +14 -0
  655. package/src/components/sandbox/SandboxConfigTab.js +48 -0
  656. package/src/components/sandbox/SandboxDependenciesTab.js +123 -0
  657. package/src/components/sandbox/SandboxDoctorSection.js +47 -0
  658. package/src/components/sandbox/SandboxOverridesTab.js +193 -0
  659. package/src/components/sandbox/SandboxSettings.js +297 -0
  660. package/src/components/shell/ExpandShellOutputContext.js +33 -0
  661. package/src/components/shell/OutputLine.js +110 -0
  662. package/src/components/shell/ShellProgressMessage.js +144 -0
  663. package/src/components/shell/ShellTimeDisplay.js +72 -0
  664. package/src/components/skills/SkillsMenu.js +239 -0
  665. package/src/components/tasks/AsyncAgentDetailDialog.js +235 -0
  666. package/src/components/tasks/BackgroundTask.js +364 -0
  667. package/src/components/tasks/BackgroundTaskStatus.js +419 -0
  668. package/src/components/tasks/BackgroundTasksDialog.js +494 -0
  669. package/src/components/tasks/DreamDetailDialog.js +251 -0
  670. package/src/components/tasks/InProcessTeammateDetailDialog.js +275 -0
  671. package/src/components/tasks/MonitorMcpDetailDialog.js +7 -0
  672. package/src/components/tasks/RemoteSessionDetailDialog.js +868 -0
  673. package/src/components/tasks/RemoteSessionProgress.js +249 -0
  674. package/src/components/tasks/ShellDetailDialog.js +403 -0
  675. package/src/components/tasks/ShellProgress.js +77 -0
  676. package/src/components/tasks/WorkflowDetailDialog.js +7 -0
  677. package/src/components/tasks/renderToolActivity.js +29 -0
  678. package/src/components/tasks/taskStatusUtils.js +94 -0
  679. package/src/components/teams/TeamStatus.js +77 -0
  680. package/src/components/teams/TeamsDialog.js +673 -0
  681. package/src/components/ui/OrderedList.js +66 -0
  682. package/src/components/ui/OrderedListItem.js +41 -0
  683. package/src/components/ui/TreeSelect.js +300 -0
  684. package/src/components/wizard/WizardDialogLayout.js +48 -0
  685. package/src/components/wizard/WizardNavigationFooter.js +11 -0
  686. package/src/components/wizard/WizardProvider.js +217 -0
  687. package/src/components/wizard/index.js +4 -0
  688. package/src/components/wizard/useWizard.js +9 -0
  689. package/src/constants/apiLimits.js +81 -0
  690. package/src/constants/betas.js +45 -0
  691. package/src/constants/common.js +29 -0
  692. package/src/constants/cyberRiskInstruction.js +23 -0
  693. package/src/constants/errorIds.js +14 -0
  694. package/src/constants/figures.js +38 -0
  695. package/src/constants/files.js +150 -0
  696. package/src/constants/github-app.js +139 -0
  697. package/src/constants/identity.js +112 -0
  698. package/src/constants/keys.js +10 -0
  699. package/src/constants/messages.js +1 -0
  700. package/src/constants/oauth.js +175 -0
  701. package/src/constants/outputStyles.js +162 -0
  702. package/src/constants/product.js +54 -0
  703. package/src/constants/prompts.js +994 -0
  704. package/src/constants/spinnerVerbs.js +98 -0
  705. package/src/constants/system.js +77 -0
  706. package/src/constants/systemPromptSections.js +39 -0
  707. package/src/constants/toolLimits.js +50 -0
  708. package/src/constants/tools.js +103 -0
  709. package/src/constants/turnCompletionVerbs.js +12 -0
  710. package/src/constants/xml.js +73 -0
  711. package/src/context/QueuedMessageContext.js +51 -0
  712. package/src/context/fpsMetrics.js +22 -0
  713. package/src/context/mailbox.js +35 -0
  714. package/src/context/modalContext.js +34 -0
  715. package/src/context/notifications.js +199 -0
  716. package/src/context/overlayContext.js +149 -0
  717. package/src/context/promptOverlayContext.js +118 -0
  718. package/src/context/stats.js +207 -0
  719. package/src/context/voice.js +74 -0
  720. package/src/context.js +146 -0
  721. package/src/coordinator/coordinatorMode.js +345 -0
  722. package/src/coordinator/workerAgent.js +24 -0
  723. package/src/cost-tracker.js +208 -0
  724. package/src/costHook.js +17 -0
  725. package/src/daemon/main.js +19 -0
  726. package/src/dialogLaunchers.js +77 -0
  727. package/src/entrypoints/agentSdkTypes.js +202 -0
  728. package/src/entrypoints/cli.js +226 -0
  729. package/src/entrypoints/init.js +265 -0
  730. package/src/entrypoints/mcp.js +141 -0
  731. package/src/entrypoints/sandboxTypes.js +112 -0
  732. package/src/entrypoints/sdk/controlSchemas.js +452 -0
  733. package/src/entrypoints/sdk/controlTypes.js +1 -0
  734. package/src/entrypoints/sdk/coreSchemas.js +1331 -0
  735. package/src/entrypoints/sdk/coreTypes.generated.js +3 -0
  736. package/src/entrypoints/sdk/coreTypes.js +49 -0
  737. package/src/entrypoints/sdk/runtimeTypes.js +1 -0
  738. package/src/entrypoints/sdk/sdkUtilityTypes.js +1 -0
  739. package/src/entrypoints/sdk/settingsTypes.generated.js +1 -0
  740. package/src/entrypoints/sdk/toolTypes.js +1 -0
  741. package/src/environment-runner/main.js +8 -0
  742. package/src/history.js +386 -0
  743. package/src/hooks/fileSuggestions.js +635 -0
  744. package/src/hooks/notifs/useAntOrgWarningNotification.js +5 -0
  745. package/src/hooks/notifs/useAutoModeUnavailableNotification.js +47 -0
  746. package/src/hooks/notifs/useCanSwitchToExistingSubscription.js +58 -0
  747. package/src/hooks/notifs/useDeprecationWarningNotification.js +43 -0
  748. package/src/hooks/notifs/useFastModeNotification.js +164 -0
  749. package/src/hooks/notifs/useIDEStatusIndicator.js +174 -0
  750. package/src/hooks/notifs/useInstallMessages.js +27 -0
  751. package/src/hooks/notifs/useLspInitializationNotification.js +144 -0
  752. package/src/hooks/notifs/useMcpConnectivityStatus.js +81 -0
  753. package/src/hooks/notifs/useModelMigrationNotifications.js +53 -0
  754. package/src/hooks/notifs/useNpmDeprecationNotification.js +25 -0
  755. package/src/hooks/notifs/usePluginAutoupdateNotification.js +83 -0
  756. package/src/hooks/notifs/usePluginInstallationStatus.js +128 -0
  757. package/src/hooks/notifs/useRateLimitWarningNotification.js +119 -0
  758. package/src/hooks/notifs/useSettingsErrors.js +64 -0
  759. package/src/hooks/notifs/useStartupNotification.js +33 -0
  760. package/src/hooks/notifs/useTeammateShutdownNotification.js +64 -0
  761. package/src/hooks/renderPlaceholder.js +26 -0
  762. package/src/hooks/toolPermission/PermissionContext.js +211 -0
  763. package/src/hooks/toolPermission/handlers/coordinatorHandler.js +44 -0
  764. package/src/hooks/toolPermission/handlers/interactiveHandler.js +397 -0
  765. package/src/hooks/toolPermission/handlers/swarmWorkerHandler.js +108 -0
  766. package/src/hooks/toolPermission/permissionLogging.js +145 -0
  767. package/src/hooks/unifiedSuggestions.js +130 -0
  768. package/src/hooks/useAfterFirstRender.js +12 -0
  769. package/src/hooks/useApiKeyVerification.js +63 -0
  770. package/src/hooks/useArrowKeyHistory.js +203 -0
  771. package/src/hooks/useAssistantHistory.js +193 -0
  772. package/src/hooks/useAwaySummary.js +105 -0
  773. package/src/hooks/useBackgroundTaskNavigation.js +204 -0
  774. package/src/hooks/useBlink.js +28 -0
  775. package/src/hooks/useCanUseTool.js +193 -0
  776. package/src/hooks/useCancelRequest.js +195 -0
  777. package/src/hooks/useChromeExtensionNotification.js +50 -0
  778. package/src/hooks/useClipboardImageHint.js +59 -0
  779. package/src/hooks/useCommandKeybindings.js +87 -0
  780. package/src/hooks/useCommandQueue.js +10 -0
  781. package/src/hooks/useCopyOnSelect.js +88 -0
  782. package/src/hooks/useDeferredHookMessages.js +43 -0
  783. package/src/hooks/useDiffData.js +69 -0
  784. package/src/hooks/useDiffInIDE.js +252 -0
  785. package/src/hooks/useDirectConnect.js +150 -0
  786. package/src/hooks/useDoublePress.js +44 -0
  787. package/src/hooks/useDynamicConfig.js +17 -0
  788. package/src/hooks/useElapsedTime.js +25 -0
  789. package/src/hooks/useExitOnCtrlCD.js +57 -0
  790. package/src/hooks/useExitOnCtrlCDWithKeybindings.js +17 -0
  791. package/src/hooks/useFileHistorySnapshotInit.js +14 -0
  792. package/src/hooks/useGlobalKeybindings.js +213 -0
  793. package/src/hooks/useHistorySearch.js +241 -0
  794. package/src/hooks/useIDEIntegration.js +56 -0
  795. package/src/hooks/useIdeAtMentioned.js +51 -0
  796. package/src/hooks/useIdeConnectionStatus.js +21 -0
  797. package/src/hooks/useIdeLogging.js +29 -0
  798. package/src/hooks/useIdeSelection.js +106 -0
  799. package/src/hooks/useInboxPoller.js +709 -0
  800. package/src/hooks/useInputBuffer.js +73 -0
  801. package/src/hooks/useIssueFlagBanner.js +115 -0
  802. package/src/hooks/useLogMessages.js +98 -0
  803. package/src/hooks/useLspPluginRecommendation.js +176 -0
  804. package/src/hooks/useMailboxBridge.js +15 -0
  805. package/src/hooks/useMainLoopModel.js +25 -0
  806. package/src/hooks/useManagePlugins.js +261 -0
  807. package/src/hooks/useMemoryUsage.js +28 -0
  808. package/src/hooks/useMergedClients.js +11 -0
  809. package/src/hooks/useMergedCommands.js +10 -0
  810. package/src/hooks/useMergedTools.js +32 -0
  811. package/src/hooks/useMinDisplayTime.js +26 -0
  812. package/src/hooks/useNotifyAfterTimeout.js +51 -0
  813. package/src/hooks/useOfficialMarketplaceNotification.js +47 -0
  814. package/src/hooks/usePasteHandler.js +195 -0
  815. package/src/hooks/usePluginRecommendationBase.js +101 -0
  816. package/src/hooks/usePrStatus.js +91 -0
  817. package/src/hooks/usePromptSuggestion.js +128 -0
  818. package/src/hooks/usePromptsFromClaudeInChrome.js +66 -0
  819. package/src/hooks/useQueueProcessor.js +46 -0
  820. package/src/hooks/useRemoteSession.js +431 -0
  821. package/src/hooks/useReplBridge.js +715 -0
  822. package/src/hooks/useSSHSession.js +167 -0
  823. package/src/hooks/useScheduledTasks.js +104 -0
  824. package/src/hooks/useSearchInput.js +302 -0
  825. package/src/hooks/useSessionBackgrounding.js +132 -0
  826. package/src/hooks/useSettings.js +10 -0
  827. package/src/hooks/useSettingsChange.js +13 -0
  828. package/src/hooks/useSkillImprovementSurvey.js +69 -0
  829. package/src/hooks/useSkillsChange.js +51 -0
  830. package/src/hooks/useSwarmInitialization.js +67 -0
  831. package/src/hooks/useSwarmPermissionPoller.js +215 -0
  832. package/src/hooks/useTaskListWatcher.js +157 -0
  833. package/src/hooks/useTasksV2.js +220 -0
  834. package/src/hooks/useTeammateViewAutoExit.js +55 -0
  835. package/src/hooks/useTeleportResume.js +81 -0
  836. package/src/hooks/useTerminalSize.js +9 -0
  837. package/src/hooks/useTextInput.js +397 -0
  838. package/src/hooks/useThaddeusHintRecommendation.js +117 -0
  839. package/src/hooks/useTimeout.js +10 -0
  840. package/src/hooks/useTurnDiffs.js +160 -0
  841. package/src/hooks/useTypeahead.js +1250 -0
  842. package/src/hooks/useUpdateNotification.js +21 -0
  843. package/src/hooks/useVimInput.js +232 -0
  844. package/src/hooks/useVirtualScroll.js +627 -0
  845. package/src/hooks/useVoice.js +952 -0
  846. package/src/hooks/useVoiceEnabled.js +21 -0
  847. package/src/hooks/useVoiceIntegration.js +629 -0
  848. package/src/infrastructure/audit.js +210 -0
  849. package/src/infrastructure/guardrails.js +513 -0
  850. package/src/infrastructure/index.js +11 -0
  851. package/src/ink/Ansi.js +269 -0
  852. package/src/ink/bidi.js +117 -0
  853. package/src/ink/clearTerminal.js +58 -0
  854. package/src/ink/colorize.js +198 -0
  855. package/src/ink/components/AlternateScreen.js +74 -0
  856. package/src/ink/components/App.js +562 -0
  857. package/src/ink/components/AppContext.js +11 -0
  858. package/src/ink/components/Box.js +155 -0
  859. package/src/ink/components/Button.js +166 -0
  860. package/src/ink/components/ClockContext.js +108 -0
  861. package/src/ink/components/CursorDeclarationContext.js +3 -0
  862. package/src/ink/components/ErrorOverview.js +50 -0
  863. package/src/ink/components/Link.js +34 -0
  864. package/src/ink/components/Newline.js +30 -0
  865. package/src/ink/components/NoSelect.js +57 -0
  866. package/src/ink/components/RawAnsi.js +46 -0
  867. package/src/ink/components/ScrollBox.js +171 -0
  868. package/src/ink/components/Spacer.js +20 -0
  869. package/src/ink/components/StdinContext.js +16 -0
  870. package/src/ink/components/TerminalFocusContext.js +45 -0
  871. package/src/ink/components/TerminalSizeContext.js +3 -0
  872. package/src/ink/components/Text.js +195 -0
  873. package/src/ink/constants.js +2 -0
  874. package/src/ink/dom.js +298 -0
  875. package/src/ink/events/click-event.js +36 -0
  876. package/src/ink/events/dispatcher.js +172 -0
  877. package/src/ink/events/emitter.js +31 -0
  878. package/src/ink/events/event-handlers.js +30 -0
  879. package/src/ink/events/event.js +9 -0
  880. package/src/ink/events/focus-event.js +16 -0
  881. package/src/ink/events/input-event.js +161 -0
  882. package/src/ink/events/keyboard-event.js +46 -0
  883. package/src/ink/events/terminal-event.js +78 -0
  884. package/src/ink/events/terminal-focus-event.js +15 -0
  885. package/src/ink/focus.js +158 -0
  886. package/src/ink/frame.js +30 -0
  887. package/src/ink/get-max-width.js +23 -0
  888. package/src/ink/hit-test.js +113 -0
  889. package/src/ink/hooks/use-animation-frame.js +48 -0
  890. package/src/ink/hooks/use-app.js +7 -0
  891. package/src/ink/hooks/use-declared-cursor.js +60 -0
  892. package/src/ink/hooks/use-input.js +70 -0
  893. package/src/ink/hooks/use-interval.js +54 -0
  894. package/src/ink/hooks/use-search-highlight.js +32 -0
  895. package/src/ink/hooks/use-selection.js +60 -0
  896. package/src/ink/hooks/use-stdin.js +7 -0
  897. package/src/ink/hooks/use-tab-status.js +57 -0
  898. package/src/ink/hooks/use-terminal-focus.js +15 -0
  899. package/src/ink/hooks/use-terminal-title.js +29 -0
  900. package/src/ink/hooks/use-terminal-viewport.js +77 -0
  901. package/src/ink/ink.js +1645 -0
  902. package/src/ink/instances.js +7 -0
  903. package/src/ink/layout/engine.js +4 -0
  904. package/src/ink/layout/geometry.js +61 -0
  905. package/src/ink/layout/node.js +62 -0
  906. package/src/ink/layout/yoga.js +237 -0
  907. package/src/ink/line-width-cache.js +19 -0
  908. package/src/ink/log-update.js +583 -0
  909. package/src/ink/measure-element.js +8 -0
  910. package/src/ink/measure-text.js +35 -0
  911. package/src/ink/node-cache.js +30 -0
  912. package/src/ink/optimizer.js +81 -0
  913. package/src/ink/output.js +556 -0
  914. package/src/ink/parse-keypress.js +695 -0
  915. package/src/ink/reconciler.js +384 -0
  916. package/src/ink/render-border.js +134 -0
  917. package/src/ink/render-node-to-output.js +1216 -0
  918. package/src/ink/render-to-screen.js +171 -0
  919. package/src/ink/renderer.js +129 -0
  920. package/src/ink/root.js +80 -0
  921. package/src/ink/screen.js +1132 -0
  922. package/src/ink/searchHighlight.js +78 -0
  923. package/src/ink/selection.js +792 -0
  924. package/src/ink/squash-text-nodes.js +56 -0
  925. package/src/ink/stringWidth.js +200 -0
  926. package/src/ink/styles.js +299 -0
  927. package/src/ink/supports-hyperlinks.js +40 -0
  928. package/src/ink/tabstops.js +39 -0
  929. package/src/ink/terminal-focus-state.js +35 -0
  930. package/src/ink/terminal-querier.js +173 -0
  931. package/src/ink/terminal.js +208 -0
  932. package/src/ink/termio/ansi.js +70 -0
  933. package/src/ink/termio/csi.js +260 -0
  934. package/src/ink/termio/dec.js +53 -0
  935. package/src/ink/termio/esc.js +55 -0
  936. package/src/ink/termio/osc.js +432 -0
  937. package/src/ink/termio/parser.js +356 -0
  938. package/src/ink/termio/sgr.js +292 -0
  939. package/src/ink/termio/tokenize.js +264 -0
  940. package/src/ink/termio/types.js +55 -0
  941. package/src/ink/termio.js +24 -0
  942. package/src/ink/useTerminalNotification.js +57 -0
  943. package/src/ink/warn.js +10 -0
  944. package/src/ink/widest-line.js +14 -0
  945. package/src/ink/wrap-text.js +54 -0
  946. package/src/ink/wrapAnsi.js +6 -0
  947. package/src/ink.js +50 -0
  948. package/src/integrations/credentialStore.js +176 -0
  949. package/src/integrations/index.js +5 -0
  950. package/src/integrations/integrationManager.js +180 -0
  951. package/src/integrations/providers/BaseProvider.js +180 -0
  952. package/src/integrations/providers/GitHubProvider.js +217 -0
  953. package/src/integrations/providers/GmailProvider.js +204 -0
  954. package/src/integrations/providers/GoogleCalendarProvider.js +113 -0
  955. package/src/integrations/providers/HubSpotProvider.js +159 -0
  956. package/src/integrations/providers/JiraProvider.js +216 -0
  957. package/src/integrations/providers/NotionProvider.js +221 -0
  958. package/src/integrations/providers/QuickBooksProvider.js +176 -0
  959. package/src/integrations/providers/SlackProvider.js +174 -0
  960. package/src/integrations/providers/StripeProvider.js +206 -0
  961. package/src/integrations/providers/TwilioProvider.js +239 -0
  962. package/src/integrations/providers/_template.js +112 -0
  963. package/src/integrations/types.js +7 -0
  964. package/src/interactiveHelpers.js +308 -0
  965. package/src/jobs/classifier.js +6 -0
  966. package/src/keybindings/KeybindingContext.js +184 -0
  967. package/src/keybindings/KeybindingProviderSetup.js +259 -0
  968. package/src/keybindings/defaultBindings.js +333 -0
  969. package/src/keybindings/loadUserBindings.js +393 -0
  970. package/src/keybindings/match.js +111 -0
  971. package/src/keybindings/parser.js +184 -0
  972. package/src/keybindings/reservedShortcuts.js +109 -0
  973. package/src/keybindings/resolver.js +182 -0
  974. package/src/keybindings/schema.js +205 -0
  975. package/src/keybindings/shortcutFormat.js +48 -0
  976. package/src/keybindings/template.js +40 -0
  977. package/src/keybindings/useKeybinding.js +161 -0
  978. package/src/keybindings/useShortcutDisplay.js +43 -0
  979. package/src/keybindings/validate.js +395 -0
  980. package/src/main.js +4128 -0
  981. package/src/memdir/findRelevantMemories.js +99 -0
  982. package/src/memdir/memdir.js +406 -0
  983. package/src/memdir/memoryAge.js +52 -0
  984. package/src/memdir/memoryScan.js +65 -0
  985. package/src/memdir/memoryShapeTelemetry.js +8 -0
  986. package/src/memdir/memoryTypes.js +260 -0
  987. package/src/memdir/paths.js +235 -0
  988. package/src/memdir/teamMemPaths.js +261 -0
  989. package/src/memdir/teamMemPrompts.js +82 -0
  990. package/src/migrations/migrateAutoUpdatesToSettings.js +47 -0
  991. package/src/migrations/migrateBypassPermissionsAcceptedToSettings.js +32 -0
  992. package/src/migrations/migrateEnableAllProjectMcpServersToSettings.js +83 -0
  993. package/src/migrations/migrateFennecToOpus.js +39 -0
  994. package/src/migrations/migrateLegacyOpusToCurrent.js +44 -0
  995. package/src/migrations/migrateOpusToOpus1m.js +31 -0
  996. package/src/migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.js +23 -0
  997. package/src/migrations/migrateSonnet1mToSonnet45.js +38 -0
  998. package/src/migrations/migrateSonnet45ToSonnet46.js +48 -0
  999. package/src/migrations/resetAutoModeOptInForDefaultOffer.js +47 -0
  1000. package/src/migrations/resetProToOpusDefault.js +46 -0
  1001. package/src/moreright/useMoreRight.js +13 -0
  1002. package/src/native-ts/color-diff/index.js +819 -0
  1003. package/src/native-ts/file-index/index.js +328 -0
  1004. package/src/native-ts/yoga-layout/enums.js +101 -0
  1005. package/src/native-ts/yoga-layout/index.js +2113 -0
  1006. package/src/outputStyles/loadOutputStylesDir.js +71 -0
  1007. package/src/plugins/builtinPlugins.js +132 -0
  1008. package/src/plugins/bundled/index.js +22 -0
  1009. package/src/proactive/index.js +138 -0
  1010. package/src/proactive/useProactive.js +82 -0
  1011. package/src/projectOnboardingState.js +61 -0
  1012. package/src/query/config.js +17 -0
  1013. package/src/query/deps.js +12 -0
  1014. package/src/query/stopHooks.js +332 -0
  1015. package/src/query/tokenBudget.js +49 -0
  1016. package/src/query.js +1264 -0
  1017. package/src/remote/RemoteSessionManager.js +172 -0
  1018. package/src/remote/SessionsWebSocket.js +308 -0
  1019. package/src/remote/remotePermissionBridge.js +70 -0
  1020. package/src/remote/sdkMessageAdapter.js +227 -0
  1021. package/src/replLauncher.js +7 -0
  1022. package/src/schemas/hooks.js +174 -0
  1023. package/src/screens/Doctor.js +580 -0
  1024. package/src/screens/REPL.js +4500 -0
  1025. package/src/screens/ResumeConversation.js +339 -0
  1026. package/src/self-hosted-runner/main.js +8 -0
  1027. package/src/server/backends/dangerousBackend.js +8 -0
  1028. package/src/server/connectHeadless.js +6 -0
  1029. package/src/server/createDirectConnectSession.js +62 -0
  1030. package/src/server/directConnectManager.js +153 -0
  1031. package/src/server/lockfile.js +11 -0
  1032. package/src/server/parseConnectUrl.js +20 -0
  1033. package/src/server/server.js +12 -0
  1034. package/src/server/serverBanner.js +9 -0
  1035. package/src/server/serverLog.js +11 -0
  1036. package/src/server/sessionManager.js +19 -0
  1037. package/src/server/types.js +7 -0
  1038. package/src/services/AgentSummary/agentSummary.js +147 -0
  1039. package/src/services/MagicDocs/magicDocs.js +193 -0
  1040. package/src/services/MagicDocs/prompts.js +110 -0
  1041. package/src/services/PromptSuggestion/promptSuggestion.js +402 -0
  1042. package/src/services/PromptSuggestion/speculation.js +643 -0
  1043. package/src/services/SessionMemory/prompts.js +254 -0
  1044. package/src/services/SessionMemory/sessionMemory.js +358 -0
  1045. package/src/services/SessionMemory/sessionMemoryUtils.js +157 -0
  1046. package/src/services/analytics/config.js +27 -0
  1047. package/src/services/analytics/datadog.js +26 -0
  1048. package/src/services/analytics/firstPartyEventLogger.js +65 -0
  1049. package/src/services/analytics/firstPartyEventLoggingExporter.js +595 -0
  1050. package/src/services/analytics/growthbook.js +103 -0
  1051. package/src/services/analytics/index.js +91 -0
  1052. package/src/services/analytics/metadata.js +696 -0
  1053. package/src/services/analytics/sink.js +19 -0
  1054. package/src/services/analytics/sinkKillswitch.js +19 -0
  1055. package/src/services/api/adminRequests.js +57 -0
  1056. package/src/services/api/bootstrap.js +118 -0
  1057. package/src/services/api/claude.js +2466 -0
  1058. package/src/services/api/client.js +335 -0
  1059. package/src/services/api/dumpPrompts.js +174 -0
  1060. package/src/services/api/emptyUsage.js +20 -0
  1061. package/src/services/api/errorUtils.js +203 -0
  1062. package/src/services/api/errors.js +926 -0
  1063. package/src/services/api/filesApi.js +523 -0
  1064. package/src/services/api/firstTokenDate.js +49 -0
  1065. package/src/services/api/grove.js +44 -0
  1066. package/src/services/api/logging.js +484 -0
  1067. package/src/services/api/metricsOptOut.js +15 -0
  1068. package/src/services/api/overageCreditGrant.js +123 -0
  1069. package/src/services/api/promptCacheBreakDetection.js +510 -0
  1070. package/src/services/api/referral.js +219 -0
  1071. package/src/services/api/sessionIngress.js +358 -0
  1072. package/src/services/api/ultrareviewQuota.js +29 -0
  1073. package/src/services/api/usage.js +31 -0
  1074. package/src/services/api/withRetry.js +587 -0
  1075. package/src/services/api/xai/anthropic-shim.js +885 -0
  1076. package/src/services/api/xai/brightDataSearch.js +161 -0
  1077. package/src/services/api/xai/thaddeus-engine.js +605 -0
  1078. package/src/services/api/xai/xai-client.js +276 -0
  1079. package/src/services/autoDream/autoDream.js +244 -0
  1080. package/src/services/autoDream/config.js +17 -0
  1081. package/src/services/autoDream/consolidationLock.js +122 -0
  1082. package/src/services/autoDream/consolidationPrompt.js +55 -0
  1083. package/src/services/awaySummary.js +61 -0
  1084. package/src/services/claudeAiLimits.js +331 -0
  1085. package/src/services/claudeAiLimitsHook.js +15 -0
  1086. package/src/services/compact/apiMicrocompact.js +97 -0
  1087. package/src/services/compact/autoCompact.js +234 -0
  1088. package/src/services/compact/cachedMCConfig.js +5 -0
  1089. package/src/services/compact/compact.js +1256 -0
  1090. package/src/services/compact/compactWarningHook.js +12 -0
  1091. package/src/services/compact/compactWarningState.js +15 -0
  1092. package/src/services/compact/grouping.js +58 -0
  1093. package/src/services/compact/microCompact.js +414 -0
  1094. package/src/services/compact/postCompactCleanup.js +70 -0
  1095. package/src/services/compact/prompt.js +325 -0
  1096. package/src/services/compact/reactiveCompact.js +20 -0
  1097. package/src/services/compact/sessionMemoryCompact.js +467 -0
  1098. package/src/services/compact/snipCompact.js +23 -0
  1099. package/src/services/compact/snipProjection.js +11 -0
  1100. package/src/services/compact/timeBasedMCConfig.js +11 -0
  1101. package/src/services/contextCollapse/index.js +33 -0
  1102. package/src/services/contextCollapse/operations.js +5 -0
  1103. package/src/services/contextCollapse/persist.js +5 -0
  1104. package/src/services/diagnosticTracking.js +282 -0
  1105. package/src/services/elevenlabsTTS.js +245 -0
  1106. package/src/services/extractMemories/extractMemories.js +442 -0
  1107. package/src/services/extractMemories/prompts.js +129 -0
  1108. package/src/services/internalLogging.js +68 -0
  1109. package/src/services/lsp/LSPClient.js +306 -0
  1110. package/src/services/lsp/LSPDiagnosticRegistry.js +277 -0
  1111. package/src/services/lsp/LSPServerInstance.js +388 -0
  1112. package/src/services/lsp/LSPServerManager.js +305 -0
  1113. package/src/services/lsp/config.js +57 -0
  1114. package/src/services/lsp/manager.js +246 -0
  1115. package/src/services/lsp/passiveFeedback.js +226 -0
  1116. package/src/services/mcp/InProcessTransport.js +54 -0
  1117. package/src/services/mcp/MCPConnectionManager.js +50 -0
  1118. package/src/services/mcp/SdkControlTransport.js +115 -0
  1119. package/src/services/mcp/auth.js +1882 -0
  1120. package/src/services/mcp/channelAllowlist.js +57 -0
  1121. package/src/services/mcp/channelNotification.js +235 -0
  1122. package/src/services/mcp/channelPermissions.js +192 -0
  1123. package/src/services/mcp/claudeai.js +123 -0
  1124. package/src/services/mcp/client.js +2478 -0
  1125. package/src/services/mcp/config.js +1271 -0
  1126. package/src/services/mcp/elicitationHandler.js +192 -0
  1127. package/src/services/mcp/envExpansion.js +30 -0
  1128. package/src/services/mcp/headersHelper.js +93 -0
  1129. package/src/services/mcp/mcpStringUtils.js +85 -0
  1130. package/src/services/mcp/normalization.js +21 -0
  1131. package/src/services/mcp/oauthPort.js +69 -0
  1132. package/src/services/mcp/officialRegistry.js +20 -0
  1133. package/src/services/mcp/types.js +94 -0
  1134. package/src/services/mcp/useManageMCPConnections.js +818 -0
  1135. package/src/services/mcp/utils.js +433 -0
  1136. package/src/services/mcp/vscodeSdkMcp.js +69 -0
  1137. package/src/services/mcp/xaa.js +342 -0
  1138. package/src/services/mcp/xaaIdpLogin.js +377 -0
  1139. package/src/services/mcpServerApproval.js +30 -0
  1140. package/src/services/mockRateLimits.js +666 -0
  1141. package/src/services/notifier.js +114 -0
  1142. package/src/services/oauth/auth-code-listener.js +165 -0
  1143. package/src/services/oauth/client.js +397 -0
  1144. package/src/services/oauth/crypto.js +19 -0
  1145. package/src/services/oauth/getOauthProfile.js +48 -0
  1146. package/src/services/oauth/index.js +133 -0
  1147. package/src/services/plugins/PluginInstallationManager.js +139 -0
  1148. package/src/services/plugins/pluginCliCommands.js +230 -0
  1149. package/src/services/plugins/pluginOperations.js +826 -0
  1150. package/src/services/policyLimits/index.js +547 -0
  1151. package/src/services/policyLimits/types.js +9 -0
  1152. package/src/services/preventSleep.js +143 -0
  1153. package/src/services/rateLimitMessages.js +271 -0
  1154. package/src/services/rateLimitMocking.js +91 -0
  1155. package/src/services/remoteManagedSettings/index.js +534 -0
  1156. package/src/services/remoteManagedSettings/securityCheck.js +60 -0
  1157. package/src/services/remoteManagedSettings/syncCache.js +90 -0
  1158. package/src/services/remoteManagedSettings/syncCacheState.js +89 -0
  1159. package/src/services/remoteManagedSettings/types.js +12 -0
  1160. package/src/services/sessionTranscript/sessionTranscript.js +5 -0
  1161. package/src/services/settingsSync/index.js +478 -0
  1162. package/src/services/settingsSync/types.js +35 -0
  1163. package/src/services/skillSearch/featureCheck.js +8 -0
  1164. package/src/services/skillSearch/localSearch.js +5 -0
  1165. package/src/services/skillSearch/prefetch.js +8 -0
  1166. package/src/services/skillSearch/remoteSkillLoader.js +8 -0
  1167. package/src/services/skillSearch/remoteSkillState.js +11 -0
  1168. package/src/services/skillSearch/signals.js +3 -0
  1169. package/src/services/skillSearch/telemetry.js +8 -0
  1170. package/src/services/teamMemorySync/index.js +976 -0
  1171. package/src/services/teamMemorySync/secretScanner.js +275 -0
  1172. package/src/services/teamMemorySync/teamMemSecretGuard.js +33 -0
  1173. package/src/services/teamMemorySync/types.js +47 -0
  1174. package/src/services/teamMemorySync/watcher.js +326 -0
  1175. package/src/services/thaddeusAuth.js +485 -0
  1176. package/src/services/thaddeusAuthTypes.js +9 -0
  1177. package/src/services/thaddeusLoginFlow.js +236 -0
  1178. package/src/services/tips/tipHistory.js +17 -0
  1179. package/src/services/tips/tipRegistry.js +593 -0
  1180. package/src/services/tips/tipScheduler.js +40 -0
  1181. package/src/services/tokenEstimation.js +365 -0
  1182. package/src/services/toolUseSummary/toolUseSummaryGenerator.js +87 -0
  1183. package/src/services/tools/StreamingToolExecutor.js +413 -0
  1184. package/src/services/tools/toolExecution.js +1309 -0
  1185. package/src/services/tools/toolHooks.js +454 -0
  1186. package/src/services/tools/toolOrchestration.js +110 -0
  1187. package/src/services/vcr.js +291 -0
  1188. package/src/services/voice.js +392 -0
  1189. package/src/services/voiceKeyterms.js +94 -0
  1190. package/src/services/voiceStreamSTT.js +405 -0
  1191. package/src/setup.js +310 -0
  1192. package/src/skills/bundled/batch.js +114 -0
  1193. package/src/skills/bundled/claudeApi.js +145 -0
  1194. package/src/skills/bundled/claudeApiContent.js +71 -0
  1195. package/src/skills/bundled/claudeInChrome.js +27 -0
  1196. package/src/skills/bundled/debug.js +99 -0
  1197. package/src/skills/bundled/dream.js +49 -0
  1198. package/src/skills/bundled/emailSetup.js +196 -0
  1199. package/src/skills/bundled/hunter.js +28 -0
  1200. package/src/skills/bundled/index.js +80 -0
  1201. package/src/skills/bundled/keybindings.js +292 -0
  1202. package/src/skills/bundled/loop.js +81 -0
  1203. package/src/skills/bundled/loremIpsum.js +264 -0
  1204. package/src/skills/bundled/reactor.js +31 -0
  1205. package/src/skills/bundled/remember.js +73 -0
  1206. package/src/skills/bundled/runSkillGenerator.js +12 -0
  1207. package/src/skills/bundled/scheduleRemoteAgents.js +373 -0
  1208. package/src/skills/bundled/simplify.js +66 -0
  1209. package/src/skills/bundled/skillify.js +182 -0
  1210. package/src/skills/bundled/stuck.js +69 -0
  1211. package/src/skills/bundled/updateConfig.js +463 -0
  1212. package/src/skills/bundled/verify.js +23 -0
  1213. package/src/skills/bundled/verifyContent.js +10 -0
  1214. package/src/skills/bundledSkills.js +159 -0
  1215. package/src/skills/loadSkillsDir.js +736 -0
  1216. package/src/skills/mcpSkillBuilders.js +10 -0
  1217. package/src/skills/mcpSkills.js +5 -0
  1218. package/src/state/AppState.js +182 -0
  1219. package/src/state/AppStateStore.js +117 -0
  1220. package/src/state/onChangeAppState.js +132 -0
  1221. package/src/state/selectors.js +51 -0
  1222. package/src/state/store.js +21 -0
  1223. package/src/state/teammateViewHelpers.js +124 -0
  1224. package/src/stubs/ant-chrome-mcp/index.js +4 -0
  1225. package/src/stubs/ant-computer-use-input/index.js +2 -0
  1226. package/src/stubs/ant-computer-use-mcp/index.js +7 -0
  1227. package/src/stubs/ant-computer-use-mcp/sentinelApps.js +2 -0
  1228. package/src/stubs/ant-computer-use-mcp/types.js +3 -0
  1229. package/src/stubs/ant-computer-use-swift/index.js +1 -0
  1230. package/src/stubs/anthropic-sandbox/index.js +34 -0
  1231. package/src/tasks/DreamTask/DreamTask.js +99 -0
  1232. package/src/tasks/InProcessTeammateTask/InProcessTeammateTask.js +116 -0
  1233. package/src/tasks/InProcessTeammateTask/types.js +35 -0
  1234. package/src/tasks/LocalAgentTask/LocalAgentTask.js +507 -0
  1235. package/src/tasks/LocalMainSessionTask.js +338 -0
  1236. package/src/tasks/LocalShellTask/LocalShellTask.js +475 -0
  1237. package/src/tasks/LocalShellTask/guards.js +9 -0
  1238. package/src/tasks/LocalShellTask/killShellTasks.js +59 -0
  1239. package/src/tasks/LocalWorkflowTask/LocalWorkflowTask.js +7 -0
  1240. package/src/tasks/MonitorMcpTask/MonitorMcpTask.js +20 -0
  1241. package/src/tasks/RemoteAgentTask/RemoteAgentTask.js +742 -0
  1242. package/src/tasks/pillLabel.js +69 -0
  1243. package/src/tasks/stopTask.js +67 -0
  1244. package/src/tasks/types.js +18 -0
  1245. package/src/tasks.js +37 -0
  1246. package/src/tools/AIEmployeesTool/AIEmployeesTool.js +674 -0
  1247. package/src/tools/AIEmployeesTool/constants.js +1 -0
  1248. package/src/tools/AIEmployeesTool/prompt.js +56 -0
  1249. package/src/tools/AgentTool/AgentTool.js +1221 -0
  1250. package/src/tools/AgentTool/UI.js +593 -0
  1251. package/src/tools/AgentTool/agentColorManager.js +43 -0
  1252. package/src/tools/AgentTool/agentDisplay.js +72 -0
  1253. package/src/tools/AgentTool/agentMemory.js +125 -0
  1254. package/src/tools/AgentTool/agentMemorySnapshot.js +136 -0
  1255. package/src/tools/AgentTool/agentToolUtils.js +456 -0
  1256. package/src/tools/AgentTool/built-in/exploreAgent.js +76 -0
  1257. package/src/tools/AgentTool/built-in/generalPurposeAgent.js +28 -0
  1258. package/src/tools/AgentTool/built-in/planAgent.js +87 -0
  1259. package/src/tools/AgentTool/built-in/statuslineSetup.js +140 -0
  1260. package/src/tools/AgentTool/built-in/thaddeusGuideAgent.js +174 -0
  1261. package/src/tools/AgentTool/built-in/verificationAgent.js +146 -0
  1262. package/src/tools/AgentTool/builtInAgents.js +56 -0
  1263. package/src/tools/AgentTool/constants.js +11 -0
  1264. package/src/tools/AgentTool/forkSubagent.js +177 -0
  1265. package/src/tools/AgentTool/loadAgentsDir.js +497 -0
  1266. package/src/tools/AgentTool/prompt.js +260 -0
  1267. package/src/tools/AgentTool/resumeAgent.js +182 -0
  1268. package/src/tools/AgentTool/runAgent.js +627 -0
  1269. package/src/tools/AppointmentsTool/AppointmentsTool.js +628 -0
  1270. package/src/tools/AppointmentsTool/constants.js +1 -0
  1271. package/src/tools/AppointmentsTool/prompt.js +15 -0
  1272. package/src/tools/AskUserQuestionTool/AskUserQuestionTool.js +238 -0
  1273. package/src/tools/AskUserQuestionTool/prompt.js +38 -0
  1274. package/src/tools/BashTool/BashTool.js +1009 -0
  1275. package/src/tools/BashTool/BashToolResultMessage.js +169 -0
  1276. package/src/tools/BashTool/UI.js +134 -0
  1277. package/src/tools/BashTool/bashCommandHelpers.js +184 -0
  1278. package/src/tools/BashTool/bashPermissions.js +2023 -0
  1279. package/src/tools/BashTool/bashSecurity.js +2267 -0
  1280. package/src/tools/BashTool/commandSemantics.js +105 -0
  1281. package/src/tools/BashTool/commentLabel.js +14 -0
  1282. package/src/tools/BashTool/destructiveCommandWarning.js +88 -0
  1283. package/src/tools/BashTool/modeValidation.js +86 -0
  1284. package/src/tools/BashTool/pathValidation.js +1079 -0
  1285. package/src/tools/BashTool/prompt.js +333 -0
  1286. package/src/tools/BashTool/readOnlyValidation.js +1794 -0
  1287. package/src/tools/BashTool/sedEditParser.js +282 -0
  1288. package/src/tools/BashTool/sedValidation.js +580 -0
  1289. package/src/tools/BashTool/shouldUseSandbox.js +125 -0
  1290. package/src/tools/BashTool/toolName.js +2 -0
  1291. package/src/tools/BashTool/utils.js +180 -0
  1292. package/src/tools/BriefTool/BriefTool.js +173 -0
  1293. package/src/tools/BriefTool/UI.js +67 -0
  1294. package/src/tools/BriefTool/attachments.js +86 -0
  1295. package/src/tools/BriefTool/prompt.js +19 -0
  1296. package/src/tools/BriefTool/upload.js +136 -0
  1297. package/src/tools/CalendarTool/CalendarTool.js +498 -0
  1298. package/src/tools/CalendarTool/constants.js +1 -0
  1299. package/src/tools/CalendarTool/prompt.js +11 -0
  1300. package/src/tools/ConfigTool/ConfigTool.js +398 -0
  1301. package/src/tools/ConfigTool/UI.js +25 -0
  1302. package/src/tools/ConfigTool/constants.js +1 -0
  1303. package/src/tools/ConfigTool/prompt.js +82 -0
  1304. package/src/tools/ConfigTool/supportedSettings.js +180 -0
  1305. package/src/tools/ContactsTool/ContactsTool.js +648 -0
  1306. package/src/tools/ContactsTool/constants.js +1 -0
  1307. package/src/tools/ContactsTool/prompt.js +15 -0
  1308. package/src/tools/CtxInspectTool/CtxInspectTool.js +44 -0
  1309. package/src/tools/DiscoverSkillsTool/prompt.js +4 -0
  1310. package/src/tools/EmailReadTool/index.js +410 -0
  1311. package/src/tools/EmailSendTool/index.js +178 -0
  1312. package/src/tools/EnterPlanModeTool/EnterPlanModeTool.js +98 -0
  1313. package/src/tools/EnterPlanModeTool/UI.js +14 -0
  1314. package/src/tools/EnterPlanModeTool/constants.js +1 -0
  1315. package/src/tools/EnterPlanModeTool/prompt.js +164 -0
  1316. package/src/tools/EnterWorktreeTool/EnterWorktreeTool.js +104 -0
  1317. package/src/tools/EnterWorktreeTool/UI.js +9 -0
  1318. package/src/tools/EnterWorktreeTool/constants.js +1 -0
  1319. package/src/tools/EnterWorktreeTool/prompt.js +30 -0
  1320. package/src/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js +383 -0
  1321. package/src/tools/ExitPlanModeTool/UI.js +32 -0
  1322. package/src/tools/ExitPlanModeTool/constants.js +2 -0
  1323. package/src/tools/ExitPlanModeTool/prompt.js +27 -0
  1324. package/src/tools/ExitWorktreeTool/ExitWorktreeTool.js +257 -0
  1325. package/src/tools/ExitWorktreeTool/UI.js +10 -0
  1326. package/src/tools/ExitWorktreeTool/constants.js +1 -0
  1327. package/src/tools/ExitWorktreeTool/prompt.js +32 -0
  1328. package/src/tools/FileEditTool/FileEditTool.js +480 -0
  1329. package/src/tools/FileEditTool/UI.js +202 -0
  1330. package/src/tools/FileEditTool/constants.js +7 -0
  1331. package/src/tools/FileEditTool/prompt.js +24 -0
  1332. package/src/tools/FileEditTool/types.js +50 -0
  1333. package/src/tools/FileEditTool/utils.js +579 -0
  1334. package/src/tools/FileReadTool/FileReadTool.js +889 -0
  1335. package/src/tools/FileReadTool/UI.js +126 -0
  1336. package/src/tools/FileReadTool/imageProcessor.js +46 -0
  1337. package/src/tools/FileReadTool/limits.js +70 -0
  1338. package/src/tools/FileReadTool/prompt.js +31 -0
  1339. package/src/tools/FileWriteTool/FileWriteTool.js +341 -0
  1340. package/src/tools/FileWriteTool/UI.js +339 -0
  1341. package/src/tools/FileWriteTool/prompt.js +15 -0
  1342. package/src/tools/GlobTool/GlobTool.js +161 -0
  1343. package/src/tools/GlobTool/UI.js +40 -0
  1344. package/src/tools/GlobTool/prompt.js +6 -0
  1345. package/src/tools/GrepTool/GrepTool.js +439 -0
  1346. package/src/tools/GrepTool/UI.js +155 -0
  1347. package/src/tools/GrepTool/prompt.js +16 -0
  1348. package/src/tools/IntegrationsTool/IntegrationsTool.js +217 -0
  1349. package/src/tools/IntegrationsTool/constants.js +1 -0
  1350. package/src/tools/IntegrationsTool/prompt.js +41 -0
  1351. package/src/tools/InteractionsTool/InteractionsTool.js +525 -0
  1352. package/src/tools/InteractionsTool/constants.js +1 -0
  1353. package/src/tools/InteractionsTool/prompt.js +14 -0
  1354. package/src/tools/InvoicesTool/InvoicesTool.js +581 -0
  1355. package/src/tools/InvoicesTool/constants.js +1 -0
  1356. package/src/tools/InvoicesTool/prompt.js +15 -0
  1357. package/src/tools/LSPTool/LSPTool.js +660 -0
  1358. package/src/tools/LSPTool/UI.js +205 -0
  1359. package/src/tools/LSPTool/formatters.js +445 -0
  1360. package/src/tools/LSPTool/prompt.js +20 -0
  1361. package/src/tools/LSPTool/schemas.js +197 -0
  1362. package/src/tools/LSPTool/symbolContext.js +75 -0
  1363. package/src/tools/LeadScorerTool/LeadScorerTool.js +509 -0
  1364. package/src/tools/LeadScorerTool/constants.js +1 -0
  1365. package/src/tools/LeadScorerTool/prompt.js +11 -0
  1366. package/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +100 -0
  1367. package/src/tools/ListMcpResourcesTool/UI.js +17 -0
  1368. package/src/tools/ListMcpResourcesTool/prompt.js +18 -0
  1369. package/src/tools/ListPeersTool/ListPeersTool.js +45 -0
  1370. package/src/tools/MCPTool/MCPTool.js +60 -0
  1371. package/src/tools/MCPTool/UI.js +343 -0
  1372. package/src/tools/MCPTool/classifyForCollapse.js +597 -0
  1373. package/src/tools/MCPTool/prompt.js +3 -0
  1374. package/src/tools/McpAuthTool/McpAuthTool.js +162 -0
  1375. package/src/tools/MonitorTool/MonitorTool.js +55 -0
  1376. package/src/tools/NotebookEditTool/NotebookEditTool.js +421 -0
  1377. package/src/tools/NotebookEditTool/UI.js +41 -0
  1378. package/src/tools/NotebookEditTool/constants.js +2 -0
  1379. package/src/tools/NotebookEditTool/prompt.js +2 -0
  1380. package/src/tools/OverflowTestTool/OverflowTestTool.js +51 -0
  1381. package/src/tools/PhoneBridgeTool/PhoneBridgeTool.js +301 -0
  1382. package/src/tools/PhoneBridgeTool/constants.js +1 -0
  1383. package/src/tools/PhoneBridgeTool/prompt.js +26 -0
  1384. package/src/tools/PowerShellTool/PowerShellTool.js +900 -0
  1385. package/src/tools/PowerShellTool/UI.js +58 -0
  1386. package/src/tools/PowerShellTool/clmTypes.js +207 -0
  1387. package/src/tools/PowerShellTool/commandSemantics.js +115 -0
  1388. package/src/tools/PowerShellTool/commonParameters.js +27 -0
  1389. package/src/tools/PowerShellTool/destructiveCommandWarning.js +92 -0
  1390. package/src/tools/PowerShellTool/gitSafety.js +185 -0
  1391. package/src/tools/PowerShellTool/modeValidation.js +357 -0
  1392. package/src/tools/PowerShellTool/pathValidation.js +1712 -0
  1393. package/src/tools/PowerShellTool/powershellPermissions.js +1351 -0
  1394. package/src/tools/PowerShellTool/powershellSecurity.js +942 -0
  1395. package/src/tools/PowerShellTool/prompt.js +132 -0
  1396. package/src/tools/PowerShellTool/readOnlyValidation.js +1633 -0
  1397. package/src/tools/PowerShellTool/toolName.js +2 -0
  1398. package/src/tools/PushNotificationTool/PushNotificationTool.js +35 -0
  1399. package/src/tools/REPLTool/REPLTool.js +44 -0
  1400. package/src/tools/REPLTool/constants.js +43 -0
  1401. package/src/tools/REPLTool/primitiveTools.js +36 -0
  1402. package/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +112 -0
  1403. package/src/tools/ReadMcpResourceTool/UI.js +24 -0
  1404. package/src/tools/ReadMcpResourceTool/prompt.js +15 -0
  1405. package/src/tools/RemoteTriggerTool/RemoteTriggerTool.js +142 -0
  1406. package/src/tools/RemoteTriggerTool/UI.js +12 -0
  1407. package/src/tools/RemoteTriggerTool/prompt.js +12 -0
  1408. package/src/tools/ReviewArtifactTool/ReviewArtifactTool.js +51 -0
  1409. package/src/tools/ScheduleCronTool/CronCreateTool.js +120 -0
  1410. package/src/tools/ScheduleCronTool/CronDeleteTool.js +74 -0
  1411. package/src/tools/ScheduleCronTool/CronListTool.js +77 -0
  1412. package/src/tools/ScheduleCronTool/UI.js +29 -0
  1413. package/src/tools/ScheduleCronTool/prompt.js +115 -0
  1414. package/src/tools/SendMessageTool/SendMessageTool.js +673 -0
  1415. package/src/tools/SendMessageTool/UI.js +24 -0
  1416. package/src/tools/SendMessageTool/constants.js +1 -0
  1417. package/src/tools/SendMessageTool/prompt.js +47 -0
  1418. package/src/tools/SendUserFileTool/SendUserFileTool.js +35 -0
  1419. package/src/tools/SendUserFileTool/prompt.js +5 -0
  1420. package/src/tools/SkillTool/SkillTool.js +825 -0
  1421. package/src/tools/SkillTool/UI.js +61 -0
  1422. package/src/tools/SkillTool/constants.js +1 -0
  1423. package/src/tools/SkillTool/prompt.js +184 -0
  1424. package/src/tools/SleepTool/SleepTool.js +42 -0
  1425. package/src/tools/SleepTool/prompt.js +14 -0
  1426. package/src/tools/SnipTool/SnipTool.js +47 -0
  1427. package/src/tools/SnipTool/prompt.js +5 -0
  1428. package/src/tools/SubscribePRTool/SubscribePRTool.js +49 -0
  1429. package/src/tools/SuggestBackgroundPRTool/SuggestBackgroundPRTool.js +44 -0
  1430. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.js +138 -0
  1431. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.ts +1 -1
  1432. package/src/tools/TaskCreateTool/TaskCreateTool.js +104 -0
  1433. package/src/tools/TaskCreateTool/constants.js +1 -0
  1434. package/src/tools/TaskCreateTool/prompt.js +52 -0
  1435. package/src/tools/TaskGetTool/TaskGetTool.js +106 -0
  1436. package/src/tools/TaskGetTool/constants.js +1 -0
  1437. package/src/tools/TaskGetTool/prompt.js +23 -0
  1438. package/src/tools/TaskListTool/TaskListTool.js +89 -0
  1439. package/src/tools/TaskListTool/constants.js +1 -0
  1440. package/src/tools/TaskListTool/prompt.js +44 -0
  1441. package/src/tools/TaskOutputTool/TaskOutputTool.js +536 -0
  1442. package/src/tools/TaskOutputTool/constants.js +1 -0
  1443. package/src/tools/TaskStopTool/TaskStopTool.js +110 -0
  1444. package/src/tools/TaskStopTool/UI.js +31 -0
  1445. package/src/tools/TaskStopTool/prompt.js +7 -0
  1446. package/src/tools/TaskUpdateTool/TaskUpdateTool.js +301 -0
  1447. package/src/tools/TaskUpdateTool/constants.js +1 -0
  1448. package/src/tools/TaskUpdateTool/prompt.js +76 -0
  1449. package/src/tools/TeamCreateTool/TeamCreateTool.js +177 -0
  1450. package/src/tools/TeamCreateTool/UI.js +4 -0
  1451. package/src/tools/TeamCreateTool/constants.js +1 -0
  1452. package/src/tools/TeamCreateTool/prompt.js +113 -0
  1453. package/src/tools/TeamDeleteTool/TeamDeleteTool.js +102 -0
  1454. package/src/tools/TeamDeleteTool/UI.js +13 -0
  1455. package/src/tools/TeamDeleteTool/constants.js +1 -0
  1456. package/src/tools/TeamDeleteTool/prompt.js +16 -0
  1457. package/src/tools/TerminalCaptureTool/TerminalCaptureTool.js +47 -0
  1458. package/src/tools/TerminalCaptureTool/prompt.js +11 -0
  1459. package/src/tools/TodoWriteTool/TodoWriteTool.js +99 -0
  1460. package/src/tools/TodoWriteTool/constants.js +1 -0
  1461. package/src/tools/TodoWriteTool/prompt.js +181 -0
  1462. package/src/tools/ToolSearchTool/ToolSearchTool.js +357 -0
  1463. package/src/tools/ToolSearchTool/constants.js +1 -0
  1464. package/src/tools/ToolSearchTool/prompt.js +97 -0
  1465. package/src/tools/TungstenTool/TungstenLiveMonitor.js +7 -0
  1466. package/src/tools/TungstenTool/TungstenTool.js +3 -0
  1467. package/src/tools/VerifyPlanExecutionTool/VerifyPlanExecutionTool.js +45 -0
  1468. package/src/tools/VerifyPlanExecutionTool/constants.js +2 -0
  1469. package/src/tools/WebBrowserTool/WebBrowserPanel.js +5 -0
  1470. package/src/tools/WebBrowserTool/WebBrowserTool.js +58 -0
  1471. package/src/tools/WebFetchTool/UI.js +31 -0
  1472. package/src/tools/WebFetchTool/WebFetchTool.js +246 -0
  1473. package/src/tools/WebFetchTool/preapproved.js +154 -0
  1474. package/src/tools/WebFetchTool/prompt.js +39 -0
  1475. package/src/tools/WebFetchTool/utils.js +368 -0
  1476. package/src/tools/WebSearchTool/UI.js +67 -0
  1477. package/src/tools/WebSearchTool/WebSearchTool.js +396 -0
  1478. package/src/tools/WebSearchTool/prompt.js +32 -0
  1479. package/src/tools/WorkflowTool/WorkflowPermissionRequest.js +7 -0
  1480. package/src/tools/WorkflowTool/WorkflowTool.js +51 -0
  1481. package/src/tools/WorkflowTool/bundled/index.js +5 -0
  1482. package/src/tools/WorkflowTool/constants.js +1 -0
  1483. package/src/tools/WorkflowTool/createWorkflowCommand.js +5 -0
  1484. package/src/tools/shared/gitOperationTracking.js +220 -0
  1485. package/src/tools/shared/spawnMultiAgent.js +805 -0
  1486. package/src/tools/testing/TestingPermissionTool.js +72 -0
  1487. package/src/tools/utils.js +24 -0
  1488. package/src/tools.js +365 -0
  1489. package/src/types/command.js +8 -0
  1490. package/src/types/connectorText.js +3 -0
  1491. package/src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.js +673 -0
  1492. package/src/types/generated/events_mono/common/v1/auth.js +49 -0
  1493. package/src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.js +147 -0
  1494. package/src/types/generated/google/protobuf/timestamp.js +38 -0
  1495. package/src/types/hooks.js +153 -0
  1496. package/src/types/ids.js +27 -0
  1497. package/src/types/logs.js +11 -0
  1498. package/src/types/permissions.js +25 -0
  1499. package/src/types/plugin.js +72 -0
  1500. package/src/types/textInputTypes.js +20 -0
  1501. package/src/upstreamproxy/relay.js +346 -0
  1502. package/src/upstreamproxy/upstreamproxy.js +234 -0
  1503. package/src/utils/CircularBuffer.js +75 -0
  1504. package/src/utils/Cursor.js +1229 -0
  1505. package/src/utils/QueryGuard.js +115 -0
  1506. package/src/utils/Shell.js +374 -0
  1507. package/src/utils/ShellCommand.js +336 -0
  1508. package/src/utils/abortController.js +74 -0
  1509. package/src/utils/activityManager.js +127 -0
  1510. package/src/utils/advisor.js +77 -0
  1511. package/src/utils/agentContext.js +91 -0
  1512. package/src/utils/agentId.js +83 -0
  1513. package/src/utils/agentSwarmsEnabled.js +37 -0
  1514. package/src/utils/agenticSessionSearch.js +255 -0
  1515. package/src/utils/analyzeContext.js +846 -0
  1516. package/src/utils/ansiToPng.js +259 -0
  1517. package/src/utils/ansiToSvg.js +207 -0
  1518. package/src/utils/api.js +555 -0
  1519. package/src/utils/apiPreconnect.js +62 -0
  1520. package/src/utils/appleTerminalBackup.js +95 -0
  1521. package/src/utils/argumentSubstitution.js +114 -0
  1522. package/src/utils/array.js +12 -0
  1523. package/src/utils/asciicast.js +200 -0
  1524. package/src/utils/attachments.js +2518 -0
  1525. package/src/utils/attribution.js +308 -0
  1526. package/src/utils/auth.js +1598 -0
  1527. package/src/utils/authFileDescriptor.js +152 -0
  1528. package/src/utils/authPortable.js +14 -0
  1529. package/src/utils/autoModeDenials.js +15 -0
  1530. package/src/utils/autoRunIssue.js +113 -0
  1531. package/src/utils/autoUpdater.js +457 -0
  1532. package/src/utils/aws.js +44 -0
  1533. package/src/utils/awsAuthStatusManager.js +66 -0
  1534. package/src/utils/background/remote/preconditions.js +175 -0
  1535. package/src/utils/background/remote/remoteSession.js +53 -0
  1536. package/src/utils/backgroundHousekeeping.js +64 -0
  1537. package/src/utils/bash/ParsedCommand.js +241 -0
  1538. package/src/utils/bash/ShellSnapshot.js +489 -0
  1539. package/src/utils/bash/ast.js +2590 -0
  1540. package/src/utils/bash/bashParser.js +4355 -0
  1541. package/src/utils/bash/bashPipeCommand.js +249 -0
  1542. package/src/utils/bash/commands.js +1131 -0
  1543. package/src/utils/bash/heredoc.js +647 -0
  1544. package/src/utils/bash/parser.js +195 -0
  1545. package/src/utils/bash/prefix.js +154 -0
  1546. package/src/utils/bash/registry.js +23 -0
  1547. package/src/utils/bash/shellCompletion.js +196 -0
  1548. package/src/utils/bash/shellPrefix.js +25 -0
  1549. package/src/utils/bash/shellQuote.js +253 -0
  1550. package/src/utils/bash/shellQuoting.js +106 -0
  1551. package/src/utils/bash/specs/alias.js +11 -0
  1552. package/src/utils/bash/specs/index.js +16 -0
  1553. package/src/utils/bash/specs/nohup.js +10 -0
  1554. package/src/utils/bash/specs/pyright.js +88 -0
  1555. package/src/utils/bash/specs/sleep.js +10 -0
  1556. package/src/utils/bash/specs/srun.js +28 -0
  1557. package/src/utils/bash/specs/time.js +10 -0
  1558. package/src/utils/bash/specs/timeout.js +17 -0
  1559. package/src/utils/bash/treeSitterAnalysis.js +407 -0
  1560. package/src/utils/betas.js +331 -0
  1561. package/src/utils/billing.js +54 -0
  1562. package/src/utils/binaryCheck.js +40 -0
  1563. package/src/utils/browser.js +58 -0
  1564. package/src/utils/bufferedWriter.js +77 -0
  1565. package/src/utils/bundledMode.js +19 -0
  1566. package/src/utils/businessDb.js +390 -0
  1567. package/src/utils/caCerts.js +91 -0
  1568. package/src/utils/caCertsConfig.js +77 -0
  1569. package/src/utils/cachePaths.js +28 -0
  1570. package/src/utils/classifierApprovals.js +66 -0
  1571. package/src/utils/classifierApprovalsHook.js +10 -0
  1572. package/src/utils/claudeDesktop.js +108 -0
  1573. package/src/utils/claudeInChrome/chromeNativeHost.js +416 -0
  1574. package/src/utils/claudeInChrome/common.js +466 -0
  1575. package/src/utils/claudeInChrome/mcpServer.js +237 -0
  1576. package/src/utils/claudeInChrome/prompt.js +79 -0
  1577. package/src/utils/claudeInChrome/setup.js +304 -0
  1578. package/src/utils/claudeInChrome/setupPortable.js +172 -0
  1579. package/src/utils/claudeInChrome/toolRendering.js +235 -0
  1580. package/src/utils/claudemd.js +1052 -0
  1581. package/src/utils/cleanup.js +514 -0
  1582. package/src/utils/cleanupRegistry.js +22 -0
  1583. package/src/utils/cliArgs.js +53 -0
  1584. package/src/utils/cliHighlight.js +45 -0
  1585. package/src/utils/codeIndexing.js +149 -0
  1586. package/src/utils/collapseBackgroundBashNotifications.js +70 -0
  1587. package/src/utils/collapseHookSummaries.js +48 -0
  1588. package/src/utils/collapseReadSearch.js +869 -0
  1589. package/src/utils/collapseTeammateShutdowns.js +44 -0
  1590. package/src/utils/combinedAbortSignal.js +40 -0
  1591. package/src/utils/commandLifecycle.js +7 -0
  1592. package/src/utils/commitAttribution.js +718 -0
  1593. package/src/utils/completionCache.js +138 -0
  1594. package/src/utils/computerUse/appNames.js +170 -0
  1595. package/src/utils/computerUse/cleanup.js +65 -0
  1596. package/src/utils/computerUse/common.js +56 -0
  1597. package/src/utils/computerUse/computerUseLock.js +183 -0
  1598. package/src/utils/computerUse/drainRunLoop.js +71 -0
  1599. package/src/utils/computerUse/escHotkey.js +53 -0
  1600. package/src/utils/computerUse/executor.js +480 -0
  1601. package/src/utils/computerUse/gates.js +55 -0
  1602. package/src/utils/computerUse/hostAdapter.js +62 -0
  1603. package/src/utils/computerUse/inputLoader.js +25 -0
  1604. package/src/utils/computerUse/mcpServer.js +84 -0
  1605. package/src/utils/computerUse/setup.js +42 -0
  1606. package/src/utils/computerUse/swiftLoader.js +18 -0
  1607. package/src/utils/computerUse/toolRendering.js +101 -0
  1608. package/src/utils/computerUse/wrapper.js +317 -0
  1609. package/src/utils/concurrentSessions.js +179 -0
  1610. package/src/utils/config.js +1078 -0
  1611. package/src/utils/configConstants.js +18 -0
  1612. package/src/utils/contentArray.js +45 -0
  1613. package/src/utils/context.js +185 -0
  1614. package/src/utils/contextAnalysis.js +171 -0
  1615. package/src/utils/contextSuggestions.js +158 -0
  1616. package/src/utils/controlMessageCompat.js +31 -0
  1617. package/src/utils/conversationRecovery.js +434 -0
  1618. package/src/utils/cron.js +260 -0
  1619. package/src/utils/cronJitterConfig.js +62 -0
  1620. package/src/utils/cronScheduler.js +388 -0
  1621. package/src/utils/cronTasks.js +328 -0
  1622. package/src/utils/cronTasksLock.js +159 -0
  1623. package/src/utils/crossProjectResume.js +46 -0
  1624. package/src/utils/crypto.js +13 -0
  1625. package/src/utils/cwd.js +29 -0
  1626. package/src/utils/debug.js +220 -0
  1627. package/src/utils/debugFilter.js +125 -0
  1628. package/src/utils/deepLink/banner.js +103 -0
  1629. package/src/utils/deepLink/parseDeepLink.js +138 -0
  1630. package/src/utils/deepLink/protocolHandler.js +119 -0
  1631. package/src/utils/deepLink/registerProtocol.js +291 -0
  1632. package/src/utils/deepLink/terminalLauncher.js +455 -0
  1633. package/src/utils/deepLink/terminalPreference.js +51 -0
  1634. package/src/utils/desktopDeepLink.js +208 -0
  1635. package/src/utils/detectRepository.js +157 -0
  1636. package/src/utils/diagLogs.js +74 -0
  1637. package/src/utils/diff.js +108 -0
  1638. package/src/utils/directMemberMessage.js +34 -0
  1639. package/src/utils/displayTags.js +46 -0
  1640. package/src/utils/doctorContextWarnings.js +179 -0
  1641. package/src/utils/doctorDiagnostic.js +494 -0
  1642. package/src/utils/dxt/helpers.js +64 -0
  1643. package/src/utils/dxt/zip.js +167 -0
  1644. package/src/utils/earlyInput.js +166 -0
  1645. package/src/utils/editor.js +163 -0
  1646. package/src/utils/effort.js +271 -0
  1647. package/src/utils/embeddedTools.js +26 -0
  1648. package/src/utils/employeeChat.js +271 -0
  1649. package/src/utils/employeeDb.js +326 -0
  1650. package/src/utils/env.js +358 -0
  1651. package/src/utils/envDynamic.js +130 -0
  1652. package/src/utils/envUtils.js +161 -0
  1653. package/src/utils/envValidation.js +26 -0
  1654. package/src/utils/errorLogSink.js +196 -0
  1655. package/src/utils/errors.js +207 -0
  1656. package/src/utils/exampleCommands.js +165 -0
  1657. package/src/utils/execFileNoThrow.js +93 -0
  1658. package/src/utils/execFileNoThrowPortable.js +49 -0
  1659. package/src/utils/execSyncWrapper.js +6 -0
  1660. package/src/utils/exportRenderer.js +71 -0
  1661. package/src/utils/extraUsage.js +19 -0
  1662. package/src/utils/fastMode.js +393 -0
  1663. package/src/utils/file.js +467 -0
  1664. package/src/utils/fileHistory.js +851 -0
  1665. package/src/utils/fileOperationAnalytics.js +45 -0
  1666. package/src/utils/filePersistence/filePersistence.js +212 -0
  1667. package/src/utils/filePersistence/outputsScanner.js +104 -0
  1668. package/src/utils/filePersistence/types.js +4 -0
  1669. package/src/utils/fileRead.js +81 -0
  1670. package/src/utils/fileReadCache.js +78 -0
  1671. package/src/utils/fileStateCache.js +99 -0
  1672. package/src/utils/findExecutable.js +13 -0
  1673. package/src/utils/fingerprint.js +58 -0
  1674. package/src/utils/forkedAgent.js +410 -0
  1675. package/src/utils/format.js +238 -0
  1676. package/src/utils/formatBriefTimestamp.js +72 -0
  1677. package/src/utils/fpsTracker.js +34 -0
  1678. package/src/utils/frontmatterParser.js +260 -0
  1679. package/src/utils/fsOperations.js +555 -0
  1680. package/src/utils/fullscreen.js +194 -0
  1681. package/src/utils/generatedFiles.js +122 -0
  1682. package/src/utils/generators.js +67 -0
  1683. package/src/utils/genericProcessUtils.js +155 -0
  1684. package/src/utils/getWorktreePaths.js +56 -0
  1685. package/src/utils/getWorktreePathsPortable.js +23 -0
  1686. package/src/utils/ghPrStatus.js +71 -0
  1687. package/src/utils/git/gitConfigParser.js +226 -0
  1688. package/src/utils/git/gitFilesystem.js +606 -0
  1689. package/src/utils/git/gitignore.js +84 -0
  1690. package/src/utils/git.js +725 -0
  1691. package/src/utils/gitDiff.js +395 -0
  1692. package/src/utils/gitSettings.js +18 -0
  1693. package/src/utils/github/ghAuthStatus.js +23 -0
  1694. package/src/utils/githubRepoPathMapping.js +135 -0
  1695. package/src/utils/glob.js +90 -0
  1696. package/src/utils/gracefulShutdown.js +447 -0
  1697. package/src/utils/groupToolUses.js +126 -0
  1698. package/src/utils/handlePromptSubmit.js +398 -0
  1699. package/src/utils/hash.js +44 -0
  1700. package/src/utils/headlessProfiler.js +147 -0
  1701. package/src/utils/heapDumpService.js +201 -0
  1702. package/src/utils/heatmap.js +151 -0
  1703. package/src/utils/highlightMatch.js +29 -0
  1704. package/src/utils/hooks/AsyncHookRegistry.js +187 -0
  1705. package/src/utils/hooks/apiQueryHookHelper.js +77 -0
  1706. package/src/utils/hooks/execAgentHook.js +257 -0
  1707. package/src/utils/hooks/execHttpHook.js +184 -0
  1708. package/src/utils/hooks/execPromptHook.js +171 -0
  1709. package/src/utils/hooks/fileChangedWatcher.js +161 -0
  1710. package/src/utils/hooks/hookEvents.js +111 -0
  1711. package/src/utils/hooks/hookHelpers.js +60 -0
  1712. package/src/utils/hooks/hooksConfigManager.js +323 -0
  1713. package/src/utils/hooks/hooksConfigSnapshot.js +114 -0
  1714. package/src/utils/hooks/hooksSettings.js +204 -0
  1715. package/src/utils/hooks/postSamplingHooks.js +39 -0
  1716. package/src/utils/hooks/registerFrontmatterHooks.js +47 -0
  1717. package/src/utils/hooks/registerSkillHooks.js +40 -0
  1718. package/src/utils/hooks/sessionHooks.js +252 -0
  1719. package/src/utils/hooks/skillImprovement.js +211 -0
  1720. package/src/utils/hooks/ssrfGuard.js +258 -0
  1721. package/src/utils/hooks.js +3668 -0
  1722. package/src/utils/horizontalScroll.js +108 -0
  1723. package/src/utils/http.js +120 -0
  1724. package/src/utils/hyperlink.js +28 -0
  1725. package/src/utils/iTermBackup.js +48 -0
  1726. package/src/utils/ide.js +1195 -0
  1727. package/src/utils/idePathConversion.js +66 -0
  1728. package/src/utils/idleTimeout.js +44 -0
  1729. package/src/utils/imagePaste.js +343 -0
  1730. package/src/utils/imageResizer.js +664 -0
  1731. package/src/utils/imageStore.js +150 -0
  1732. package/src/utils/imageValidation.js +92 -0
  1733. package/src/utils/immediateCommand.js +12 -0
  1734. package/src/utils/inProcessTeammateHelpers.js +71 -0
  1735. package/src/utils/ink.js +20 -0
  1736. package/src/utils/intl.js +83 -0
  1737. package/src/utils/jetbrains.js +152 -0
  1738. package/src/utils/json.js +231 -0
  1739. package/src/utils/jsonRead.js +14 -0
  1740. package/src/utils/keyboardShortcuts.js +11 -0
  1741. package/src/utils/lazySchema.js +8 -0
  1742. package/src/utils/listSessionsImpl.js +332 -0
  1743. package/src/utils/localInstaller.js +130 -0
  1744. package/src/utils/lockfile.js +30 -0
  1745. package/src/utils/log.js +280 -0
  1746. package/src/utils/logoV2Utils.js +256 -0
  1747. package/src/utils/mailbox.js +50 -0
  1748. package/src/utils/managedEnv.js +160 -0
  1749. package/src/utils/managedEnvConstants.js +185 -0
  1750. package/src/utils/markdown.js +315 -0
  1751. package/src/utils/markdownConfigLoader.js +480 -0
  1752. package/src/utils/mcp/dateTimeParser.js +102 -0
  1753. package/src/utils/mcp/elicitationValidation.js +259 -0
  1754. package/src/utils/mcpInstructionsDelta.js +97 -0
  1755. package/src/utils/mcpOutputStorage.js +159 -0
  1756. package/src/utils/mcpValidation.js +165 -0
  1757. package/src/utils/mcpWebSocketTransport.js +180 -0
  1758. package/src/utils/memoize.js +205 -0
  1759. package/src/utils/memory/types.js +9 -0
  1760. package/src/utils/memory/versions.js +7 -0
  1761. package/src/utils/memoryFileDetection.js +245 -0
  1762. package/src/utils/messagePredicates.js +6 -0
  1763. package/src/utils/messageQueueManager.js +430 -0
  1764. package/src/utils/messages/mappers.js +240 -0
  1765. package/src/utils/messages/systemInit.js +72 -0
  1766. package/src/utils/messages.js +4286 -0
  1767. package/src/utils/model/agent.js +128 -0
  1768. package/src/utils/model/aliases.js +21 -0
  1769. package/src/utils/model/antModels.js +25 -0
  1770. package/src/utils/model/bedrock.js +220 -0
  1771. package/src/utils/model/check1mAccess.js +64 -0
  1772. package/src/utils/model/configs.js +86 -0
  1773. package/src/utils/model/contextWindowUpgradeCheck.js +41 -0
  1774. package/src/utils/model/deprecation.js +72 -0
  1775. package/src/utils/model/model.js +533 -0
  1776. package/src/utils/model/modelAllowlist.js +148 -0
  1777. package/src/utils/model/modelCapabilities.js +105 -0
  1778. package/src/utils/model/modelOptions.js +450 -0
  1779. package/src/utils/model/modelStrings.js +144 -0
  1780. package/src/utils/model/modelSupportOverrides.js +40 -0
  1781. package/src/utils/model/providers.js +35 -0
  1782. package/src/utils/model/validateModel.js +131 -0
  1783. package/src/utils/modelCost.js +160 -0
  1784. package/src/utils/modifiers.js +39 -0
  1785. package/src/utils/mtls.js +132 -0
  1786. package/src/utils/nativeInstaller/download.js +370 -0
  1787. package/src/utils/nativeInstaller/index.js +8 -0
  1788. package/src/utils/nativeInstaller/installer.js +1395 -0
  1789. package/src/utils/nativeInstaller/packageManagers.js +258 -0
  1790. package/src/utils/nativeInstaller/pidLock.js +347 -0
  1791. package/src/utils/notebook.js +176 -0
  1792. package/src/utils/objectGroupBy.js +15 -0
  1793. package/src/utils/pasteStore.js +93 -0
  1794. package/src/utils/path.js +140 -0
  1795. package/src/utils/pdf.js +236 -0
  1796. package/src/utils/pdfUtils.js +61 -0
  1797. package/src/utils/peerAddress.js +20 -0
  1798. package/src/utils/permissions/PermissionMode.js +95 -0
  1799. package/src/utils/permissions/PermissionPromptToolResultSchema.js +85 -0
  1800. package/src/utils/permissions/PermissionResult.js +11 -0
  1801. package/src/utils/permissions/PermissionRule.js +19 -0
  1802. package/src/utils/permissions/PermissionUpdate.js +268 -0
  1803. package/src/utils/permissions/PermissionUpdateSchema.js +61 -0
  1804. package/src/utils/permissions/autoModeState.js +31 -0
  1805. package/src/utils/permissions/bashClassifier.js +30 -0
  1806. package/src/utils/permissions/bypassPermissionsKillswitch.js +115 -0
  1807. package/src/utils/permissions/classifierDecision.js +86 -0
  1808. package/src/utils/permissions/classifierShared.js +28 -0
  1809. package/src/utils/permissions/dangerousPatterns.js +78 -0
  1810. package/src/utils/permissions/denialTracking.js +34 -0
  1811. package/src/utils/permissions/filesystem.js +1411 -0
  1812. package/src/utils/permissions/getNextPermissionMode.js +74 -0
  1813. package/src/utils/permissions/pathValidation.js +351 -0
  1814. package/src/utils/permissions/permissionExplainer.js +188 -0
  1815. package/src/utils/permissions/permissionRuleParser.js +175 -0
  1816. package/src/utils/permissions/permissionSetup.js +1162 -0
  1817. package/src/utils/permissions/permissions.js +1063 -0
  1818. package/src/utils/permissions/permissionsLoader.js +217 -0
  1819. package/src/utils/permissions/shadowedRuleDetection.js +149 -0
  1820. package/src/utils/permissions/shellRuleMatching.js +174 -0
  1821. package/src/utils/permissions/yoloClassifier.js +1193 -0
  1822. package/src/utils/planModeV2.js +75 -0
  1823. package/src/utils/plans.js +334 -0
  1824. package/src/utils/platform.js +122 -0
  1825. package/src/utils/plugins/addDirPluginSettings.js +53 -0
  1826. package/src/utils/plugins/cacheUtils.js +174 -0
  1827. package/src/utils/plugins/dependencyResolver.js +244 -0
  1828. package/src/utils/plugins/fetchTelemetry.js +108 -0
  1829. package/src/utils/plugins/gitAvailability.js +65 -0
  1830. package/src/utils/plugins/headlessPluginInstall.js +136 -0
  1831. package/src/utils/plugins/hintRecommendation.js +136 -0
  1832. package/src/utils/plugins/installCounts.js +221 -0
  1833. package/src/utils/plugins/installedPluginsManager.js +1003 -0
  1834. package/src/utils/plugins/loadPluginAgents.js +219 -0
  1835. package/src/utils/plugins/loadPluginCommands.js +595 -0
  1836. package/src/utils/plugins/loadPluginHooks.js +239 -0
  1837. package/src/utils/plugins/loadPluginOutputStyles.js +112 -0
  1838. package/src/utils/plugins/lspPluginIntegration.js +293 -0
  1839. package/src/utils/plugins/lspRecommendation.js +278 -0
  1840. package/src/utils/plugins/managedPlugins.js +26 -0
  1841. package/src/utils/plugins/marketplaceHelpers.js +470 -0
  1842. package/src/utils/plugins/marketplaceManager.js +1939 -0
  1843. package/src/utils/plugins/mcpPluginIntegration.js +465 -0
  1844. package/src/utils/plugins/mcpbHandler.js +708 -0
  1845. package/src/utils/plugins/officialMarketplace.js +19 -0
  1846. package/src/utils/plugins/officialMarketplaceGcs.js +202 -0
  1847. package/src/utils/plugins/officialMarketplaceStartupCheck.js +344 -0
  1848. package/src/utils/plugins/orphanedPluginFilter.js +96 -0
  1849. package/src/utils/plugins/parseMarketplaceInput.js +143 -0
  1850. package/src/utils/plugins/performStartupChecks.js +66 -0
  1851. package/src/utils/plugins/pluginAutoupdate.js +210 -0
  1852. package/src/utils/plugins/pluginBlocklist.js +93 -0
  1853. package/src/utils/plugins/pluginDirectories.js +170 -0
  1854. package/src/utils/plugins/pluginFlagging.js +173 -0
  1855. package/src/utils/plugins/pluginIdentifier.js +78 -0
  1856. package/src/utils/plugins/pluginInstallationHelpers.js +400 -0
  1857. package/src/utils/plugins/pluginLoader.js +2426 -0
  1858. package/src/utils/plugins/pluginOptionsStorage.js +311 -0
  1859. package/src/utils/plugins/pluginPolicy.js +18 -0
  1860. package/src/utils/plugins/pluginStartupCheck.js +261 -0
  1861. package/src/utils/plugins/pluginVersioning.js +128 -0
  1862. package/src/utils/plugins/reconciler.js +181 -0
  1863. package/src/utils/plugins/refresh.js +162 -0
  1864. package/src/utils/plugins/schemas.js +1283 -0
  1865. package/src/utils/plugins/validatePlugin.js +765 -0
  1866. package/src/utils/plugins/walkPluginMarkdown.js +49 -0
  1867. package/src/utils/plugins/zipCache.js +346 -0
  1868. package/src/utils/plugins/zipCacheAdapters.js +133 -0
  1869. package/src/utils/powershell/dangerousCmdlets.js +174 -0
  1870. package/src/utils/powershell/parser.js +1357 -0
  1871. package/src/utils/powershell/staticPrefix.js +277 -0
  1872. package/src/utils/preflightChecks.js +147 -0
  1873. package/src/utils/privacyLevel.js +49 -0
  1874. package/src/utils/process.js +56 -0
  1875. package/src/utils/processUserInput/processBashCommand.js +118 -0
  1876. package/src/utils/processUserInput/processSlashCommand.js +845 -0
  1877. package/src/utils/processUserInput/processTextPrompt.js +68 -0
  1878. package/src/utils/processUserInput/processUserInput.js +344 -0
  1879. package/src/utils/profilerBase.js +32 -0
  1880. package/src/utils/promptCategory.js +39 -0
  1881. package/src/utils/promptEditor.js +151 -0
  1882. package/src/utils/promptShellExecution.js +117 -0
  1883. package/src/utils/protectedNamespace.js +4 -0
  1884. package/src/utils/proxy.js +345 -0
  1885. package/src/utils/queryContext.js +110 -0
  1886. package/src/utils/queryHelpers.js +436 -0
  1887. package/src/utils/queryProfiler.js +242 -0
  1888. package/src/utils/queueProcessor.js +70 -0
  1889. package/src/utils/readEditContext.js +176 -0
  1890. package/src/utils/readFileInRange.js +278 -0
  1891. package/src/utils/releaseNotes.js +307 -0
  1892. package/src/utils/renderOptions.js +67 -0
  1893. package/src/utils/ripgrep.js +521 -0
  1894. package/src/utils/sandbox/sandbox-adapter.js +750 -0
  1895. package/src/utils/sandbox/sandbox-ui-utils.js +11 -0
  1896. package/src/utils/sanitization.js +72 -0
  1897. package/src/utils/screenshotClipboard.js +89 -0
  1898. package/src/utils/sdkEventQueue.js +49 -0
  1899. package/src/utils/secureStorage/fallbackStorage.js +59 -0
  1900. package/src/utils/secureStorage/index.js +13 -0
  1901. package/src/utils/secureStorage/keychainPrefetch.js +91 -0
  1902. package/src/utils/secureStorage/macOsKeychainHelpers.js +91 -0
  1903. package/src/utils/secureStorage/macOsKeychainStorage.js +192 -0
  1904. package/src/utils/secureStorage/plainTextStorage.js +81 -0
  1905. package/src/utils/semanticBoolean.js +23 -0
  1906. package/src/utils/semanticNumber.js +34 -0
  1907. package/src/utils/semver.js +51 -0
  1908. package/src/utils/sequential.js +43 -0
  1909. package/src/utils/sessionActivity.js +120 -0
  1910. package/src/utils/sessionEnvVars.js +18 -0
  1911. package/src/utils/sessionEnvironment.js +131 -0
  1912. package/src/utils/sessionFileAccessHooks.js +205 -0
  1913. package/src/utils/sessionIngressAuth.js +113 -0
  1914. package/src/utils/sessionRestore.js +357 -0
  1915. package/src/utils/sessionStart.js +165 -0
  1916. package/src/utils/sessionState.js +76 -0
  1917. package/src/utils/sessionStorage.js +4162 -0
  1918. package/src/utils/sessionStoragePortable.js +665 -0
  1919. package/src/utils/sessionTitle.js +120 -0
  1920. package/src/utils/sessionUrl.js +50 -0
  1921. package/src/utils/set.js +50 -0
  1922. package/src/utils/settings/allErrors.js +29 -0
  1923. package/src/utils/settings/applySettingsChange.js +65 -0
  1924. package/src/utils/settings/changeDetector.js +409 -0
  1925. package/src/utils/settings/constants.js +166 -0
  1926. package/src/utils/settings/internalWrites.js +33 -0
  1927. package/src/utils/settings/managedPath.js +29 -0
  1928. package/src/utils/settings/mdm/constants.js +62 -0
  1929. package/src/utils/settings/mdm/rawRead.js +97 -0
  1930. package/src/utils/settings/mdm/settings.js +254 -0
  1931. package/src/utils/settings/permissionValidation.js +224 -0
  1932. package/src/utils/settings/pluginOnlyPolicy.js +53 -0
  1933. package/src/utils/settings/schemaOutput.js +7 -0
  1934. package/src/utils/settings/settings.js +791 -0
  1935. package/src/utils/settings/settingsCache.js +47 -0
  1936. package/src/utils/settings/toolValidationConfig.js +76 -0
  1937. package/src/utils/settings/types.js +846 -0
  1938. package/src/utils/settings/validateEditTool.js +34 -0
  1939. package/src/utils/settings/validation.js +192 -0
  1940. package/src/utils/settings/validationTips.js +111 -0
  1941. package/src/utils/shell/bashProvider.js +202 -0
  1942. package/src/utils/shell/outputLimits.js +7 -0
  1943. package/src/utils/shell/powershellDetection.js +96 -0
  1944. package/src/utils/shell/powershellProvider.js +104 -0
  1945. package/src/utils/shell/prefix.js +246 -0
  1946. package/src/utils/shell/readOnlyCommandValidation.js +1776 -0
  1947. package/src/utils/shell/resolveDefaultShell.js +13 -0
  1948. package/src/utils/shell/shellProvider.js +2 -0
  1949. package/src/utils/shell/shellToolUtils.js +21 -0
  1950. package/src/utils/shell/specPrefix.js +198 -0
  1951. package/src/utils/shellConfig.js +136 -0
  1952. package/src/utils/sideQuery.js +134 -0
  1953. package/src/utils/sideQuestion.js +121 -0
  1954. package/src/utils/signal.js +34 -0
  1955. package/src/utils/sinks.js +15 -0
  1956. package/src/utils/skills/skillChangeDetector.js +264 -0
  1957. package/src/utils/slashCommandParsing.js +46 -0
  1958. package/src/utils/sleep.js +72 -0
  1959. package/src/utils/sliceAnsi.js +74 -0
  1960. package/src/utils/slowOperations.js +216 -0
  1961. package/src/utils/standaloneAgent.js +20 -0
  1962. package/src/utils/startupProfiler.js +149 -0
  1963. package/src/utils/staticRender.js +104 -0
  1964. package/src/utils/stats.js +802 -0
  1965. package/src/utils/statsCache.js +330 -0
  1966. package/src/utils/status.js +359 -0
  1967. package/src/utils/statusNoticeDefinitions.js +123 -0
  1968. package/src/utils/statusNoticeHelpers.js +15 -0
  1969. package/src/utils/stream.js +73 -0
  1970. package/src/utils/streamJsonStdoutGuard.js +107 -0
  1971. package/src/utils/streamlinedTransform.js +162 -0
  1972. package/src/utils/stringUtils.js +202 -0
  1973. package/src/utils/subprocessEnv.js +87 -0
  1974. package/src/utils/suggestions/commandSuggestions.js +458 -0
  1975. package/src/utils/suggestions/directoryCompletion.js +191 -0
  1976. package/src/utils/suggestions/shellHistoryCompletion.js +95 -0
  1977. package/src/utils/suggestions/skillUsageTracking.js +50 -0
  1978. package/src/utils/suggestions/slackChannelSuggestions.js +169 -0
  1979. package/src/utils/swarm/It2SetupPrompt.js +386 -0
  1980. package/src/utils/swarm/backends/ITermBackend.js +276 -0
  1981. package/src/utils/swarm/backends/InProcessBackend.js +237 -0
  1982. package/src/utils/swarm/backends/PaneBackendExecutor.js +250 -0
  1983. package/src/utils/swarm/backends/TmuxBackend.js +574 -0
  1984. package/src/utils/swarm/backends/detection.js +112 -0
  1985. package/src/utils/swarm/backends/it2Setup.js +185 -0
  1986. package/src/utils/swarm/backends/registry.js +369 -0
  1987. package/src/utils/swarm/backends/teammateModeSnapshot.js +68 -0
  1988. package/src/utils/swarm/backends/types.js +9 -0
  1989. package/src/utils/swarm/constants.js +29 -0
  1990. package/src/utils/swarm/inProcessRunner.js +1021 -0
  1991. package/src/utils/swarm/leaderPermissionBridge.js +31 -0
  1992. package/src/utils/swarm/permissionSync.js +667 -0
  1993. package/src/utils/swarm/reconnection.js +82 -0
  1994. package/src/utils/swarm/spawnInProcess.js +218 -0
  1995. package/src/utils/swarm/spawnUtils.js +123 -0
  1996. package/src/utils/swarm/teamHelpers.js +484 -0
  1997. package/src/utils/swarm/teammateInit.js +87 -0
  1998. package/src/utils/swarm/teammateLayoutManager.js +82 -0
  1999. package/src/utils/swarm/teammateModel.js +9 -0
  2000. package/src/utils/swarm/teammatePromptAddendum.js +17 -0
  2001. package/src/utils/systemDirectories.js +51 -0
  2002. package/src/utils/systemPrompt.js +88 -0
  2003. package/src/utils/systemPromptType.js +9 -0
  2004. package/src/utils/systemTheme.js +108 -0
  2005. package/src/utils/taggedId.js +49 -0
  2006. package/src/utils/task/TaskOutput.js +320 -0
  2007. package/src/utils/task/diskOutput.js +387 -0
  2008. package/src/utils/task/framework.js +236 -0
  2009. package/src/utils/task/outputFormatting.js +24 -0
  2010. package/src/utils/task/sdkProgress.js +24 -0
  2011. package/src/utils/taskSummary.js +3 -0
  2012. package/src/utils/tasks.js +672 -0
  2013. package/src/utils/teamDiscovery.js +48 -0
  2014. package/src/utils/teamMemoryOps.js +67 -0
  2015. package/src/utils/teammate.js +237 -0
  2016. package/src/utils/teammateContext.js +56 -0
  2017. package/src/utils/teammateMailbox.js +793 -0
  2018. package/src/utils/telemetry/betaSessionTracing.js +25 -0
  2019. package/src/utils/telemetry/bigqueryExporter.js +17 -0
  2020. package/src/utils/telemetry/events.js +7 -0
  2021. package/src/utils/telemetry/instrumentation.js +16 -0
  2022. package/src/utils/telemetry/logger.js +25 -0
  2023. package/src/utils/telemetry/perfettoTracing.js +882 -0
  2024. package/src/utils/telemetry/pluginTelemetry.js +76 -0
  2025. package/src/utils/telemetry/sessionTracing.js +62 -0
  2026. package/src/utils/telemetry/skillLoadedEvent.js +4 -0
  2027. package/src/utils/telemetryAttributes.js +56 -0
  2028. package/src/utils/teleport/api.js +299 -0
  2029. package/src/utils/teleport/environmentSelection.js +55 -0
  2030. package/src/utils/teleport/environments.js +84 -0
  2031. package/src/utils/teleport/gitBundle.js +192 -0
  2032. package/src/utils/teleport.js +1047 -0
  2033. package/src/utils/tempfile.js +26 -0
  2034. package/src/utils/terminal.js +105 -0
  2035. package/src/utils/terminalPanel.js +155 -0
  2036. package/src/utils/textHighlighting.js +113 -0
  2037. package/src/utils/thaddeusHints.js +142 -0
  2038. package/src/utils/theme.js +525 -0
  2039. package/src/utils/thinking.js +130 -0
  2040. package/src/utils/timeouts.js +35 -0
  2041. package/src/utils/tmuxSocket.js +373 -0
  2042. package/src/utils/todo/types.js +9 -0
  2043. package/src/utils/tokenBudget.js +62 -0
  2044. package/src/utils/tokens.js +223 -0
  2045. package/src/utils/toolErrors.js +101 -0
  2046. package/src/utils/toolPool.js +61 -0
  2047. package/src/utils/toolResultStorage.js +768 -0
  2048. package/src/utils/toolSchemaCache.js +7 -0
  2049. package/src/utils/toolSearch.js +551 -0
  2050. package/src/utils/transcriptSearch.js +200 -0
  2051. package/src/utils/treeify.js +111 -0
  2052. package/src/utils/truncate.js +164 -0
  2053. package/src/utils/udsClient.js +5 -0
  2054. package/src/utils/udsMessaging.js +23 -0
  2055. package/src/utils/ultraplan/ccrSession.js +264 -0
  2056. package/src/utils/ultraplan/keyword.js +122 -0
  2057. package/src/utils/unaryLogging.js +16 -0
  2058. package/src/utils/undercover.js +89 -0
  2059. package/src/utils/user.js +137 -0
  2060. package/src/utils/userAgent.js +9 -0
  2061. package/src/utils/userPromptKeywords.js +21 -0
  2062. package/src/utils/uuid.js +22 -0
  2063. package/src/utils/warningHandler.js +97 -0
  2064. package/src/utils/which.js +75 -0
  2065. package/src/utils/windowsPaths.js +146 -0
  2066. package/src/utils/withResolvers.js +13 -0
  2067. package/src/utils/words.js +793 -0
  2068. package/src/utils/workforceIntent.js +192 -0
  2069. package/src/utils/workloadContext.js +42 -0
  2070. package/src/utils/worktree.js +1142 -0
  2071. package/src/utils/worktreeModeEnabled.js +11 -0
  2072. package/src/utils/xdg.js +52 -0
  2073. package/src/utils/xml.js +15 -0
  2074. package/src/utils/yaml.js +14 -0
  2075. package/src/utils/zodToJsonSchema.js +19 -0
  2076. package/src/vim/motions.js +73 -0
  2077. package/src/vim/operators.js +401 -0
  2078. package/src/vim/textObjects.js +153 -0
  2079. package/src/vim/transitions.js +340 -0
  2080. package/src/vim/types.js +93 -0
  2081. package/src/voice/voiceModeEnabled.js +20 -0
  2082. package/thaddeus-terminal.ts +401 -3
@@ -0,0 +1,4294 @@
1
+ // biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
2
+ import { feature } from 'bun:bundle';
3
+ import { readFile, stat } from 'fs/promises';
4
+ import { dirname } from 'path';
5
+ import { downloadUserSettings, redownloadUserSettings, } from 'src/services/settingsSync/index.js';
6
+ import { waitForRemoteManagedSettingsToLoad } from 'src/services/remoteManagedSettings/index.js';
7
+ import { StructuredIO } from 'src/cli/structuredIO.js';
8
+ import { RemoteIO } from 'src/cli/remoteIO.js';
9
+ import { formatDescriptionWithSource, getCommandName, } from 'src/commands.js';
10
+ import { createStreamlinedTransformer } from 'src/utils/streamlinedTransform.js';
11
+ import { installStreamJsonStdoutGuard } from 'src/utils/streamJsonStdoutGuard.js';
12
+ import { assembleToolPool, filterToolsByDenyRules } from 'src/tools.js';
13
+ import uniqBy from 'lodash-es/uniqBy.js';
14
+ import { uniq } from 'src/utils/array.js';
15
+ import { mergeAndFilterTools } from 'src/utils/toolPool.js';
16
+ import { logEvent, } from 'src/services/analytics/index.js';
17
+ import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js';
18
+ import { logForDebugging } from 'src/utils/debug.js';
19
+ import { logForDiagnosticsNoPII, withDiagnosticsTiming, } from 'src/utils/diagLogs.js';
20
+ import { toolMatchesName } from 'src/Tool.js';
21
+ import { isBuiltInAgent, parseAgentsFromJson, } from 'src/tools/AgentTool/loadAgentsDir.js';
22
+ import { dequeue, dequeueAllMatching, enqueue, hasCommandsInQueue, peek, subscribeToCommandQueue, getCommandsByMaxPriority, } from 'src/utils/messageQueueManager.js';
23
+ import { notifyCommandLifecycle } from 'src/utils/commandLifecycle.js';
24
+ import { getSessionState, notifySessionStateChanged, notifySessionMetadataChanged, setPermissionModeChangedListener, } from 'src/utils/sessionState.js';
25
+ import { externalMetadataToAppState } from 'src/state/onChangeAppState.js';
26
+ import { getInMemoryErrors, logError, logMCPDebug } from 'src/utils/log.js';
27
+ import { writeToStdout, registerProcessOutputErrorHandlers, } from 'src/utils/process.js';
28
+ import { EMPTY_USAGE } from 'src/services/api/logging.js';
29
+ import { loadConversationForResume, } from 'src/utils/conversationRecovery.js';
30
+ import { ChannelMessageNotificationSchema, gateChannelServer, wrapChannelMessage, findChannelEntry, } from 'src/services/mcp/channelNotification.js';
31
+ import { isChannelAllowlisted, isChannelsEnabled, } from 'src/services/mcp/channelAllowlist.js';
32
+ import { parsePluginIdentifier } from 'src/utils/plugins/pluginIdentifier.js';
33
+ import { validateUuid } from 'src/utils/uuid.js';
34
+ import { fromArray } from 'src/utils/generators.js';
35
+ import { ask } from 'src/QueryEngine.js';
36
+ import { createFileStateCacheWithSizeLimit, mergeFileStateCaches, READ_FILE_STATE_CACHE_SIZE, } from 'src/utils/fileStateCache.js';
37
+ import { expandPath } from 'src/utils/path.js';
38
+ import { extractReadFilesFromMessages } from 'src/utils/queryHelpers.js';
39
+ import { registerHookEventHandler } from 'src/utils/hooks/hookEvents.js';
40
+ import { executeFilePersistence } from 'src/utils/filePersistence/filePersistence.js';
41
+ import { finalizePendingAsyncHooks } from 'src/utils/hooks/AsyncHookRegistry.js';
42
+ import { gracefulShutdown, gracefulShutdownSync, isShuttingDown, } from 'src/utils/gracefulShutdown.js';
43
+ import { registerCleanup } from 'src/utils/cleanupRegistry.js';
44
+ import { createIdleTimeoutManager } from 'src/utils/idleTimeout.js';
45
+ import { cwd } from 'process';
46
+ import { getCwd } from 'src/utils/cwd.js';
47
+ import omit from 'lodash-es/omit.js';
48
+ import reject from 'lodash-es/reject.js';
49
+ import { isPolicyAllowed } from 'src/services/policyLimits/index.js';
50
+ import { getRemoteSessionUrl } from 'src/constants/product.js';
51
+ import { buildBridgeConnectUrl } from 'src/bridge/bridgeStatusUtil.js';
52
+ import { extractInboundMessageFields } from 'src/bridge/inboundMessages.js';
53
+ import { resolveAndPrepend } from 'src/bridge/inboundAttachments.js';
54
+ import { hasPermissionsToUseTool } from 'src/utils/permissions/permissions.js';
55
+ import { safeParseJSON } from 'src/utils/json.js';
56
+ import { outputSchema as permissionToolOutputSchema, permissionPromptToolResultToPermissionDecision, } from 'src/utils/permissions/PermissionPromptToolResultSchema.js';
57
+ import { createAbortController } from 'src/utils/abortController.js';
58
+ import { createCombinedAbortSignal } from 'src/utils/combinedAbortSignal.js';
59
+ import { generateSessionTitle } from 'src/utils/sessionTitle.js';
60
+ import { buildSideQuestionFallbackParams } from 'src/utils/queryContext.js';
61
+ import { runSideQuestion } from 'src/utils/sideQuestion.js';
62
+ import { processSessionStartHooks, processSetupHooks, takeInitialUserMessage, } from 'src/utils/sessionStart.js';
63
+ import { DEFAULT_OUTPUT_STYLE_NAME, getAllOutputStyles, } from 'src/constants/outputStyles.js';
64
+ import { TEAMMATE_MESSAGE_TAG, TICK_TAG } from 'src/constants/xml.js';
65
+ import { getSettings_DEPRECATED, getSettingsWithSources, } from 'src/utils/settings/settings.js';
66
+ import { settingsChangeDetector } from 'src/utils/settings/changeDetector.js';
67
+ import { applySettingsChange } from 'src/utils/settings/applySettingsChange.js';
68
+ import { isFastModeAvailable, isFastModeEnabled, isFastModeSupportedByModel, getFastModeState, } from 'src/utils/fastMode.js';
69
+ import { isAutoModeGateEnabled, getAutoModeUnavailableNotification, getAutoModeUnavailableReason, isBypassPermissionsModeDisabled, transitionPermissionMode, } from 'src/utils/permissions/permissionSetup.js';
70
+ import { tryGenerateSuggestion, logSuggestionOutcome, logSuggestionSuppressed, } from 'src/services/PromptSuggestion/promptSuggestion.js';
71
+ import { getLastCacheSafeParams } from 'src/utils/forkedAgent.js';
72
+ import { getAccountInformation } from 'src/utils/auth.js';
73
+ import { OAuthService } from 'src/services/oauth/index.js';
74
+ import { installOAuthTokens } from 'src/cli/handlers/auth.js';
75
+ import { getAPIProvider } from 'src/utils/model/providers.js';
76
+ import { AwsAuthStatusManager } from 'src/utils/awsAuthStatusManager.js';
77
+ import { registerHookCallbacks, setInitJsonSchema, getInitJsonSchema, setSdkAgentProgressSummariesEnabled, } from 'src/bootstrap/state.js';
78
+ import { createSyntheticOutputTool } from 'src/tools/SyntheticOutputTool/SyntheticOutputTool.js';
79
+ import { parseSessionIdentifier } from 'src/utils/sessionUrl.js';
80
+ import { hydrateRemoteSession, hydrateFromCCRv2InternalEvents, resetSessionFilePointer, doesMessageExistInSession, findUnresolvedToolUse, recordAttributionSnapshot, saveAgentSetting, saveMode, saveAiGeneratedTitle, restoreSessionMetadata, } from 'src/utils/sessionStorage.js';
81
+ import { incrementPromptCount } from 'src/utils/commitAttribution.js';
82
+ import { setupSdkMcpClients, connectToServer, clearServerCache, fetchToolsForClient, areMcpConfigsEqual, reconnectMcpServerImpl, } from 'src/services/mcp/client.js';
83
+ import { filterMcpServersByPolicy, getMcpConfigByName, isMcpServerDisabled, setMcpServerEnabled, } from 'src/services/mcp/config.js';
84
+ import { performMCPOAuthFlow, revokeServerTokens, } from 'src/services/mcp/auth.js';
85
+ import { runElicitationHooks, runElicitationResultHooks, } from 'src/services/mcp/elicitationHandler.js';
86
+ import { executeNotificationHooks } from 'src/utils/hooks.js';
87
+ import { ElicitRequestSchema, ElicitationCompleteNotificationSchema, } from '@modelcontextprotocol/sdk/types.js';
88
+ import { getMcpPrefix } from 'src/services/mcp/mcpStringUtils.js';
89
+ import { commandBelongsToServer, filterToolsByServer, } from 'src/services/mcp/utils.js';
90
+ import { setupVscodeSdkMcp } from 'src/services/mcp/vscodeSdkMcp.js';
91
+ import { getAllMcpConfigs } from 'src/services/mcp/config.js';
92
+ import { isQualifiedForGrove, checkGroveForNonInteractive, } from 'src/services/api/grove.js';
93
+ import { toInternalMessages, toSDKRateLimitInfo, } from 'src/utils/messages/mappers.js';
94
+ import { createModelSwitchBreadcrumbs } from 'src/utils/messages.js';
95
+ import { collectContextData } from 'src/commands/context/context-noninteractive.js';
96
+ import { LOCAL_COMMAND_STDOUT_TAG } from 'src/constants/xml.js';
97
+ import { statusListeners, } from 'src/services/claudeAiLimits.js';
98
+ import { getDefaultMainLoopModel, getMainLoopModel, modelDisplayString, parseUserSpecifiedModel, } from 'src/utils/model/model.js';
99
+ import { getModelOptions } from 'src/utils/model/modelOptions.js';
100
+ import { modelSupportsEffort, modelSupportsMaxEffort, EFFORT_LEVELS, resolveAppliedEffort, } from 'src/utils/effort.js';
101
+ import { modelSupportsAdaptiveThinking } from 'src/utils/thinking.js';
102
+ import { modelSupportsAutoMode } from 'src/utils/betas.js';
103
+ import { ensureModelStringsInitialized } from 'src/utils/model/modelStrings.js';
104
+ import { getSessionId, setMainLoopModelOverride, setMainThreadAgentType, switchSession, isSessionPersistenceDisabled, getIsRemoteMode, getFlagSettingsInline, setFlagSettingsInline, getMainThreadAgentType, getAllowedChannels, setAllowedChannels, } from 'src/bootstrap/state.js';
105
+ import { runWithWorkload, WORKLOAD_CRON } from 'src/utils/workloadContext.js';
106
+ import { randomUUID } from 'crypto';
107
+ import { fileHistoryRewind, fileHistoryCanRestore, fileHistoryEnabled, fileHistoryGetDiffStats, } from 'src/utils/fileHistory.js';
108
+ import { restoreAgentFromSession, restoreSessionStateFromLog, } from 'src/utils/sessionRestore.js';
109
+ import { SandboxManager } from 'src/utils/sandbox/sandbox-adapter.js';
110
+ import { headlessProfilerStartTurn, headlessProfilerCheckpoint, logHeadlessProfilerTurn, } from 'src/utils/headlessProfiler.js';
111
+ import { startQueryProfile, logQueryProfileReport, } from 'src/utils/queryProfiler.js';
112
+ import { asSessionId } from 'src/types/ids.js';
113
+ import { jsonStringify } from '../utils/slowOperations.js';
114
+ import { skillChangeDetector } from '../utils/skills/skillChangeDetector.js';
115
+ import { getCommands, clearCommandsCache } from '../commands.js';
116
+ import { isBareMode, isEnvTruthy, isEnvDefinedFalsy, } from '../utils/envUtils.js';
117
+ import { installPluginsForHeadless } from '../utils/plugins/headlessPluginInstall.js';
118
+ import { refreshActivePlugins } from '../utils/plugins/refresh.js';
119
+ import { loadAllPluginsCacheOnly } from '../utils/plugins/pluginLoader.js';
120
+ import { isTeamLead, hasActiveInProcessTeammates, hasWorkingInProcessTeammates, waitForTeammatesToBecomeIdle, } from '../utils/teammate.js';
121
+ import { readUnreadMessages, markMessagesAsRead, isShutdownApproved, } from '../utils/teammateMailbox.js';
122
+ import { removeTeammateFromTeamFile } from '../utils/swarm/teamHelpers.js';
123
+ import { unassignTeammateTasks } from '../utils/tasks.js';
124
+ import { getRunningTasks } from '../utils/task/framework.js';
125
+ import { isBackgroundTask } from '../tasks/types.js';
126
+ import { stopTask } from '../tasks/stopTask.js';
127
+ import { drainSdkEvents } from '../utils/sdkEventQueue.js';
128
+ import { initializeGrowthBook } from '../services/analytics/growthbook.js';
129
+ import { errorMessage, toError } from '../utils/errors.js';
130
+ import { sleep } from '../utils/sleep.js';
131
+ import { isExtractModeActive } from '../memdir/paths.js';
132
+ // Dead code elimination: conditional imports
133
+ /* eslint-disable @typescript-eslint/no-require-imports */
134
+ const coordinatorModeModule = feature('COORDINATOR_MODE')
135
+ ? require('../coordinator/coordinatorMode.js')
136
+ : null;
137
+ const proactiveModule = feature('PROACTIVE') || feature('KAIROS')
138
+ ? require('../proactive/index.js')
139
+ : null;
140
+ const cronSchedulerModule = feature('AGENT_TRIGGERS')
141
+ ? require('../utils/cronScheduler.js')
142
+ : null;
143
+ const cronJitterConfigModule = feature('AGENT_TRIGGERS')
144
+ ? require('../utils/cronJitterConfig.js')
145
+ : null;
146
+ const cronGate = feature('AGENT_TRIGGERS')
147
+ ? require('../tools/ScheduleCronTool/prompt.js')
148
+ : null;
149
+ const extractMemoriesModule = feature('EXTRACT_MEMORIES')
150
+ ? require('../services/extractMemories/extractMemories.js')
151
+ : null;
152
+ /* eslint-enable @typescript-eslint/no-require-imports */
153
+ const SHUTDOWN_TEAM_PROMPT = `<system-reminder>
154
+ You are running in non-interactive mode and cannot return a response to the user until your team is shut down.
155
+
156
+ You MUST shut down your team before preparing your final response:
157
+ 1. Use requestShutdown to ask each team member to shut down gracefully
158
+ 2. Wait for shutdown approvals
159
+ 3. Use the cleanup operation to clean up the team
160
+ 4. Only then provide your final response to the user
161
+
162
+ The user cannot receive your response until the team is completely shut down.
163
+ </system-reminder>
164
+
165
+ Shut down your team and prepare your final response for the user.`;
166
+ // Track message UUIDs received during the current session runtime
167
+ const MAX_RECEIVED_UUIDS = 10_000;
168
+ const receivedMessageUuids = new Set();
169
+ const receivedMessageUuidsOrder = [];
170
+ function trackReceivedMessageUuid(uuid) {
171
+ if (receivedMessageUuids.has(uuid)) {
172
+ return false; // duplicate
173
+ }
174
+ receivedMessageUuids.add(uuid);
175
+ receivedMessageUuidsOrder.push(uuid);
176
+ // Evict oldest entries when at capacity
177
+ if (receivedMessageUuidsOrder.length > MAX_RECEIVED_UUIDS) {
178
+ const toEvict = receivedMessageUuidsOrder.splice(0, receivedMessageUuidsOrder.length - MAX_RECEIVED_UUIDS);
179
+ for (const old of toEvict) {
180
+ receivedMessageUuids.delete(old);
181
+ }
182
+ }
183
+ return true; // new UUID
184
+ }
185
+ function toBlocks(v) {
186
+ return typeof v === 'string' ? [{ type: 'text', text: v }] : v;
187
+ }
188
+ /**
189
+ * Join prompt values from multiple queued commands into one. Strings are
190
+ * newline-joined; if any value is a block array, all values are normalized
191
+ * to blocks and concatenated.
192
+ */
193
+ export function joinPromptValues(values) {
194
+ if (values.length === 1)
195
+ return values[0];
196
+ if (values.every(v => typeof v === 'string')) {
197
+ return values.join('\n');
198
+ }
199
+ return values.flatMap(toBlocks);
200
+ }
201
+ /**
202
+ * Whether `next` can be batched into the same ask() call as `head`. Only
203
+ * prompt-mode commands batch, and only when the workload tag matches (so the
204
+ * combined turn is attributed correctly) and the isMeta flag matches (so a
205
+ * proactive tick can't merge into a user prompt and lose its hidden-in-
206
+ * transcript marking when the head is spread over the merged command).
207
+ */
208
+ export function canBatchWith(head, next) {
209
+ return (next !== undefined &&
210
+ next.mode === 'prompt' &&
211
+ next.workload === head.workload &&
212
+ next.isMeta === head.isMeta);
213
+ }
214
+ export async function runHeadless(inputPrompt, getAppState, setAppState, commands, tools, sdkMcpConfigs, agents, options) {
215
+ if (process.env.USER_TYPE === 'ant' &&
216
+ isEnvTruthy(process.env.THADDEUS_EXIT_AFTER_FIRST_RENDER)) {
217
+ process.stderr.write(`\nStartup time: ${Math.round(process.uptime() * 1000)}ms\n`);
218
+ // eslint-disable-next-line custom-rules/no-process-exit
219
+ process.exit(0);
220
+ }
221
+ // Fire user settings download now so it overlaps with the MCP/tool setup
222
+ // below. Managed settings already started in main.tsx preAction; this gives
223
+ // user settings a similar head start. The cached promise is joined in
224
+ // installPluginsAndApplyMcpInBackground before plugin install reads
225
+ // enabledPlugins.
226
+ if (feature('DOWNLOAD_USER_SETTINGS') &&
227
+ (isEnvTruthy(process.env.THADDEUS_REMOTE) || getIsRemoteMode())) {
228
+ void downloadUserSettings();
229
+ }
230
+ // In headless mode there is no React tree, so the useSettingsChange hook
231
+ // never runs. Subscribe directly so that settings changes (including
232
+ // managed-settings / policy updates) are fully applied.
233
+ settingsChangeDetector.subscribe(source => {
234
+ applySettingsChange(source, setAppState);
235
+ // In headless mode, also sync the denormalized fastMode field from
236
+ // settings. The TUI manages fastMode via the UI so it skips this.
237
+ if (isFastModeEnabled()) {
238
+ setAppState(prev => {
239
+ const s = prev.settings;
240
+ const fastMode = s.fastMode === true && !s.fastModePerSessionOptIn;
241
+ return { ...prev, fastMode };
242
+ });
243
+ }
244
+ });
245
+ // Proactive activation is now handled in main.tsx before getTools() so
246
+ // SleepTool passes isEnabled() filtering. This fallback covers the case
247
+ // where THADDEUS_PROACTIVE is set but main.tsx's check didn't fire
248
+ // (e.g. env was injected by the SDK transport after argv parsing).
249
+ if ((feature('PROACTIVE') || feature('KAIROS')) &&
250
+ proactiveModule &&
251
+ !proactiveModule.isProactiveActive() &&
252
+ isEnvTruthy(process.env.THADDEUS_PROACTIVE)) {
253
+ proactiveModule.activateProactive('command');
254
+ }
255
+ // Periodically force a full GC to keep memory usage in check
256
+ if (typeof Bun !== 'undefined') {
257
+ const gcTimer = setInterval(Bun.gc, 1000);
258
+ gcTimer.unref();
259
+ }
260
+ // Start headless profiler for first turn
261
+ headlessProfilerStartTurn();
262
+ headlessProfilerCheckpoint('runHeadless_entry');
263
+ // Check Grove requirements for non-interactive consumer subscribers
264
+ if (await isQualifiedForGrove()) {
265
+ await checkGroveForNonInteractive();
266
+ }
267
+ headlessProfilerCheckpoint('after_grove_check');
268
+ // Initialize GrowthBook so feature flags take effect in headless mode.
269
+ // Without this, the disk cache is empty and all flags fall back to defaults.
270
+ void initializeGrowthBook();
271
+ if (options.resumeSessionAt && !options.resume) {
272
+ process.stderr.write(`Error: --resume-session-at requires --resume\n`);
273
+ gracefulShutdownSync(1);
274
+ return;
275
+ }
276
+ if (options.rewindFiles && !options.resume) {
277
+ process.stderr.write(`Error: --rewind-files requires --resume\n`);
278
+ gracefulShutdownSync(1);
279
+ return;
280
+ }
281
+ if (options.rewindFiles && inputPrompt) {
282
+ process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt\n`);
283
+ gracefulShutdownSync(1);
284
+ return;
285
+ }
286
+ const structuredIO = getStructuredIO(inputPrompt, options);
287
+ // When emitting NDJSON for SDK clients, any stray write to stdout (debug
288
+ // prints, dependency console.log, library banners) breaks the client's
289
+ // line-by-line JSON parser. Install a guard that diverts non-JSON lines to
290
+ // stderr so the stream stays clean. Must run before the first
291
+ // structuredIO.write below.
292
+ if (options.outputFormat === 'stream-json') {
293
+ installStreamJsonStdoutGuard();
294
+ }
295
+ // #34044: if user explicitly set sandbox.enabled=true but deps are missing,
296
+ // isSandboxingEnabled() returns false silently. Surface the reason so users
297
+ // know their security config isn't being enforced.
298
+ const sandboxUnavailableReason = SandboxManager.getSandboxUnavailableReason();
299
+ if (sandboxUnavailableReason) {
300
+ if (SandboxManager.isSandboxRequired()) {
301
+ process.stderr.write(`\nError: sandbox required but unavailable: ${sandboxUnavailableReason}\n` +
302
+ ` sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`);
303
+ gracefulShutdownSync(1);
304
+ return;
305
+ }
306
+ process.stderr.write(`\n⚠ Sandbox disabled: ${sandboxUnavailableReason}\n` +
307
+ ` Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced.\n\n`);
308
+ }
309
+ else if (SandboxManager.isSandboxingEnabled()) {
310
+ // Initialize sandbox with a callback that forwards network permission
311
+ // requests to the SDK host via the can_use_tool control_request protocol.
312
+ // This must happen after structuredIO is created so we can send requests.
313
+ try {
314
+ await SandboxManager.initialize(structuredIO.createSandboxAskCallback());
315
+ }
316
+ catch (err) {
317
+ process.stderr.write(`\n❌ Sandbox Error: ${errorMessage(err)}\n`);
318
+ gracefulShutdownSync(1, 'other');
319
+ return;
320
+ }
321
+ }
322
+ if (options.outputFormat === 'stream-json' && options.verbose) {
323
+ registerHookEventHandler(event => {
324
+ const message = (() => {
325
+ switch (event.type) {
326
+ case 'started':
327
+ return {
328
+ type: 'system',
329
+ subtype: 'hook_started',
330
+ hook_id: event.hookId,
331
+ hook_name: event.hookName,
332
+ hook_event: event.hookEvent,
333
+ uuid: randomUUID(),
334
+ session_id: getSessionId(),
335
+ };
336
+ case 'progress':
337
+ return {
338
+ type: 'system',
339
+ subtype: 'hook_progress',
340
+ hook_id: event.hookId,
341
+ hook_name: event.hookName,
342
+ hook_event: event.hookEvent,
343
+ stdout: event.stdout,
344
+ stderr: event.stderr,
345
+ output: event.output,
346
+ uuid: randomUUID(),
347
+ session_id: getSessionId(),
348
+ };
349
+ case 'response':
350
+ return {
351
+ type: 'system',
352
+ subtype: 'hook_response',
353
+ hook_id: event.hookId,
354
+ hook_name: event.hookName,
355
+ hook_event: event.hookEvent,
356
+ output: event.output,
357
+ stdout: event.stdout,
358
+ stderr: event.stderr,
359
+ exit_code: event.exitCode,
360
+ outcome: event.outcome,
361
+ uuid: randomUUID(),
362
+ session_id: getSessionId(),
363
+ };
364
+ }
365
+ })();
366
+ void structuredIO.write(message);
367
+ });
368
+ }
369
+ if (options.setupTrigger) {
370
+ await processSetupHooks(options.setupTrigger);
371
+ }
372
+ headlessProfilerCheckpoint('before_loadInitialMessages');
373
+ const appState = getAppState();
374
+ const { messages: initialMessages, turnInterruptionState, agentSetting: resumedAgentSetting, } = await loadInitialMessages(setAppState, {
375
+ continue: options.continue,
376
+ teleport: options.teleport,
377
+ resume: options.resume,
378
+ resumeSessionAt: options.resumeSessionAt,
379
+ forkSession: options.forkSession,
380
+ outputFormat: options.outputFormat,
381
+ sessionStartHooksPromise: options.sessionStartHooksPromise,
382
+ restoredWorkerState: structuredIO.restoredWorkerState,
383
+ });
384
+ // SessionStart hooks can emit initialUserMessage — the first user turn for
385
+ // headless orchestrator sessions where stdin is empty and additionalContext
386
+ // alone (an attachment, not a turn) would leave the REPL with nothing to
387
+ // respond to. The hook promise is awaited inside loadInitialMessages, so the
388
+ // module-level pending value is set by the time we get here.
389
+ const hookInitialUserMessage = takeInitialUserMessage();
390
+ if (hookInitialUserMessage) {
391
+ structuredIO.prependUserMessage(hookInitialUserMessage);
392
+ }
393
+ // Restore agent setting from the resumed session (if not overridden by current --agent flag
394
+ // or settings-based agent, which would already have set mainThreadAgentType in main.tsx)
395
+ if (!options.agent && !getMainThreadAgentType() && resumedAgentSetting) {
396
+ const { agentDefinition: restoredAgent } = restoreAgentFromSession(resumedAgentSetting, undefined, { activeAgents: agents, allAgents: agents });
397
+ if (restoredAgent) {
398
+ setAppState(prev => ({ ...prev, agent: restoredAgent.agentType }));
399
+ // Apply the agent's system prompt for non-built-in agents (mirrors main.tsx initial --agent path)
400
+ if (!options.systemPrompt && !isBuiltInAgent(restoredAgent)) {
401
+ const agentSystemPrompt = restoredAgent.getSystemPrompt();
402
+ if (agentSystemPrompt) {
403
+ options.systemPrompt = agentSystemPrompt;
404
+ }
405
+ }
406
+ // Re-persist agent setting so future resumes maintain the agent
407
+ saveAgentSetting(restoredAgent.agentType);
408
+ }
409
+ }
410
+ // gracefulShutdownSync schedules an async shutdown and sets process.exitCode.
411
+ // If a loadInitialMessages error path triggered it, bail early to avoid
412
+ // unnecessary work while the process winds down.
413
+ if (initialMessages.length === 0 && process.exitCode !== undefined) {
414
+ return;
415
+ }
416
+ // Handle --rewind-files: restore filesystem and exit immediately
417
+ if (options.rewindFiles) {
418
+ // File history snapshots are only created for user messages,
419
+ // so we require the target to be a user message
420
+ const targetMessage = initialMessages.find(m => m.uuid === options.rewindFiles);
421
+ if (!targetMessage || targetMessage.type !== 'user') {
422
+ process.stderr.write(`Error: --rewind-files requires a user message UUID, but ${options.rewindFiles} is not a user message in this session\n`);
423
+ gracefulShutdownSync(1);
424
+ return;
425
+ }
426
+ const currentAppState = getAppState();
427
+ const result = await handleRewindFiles(options.rewindFiles, currentAppState, setAppState, false);
428
+ if (!result.canRewind) {
429
+ process.stderr.write(`Error: ${result.error || 'Unexpected error'}\n`);
430
+ gracefulShutdownSync(1);
431
+ return;
432
+ }
433
+ // Rewind complete - exit successfully
434
+ process.stdout.write(`Files rewound to state at message ${options.rewindFiles}\n`);
435
+ gracefulShutdownSync(0);
436
+ return;
437
+ }
438
+ // Check if we need input prompt - skip if we're resuming with a valid session ID/JSONL file or using SDK URL
439
+ const hasValidResumeSessionId = typeof options.resume === 'string' &&
440
+ (Boolean(validateUuid(options.resume)) || options.resume.endsWith('.jsonl'));
441
+ const isUsingSdkUrl = Boolean(options.sdkUrl);
442
+ if (!inputPrompt && !hasValidResumeSessionId && !isUsingSdkUrl) {
443
+ process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print\n`);
444
+ gracefulShutdownSync(1);
445
+ return;
446
+ }
447
+ if (options.outputFormat === 'stream-json' && !options.verbose) {
448
+ process.stderr.write('Error: When using --print, --output-format=stream-json requires --verbose\n');
449
+ gracefulShutdownSync(1);
450
+ return;
451
+ }
452
+ // Filter out MCP tools that are in the deny list
453
+ const allowedMcpTools = filterToolsByDenyRules(appState.mcp.tools, appState.toolPermissionContext);
454
+ let filteredTools = [...tools, ...allowedMcpTools];
455
+ // When using SDK URL, always use stdio permission prompting to delegate to the SDK
456
+ const effectivePermissionPromptToolName = options.sdkUrl
457
+ ? 'stdio'
458
+ : options.permissionPromptToolName;
459
+ // Callback for when a permission prompt is shown
460
+ const onPermissionPrompt = (details) => {
461
+ if (feature('COMMIT_ATTRIBUTION')) {
462
+ setAppState(prev => ({
463
+ ...prev,
464
+ attribution: {
465
+ ...prev.attribution,
466
+ permissionPromptCount: prev.attribution.permissionPromptCount + 1,
467
+ },
468
+ }));
469
+ }
470
+ notifySessionStateChanged('requires_action', details);
471
+ };
472
+ const canUseTool = getCanUseToolFn(effectivePermissionPromptToolName, structuredIO, () => getAppState().mcp.tools, onPermissionPrompt);
473
+ if (options.permissionPromptToolName) {
474
+ // Remove the permission prompt tool from the list of available tools.
475
+ filteredTools = filteredTools.filter(tool => !toolMatchesName(tool, options.permissionPromptToolName));
476
+ }
477
+ // Install errors handlers to gracefully handle broken pipes (e.g., when parent process dies)
478
+ registerProcessOutputErrorHandlers();
479
+ headlessProfilerCheckpoint('after_loadInitialMessages');
480
+ // Ensure model strings are initialized before generating model options.
481
+ // For Bedrock users, this waits for the profile fetch to get correct region strings.
482
+ await ensureModelStringsInitialized();
483
+ headlessProfilerCheckpoint('after_modelStrings');
484
+ // UDS inbox store registration is deferred until after `run` is defined
485
+ // so we can pass `run` as the onEnqueue callback (see below).
486
+ // Only `json` + `verbose` needs the full array (jsonStringify(messages) below).
487
+ // For stream-json (SDK/CCR) and default text output, only the last message is
488
+ // read for the exit code / final result. Avoid accumulating every message in
489
+ // memory for the entire session.
490
+ const needsFullArray = options.outputFormat === 'json' && options.verbose;
491
+ const messages = [];
492
+ let lastMessage;
493
+ // Streamlined mode transforms messages when THADDEUS_STREAMLINED_OUTPUT=true and using stream-json
494
+ // Build flag gates this out of external builds; env var is the runtime opt-in for ant builds
495
+ const transformToStreamlined = feature('STREAMLINED_OUTPUT') &&
496
+ isEnvTruthy(process.env.THADDEUS_STREAMLINED_OUTPUT) &&
497
+ options.outputFormat === 'stream-json'
498
+ ? createStreamlinedTransformer()
499
+ : null;
500
+ headlessProfilerCheckpoint('before_runHeadlessStreaming');
501
+ for await (const message of runHeadlessStreaming(structuredIO, appState.mcp.clients, [...commands, ...appState.mcp.commands], filteredTools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents, options, turnInterruptionState)) {
502
+ if (transformToStreamlined) {
503
+ // Streamlined mode: transform messages and stream immediately
504
+ const transformed = transformToStreamlined(message);
505
+ if (transformed) {
506
+ await structuredIO.write(transformed);
507
+ }
508
+ }
509
+ else if (options.outputFormat === 'stream-json' && options.verbose) {
510
+ await structuredIO.write(message);
511
+ }
512
+ // Should not be getting control messages or stream events in non-stream mode.
513
+ // Also filter out streamlined types since they're only produced by the transformer.
514
+ // SDK-only system events are excluded so lastMessage stays at the result
515
+ // (session_state_changed(idle) and any late task_notification drain after
516
+ // result in the finally block).
517
+ if (message.type !== 'control_response' &&
518
+ message.type !== 'control_request' &&
519
+ message.type !== 'control_cancel_request' &&
520
+ !(message.type === 'system' &&
521
+ (message.subtype === 'session_state_changed' ||
522
+ message.subtype === 'task_notification' ||
523
+ message.subtype === 'task_started' ||
524
+ message.subtype === 'task_progress' ||
525
+ message.subtype === 'post_turn_summary')) &&
526
+ message.type !== 'stream_event' &&
527
+ message.type !== 'keep_alive' &&
528
+ message.type !== 'streamlined_text' &&
529
+ message.type !== 'streamlined_tool_use_summary' &&
530
+ message.type !== 'prompt_suggestion') {
531
+ if (needsFullArray) {
532
+ messages.push(message);
533
+ }
534
+ lastMessage = message;
535
+ }
536
+ }
537
+ switch (options.outputFormat) {
538
+ case 'json':
539
+ if (!lastMessage || lastMessage.type !== 'result') {
540
+ throw new Error('No messages returned');
541
+ }
542
+ if (options.verbose) {
543
+ writeToStdout(jsonStringify(messages) + '\n');
544
+ break;
545
+ }
546
+ writeToStdout(jsonStringify(lastMessage) + '\n');
547
+ break;
548
+ case 'stream-json':
549
+ // already logged above
550
+ break;
551
+ default:
552
+ if (!lastMessage || lastMessage.type !== 'result') {
553
+ throw new Error('No messages returned');
554
+ }
555
+ switch (lastMessage.subtype) {
556
+ case 'success':
557
+ writeToStdout(lastMessage.result.endsWith('\n')
558
+ ? lastMessage.result
559
+ : lastMessage.result + '\n');
560
+ break;
561
+ case 'error_during_execution':
562
+ writeToStdout(`Execution error`);
563
+ break;
564
+ case 'error_max_turns':
565
+ writeToStdout(`Error: Reached max turns (${options.maxTurns})`);
566
+ break;
567
+ case 'error_max_budget_usd':
568
+ writeToStdout(`Error: Exceeded USD budget (${options.maxBudgetUsd})`);
569
+ break;
570
+ case 'error_max_structured_output_retries':
571
+ writeToStdout(`Error: Failed to provide valid structured output after maximum retries`);
572
+ }
573
+ }
574
+ // Log headless latency metrics for the final turn
575
+ logHeadlessProfilerTurn();
576
+ // Drain any in-flight memory extraction before shutdown. The response is
577
+ // already flushed above, so this adds no user-visible latency — it just
578
+ // delays process exit so gracefulShutdownSync's 5s failsafe doesn't kill
579
+ // the forked agent mid-flight. Gated by isExtractModeActive so the
580
+ // thaddeus_slate_thimble flag controls non-interactive extraction end-to-end.
581
+ if (feature('EXTRACT_MEMORIES') && isExtractModeActive()) {
582
+ await extractMemoriesModule.drainPendingExtraction();
583
+ }
584
+ gracefulShutdownSync(lastMessage?.type === 'result' && lastMessage?.is_error ? 1 : 0);
585
+ }
586
+ function runHeadlessStreaming(structuredIO, mcpClients, commands, tools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents, options, turnInterruptionState) {
587
+ let running = false;
588
+ let runPhase;
589
+ let inputClosed = false;
590
+ let shutdownPromptInjected = false;
591
+ let heldBackResult = null;
592
+ let abortController;
593
+ // Same queue sendRequest() enqueues to — one FIFO for everything.
594
+ const output = structuredIO.outbound;
595
+ // Ctrl+C in -p mode: abort the in-flight query, then shut down gracefully.
596
+ // gracefulShutdown persists session state and flushes analytics, with a
597
+ // failsafe timer that force-exits if cleanup hangs.
598
+ const sigintHandler = () => {
599
+ logForDiagnosticsNoPII('info', 'shutdown_signal', { signal: 'SIGINT' });
600
+ if (abortController && !abortController.signal.aborted) {
601
+ abortController.abort();
602
+ }
603
+ void gracefulShutdown(0);
604
+ };
605
+ process.on('SIGINT', sigintHandler);
606
+ // Dump run()'s state at SIGTERM so a stuck session's healthsweep can name
607
+ // the do/while(waitingForAgents) poll without reading the transcript.
608
+ registerCleanup(async () => {
609
+ const bg = {};
610
+ for (const t of getRunningTasks(getAppState())) {
611
+ if (isBackgroundTask(t))
612
+ bg[t.type] = (bg[t.type] ?? 0) + 1;
613
+ }
614
+ logForDiagnosticsNoPII('info', 'run_state_at_shutdown', {
615
+ run_active: running,
616
+ run_phase: runPhase,
617
+ worker_status: getSessionState(),
618
+ internal_events_pending: structuredIO.internalEventsPending,
619
+ bg_tasks: bg,
620
+ });
621
+ });
622
+ // Wire the central onChangeAppState mode-diff hook to the SDK output stream.
623
+ // This fires whenever ANY code path mutates toolPermissionContext.mode —
624
+ // Shift+Tab, ExitPlanMode dialog, /plan slash command, rewind, bridge
625
+ // set_permission_mode, the query loop, stop_task — rather than the two
626
+ // paths that previously went through a bespoke wrapper.
627
+ // The wrapper's body was fully redundant (it enqueued here AND called
628
+ // notifySessionMetadataChanged, both of which onChangeAppState now covers);
629
+ // keeping it would double-emit status messages.
630
+ setPermissionModeChangedListener(newMode => {
631
+ // Only emit for SDK-exposed modes.
632
+ if (newMode === 'default' ||
633
+ newMode === 'acceptEdits' ||
634
+ newMode === 'bypassPermissions' ||
635
+ newMode === 'plan' ||
636
+ newMode === (feature('TRANSCRIPT_CLASSIFIER') && 'auto') ||
637
+ newMode === 'dontAsk') {
638
+ output.enqueue({
639
+ type: 'system',
640
+ subtype: 'status',
641
+ status: null,
642
+ permissionMode: newMode,
643
+ uuid: randomUUID(),
644
+ session_id: getSessionId(),
645
+ });
646
+ }
647
+ });
648
+ // Prompt suggestion tracking (push model)
649
+ const suggestionState = {
650
+ abortController: null,
651
+ inflightPromise: null,
652
+ lastEmitted: null,
653
+ pendingSuggestion: null,
654
+ pendingLastEmittedEntry: null,
655
+ };
656
+ // Set up AWS auth status listener if enabled
657
+ let unsubscribeAuthStatus;
658
+ if (options.enableAuthStatus) {
659
+ const authStatusManager = AwsAuthStatusManager.getInstance();
660
+ unsubscribeAuthStatus = authStatusManager.subscribe(status => {
661
+ output.enqueue({
662
+ type: 'auth_status',
663
+ isAuthenticating: status.isAuthenticating,
664
+ output: status.output,
665
+ error: status.error,
666
+ uuid: randomUUID(),
667
+ session_id: getSessionId(),
668
+ });
669
+ });
670
+ }
671
+ // Set up rate limit status listener to emit SDKRateLimitEvent for all status changes.
672
+ // Emitting for all statuses (including 'allowed') ensures consumers can clear warnings
673
+ // when rate limits reset. The upstream emitStatusChange already deduplicates via isEqual.
674
+ const rateLimitListener = (limits) => {
675
+ const rateLimitInfo = toSDKRateLimitInfo(limits);
676
+ if (rateLimitInfo) {
677
+ output.enqueue({
678
+ type: 'rate_limit_event',
679
+ rate_limit_info: rateLimitInfo,
680
+ uuid: randomUUID(),
681
+ session_id: getSessionId(),
682
+ });
683
+ }
684
+ };
685
+ statusListeners.add(rateLimitListener);
686
+ // Messages for internal tracking, directly mutated by ask(). These messages
687
+ // include Assistant, User, Attachment, and Progress messages.
688
+ // TODO: Clean up this code to avoid passing around a mutable array.
689
+ const mutableMessages = initialMessages;
690
+ // Seed the readFileState cache from the transcript (content the model saw,
691
+ // with message timestamps) so getChangedFiles can detect external edits.
692
+ // This cache instance must persist across ask() calls, since the edit tool
693
+ // relies on this as a global state.
694
+ let readFileState = extractReadFilesFromMessages(initialMessages, cwd(), READ_FILE_STATE_CACHE_SIZE);
695
+ // Client-supplied readFileState seeds (via seed_read_state control request).
696
+ // The stdin IIFE runs concurrently with ask() — a seed arriving mid-turn
697
+ // would be lost to ask()'s clone-then-replace (QueryEngine.ts finally block)
698
+ // if written directly into readFileState. Instead, seeds land here, merge
699
+ // into getReadFileCache's view (readFileState-wins-ties: seeds fill gaps),
700
+ // and are re-applied then CLEARED in setReadFileCache. One-shot: each seed
701
+ // survives exactly one clone-replace cycle, then becomes a regular
702
+ // readFileState entry subject to compact's clear like everything else.
703
+ const pendingSeeds = createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE);
704
+ // Auto-resume interrupted turns on restart so CC continues from where it
705
+ // left off without requiring the SDK to re-send the prompt.
706
+ const resumeInterruptedTurnEnv = process.env.THADDEUS_RESUME_INTERRUPTED_TURN;
707
+ if (turnInterruptionState &&
708
+ turnInterruptionState.kind !== 'none' &&
709
+ resumeInterruptedTurnEnv) {
710
+ logForDebugging(`[print.ts] Auto-resuming interrupted turn (kind: ${turnInterruptionState.kind})`);
711
+ // Remove the interrupted message and its sentinel, then re-enqueue so
712
+ // the model sees it exactly once. For mid-turn interruptions, the
713
+ // deserialization layer transforms them into interrupted_prompt by
714
+ // appending a synthetic "Continue from where you left off." message.
715
+ removeInterruptedMessage(mutableMessages, turnInterruptionState.message);
716
+ enqueue({
717
+ mode: 'prompt',
718
+ value: turnInterruptionState.message.message.content,
719
+ uuid: randomUUID(),
720
+ });
721
+ }
722
+ const modelOptions = getModelOptions();
723
+ const modelInfos = modelOptions.map(option => {
724
+ const modelId = option.value === null ? 'default' : option.value;
725
+ const resolvedModel = modelId === 'default'
726
+ ? getDefaultMainLoopModel()
727
+ : parseUserSpecifiedModel(modelId);
728
+ const hasEffort = modelSupportsEffort(resolvedModel);
729
+ const hasAdaptiveThinking = modelSupportsAdaptiveThinking(resolvedModel);
730
+ const hasFastMode = isFastModeSupportedByModel(option.value);
731
+ const hasAutoMode = modelSupportsAutoMode(resolvedModel);
732
+ return {
733
+ value: modelId,
734
+ displayName: option.label,
735
+ description: option.description,
736
+ ...(hasEffort && {
737
+ supportsEffort: true,
738
+ supportedEffortLevels: modelSupportsMaxEffort(resolvedModel)
739
+ ? [...EFFORT_LEVELS]
740
+ : EFFORT_LEVELS.filter(l => l !== 'max'),
741
+ }),
742
+ ...(hasAdaptiveThinking && { supportsAdaptiveThinking: true }),
743
+ ...(hasFastMode && { supportsFastMode: true }),
744
+ ...(hasAutoMode && { supportsAutoMode: true }),
745
+ };
746
+ });
747
+ let activeUserSpecifiedModel = options.userSpecifiedModel;
748
+ function injectModelSwitchBreadcrumbs(modelArg, resolvedModel) {
749
+ const breadcrumbs = createModelSwitchBreadcrumbs(modelArg, modelDisplayString(resolvedModel));
750
+ mutableMessages.push(...breadcrumbs);
751
+ for (const crumb of breadcrumbs) {
752
+ if (typeof crumb.message.content === 'string' &&
753
+ crumb.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`)) {
754
+ output.enqueue({
755
+ type: 'user',
756
+ message: crumb.message,
757
+ session_id: getSessionId(),
758
+ parent_tool_use_id: null,
759
+ uuid: crumb.uuid,
760
+ timestamp: crumb.timestamp,
761
+ isReplay: true,
762
+ });
763
+ }
764
+ }
765
+ }
766
+ // Cache SDK MCP clients to avoid reconnecting on each run
767
+ let sdkClients = [];
768
+ let sdkTools = [];
769
+ // Track which MCP clients have had elicitation handlers registered
770
+ const elicitationRegistered = new Set();
771
+ /**
772
+ * Register elicitation request/completion handlers on connected MCP clients
773
+ * that haven't been registered yet. SDK MCP servers are excluded because they
774
+ * route through SdkControlClientTransport. Hooks run first (matching REPL
775
+ * behavior); if no hook responds, the request is forwarded to the SDK
776
+ * consumer via the control protocol.
777
+ */
778
+ function registerElicitationHandlers(clients) {
779
+ for (const connection of clients) {
780
+ if (connection.type !== 'connected' ||
781
+ elicitationRegistered.has(connection.name)) {
782
+ continue;
783
+ }
784
+ // Skip SDK MCP servers — elicitation flows through SdkControlClientTransport
785
+ if (connection.config.type === 'sdk') {
786
+ continue;
787
+ }
788
+ const serverName = connection.name;
789
+ // Wrapped in try/catch because setRequestHandler throws if the client wasn't
790
+ // created with elicitation capability declared (e.g., SDK-created clients).
791
+ try {
792
+ connection.client.setRequestHandler(ElicitRequestSchema, async (request, extra) => {
793
+ logMCPDebug(serverName, `Elicitation request received in print mode: ${jsonStringify(request)}`);
794
+ const mode = request.params.mode === 'url' ? 'url' : 'form';
795
+ logEvent('thaddeus_mcp_elicitation_shown', {
796
+ mode: mode,
797
+ });
798
+ // Run elicitation hooks first — they can provide a response programmatically
799
+ const hookResponse = await runElicitationHooks(serverName, request.params, extra.signal);
800
+ if (hookResponse) {
801
+ logMCPDebug(serverName, `Elicitation resolved by hook: ${jsonStringify(hookResponse)}`);
802
+ logEvent('thaddeus_mcp_elicitation_response', {
803
+ mode: mode,
804
+ action: hookResponse.action,
805
+ });
806
+ return hookResponse;
807
+ }
808
+ // Delegate to SDK consumer via control protocol
809
+ const url = 'url' in request.params
810
+ ? request.params.url
811
+ : undefined;
812
+ const requestedSchema = 'requestedSchema' in request.params
813
+ ? request.params.requestedSchema
814
+ : undefined;
815
+ const elicitationId = 'elicitationId' in request.params
816
+ ? request.params.elicitationId
817
+ : undefined;
818
+ const rawResult = await structuredIO.handleElicitation(serverName, request.params.message, requestedSchema, extra.signal, mode, url, elicitationId);
819
+ const result = await runElicitationResultHooks(serverName, rawResult, extra.signal, mode, elicitationId);
820
+ logEvent('thaddeus_mcp_elicitation_response', {
821
+ mode: mode,
822
+ action: result.action,
823
+ });
824
+ return result;
825
+ });
826
+ // Surface completion notifications to SDK consumers (URL mode)
827
+ connection.client.setNotificationHandler(ElicitationCompleteNotificationSchema, notification => {
828
+ const { elicitationId } = notification.params;
829
+ logMCPDebug(serverName, `Elicitation completion notification: ${elicitationId}`);
830
+ void executeNotificationHooks({
831
+ message: `MCP server "${serverName}" confirmed elicitation ${elicitationId} complete`,
832
+ notificationType: 'elicitation_complete',
833
+ });
834
+ output.enqueue({
835
+ type: 'system',
836
+ subtype: 'elicitation_complete',
837
+ mcp_server_name: serverName,
838
+ elicitation_id: elicitationId,
839
+ uuid: randomUUID(),
840
+ session_id: getSessionId(),
841
+ });
842
+ });
843
+ elicitationRegistered.add(serverName);
844
+ }
845
+ catch {
846
+ // setRequestHandler throws if the client wasn't created with
847
+ // elicitation capability — skip silently
848
+ }
849
+ }
850
+ }
851
+ async function updateSdkMcp() {
852
+ // Check if SDK MCP servers need to be updated (new servers added or removed)
853
+ const currentServerNames = new Set(Object.keys(sdkMcpConfigs));
854
+ const connectedServerNames = new Set(sdkClients.map(c => c.name));
855
+ // Check if there are any differences (additions or removals)
856
+ const hasNewServers = Array.from(currentServerNames).some(name => !connectedServerNames.has(name));
857
+ const hasRemovedServers = Array.from(connectedServerNames).some(name => !currentServerNames.has(name));
858
+ // Check if any SDK clients are pending and need to be upgraded
859
+ const hasPendingSdkClients = sdkClients.some(c => c.type === 'pending');
860
+ // Check if any SDK clients failed their handshake and need to be retried.
861
+ // Without this, a client that lands in 'failed' (e.g. handshake timeout on
862
+ // a WS reconnect race) stays failed forever — its name satisfies the
863
+ // connectedServerNames diff but it contributes zero tools.
864
+ const hasFailedSdkClients = sdkClients.some(c => c.type === 'failed');
865
+ const haveServersChanged = hasNewServers ||
866
+ hasRemovedServers ||
867
+ hasPendingSdkClients ||
868
+ hasFailedSdkClients;
869
+ if (haveServersChanged) {
870
+ // Clean up removed servers
871
+ for (const client of sdkClients) {
872
+ if (!currentServerNames.has(client.name)) {
873
+ if (client.type === 'connected') {
874
+ await client.cleanup();
875
+ }
876
+ }
877
+ }
878
+ // Re-initialize all SDK MCP servers with current config
879
+ const sdkSetup = await setupSdkMcpClients(sdkMcpConfigs, (serverName, message) => structuredIO.sendMcpMessage(serverName, message));
880
+ sdkClients = sdkSetup.clients;
881
+ sdkTools = sdkSetup.tools;
882
+ // Store SDK MCP tools in appState so subagents can access them via
883
+ // assembleToolPool. Only tools are stored here — SDK clients are already
884
+ // merged separately in the query loop (allMcpClients) and mcp_status handler.
885
+ // Use both old (connectedServerNames) and new (currentServerNames) to remove
886
+ // stale SDK tools when servers are added or removed.
887
+ const allSdkNames = uniq([...connectedServerNames, ...currentServerNames]);
888
+ setAppState(prev => ({
889
+ ...prev,
890
+ mcp: {
891
+ ...prev.mcp,
892
+ tools: [
893
+ ...prev.mcp.tools.filter(t => !allSdkNames.some(name => t.name.startsWith(getMcpPrefix(name)))),
894
+ ...sdkTools,
895
+ ],
896
+ },
897
+ }));
898
+ // Set up the special internal VSCode MCP server if necessary.
899
+ setupVscodeSdkMcp(sdkClients);
900
+ }
901
+ }
902
+ void updateSdkMcp();
903
+ // State for dynamically added MCP servers (via mcp_set_servers control message)
904
+ // These are separate from SDK MCP servers and support all transport types
905
+ let dynamicMcpState = {
906
+ clients: [],
907
+ tools: [],
908
+ configs: {},
909
+ };
910
+ // Shared tool assembly for ask() and the get_context_usage control request.
911
+ // Closes over the mutable sdkTools/dynamicMcpState bindings so both call
912
+ // sites see late-connecting servers.
913
+ const buildAllTools = (appState) => {
914
+ const assembledTools = assembleToolPool(appState.toolPermissionContext, appState.mcp.tools);
915
+ let allTools = uniqBy(mergeAndFilterTools([...tools, ...sdkTools, ...dynamicMcpState.tools], assembledTools, appState.toolPermissionContext.mode), 'name');
916
+ if (options.permissionPromptToolName) {
917
+ allTools = allTools.filter(tool => !toolMatchesName(tool, options.permissionPromptToolName));
918
+ }
919
+ const initJsonSchema = getInitJsonSchema();
920
+ if (initJsonSchema && !options.jsonSchema) {
921
+ const syntheticOutputResult = createSyntheticOutputTool(initJsonSchema);
922
+ if ('tool' in syntheticOutputResult) {
923
+ allTools = [...allTools, syntheticOutputResult.tool];
924
+ }
925
+ }
926
+ return allTools;
927
+ };
928
+ // Bridge handle for remote-control (SDK control message).
929
+ // Mirrors the REPL's useReplBridge hook: the handle is created when
930
+ // `remote_control` is enabled and torn down when disabled.
931
+ let bridgeHandle = null;
932
+ // Cursor into mutableMessages — tracks how far we've forwarded.
933
+ // Same index-based diff as useReplBridge's lastWrittenIndexRef.
934
+ let bridgeLastForwardedIndex = 0;
935
+ // Forward new messages from mutableMessages to the bridge.
936
+ // Called incrementally during each turn (so the web app sees progress
937
+ // and stays alive during permission waits) and again after the turn.
938
+ //
939
+ // writeMessages has its own UUID-based dedup (initialMessageUUIDs,
940
+ // recentPostedUUIDs) — the index cursor here is a pre-filter to avoid
941
+ // O(n) re-scanning of already-sent messages on every call.
942
+ function forwardMessagesToBridge() {
943
+ if (!bridgeHandle)
944
+ return;
945
+ // Guard against mutableMessages shrinking (compaction truncates it).
946
+ const startIndex = Math.min(bridgeLastForwardedIndex, mutableMessages.length);
947
+ const newMessages = mutableMessages
948
+ .slice(startIndex)
949
+ .filter(m => m.type === 'user' || m.type === 'assistant');
950
+ bridgeLastForwardedIndex = mutableMessages.length;
951
+ if (newMessages.length > 0) {
952
+ bridgeHandle.writeMessages(newMessages);
953
+ }
954
+ }
955
+ // Helper to apply MCP server changes - used by both mcp_set_servers control message
956
+ // and background plugin installation.
957
+ // NOTE: Nested function required - mutates closure state (sdkMcpConfigs, sdkClients, etc.)
958
+ let mcpChangesPromise = Promise.resolve({
959
+ response: {
960
+ added: [],
961
+ removed: [],
962
+ errors: {},
963
+ },
964
+ sdkServersChanged: false,
965
+ });
966
+ function applyMcpServerChanges(servers) {
967
+ // Serialize calls to prevent race conditions between concurrent callers
968
+ // (background plugin install and mcp_set_servers control messages)
969
+ const doWork = async () => {
970
+ const oldSdkClientNames = new Set(sdkClients.map(c => c.name));
971
+ const result = await handleMcpSetServers(servers, { configs: sdkMcpConfigs, clients: sdkClients, tools: sdkTools }, dynamicMcpState, setAppState);
972
+ // Update SDK state (need to mutate sdkMcpConfigs since it's shared)
973
+ for (const key of Object.keys(sdkMcpConfigs)) {
974
+ delete sdkMcpConfigs[key];
975
+ }
976
+ Object.assign(sdkMcpConfigs, result.newSdkState.configs);
977
+ sdkClients = result.newSdkState.clients;
978
+ sdkTools = result.newSdkState.tools;
979
+ dynamicMcpState = result.newDynamicState;
980
+ // Keep appState.mcp.tools in sync so subagents can see SDK MCP tools.
981
+ // Use both old and new SDK client names to remove stale tools.
982
+ if (result.sdkServersChanged) {
983
+ const newSdkClientNames = new Set(sdkClients.map(c => c.name));
984
+ const allSdkNames = uniq([...oldSdkClientNames, ...newSdkClientNames]);
985
+ setAppState(prev => ({
986
+ ...prev,
987
+ mcp: {
988
+ ...prev.mcp,
989
+ tools: [
990
+ ...prev.mcp.tools.filter(t => !allSdkNames.some(name => t.name.startsWith(getMcpPrefix(name)))),
991
+ ...sdkTools,
992
+ ],
993
+ },
994
+ }));
995
+ }
996
+ return {
997
+ response: result.response,
998
+ sdkServersChanged: result.sdkServersChanged,
999
+ };
1000
+ };
1001
+ mcpChangesPromise = mcpChangesPromise.then(doWork, doWork);
1002
+ return mcpChangesPromise;
1003
+ }
1004
+ // Build McpServerStatus[] for control responses. Shared by mcp_status and
1005
+ // reload_plugins handlers. Reads closure state: sdkClients, dynamicMcpState.
1006
+ function buildMcpServerStatuses() {
1007
+ const currentAppState = getAppState();
1008
+ const currentMcpClients = currentAppState.mcp.clients;
1009
+ const allMcpTools = uniqBy([...currentAppState.mcp.tools, ...dynamicMcpState.tools], 'name');
1010
+ const existingNames = new Set([
1011
+ ...currentMcpClients.map(c => c.name),
1012
+ ...sdkClients.map(c => c.name),
1013
+ ]);
1014
+ return [
1015
+ ...currentMcpClients,
1016
+ ...sdkClients,
1017
+ ...dynamicMcpState.clients.filter(c => !existingNames.has(c.name)),
1018
+ ].map(connection => {
1019
+ let config;
1020
+ if (connection.config.type === 'sse' ||
1021
+ connection.config.type === 'http') {
1022
+ config = {
1023
+ type: connection.config.type,
1024
+ url: connection.config.url,
1025
+ headers: connection.config.headers,
1026
+ oauth: connection.config.oauth,
1027
+ };
1028
+ }
1029
+ else if (connection.config.type === 'claudeai-proxy') {
1030
+ config = {
1031
+ type: 'claudeai-proxy',
1032
+ url: connection.config.url,
1033
+ id: connection.config.id,
1034
+ };
1035
+ }
1036
+ else if (connection.config.type === 'stdio' ||
1037
+ connection.config.type === undefined) {
1038
+ config = {
1039
+ type: 'stdio',
1040
+ command: connection.config.command,
1041
+ args: connection.config.args,
1042
+ };
1043
+ }
1044
+ const serverTools = connection.type === 'connected'
1045
+ ? filterToolsByServer(allMcpTools, connection.name).map(tool => ({
1046
+ name: tool.mcpInfo?.toolName ?? tool.name,
1047
+ annotations: {
1048
+ readOnly: tool.isReadOnly({}) || undefined,
1049
+ destructive: tool.isDestructive?.({}) || undefined,
1050
+ openWorld: tool.isOpenWorld?.({}) || undefined,
1051
+ },
1052
+ }))
1053
+ : undefined;
1054
+ // Capabilities passthrough with allowlist pre-filter. The IDE reads
1055
+ // experimental['claude/channel'] to decide whether to show the
1056
+ // Enable-channel prompt — only echo it if channel_enable would
1057
+ // actually pass the allowlist. Not a security boundary (the
1058
+ // handler re-runs the full gate); just avoids dead buttons.
1059
+ let capabilities;
1060
+ if ((feature('KAIROS') || feature('KAIROS_CHANNELS')) &&
1061
+ connection.type === 'connected' &&
1062
+ connection.capabilities.experimental) {
1063
+ const exp = { ...connection.capabilities.experimental };
1064
+ if (exp['claude/channel'] &&
1065
+ (!isChannelsEnabled() ||
1066
+ !isChannelAllowlisted(connection.config.pluginSource))) {
1067
+ delete exp['claude/channel'];
1068
+ }
1069
+ if (Object.keys(exp).length > 0) {
1070
+ capabilities = { experimental: exp };
1071
+ }
1072
+ }
1073
+ return {
1074
+ name: connection.name,
1075
+ status: connection.type,
1076
+ serverInfo: connection.type === 'connected' ? connection.serverInfo : undefined,
1077
+ error: connection.type === 'failed' ? connection.error : undefined,
1078
+ config,
1079
+ scope: connection.config.scope,
1080
+ tools: serverTools,
1081
+ capabilities,
1082
+ };
1083
+ });
1084
+ }
1085
+ // NOTE: Nested function required - needs closure access to applyMcpServerChanges and updateSdkMcp
1086
+ async function installPluginsAndApplyMcpInBackground() {
1087
+ try {
1088
+ // Join point for user settings (fired at runHeadless entry) and managed
1089
+ // settings (fired in main.tsx preAction). downloadUserSettings() caches
1090
+ // its promise so this awaits the same in-flight request.
1091
+ await Promise.all([
1092
+ feature('DOWNLOAD_USER_SETTINGS') &&
1093
+ (isEnvTruthy(process.env.THADDEUS_REMOTE) || getIsRemoteMode())
1094
+ ? withDiagnosticsTiming('headless_user_settings_download', () => downloadUserSettings())
1095
+ : Promise.resolve(),
1096
+ withDiagnosticsTiming('headless_managed_settings_wait', () => waitForRemoteManagedSettingsToLoad()),
1097
+ ]);
1098
+ const pluginsInstalled = await installPluginsForHeadless();
1099
+ if (pluginsInstalled) {
1100
+ await applyPluginMcpDiff();
1101
+ }
1102
+ }
1103
+ catch (error) {
1104
+ logError(error);
1105
+ }
1106
+ }
1107
+ // Background plugin installation for all headless users
1108
+ // Installs marketplaces from extraKnownMarketplaces and missing enabled plugins
1109
+ // THADDEUS_SYNC_PLUGIN_INSTALL=true: resolved in run() before the first
1110
+ // query so plugins are guaranteed available on the first ask().
1111
+ let pluginInstallPromise = null;
1112
+ // --bare / SIMPLE: skip plugin install. Scripted calls don't add plugins
1113
+ // mid-session; the next interactive run reconciles.
1114
+ if (!isBareMode()) {
1115
+ if (isEnvTruthy(process.env.THADDEUS_SYNC_PLUGIN_INSTALL)) {
1116
+ pluginInstallPromise = installPluginsAndApplyMcpInBackground();
1117
+ }
1118
+ else {
1119
+ void installPluginsAndApplyMcpInBackground();
1120
+ }
1121
+ }
1122
+ // Idle timeout management
1123
+ const idleTimeout = createIdleTimeoutManager(() => !running);
1124
+ // Mutable commands and agents for hot reloading
1125
+ let currentCommands = commands;
1126
+ let currentAgents = agents;
1127
+ // Clear all plugin-related caches, reload commands/agents/hooks.
1128
+ // Called after THADDEUS_SYNC_PLUGIN_INSTALL completes (before first query)
1129
+ // and after non-sync background install finishes.
1130
+ // refreshActivePlugins calls clearAllCaches() which is required because
1131
+ // loadAllPlugins() may have run during main.tsx startup BEFORE managed
1132
+ // settings were fetched. Without clearing, getCommands() would rebuild
1133
+ // from a stale plugin list.
1134
+ async function refreshPluginState() {
1135
+ // refreshActivePlugins handles the full cache sweep (clearAllCaches),
1136
+ // reloads all plugin component loaders, writes AppState.plugins +
1137
+ // AppState.agentDefinitions, registers hooks, and bumps mcp.pluginReconnectKey.
1138
+ const { agentDefinitions: freshAgentDefs } = await refreshActivePlugins(setAppState);
1139
+ // Headless-specific: currentCommands/currentAgents are local mutable refs
1140
+ // captured by the query loop (REPL uses AppState instead). getCommands is
1141
+ // fresh because refreshActivePlugins cleared its cache.
1142
+ currentCommands = await getCommands(cwd());
1143
+ // Preserve SDK-provided agents (--agents CLI flag or SDK initialize
1144
+ // control_request) — both inject via parseAgentsFromJson with
1145
+ // source='flagSettings'. loadMarkdownFilesForSubdir never assigns this
1146
+ // source, so it cleanly discriminates "injected, not disk-loadable".
1147
+ //
1148
+ // The previous filter used a negative set-diff (!freshAgentTypes.has(a))
1149
+ // which also matched plugin agents that were in the poisoned initial
1150
+ // currentAgents but correctly excluded from freshAgentDefs after managed
1151
+ // settings applied — leaking policy-blocked agents into the init message.
1152
+ // See gh-23085: isBridgeEnabled() at Commander-definition time poisoned
1153
+ // the settings cache before setEligibility(true) ran.
1154
+ const sdkAgents = currentAgents.filter(a => a.source === 'flagSettings');
1155
+ currentAgents = [...freshAgentDefs.allAgents, ...sdkAgents];
1156
+ }
1157
+ // Re-diff MCP configs after plugin state changes. Filters to
1158
+ // process-transport-supported types and carries SDK-mode servers through
1159
+ // so applyMcpServerChanges' diff doesn't close their transports.
1160
+ // Nested: needs closure access to sdkMcpConfigs, applyMcpServerChanges,
1161
+ // updateSdkMcp.
1162
+ async function applyPluginMcpDiff() {
1163
+ const { servers: newConfigs } = await getAllMcpConfigs();
1164
+ const supportedConfigs = {};
1165
+ for (const [name, config] of Object.entries(newConfigs)) {
1166
+ const type = config.type;
1167
+ if (type === undefined ||
1168
+ type === 'stdio' ||
1169
+ type === 'sse' ||
1170
+ type === 'http' ||
1171
+ type === 'sdk') {
1172
+ supportedConfigs[name] = config;
1173
+ }
1174
+ }
1175
+ for (const [name, config] of Object.entries(sdkMcpConfigs)) {
1176
+ if (config.type === 'sdk' && !(name in supportedConfigs)) {
1177
+ supportedConfigs[name] = config;
1178
+ }
1179
+ }
1180
+ const { response, sdkServersChanged } = await applyMcpServerChanges(supportedConfigs);
1181
+ if (sdkServersChanged) {
1182
+ void updateSdkMcp();
1183
+ }
1184
+ logForDebugging(`Headless MCP refresh: added=${response.added.length}, removed=${response.removed.length}`);
1185
+ }
1186
+ // Subscribe to skill changes for hot reloading
1187
+ const unsubscribeSkillChanges = skillChangeDetector.subscribe(() => {
1188
+ clearCommandsCache();
1189
+ void getCommands(cwd()).then(newCommands => {
1190
+ currentCommands = newCommands;
1191
+ });
1192
+ });
1193
+ // Proactive mode: schedule a tick to keep the model looping autonomously.
1194
+ // setTimeout(0) yields to the event loop so pending stdin messages
1195
+ // (interrupts, user messages) are processed before the tick fires.
1196
+ const scheduleProactiveTick = feature('PROACTIVE') || feature('KAIROS')
1197
+ ? () => {
1198
+ setTimeout(() => {
1199
+ if (!proactiveModule?.isProactiveActive() ||
1200
+ proactiveModule.isProactivePaused() ||
1201
+ inputClosed) {
1202
+ return;
1203
+ }
1204
+ const tickContent = `<${TICK_TAG}>${new Date().toLocaleTimeString()}</${TICK_TAG}>`;
1205
+ enqueue({
1206
+ mode: 'prompt',
1207
+ value: tickContent,
1208
+ uuid: randomUUID(),
1209
+ priority: 'later',
1210
+ isMeta: true,
1211
+ });
1212
+ void run();
1213
+ }, 0);
1214
+ }
1215
+ : undefined;
1216
+ // Abort the current operation when a 'now' priority message arrives.
1217
+ subscribeToCommandQueue(() => {
1218
+ if (abortController && getCommandsByMaxPriority('now').length > 0) {
1219
+ abortController.abort('interrupt');
1220
+ }
1221
+ });
1222
+ const run = async () => {
1223
+ if (running) {
1224
+ return;
1225
+ }
1226
+ running = true;
1227
+ runPhase = undefined;
1228
+ notifySessionStateChanged('running');
1229
+ idleTimeout.stop();
1230
+ headlessProfilerCheckpoint('run_entry');
1231
+ // TODO(custom-tool-refactor): Should move to the init message, like browser
1232
+ await updateSdkMcp();
1233
+ headlessProfilerCheckpoint('after_updateSdkMcp');
1234
+ // Resolve deferred plugin installation (THADDEUS_SYNC_PLUGIN_INSTALL).
1235
+ // The promise was started eagerly so installation overlaps with other init.
1236
+ // Awaiting here guarantees plugins are available before the first ask().
1237
+ // If THADDEUS_SYNC_PLUGIN_INSTALL_TIMEOUT_MS is set, races against that
1238
+ // deadline and proceeds without plugins on timeout (logging an error).
1239
+ if (pluginInstallPromise) {
1240
+ const timeoutMs = parseInt(process.env.THADDEUS_SYNC_PLUGIN_INSTALL_TIMEOUT_MS || '', 10);
1241
+ if (timeoutMs > 0) {
1242
+ const timeout = sleep(timeoutMs).then(() => 'timeout');
1243
+ const result = await Promise.race([pluginInstallPromise, timeout]);
1244
+ if (result === 'timeout') {
1245
+ logError(new Error(`THADDEUS_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${timeoutMs}ms`));
1246
+ logEvent('thaddeus_sync_plugin_install_timeout', {
1247
+ timeout_ms: timeoutMs,
1248
+ });
1249
+ }
1250
+ }
1251
+ else {
1252
+ await pluginInstallPromise;
1253
+ }
1254
+ pluginInstallPromise = null;
1255
+ // Refresh commands, agents, and hooks now that plugins are installed
1256
+ await refreshPluginState();
1257
+ // Set up hot-reload for plugin hooks now that the initial install is done.
1258
+ // In sync-install mode, setup.ts skips this to avoid racing with the install.
1259
+ const { setupPluginHookHotReload } = await import('../utils/plugins/loadPluginHooks.js');
1260
+ setupPluginHookHotReload();
1261
+ }
1262
+ // Only main-thread commands (agentId===undefined) — subagent
1263
+ // notifications are drained by the subagent's mid-turn gate in query.ts.
1264
+ // Defined outside the try block so it's accessible in the post-finally
1265
+ // queue re-checks at the bottom of run().
1266
+ const isMainThread = (cmd) => cmd.agentId === undefined;
1267
+ try {
1268
+ let command;
1269
+ let waitingForAgents = false;
1270
+ // Extract command processing into a named function for the do-while pattern.
1271
+ // Drains the queue, batching consecutive prompt-mode commands into one
1272
+ // ask() call so messages that queued up during a long turn coalesce
1273
+ // into a single follow-up turn instead of N separate turns.
1274
+ const drainCommandQueue = async () => {
1275
+ while ((command = dequeue(isMainThread))) {
1276
+ if (command.mode !== 'prompt' &&
1277
+ command.mode !== 'orphaned-permission' &&
1278
+ command.mode !== 'task-notification') {
1279
+ throw new Error('only prompt commands are supported in streaming mode');
1280
+ }
1281
+ // Non-prompt commands (task-notification, orphaned-permission) carry
1282
+ // side effects or orphanedPermission state, so they process singly.
1283
+ // Prompt commands greedily collect followers with matching workload.
1284
+ const batch = [command];
1285
+ if (command.mode === 'prompt') {
1286
+ while (canBatchWith(command, peek(isMainThread))) {
1287
+ batch.push(dequeue(isMainThread));
1288
+ }
1289
+ if (batch.length > 1) {
1290
+ command = {
1291
+ ...command,
1292
+ value: joinPromptValues(batch.map(c => c.value)),
1293
+ uuid: batch.findLast(c => c.uuid)?.uuid ?? command.uuid,
1294
+ };
1295
+ }
1296
+ }
1297
+ const batchUuids = batch.map(c => c.uuid).filter(u => u !== undefined);
1298
+ // QueryEngine will emit a replay for command.uuid (the last uuid in
1299
+ // the batch) via its messagesToAck path. Emit replays here for the
1300
+ // rest so consumers that track per-uuid delivery (clank's
1301
+ // asyncMessages footer, CCR) see an ack for every message they sent,
1302
+ // not just the one that survived the merge.
1303
+ if (options.replayUserMessages && batch.length > 1) {
1304
+ for (const c of batch) {
1305
+ if (c.uuid && c.uuid !== command.uuid) {
1306
+ output.enqueue({
1307
+ type: 'user',
1308
+ message: { role: 'user', content: c.value },
1309
+ session_id: getSessionId(),
1310
+ parent_tool_use_id: null,
1311
+ uuid: c.uuid,
1312
+ isReplay: true,
1313
+ });
1314
+ }
1315
+ }
1316
+ }
1317
+ // Combine all MCP clients. appState.mcp is populated incrementally
1318
+ // per-server by main.tsx (mirrors useManageMCPConnections). Reading
1319
+ // fresh per-command means late-connecting servers are visible on the
1320
+ // next turn. registerElicitationHandlers is idempotent (tracking set).
1321
+ const appState = getAppState();
1322
+ const allMcpClients = [
1323
+ ...appState.mcp.clients,
1324
+ ...sdkClients,
1325
+ ...dynamicMcpState.clients,
1326
+ ];
1327
+ registerElicitationHandlers(allMcpClients);
1328
+ // Channel handlers for servers allowlisted via --channels at
1329
+ // construction time (or enableChannel() mid-session). Runs every
1330
+ // turn like registerElicitationHandlers — idempotent per-client
1331
+ // (setNotificationHandler replaces, not stacks) and no-ops for
1332
+ // non-allowlisted servers (one feature-flag check).
1333
+ for (const client of allMcpClients) {
1334
+ reregisterChannelHandlerAfterReconnect(client);
1335
+ }
1336
+ const allTools = buildAllTools(appState);
1337
+ for (const uuid of batchUuids) {
1338
+ notifyCommandLifecycle(uuid, 'started');
1339
+ }
1340
+ // Task notifications arrive when background agents complete.
1341
+ // Emit an SDK system event for SDK consumers, then fall through
1342
+ // to ask() so the model sees the agent result and can act on it.
1343
+ // This matches TUI behavior where useQueueProcessor always feeds
1344
+ // notifications to the model regardless of coordinator mode.
1345
+ if (command.mode === 'task-notification') {
1346
+ const notificationText = typeof command.value === 'string' ? command.value : '';
1347
+ // Parse the XML-formatted notification
1348
+ const taskIdMatch = notificationText.match(/<task-id>([^<]+)<\/task-id>/);
1349
+ const toolUseIdMatch = notificationText.match(/<tool-use-id>([^<]+)<\/tool-use-id>/);
1350
+ const outputFileMatch = notificationText.match(/<output-file>([^<]+)<\/output-file>/);
1351
+ const statusMatch = notificationText.match(/<status>([^<]+)<\/status>/);
1352
+ const summaryMatch = notificationText.match(/<summary>([^<]+)<\/summary>/);
1353
+ const isValidStatus = (s) => s === 'completed' ||
1354
+ s === 'failed' ||
1355
+ s === 'stopped' ||
1356
+ s === 'killed';
1357
+ const rawStatus = statusMatch?.[1];
1358
+ const status = isValidStatus(rawStatus)
1359
+ ? rawStatus === 'killed'
1360
+ ? 'stopped'
1361
+ : rawStatus
1362
+ : 'completed';
1363
+ const usageMatch = notificationText.match(/<usage>([\s\S]*?)<\/usage>/);
1364
+ const usageContent = usageMatch?.[1] ?? '';
1365
+ const totalTokensMatch = usageContent.match(/<total_tokens>(\d+)<\/total_tokens>/);
1366
+ const toolUsesMatch = usageContent.match(/<tool_uses>(\d+)<\/tool_uses>/);
1367
+ const durationMsMatch = usageContent.match(/<duration_ms>(\d+)<\/duration_ms>/);
1368
+ // Only emit a task_notification SDK event when a <status> tag is
1369
+ // present — that means this is a terminal notification (completed/
1370
+ // failed/stopped). Stream events from enqueueStreamEvent carry no
1371
+ // <status> (they're progress pings); emitting them here would
1372
+ // default to 'completed' and falsely close the task for SDK
1373
+ // consumers. Terminal bookends are now emitted directly via
1374
+ // emitTaskTerminatedSdk, so skipping statusless events is safe.
1375
+ if (statusMatch) {
1376
+ output.enqueue({
1377
+ type: 'system',
1378
+ subtype: 'task_notification',
1379
+ task_id: taskIdMatch?.[1] ?? '',
1380
+ tool_use_id: toolUseIdMatch?.[1],
1381
+ status,
1382
+ output_file: outputFileMatch?.[1] ?? '',
1383
+ summary: summaryMatch?.[1] ?? '',
1384
+ usage: totalTokensMatch && toolUsesMatch
1385
+ ? {
1386
+ total_tokens: parseInt(totalTokensMatch[1], 10),
1387
+ tool_uses: parseInt(toolUsesMatch[1], 10),
1388
+ duration_ms: durationMsMatch
1389
+ ? parseInt(durationMsMatch[1], 10)
1390
+ : 0,
1391
+ }
1392
+ : undefined,
1393
+ session_id: getSessionId(),
1394
+ uuid: randomUUID(),
1395
+ });
1396
+ }
1397
+ // No continue -- fall through to ask() so the model processes the result
1398
+ }
1399
+ const input = command.value;
1400
+ if (structuredIO instanceof RemoteIO && command.mode === 'prompt') {
1401
+ logEvent('thaddeus_bridge_message_received', {
1402
+ is_repl: false,
1403
+ });
1404
+ }
1405
+ // Abort any in-flight suggestion generation and track acceptance
1406
+ suggestionState.abortController?.abort();
1407
+ suggestionState.abortController = null;
1408
+ suggestionState.pendingSuggestion = null;
1409
+ suggestionState.pendingLastEmittedEntry = null;
1410
+ if (suggestionState.lastEmitted) {
1411
+ if (command.mode === 'prompt') {
1412
+ // SDK user messages enqueue ContentBlockParam[], not a plain string
1413
+ const inputText = typeof input === 'string'
1414
+ ? input
1415
+ : input.find(b => b.type === 'text')?.text;
1416
+ if (typeof inputText === 'string') {
1417
+ logSuggestionOutcome(suggestionState.lastEmitted.text, inputText, suggestionState.lastEmitted.emittedAt, suggestionState.lastEmitted.promptId, suggestionState.lastEmitted.generationRequestId);
1418
+ }
1419
+ suggestionState.lastEmitted = null;
1420
+ }
1421
+ }
1422
+ abortController = createAbortController();
1423
+ const turnStartTime = feature('FILE_PERSISTENCE')
1424
+ ? Date.now()
1425
+ : undefined;
1426
+ headlessProfilerCheckpoint('before_ask');
1427
+ startQueryProfile();
1428
+ // Per-iteration ALS context so bg agents spawned inside ask()
1429
+ // inherit workload across their detached awaits. In-process cron
1430
+ // stamps cmd.workload; the SDK --workload flag is options.workload.
1431
+ // const-capture: TS loses `while ((command = dequeue()))` narrowing
1432
+ // inside the closure.
1433
+ const cmd = command;
1434
+ await runWithWorkload(cmd.workload ?? options.workload, async () => {
1435
+ for await (const message of ask({
1436
+ commands: uniqBy([...currentCommands, ...appState.mcp.commands], 'name'),
1437
+ prompt: input,
1438
+ promptUuid: cmd.uuid,
1439
+ isMeta: cmd.isMeta,
1440
+ cwd: cwd(),
1441
+ tools: allTools,
1442
+ verbose: options.verbose,
1443
+ mcpClients: allMcpClients,
1444
+ thinkingConfig: options.thinkingConfig,
1445
+ maxTurns: options.maxTurns,
1446
+ maxBudgetUsd: options.maxBudgetUsd,
1447
+ taskBudget: options.taskBudget,
1448
+ canUseTool,
1449
+ userSpecifiedModel: activeUserSpecifiedModel,
1450
+ fallbackModel: options.fallbackModel,
1451
+ jsonSchema: getInitJsonSchema() ?? options.jsonSchema,
1452
+ mutableMessages,
1453
+ getReadFileCache: () => pendingSeeds.size === 0
1454
+ ? readFileState
1455
+ : mergeFileStateCaches(readFileState, pendingSeeds),
1456
+ setReadFileCache: cache => {
1457
+ readFileState = cache;
1458
+ for (const [path, seed] of pendingSeeds.entries()) {
1459
+ const existing = readFileState.get(path);
1460
+ if (!existing || seed.timestamp > existing.timestamp) {
1461
+ readFileState.set(path, seed);
1462
+ }
1463
+ }
1464
+ pendingSeeds.clear();
1465
+ },
1466
+ customSystemPrompt: options.systemPrompt,
1467
+ appendSystemPrompt: options.appendSystemPrompt,
1468
+ getAppState,
1469
+ setAppState,
1470
+ abortController,
1471
+ replayUserMessages: options.replayUserMessages,
1472
+ includePartialMessages: options.includePartialMessages,
1473
+ handleElicitation: (serverName, params, elicitSignal) => structuredIO.handleElicitation(serverName, params.message, undefined, elicitSignal, params.mode, params.url, 'elicitationId' in params ? params.elicitationId : undefined),
1474
+ agents: currentAgents,
1475
+ orphanedPermission: cmd.orphanedPermission,
1476
+ setSDKStatus: status => {
1477
+ output.enqueue({
1478
+ type: 'system',
1479
+ subtype: 'status',
1480
+ status,
1481
+ session_id: getSessionId(),
1482
+ uuid: randomUUID(),
1483
+ });
1484
+ },
1485
+ })) {
1486
+ // Forward messages to bridge incrementally (mid-turn) so
1487
+ // claude.ai sees progress and the connection stays alive
1488
+ // while blocked on permission requests.
1489
+ forwardMessagesToBridge();
1490
+ if (message.type === 'result') {
1491
+ // Flush pending SDK events so they appear before result on the stream.
1492
+ for (const event of drainSdkEvents()) {
1493
+ output.enqueue(event);
1494
+ }
1495
+ // Hold-back: don't emit result while background agents are running
1496
+ const currentState = getAppState();
1497
+ if (getRunningTasks(currentState).some(t => (t.type === 'local_agent' ||
1498
+ t.type === 'local_workflow') &&
1499
+ isBackgroundTask(t))) {
1500
+ heldBackResult = message;
1501
+ }
1502
+ else {
1503
+ heldBackResult = null;
1504
+ output.enqueue(message);
1505
+ }
1506
+ }
1507
+ else {
1508
+ // Flush SDK events (task_started, task_progress) so background
1509
+ // agent progress is streamed in real-time, not batched until result.
1510
+ for (const event of drainSdkEvents()) {
1511
+ output.enqueue(event);
1512
+ }
1513
+ output.enqueue(message);
1514
+ }
1515
+ }
1516
+ }); // end runWithWorkload
1517
+ // Reactor voice channel — emit response text for TTS
1518
+ // Fully inlined — no require() or import needed. Uses globalThis
1519
+ // directly to eliminate any possible module identity / resolution issue.
1520
+ try {
1521
+ const G = globalThis;
1522
+ const reactorPending = G.__reactorPending;
1523
+ if (reactorPending && reactorPending.size > 0) {
1524
+ const rUuid = cmd.uuid ?? batchUuids[batchUuids.length - 1];
1525
+ console.log(`[Reactor Bus] Turn complete — UUID ${rUuid}, pending=${reactorPending.size}, keys=${[...reactorPending.keys()].join(',')}`);
1526
+ // Find callback — try exact match, then all batch UUIDs, then single-pending fallback
1527
+ const rKey = String(rUuid);
1528
+ let rCb = reactorPending.get(rKey);
1529
+ if (rCb) {
1530
+ reactorPending.delete(rKey);
1531
+ }
1532
+ else {
1533
+ // Try all batch UUIDs (commands may be batched, UUID order can shift)
1534
+ for (const bUuid of batchUuids) {
1535
+ const bKey = String(bUuid);
1536
+ rCb = reactorPending.get(bKey);
1537
+ if (rCb) {
1538
+ console.log(`[Reactor Bus] Matched via batch UUID: ${bKey}`);
1539
+ reactorPending.delete(bKey);
1540
+ break;
1541
+ }
1542
+ }
1543
+ // Last resort: single-pending fallback
1544
+ if (!rCb && reactorPending.size === 1) {
1545
+ const [fk, fcb] = [...reactorPending.entries()][0];
1546
+ console.log(`[Reactor Bus] UUID mismatch — using single-pending fallback: ${fk}`);
1547
+ rCb = fcb;
1548
+ reactorPending.delete(fk);
1549
+ }
1550
+ }
1551
+ if (rCb) {
1552
+ // Extract last assistant text from mutableMessages
1553
+ let rText = '';
1554
+ for (let ri = mutableMessages.length - 1; ri >= 0; ri--) {
1555
+ const rm = mutableMessages[ri];
1556
+ if (rm?.type !== 'assistant')
1557
+ continue;
1558
+ const rmsg = rm.message;
1559
+ const rcontent = rmsg?.content ?? rm.content;
1560
+ if (!rcontent)
1561
+ continue;
1562
+ if (typeof rcontent === 'string') {
1563
+ rText = rcontent;
1564
+ }
1565
+ else if (Array.isArray(rcontent)) {
1566
+ rText = rcontent
1567
+ .filter((b) => b.type === 'text')
1568
+ .map((b) => String(b.text || ''))
1569
+ .join('\n');
1570
+ }
1571
+ if (rText.trim())
1572
+ break;
1573
+ }
1574
+ const rFinal = rText.trim() ||
1575
+ 'Command processed. Check the terminal for details.';
1576
+ console.log(`[Reactor Bus] Emitting (${rFinal.length} chars): ${rFinal.slice(0, 80)}...`);
1577
+ rCb(rFinal);
1578
+ }
1579
+ }
1580
+ }
1581
+ catch (e) {
1582
+ console.error('[Reactor Bus] Error:', e);
1583
+ }
1584
+ for (const uuid of batchUuids) {
1585
+ notifyCommandLifecycle(uuid, 'completed');
1586
+ }
1587
+ // Forward messages to bridge after each turn
1588
+ forwardMessagesToBridge();
1589
+ bridgeHandle?.sendResult();
1590
+ if (feature('FILE_PERSISTENCE') && turnStartTime !== undefined) {
1591
+ void executeFilePersistence(turnStartTime, abortController.signal, result => {
1592
+ output.enqueue({
1593
+ type: 'system',
1594
+ subtype: 'files_persisted',
1595
+ files: result.files,
1596
+ failed: result.failed,
1597
+ processed_at: new Date().toISOString(),
1598
+ uuid: randomUUID(),
1599
+ session_id: getSessionId(),
1600
+ });
1601
+ });
1602
+ }
1603
+ // Generate and emit prompt suggestion for SDK consumers
1604
+ if (options.promptSuggestions &&
1605
+ !isEnvDefinedFalsy(process.env.THADDEUS_ENABLE_PROMPT_SUGGESTION)) {
1606
+ // TS narrows suggestionState to never in the while loop body;
1607
+ // cast via unknown to reset narrowing.
1608
+ const state = suggestionState;
1609
+ state.abortController?.abort();
1610
+ const localAbort = new AbortController();
1611
+ suggestionState.abortController = localAbort;
1612
+ const cacheSafeParams = getLastCacheSafeParams();
1613
+ if (!cacheSafeParams) {
1614
+ logSuggestionSuppressed('sdk_no_params', undefined, undefined, 'sdk');
1615
+ }
1616
+ else {
1617
+ // Use a ref object so the IIFE's finally can compare against its own
1618
+ // promise without a self-reference (which upsets TypeScript's flow analysis).
1619
+ const ref = { promise: null };
1620
+ ref.promise = (async () => {
1621
+ try {
1622
+ const result = await tryGenerateSuggestion(localAbort, mutableMessages, getAppState, cacheSafeParams, 'sdk');
1623
+ if (!result || localAbort.signal.aborted)
1624
+ return;
1625
+ const suggestionMsg = {
1626
+ type: 'prompt_suggestion',
1627
+ suggestion: result.suggestion,
1628
+ uuid: randomUUID(),
1629
+ session_id: getSessionId(),
1630
+ };
1631
+ const lastEmittedEntry = {
1632
+ text: result.suggestion,
1633
+ emittedAt: Date.now(),
1634
+ promptId: result.promptId,
1635
+ generationRequestId: result.generationRequestId,
1636
+ };
1637
+ // Defer emission if the result is being held for background agents,
1638
+ // so that prompt_suggestion always arrives after result.
1639
+ // Only set lastEmitted when the suggestion is actually delivered
1640
+ // to the consumer; deferred suggestions may be discarded before
1641
+ // delivery if a new command arrives first.
1642
+ if (heldBackResult) {
1643
+ suggestionState.pendingSuggestion = suggestionMsg;
1644
+ suggestionState.pendingLastEmittedEntry = {
1645
+ text: lastEmittedEntry.text,
1646
+ promptId: lastEmittedEntry.promptId,
1647
+ generationRequestId: lastEmittedEntry.generationRequestId,
1648
+ };
1649
+ }
1650
+ else {
1651
+ suggestionState.lastEmitted = lastEmittedEntry;
1652
+ output.enqueue(suggestionMsg);
1653
+ }
1654
+ }
1655
+ catch (error) {
1656
+ if (error instanceof Error &&
1657
+ (error.name === 'AbortError' ||
1658
+ error.name === 'APIUserAbortError')) {
1659
+ logSuggestionSuppressed('aborted', undefined, undefined, 'sdk');
1660
+ return;
1661
+ }
1662
+ logError(toError(error));
1663
+ }
1664
+ finally {
1665
+ if (suggestionState.inflightPromise === ref.promise) {
1666
+ suggestionState.inflightPromise = null;
1667
+ }
1668
+ }
1669
+ })();
1670
+ suggestionState.inflightPromise = ref.promise;
1671
+ }
1672
+ }
1673
+ // Log headless profiler metrics for this turn and start next turn
1674
+ logHeadlessProfilerTurn();
1675
+ logQueryProfileReport();
1676
+ headlessProfilerStartTurn();
1677
+ }
1678
+ };
1679
+ // Use a do-while loop to drain commands and then wait for any
1680
+ // background agents that are still running. When agents complete,
1681
+ // their notifications are enqueued and the loop re-drains.
1682
+ do {
1683
+ // Drain SDK events (task_started, task_progress) before command queue
1684
+ // so progress events precede task_notification on the stream.
1685
+ for (const event of drainSdkEvents()) {
1686
+ output.enqueue(event);
1687
+ }
1688
+ runPhase = 'draining_commands';
1689
+ await drainCommandQueue();
1690
+ // Check for running background tasks before exiting.
1691
+ // Exclude in_process_teammate — teammates are long-lived by design
1692
+ // (status: 'running' for their whole lifetime, cleaned up by the
1693
+ // shutdown protocol, not by transitioning to 'completed'). Waiting
1694
+ // on them here loops forever (gh-30008). Same exclusion already
1695
+ // exists at useBackgroundTaskNavigation.ts:55 for the same reason;
1696
+ // L1839 above is already narrower (type === 'local_agent') so it
1697
+ // doesn't hit this.
1698
+ waitingForAgents = false;
1699
+ {
1700
+ const state = getAppState();
1701
+ const hasRunningBg = getRunningTasks(state).some(t => isBackgroundTask(t) && t.type !== 'in_process_teammate');
1702
+ const hasMainThreadQueued = peek(isMainThread) !== undefined;
1703
+ if (hasRunningBg || hasMainThreadQueued) {
1704
+ waitingForAgents = true;
1705
+ if (!hasMainThreadQueued) {
1706
+ runPhase = 'waiting_for_agents';
1707
+ // No commands ready yet, wait for tasks to complete
1708
+ await sleep(100);
1709
+ }
1710
+ // Loop back to drain any newly queued commands
1711
+ }
1712
+ }
1713
+ } while (waitingForAgents);
1714
+ if (heldBackResult) {
1715
+ output.enqueue(heldBackResult);
1716
+ heldBackResult = null;
1717
+ if (suggestionState.pendingSuggestion) {
1718
+ output.enqueue(suggestionState.pendingSuggestion);
1719
+ // Now that the suggestion is actually delivered, record it for acceptance tracking
1720
+ if (suggestionState.pendingLastEmittedEntry) {
1721
+ suggestionState.lastEmitted = {
1722
+ ...suggestionState.pendingLastEmittedEntry,
1723
+ emittedAt: Date.now(),
1724
+ };
1725
+ suggestionState.pendingLastEmittedEntry = null;
1726
+ }
1727
+ suggestionState.pendingSuggestion = null;
1728
+ }
1729
+ }
1730
+ }
1731
+ catch (error) {
1732
+ // Emit error result message before shutting down
1733
+ // Write directly to structuredIO to ensure immediate delivery
1734
+ try {
1735
+ await structuredIO.write({
1736
+ type: 'result',
1737
+ subtype: 'error_during_execution',
1738
+ duration_ms: 0,
1739
+ duration_api_ms: 0,
1740
+ is_error: true,
1741
+ num_turns: 0,
1742
+ stop_reason: null,
1743
+ session_id: getSessionId(),
1744
+ total_cost_usd: 0,
1745
+ usage: EMPTY_USAGE,
1746
+ modelUsage: {},
1747
+ permission_denials: [],
1748
+ uuid: randomUUID(),
1749
+ errors: [
1750
+ errorMessage(error),
1751
+ ...getInMemoryErrors().map(_ => _.error),
1752
+ ],
1753
+ });
1754
+ }
1755
+ catch {
1756
+ // If we can't emit the error result, continue with shutdown anyway
1757
+ }
1758
+ suggestionState.abortController?.abort();
1759
+ gracefulShutdownSync(1);
1760
+ return;
1761
+ }
1762
+ finally {
1763
+ runPhase = 'finally_flush';
1764
+ // Flush pending internal events before going idle
1765
+ await structuredIO.flushInternalEvents();
1766
+ runPhase = 'finally_post_flush';
1767
+ if (!isShuttingDown()) {
1768
+ notifySessionStateChanged('idle');
1769
+ // Drain so the idle session_state_changed SDK event (plus any
1770
+ // terminal task_notification bookends emitted during bg-agent
1771
+ // teardown) reach the output stream before we block on the next
1772
+ // command. The do-while drain above only runs while
1773
+ // waitingForAgents; once we're here the next drain would be the
1774
+ // top of the next run(), which won't come if input is idle.
1775
+ for (const event of drainSdkEvents()) {
1776
+ output.enqueue(event);
1777
+ }
1778
+ }
1779
+ running = false;
1780
+ // Start idle timer when we finish processing and are waiting for input
1781
+ idleTimeout.start();
1782
+ }
1783
+ // Proactive tick: if proactive is active and queue is empty, inject a tick
1784
+ if ((feature('PROACTIVE') || feature('KAIROS')) &&
1785
+ proactiveModule?.isProactiveActive() &&
1786
+ !proactiveModule.isProactivePaused()) {
1787
+ if (peek(isMainThread) === undefined && !inputClosed) {
1788
+ scheduleProactiveTick();
1789
+ return;
1790
+ }
1791
+ }
1792
+ // Re-check the queue after releasing the mutex. A message may have
1793
+ // arrived (and called run()) between the last dequeue() returning
1794
+ // undefined and `running = false` above. In that case the caller
1795
+ // saw `running === true` and returned immediately, leaving the
1796
+ // message stranded in the queue with no one to process it.
1797
+ if (peek(isMainThread) !== undefined) {
1798
+ void run();
1799
+ return;
1800
+ }
1801
+ // Check for unread teammate messages and process them
1802
+ // This mirrors what useInboxPoller does in interactive REPL mode
1803
+ // Poll until no more messages (teammates may still be working)
1804
+ {
1805
+ const currentAppState = getAppState();
1806
+ const teamContext = currentAppState.teamContext;
1807
+ if (teamContext && isTeamLead(teamContext)) {
1808
+ const agentName = 'team-lead';
1809
+ // Poll for messages while teammates are active
1810
+ // This is needed because teammates may send messages while we're waiting
1811
+ // Keep polling until the team is shut down
1812
+ const POLL_INTERVAL_MS = 500;
1813
+ while (true) {
1814
+ // Check if teammates are still active
1815
+ const refreshedState = getAppState();
1816
+ const hasActiveTeammates = hasActiveInProcessTeammates(refreshedState) ||
1817
+ (refreshedState.teamContext &&
1818
+ Object.keys(refreshedState.teamContext.teammates).length > 0);
1819
+ if (!hasActiveTeammates) {
1820
+ logForDebugging('[print.ts] No more active teammates, stopping poll');
1821
+ break;
1822
+ }
1823
+ const unread = await readUnreadMessages(agentName, refreshedState.teamContext?.teamName);
1824
+ if (unread.length > 0) {
1825
+ logForDebugging(`[print.ts] Team-lead found ${unread.length} unread messages`);
1826
+ // Mark as read immediately to avoid duplicate processing
1827
+ await markMessagesAsRead(agentName, refreshedState.teamContext?.teamName);
1828
+ // Process shutdown_approved messages - remove teammates from team file
1829
+ // This mirrors what useInboxPoller does in interactive mode (lines 546-606)
1830
+ const teamName = refreshedState.teamContext?.teamName;
1831
+ for (const m of unread) {
1832
+ const shutdownApproval = isShutdownApproved(m.text);
1833
+ if (shutdownApproval && teamName) {
1834
+ const teammateToRemove = shutdownApproval.from;
1835
+ logForDebugging(`[print.ts] Processing shutdown_approved from ${teammateToRemove}`);
1836
+ // Find the teammate ID by name
1837
+ const teammateId = refreshedState.teamContext?.teammates
1838
+ ? Object.entries(refreshedState.teamContext.teammates).find(([, t]) => t.name === teammateToRemove)?.[0]
1839
+ : undefined;
1840
+ if (teammateId) {
1841
+ // Remove from team file
1842
+ removeTeammateFromTeamFile(teamName, {
1843
+ agentId: teammateId,
1844
+ name: teammateToRemove,
1845
+ });
1846
+ logForDebugging(`[print.ts] Removed ${teammateToRemove} from team file`);
1847
+ // Unassign tasks owned by this teammate
1848
+ await unassignTeammateTasks(teamName, teammateId, teammateToRemove, 'shutdown');
1849
+ // Remove from teamContext in AppState
1850
+ setAppState(prev => {
1851
+ if (!prev.teamContext?.teammates)
1852
+ return prev;
1853
+ if (!(teammateId in prev.teamContext.teammates))
1854
+ return prev;
1855
+ const { [teammateId]: _, ...remainingTeammates } = prev.teamContext.teammates;
1856
+ return {
1857
+ ...prev,
1858
+ teamContext: {
1859
+ ...prev.teamContext,
1860
+ teammates: remainingTeammates,
1861
+ },
1862
+ };
1863
+ });
1864
+ }
1865
+ }
1866
+ }
1867
+ // Format messages same as useInboxPoller
1868
+ const formatted = unread
1869
+ .map((m) => `<${TEAMMATE_MESSAGE_TAG} teammate_id="${m.from}"${m.color ? ` color="${m.color}"` : ''}>\n${m.text}\n</${TEAMMATE_MESSAGE_TAG}>`)
1870
+ .join('\n\n');
1871
+ // Enqueue and process
1872
+ enqueue({
1873
+ mode: 'prompt',
1874
+ value: formatted,
1875
+ uuid: randomUUID(),
1876
+ });
1877
+ void run();
1878
+ return; // run() will come back here after processing
1879
+ }
1880
+ // No messages - check if we need to prompt for shutdown
1881
+ // If input is closed and teammates are active, inject shutdown prompt once
1882
+ if (inputClosed && !shutdownPromptInjected) {
1883
+ shutdownPromptInjected = true;
1884
+ logForDebugging('[print.ts] Input closed with active teammates, injecting shutdown prompt');
1885
+ enqueue({
1886
+ mode: 'prompt',
1887
+ value: SHUTDOWN_TEAM_PROMPT,
1888
+ uuid: randomUUID(),
1889
+ });
1890
+ void run();
1891
+ return; // run() will come back here after processing
1892
+ }
1893
+ // Wait and check again
1894
+ await sleep(POLL_INTERVAL_MS);
1895
+ }
1896
+ }
1897
+ }
1898
+ if (inputClosed) {
1899
+ // Check for active swarm that needs shutdown
1900
+ const hasActiveSwarm = await (async () => {
1901
+ // Wait for any working in-process team members to finish
1902
+ const currentAppState = getAppState();
1903
+ if (hasWorkingInProcessTeammates(currentAppState)) {
1904
+ await waitForTeammatesToBecomeIdle(setAppState, currentAppState);
1905
+ }
1906
+ // Re-fetch state after potential wait
1907
+ const refreshedAppState = getAppState();
1908
+ const refreshedTeamContext = refreshedAppState.teamContext;
1909
+ const hasTeamMembersNotCleanedUp = refreshedTeamContext &&
1910
+ Object.keys(refreshedTeamContext.teammates).length > 0;
1911
+ return (hasTeamMembersNotCleanedUp ||
1912
+ hasActiveInProcessTeammates(refreshedAppState));
1913
+ })();
1914
+ if (hasActiveSwarm) {
1915
+ // Team members are idle or pane-based - inject prompt to shut down team
1916
+ enqueue({
1917
+ mode: 'prompt',
1918
+ value: SHUTDOWN_TEAM_PROMPT,
1919
+ uuid: randomUUID(),
1920
+ });
1921
+ void run();
1922
+ }
1923
+ else {
1924
+ // Wait for any in-flight push suggestion before closing the output stream.
1925
+ if (suggestionState.inflightPromise) {
1926
+ await Promise.race([suggestionState.inflightPromise, sleep(5000)]);
1927
+ }
1928
+ suggestionState.abortController?.abort();
1929
+ suggestionState.abortController = null;
1930
+ await finalizePendingAsyncHooks();
1931
+ unsubscribeSkillChanges();
1932
+ unsubscribeAuthStatus?.();
1933
+ statusListeners.delete(rateLimitListener);
1934
+ output.done();
1935
+ }
1936
+ }
1937
+ };
1938
+ // Set up UDS inbox callback so the query loop is kicked off
1939
+ // when a message arrives via the UDS socket in headless mode.
1940
+ if (feature('UDS_INBOX')) {
1941
+ /* eslint-disable @typescript-eslint/no-require-imports */
1942
+ const { setOnEnqueue } = require('../utils/udsMessaging.js');
1943
+ /* eslint-enable @typescript-eslint/no-require-imports */
1944
+ setOnEnqueue(() => {
1945
+ if (!inputClosed) {
1946
+ void run();
1947
+ }
1948
+ });
1949
+ }
1950
+ // Cron scheduler: runs scheduled_tasks.json tasks in SDK/-p mode.
1951
+ // Mirrors REPL's useScheduledTasks hook. Fired prompts enqueue + kick
1952
+ // off run() directly — unlike REPL, there's no queue subscriber here
1953
+ // that drains on enqueue while idle. The run() mutex makes this safe
1954
+ // during an active turn: the call no-ops and the post-run recheck at
1955
+ // the end of run() picks up the queued command.
1956
+ let cronScheduler = null;
1957
+ if (feature('AGENT_TRIGGERS') &&
1958
+ cronSchedulerModule &&
1959
+ cronGate?.isKairosCronEnabled()) {
1960
+ cronScheduler = cronSchedulerModule.createCronScheduler({
1961
+ onFire: prompt => {
1962
+ if (inputClosed)
1963
+ return;
1964
+ enqueue({
1965
+ mode: 'prompt',
1966
+ value: prompt,
1967
+ uuid: randomUUID(),
1968
+ priority: 'later',
1969
+ // System-generated — matches useScheduledTasks.ts REPL equivalent.
1970
+ // Without this, messages.ts metaProp eval is {} → prompt leaks
1971
+ // into visible transcript when cron fires mid-turn in -p mode.
1972
+ isMeta: true,
1973
+ // Threaded to cc_workload= in the billing-header attribution block
1974
+ // so the API can serve cron requests at lower QoS. drainCommandQueue
1975
+ // reads this per-iteration and hoists it into bootstrap state for
1976
+ // the ask() call.
1977
+ workload: WORKLOAD_CRON,
1978
+ });
1979
+ void run();
1980
+ },
1981
+ isLoading: () => running || inputClosed,
1982
+ getJitterConfig: cronJitterConfigModule?.getCronJitterConfig,
1983
+ isKilled: () => !cronGate?.isKairosCronEnabled(),
1984
+ });
1985
+ cronScheduler.start();
1986
+ }
1987
+ const sendControlResponseSuccess = function (message, response) {
1988
+ output.enqueue({
1989
+ type: 'control_response',
1990
+ response: {
1991
+ subtype: 'success',
1992
+ request_id: message.request_id,
1993
+ response: response,
1994
+ },
1995
+ });
1996
+ };
1997
+ const sendControlResponseError = function (message, errorMessage) {
1998
+ output.enqueue({
1999
+ type: 'control_response',
2000
+ response: {
2001
+ subtype: 'error',
2002
+ request_id: message.request_id,
2003
+ error: errorMessage,
2004
+ },
2005
+ });
2006
+ };
2007
+ // Handle unexpected permission responses by looking up the unresolved tool
2008
+ // call in the transcript and executing it
2009
+ const handledOrphanedToolUseIds = new Set();
2010
+ structuredIO.setUnexpectedResponseCallback(async (message) => {
2011
+ await handleOrphanedPermissionResponse({
2012
+ message,
2013
+ setAppState,
2014
+ handledToolUseIds: handledOrphanedToolUseIds,
2015
+ onEnqueued: () => {
2016
+ // The first message of a session might be the orphaned permission
2017
+ // check rather than a user prompt, so kick off the loop.
2018
+ void run();
2019
+ },
2020
+ });
2021
+ });
2022
+ // Track active OAuth flows per server so we can abort a previous flow
2023
+ // when a new mcp_authenticate request arrives for the same server.
2024
+ const activeOAuthFlows = new Map();
2025
+ // Track manual callback URL submit functions for active OAuth flows.
2026
+ // Used when localhost is not reachable (e.g., browser-based IDEs).
2027
+ const oauthCallbackSubmitters = new Map();
2028
+ // Track servers where the manual callback was actually invoked (so the
2029
+ // automatic reconnect path knows to skip — the extension will reconnect).
2030
+ const oauthManualCallbackUsed = new Set();
2031
+ // Track OAuth auth-only promises so mcp_oauth_callback_url can await
2032
+ // token exchange completion. Reconnect is handled separately by the
2033
+ // extension via handleAuthDone → mcp_reconnect.
2034
+ const oauthAuthPromises = new Map();
2035
+ // In-flight OAuth flow (claude_authenticate). Single-slot: a
2036
+ // second authenticate request cleans up the first. The service holds the
2037
+ // PKCE verifier + localhost listener; the promise settles after
2038
+ // installOAuthTokens — after it resolves, the in-process memoized token
2039
+ // cache is already cleared and the next API call picks up the new creds.
2040
+ let claudeOAuth = null;
2041
+ // This is essentially spawning a parallel async task- we have two
2042
+ // running in parallel- one reading from stdin and adding to the
2043
+ // queue to be processed and another reading from the queue,
2044
+ // processing and returning the result of the generation.
2045
+ // The process is complete when the input stream completes and
2046
+ // the last generation of the queue has complete.
2047
+ void (async () => {
2048
+ let initialized = false;
2049
+ logForDiagnosticsNoPII('info', 'cli_message_loop_started');
2050
+ for await (const message of structuredIO.structuredInput) {
2051
+ // Non-user events are handled inline (no queue). started→completed in
2052
+ // the same tick carries no information, so only fire completed.
2053
+ // control_response is reported by StructuredIO.processLine (which also
2054
+ // sees orphans that never yield here).
2055
+ const eventId = 'uuid' in message ? message.uuid : undefined;
2056
+ if (eventId &&
2057
+ message.type !== 'user' &&
2058
+ message.type !== 'control_response') {
2059
+ notifyCommandLifecycle(eventId, 'completed');
2060
+ }
2061
+ if (message.type === 'control_request') {
2062
+ if (message.request.subtype === 'interrupt') {
2063
+ // Track escapes for attribution (ant-only feature)
2064
+ if (feature('COMMIT_ATTRIBUTION')) {
2065
+ setAppState(prev => ({
2066
+ ...prev,
2067
+ attribution: {
2068
+ ...prev.attribution,
2069
+ escapeCount: prev.attribution.escapeCount + 1,
2070
+ },
2071
+ }));
2072
+ }
2073
+ if (abortController) {
2074
+ abortController.abort();
2075
+ }
2076
+ suggestionState.abortController?.abort();
2077
+ suggestionState.abortController = null;
2078
+ suggestionState.lastEmitted = null;
2079
+ suggestionState.pendingSuggestion = null;
2080
+ sendControlResponseSuccess(message);
2081
+ }
2082
+ else if (message.request.subtype === 'end_session') {
2083
+ logForDebugging(`[print.ts] end_session received, reason=${message.request.reason ?? 'unspecified'}`);
2084
+ if (abortController) {
2085
+ abortController.abort();
2086
+ }
2087
+ suggestionState.abortController?.abort();
2088
+ suggestionState.abortController = null;
2089
+ suggestionState.lastEmitted = null;
2090
+ suggestionState.pendingSuggestion = null;
2091
+ sendControlResponseSuccess(message);
2092
+ break; // exits for-await → falls through to inputClosed=true drain below
2093
+ }
2094
+ else if (message.request.subtype === 'initialize') {
2095
+ // SDK MCP server names from the initialize message
2096
+ // Populated by both browser and ProcessTransport sessions
2097
+ if (message.request.sdkMcpServers &&
2098
+ message.request.sdkMcpServers.length > 0) {
2099
+ for (const serverName of message.request.sdkMcpServers) {
2100
+ // Create placeholder config for SDK MCP servers
2101
+ // The actual server connection is managed by the SDK Query class
2102
+ sdkMcpConfigs[serverName] = {
2103
+ type: 'sdk',
2104
+ name: serverName,
2105
+ };
2106
+ }
2107
+ }
2108
+ await handleInitializeRequest(message.request, message.request_id, initialized, output, commands, modelInfos, structuredIO, !!options.enableAuthStatus, options, agents, getAppState);
2109
+ // Enable prompt suggestions in AppState when SDK consumer opts in.
2110
+ // shouldEnablePromptSuggestion() returns false for non-interactive
2111
+ // sessions, but the SDK consumer explicitly requested suggestions.
2112
+ if (message.request.promptSuggestions) {
2113
+ setAppState(prev => {
2114
+ if (prev.promptSuggestionEnabled)
2115
+ return prev;
2116
+ return { ...prev, promptSuggestionEnabled: true };
2117
+ });
2118
+ }
2119
+ if (message.request.agentProgressSummaries &&
2120
+ getFeatureValue_CACHED_MAY_BE_STALE('thaddeus_slate_prism', true)) {
2121
+ setSdkAgentProgressSummariesEnabled(true);
2122
+ }
2123
+ initialized = true;
2124
+ // If the auto-resume logic pre-enqueued a command, drain it now
2125
+ // that initialize has set up systemPrompt, agents, hooks, etc.
2126
+ if (hasCommandsInQueue()) {
2127
+ void run();
2128
+ }
2129
+ }
2130
+ else if (message.request.subtype === 'set_permission_mode') {
2131
+ const m = message.request; // for typescript (TODO: use readonly types to avoid this)
2132
+ setAppState(prev => ({
2133
+ ...prev,
2134
+ toolPermissionContext: handleSetPermissionMode(m, message.request_id, prev.toolPermissionContext, output),
2135
+ isUltraplanMode: m.ultraplan ?? prev.isUltraplanMode,
2136
+ }));
2137
+ // handleSetPermissionMode sends the control_response; the
2138
+ // notifySessionMetadataChanged that used to follow here is
2139
+ // now fired by onChangeAppState (with externalized mode name).
2140
+ }
2141
+ else if (message.request.subtype === 'set_model') {
2142
+ const requestedModel = message.request.model ?? 'default';
2143
+ const model = requestedModel === 'default'
2144
+ ? getDefaultMainLoopModel()
2145
+ : requestedModel;
2146
+ activeUserSpecifiedModel = model;
2147
+ setMainLoopModelOverride(model);
2148
+ notifySessionMetadataChanged({ model });
2149
+ injectModelSwitchBreadcrumbs(requestedModel, model);
2150
+ sendControlResponseSuccess(message);
2151
+ }
2152
+ else if (message.request.subtype === 'set_max_thinking_tokens') {
2153
+ if (message.request.max_thinking_tokens === null) {
2154
+ options.thinkingConfig = undefined;
2155
+ }
2156
+ else if (message.request.max_thinking_tokens === 0) {
2157
+ options.thinkingConfig = { type: 'disabled' };
2158
+ }
2159
+ else {
2160
+ options.thinkingConfig = {
2161
+ type: 'enabled',
2162
+ budgetTokens: message.request.max_thinking_tokens,
2163
+ };
2164
+ }
2165
+ sendControlResponseSuccess(message);
2166
+ }
2167
+ else if (message.request.subtype === 'mcp_status') {
2168
+ sendControlResponseSuccess(message, {
2169
+ mcpServers: buildMcpServerStatuses(),
2170
+ });
2171
+ }
2172
+ else if (message.request.subtype === 'get_context_usage') {
2173
+ try {
2174
+ const appState = getAppState();
2175
+ const data = await collectContextData({
2176
+ messages: mutableMessages,
2177
+ getAppState,
2178
+ options: {
2179
+ mainLoopModel: getMainLoopModel(),
2180
+ tools: buildAllTools(appState),
2181
+ agentDefinitions: appState.agentDefinitions,
2182
+ customSystemPrompt: options.systemPrompt,
2183
+ appendSystemPrompt: options.appendSystemPrompt,
2184
+ },
2185
+ });
2186
+ sendControlResponseSuccess(message, { ...data });
2187
+ }
2188
+ catch (error) {
2189
+ sendControlResponseError(message, errorMessage(error));
2190
+ }
2191
+ }
2192
+ else if (message.request.subtype === 'mcp_message') {
2193
+ // Handle MCP notifications from SDK servers
2194
+ const mcpRequest = message.request;
2195
+ const sdkClient = sdkClients.find(client => client.name === mcpRequest.server_name);
2196
+ // Check client exists - dynamically added SDK servers may have
2197
+ // placeholder clients with null client until updateSdkMcp() runs
2198
+ if (sdkClient &&
2199
+ sdkClient.type === 'connected' &&
2200
+ sdkClient.client?.transport?.onmessage) {
2201
+ sdkClient.client.transport.onmessage(mcpRequest.message);
2202
+ }
2203
+ sendControlResponseSuccess(message);
2204
+ }
2205
+ else if (message.request.subtype === 'rewind_files') {
2206
+ const appState = getAppState();
2207
+ const result = await handleRewindFiles(message.request.user_message_id, appState, setAppState, message.request.dry_run ?? false);
2208
+ if (result.canRewind || message.request.dry_run) {
2209
+ sendControlResponseSuccess(message, result);
2210
+ }
2211
+ else {
2212
+ sendControlResponseError(message, result.error ?? 'Unexpected error');
2213
+ }
2214
+ }
2215
+ else if (message.request.subtype === 'cancel_async_message') {
2216
+ const targetUuid = message.request.message_uuid;
2217
+ const removed = dequeueAllMatching(cmd => cmd.uuid === targetUuid);
2218
+ sendControlResponseSuccess(message, {
2219
+ cancelled: removed.length > 0,
2220
+ });
2221
+ }
2222
+ else if (message.request.subtype === 'seed_read_state') {
2223
+ // Client observed a Read that was later removed from context (e.g.
2224
+ // by snip), so transcript-based seeding missed it. Queued into
2225
+ // pendingSeeds; applied at the next clone-replace boundary.
2226
+ try {
2227
+ // expandPath: all other readFileState writers normalize (~, relative,
2228
+ // session cwd vs process cwd). FileEditTool looks up by expandPath'd
2229
+ // key — a verbatim client path would miss.
2230
+ const normalizedPath = expandPath(message.request.path);
2231
+ // Check disk mtime before reading content. If the file changed
2232
+ // since the client's observation, readFile would return C_current
2233
+ // but we'd store it with the client's M_observed — getChangedFiles
2234
+ // then sees disk > cache.timestamp, re-reads, diffs C_current vs
2235
+ // C_current = empty, emits no attachment, and the model is never
2236
+ // told about the C_observed → C_current change. Skipping the seed
2237
+ // makes Edit fail "file not read yet" → forces a fresh Read.
2238
+ // Math.floor matches FileReadTool and getFileModificationTime.
2239
+ const diskMtime = Math.floor((await stat(normalizedPath)).mtimeMs);
2240
+ if (diskMtime <= message.request.mtime) {
2241
+ const raw = await readFile(normalizedPath, 'utf-8');
2242
+ // Strip BOM + normalize CRLF→LF to match readFileInRange and
2243
+ // readFileSyncWithMetadata. FileEditTool's content-compare
2244
+ // fallback (for Windows mtime bumps without content change)
2245
+ // compares against LF-normalized disk reads.
2246
+ const content = (raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw).replaceAll('\r\n', '\n');
2247
+ pendingSeeds.set(normalizedPath, {
2248
+ content,
2249
+ timestamp: diskMtime,
2250
+ offset: undefined,
2251
+ limit: undefined,
2252
+ });
2253
+ }
2254
+ }
2255
+ catch {
2256
+ // ENOENT etc — skip seeding but still succeed
2257
+ }
2258
+ sendControlResponseSuccess(message);
2259
+ }
2260
+ else if (message.request.subtype === 'mcp_set_servers') {
2261
+ const { response, sdkServersChanged } = await applyMcpServerChanges(message.request.servers);
2262
+ sendControlResponseSuccess(message, response);
2263
+ // Connect SDK servers AFTER response to avoid deadlock
2264
+ if (sdkServersChanged) {
2265
+ void updateSdkMcp();
2266
+ }
2267
+ }
2268
+ else if (message.request.subtype === 'reload_plugins') {
2269
+ try {
2270
+ if (feature('DOWNLOAD_USER_SETTINGS') &&
2271
+ (isEnvTruthy(process.env.THADDEUS_REMOTE) || getIsRemoteMode())) {
2272
+ // Re-pull user settings so enabledPlugins pushed from the
2273
+ // user's local CLI take effect before the cache sweep.
2274
+ const applied = await redownloadUserSettings();
2275
+ if (applied) {
2276
+ settingsChangeDetector.notifyChange('userSettings');
2277
+ }
2278
+ }
2279
+ const r = await refreshActivePlugins(setAppState);
2280
+ const sdkAgents = currentAgents.filter(a => a.source === 'flagSettings');
2281
+ currentAgents = [...r.agentDefinitions.allAgents, ...sdkAgents];
2282
+ // Reload succeeded — gather response data best-effort so a
2283
+ // read failure doesn't mask the successful state change.
2284
+ // allSettled so one failure doesn't discard the others.
2285
+ let plugins = [];
2286
+ const [cmdsR, mcpR, pluginsR] = await Promise.allSettled([
2287
+ getCommands(cwd()),
2288
+ applyPluginMcpDiff(),
2289
+ loadAllPluginsCacheOnly(),
2290
+ ]);
2291
+ if (cmdsR.status === 'fulfilled') {
2292
+ currentCommands = cmdsR.value;
2293
+ }
2294
+ else {
2295
+ logError(cmdsR.reason);
2296
+ }
2297
+ if (mcpR.status === 'rejected') {
2298
+ logError(mcpR.reason);
2299
+ }
2300
+ if (pluginsR.status === 'fulfilled') {
2301
+ plugins = pluginsR.value.enabled.map(p => ({
2302
+ name: p.name,
2303
+ path: p.path,
2304
+ source: p.source,
2305
+ }));
2306
+ }
2307
+ else {
2308
+ logError(pluginsR.reason);
2309
+ }
2310
+ sendControlResponseSuccess(message, {
2311
+ commands: currentCommands
2312
+ .filter(cmd => cmd.userInvocable !== false)
2313
+ .map(cmd => ({
2314
+ name: getCommandName(cmd),
2315
+ description: formatDescriptionWithSource(cmd),
2316
+ argumentHint: cmd.argumentHint || '',
2317
+ })),
2318
+ agents: currentAgents.map(a => ({
2319
+ name: a.agentType,
2320
+ description: a.whenToUse,
2321
+ model: a.model === 'inherit' ? undefined : a.model,
2322
+ })),
2323
+ plugins,
2324
+ mcpServers: buildMcpServerStatuses(),
2325
+ error_count: r.error_count,
2326
+ });
2327
+ }
2328
+ catch (error) {
2329
+ sendControlResponseError(message, errorMessage(error));
2330
+ }
2331
+ }
2332
+ else if (message.request.subtype === 'mcp_reconnect') {
2333
+ const currentAppState = getAppState();
2334
+ const { serverName } = message.request;
2335
+ elicitationRegistered.delete(serverName);
2336
+ // Config-existence gate must cover the SAME sources as the
2337
+ // operations below. SDK-injected servers (query({mcpServers:{...}}))
2338
+ // and dynamically-added servers were missing here, so
2339
+ // toggleMcpServer/reconnect returned "Server not found" even though
2340
+ // the disconnect/reconnect would have worked (gh-31339 / CC-314).
2341
+ const config = getMcpConfigByName(serverName) ??
2342
+ mcpClients.find(c => c.name === serverName)?.config ??
2343
+ sdkClients.find(c => c.name === serverName)?.config ??
2344
+ dynamicMcpState.clients.find(c => c.name === serverName)?.config ??
2345
+ currentAppState.mcp.clients.find(c => c.name === serverName)
2346
+ ?.config ??
2347
+ null;
2348
+ if (!config) {
2349
+ sendControlResponseError(message, `Server not found: ${serverName}`);
2350
+ }
2351
+ else {
2352
+ const result = await reconnectMcpServerImpl(serverName, config);
2353
+ // Update appState.mcp with the new client, tools, commands, and resources
2354
+ const prefix = getMcpPrefix(serverName);
2355
+ setAppState(prev => ({
2356
+ ...prev,
2357
+ mcp: {
2358
+ ...prev.mcp,
2359
+ clients: prev.mcp.clients.map(c => c.name === serverName ? result.client : c),
2360
+ tools: [
2361
+ ...reject(prev.mcp.tools, t => t.name?.startsWith(prefix)),
2362
+ ...result.tools,
2363
+ ],
2364
+ commands: [
2365
+ ...reject(prev.mcp.commands, c => commandBelongsToServer(c, serverName)),
2366
+ ...result.commands,
2367
+ ],
2368
+ resources: result.resources && result.resources.length > 0
2369
+ ? { ...prev.mcp.resources, [serverName]: result.resources }
2370
+ : omit(prev.mcp.resources, serverName),
2371
+ },
2372
+ }));
2373
+ // Also update dynamicMcpState so run() picks up the new tools
2374
+ // on the next turn (run() reads dynamicMcpState, not appState)
2375
+ dynamicMcpState = {
2376
+ ...dynamicMcpState,
2377
+ clients: [
2378
+ ...dynamicMcpState.clients.filter(c => c.name !== serverName),
2379
+ result.client,
2380
+ ],
2381
+ tools: [
2382
+ ...dynamicMcpState.tools.filter(t => !t.name?.startsWith(prefix)),
2383
+ ...result.tools,
2384
+ ],
2385
+ };
2386
+ if (result.client.type === 'connected') {
2387
+ registerElicitationHandlers([result.client]);
2388
+ reregisterChannelHandlerAfterReconnect(result.client);
2389
+ sendControlResponseSuccess(message);
2390
+ }
2391
+ else {
2392
+ const errorMessage = result.client.type === 'failed'
2393
+ ? (result.client.error ?? 'Connection failed')
2394
+ : `Server status: ${result.client.type}`;
2395
+ sendControlResponseError(message, errorMessage);
2396
+ }
2397
+ }
2398
+ }
2399
+ else if (message.request.subtype === 'mcp_toggle') {
2400
+ const currentAppState = getAppState();
2401
+ const { serverName, enabled } = message.request;
2402
+ elicitationRegistered.delete(serverName);
2403
+ // Gate must match the client-lookup spread below (which
2404
+ // includes sdkClients and dynamicMcpState.clients). Same fix as
2405
+ // mcp_reconnect above (gh-31339 / CC-314).
2406
+ const config = getMcpConfigByName(serverName) ??
2407
+ mcpClients.find(c => c.name === serverName)?.config ??
2408
+ sdkClients.find(c => c.name === serverName)?.config ??
2409
+ dynamicMcpState.clients.find(c => c.name === serverName)?.config ??
2410
+ currentAppState.mcp.clients.find(c => c.name === serverName)
2411
+ ?.config ??
2412
+ null;
2413
+ if (!config) {
2414
+ sendControlResponseError(message, `Server not found: ${serverName}`);
2415
+ }
2416
+ else if (!enabled) {
2417
+ // Disabling: persist + disconnect (matches TUI toggleMcpServer behavior)
2418
+ setMcpServerEnabled(serverName, false);
2419
+ const client = [
2420
+ ...mcpClients,
2421
+ ...sdkClients,
2422
+ ...dynamicMcpState.clients,
2423
+ ...currentAppState.mcp.clients,
2424
+ ].find(c => c.name === serverName);
2425
+ if (client && client.type === 'connected') {
2426
+ await clearServerCache(serverName, config);
2427
+ }
2428
+ // Update appState.mcp to reflect disabled status and remove tools/commands/resources
2429
+ const prefix = getMcpPrefix(serverName);
2430
+ setAppState(prev => ({
2431
+ ...prev,
2432
+ mcp: {
2433
+ ...prev.mcp,
2434
+ clients: prev.mcp.clients.map(c => c.name === serverName
2435
+ ? { name: serverName, type: 'disabled', config }
2436
+ : c),
2437
+ tools: reject(prev.mcp.tools, t => t.name?.startsWith(prefix)),
2438
+ commands: reject(prev.mcp.commands, c => commandBelongsToServer(c, serverName)),
2439
+ resources: omit(prev.mcp.resources, serverName),
2440
+ },
2441
+ }));
2442
+ sendControlResponseSuccess(message);
2443
+ }
2444
+ else {
2445
+ // Enabling: persist + reconnect
2446
+ setMcpServerEnabled(serverName, true);
2447
+ const result = await reconnectMcpServerImpl(serverName, config);
2448
+ // Update appState.mcp with the new client, tools, commands, and resources
2449
+ // This ensures the LLM sees updated tools after enabling the server
2450
+ const prefix = getMcpPrefix(serverName);
2451
+ setAppState(prev => ({
2452
+ ...prev,
2453
+ mcp: {
2454
+ ...prev.mcp,
2455
+ clients: prev.mcp.clients.map(c => c.name === serverName ? result.client : c),
2456
+ tools: [
2457
+ ...reject(prev.mcp.tools, t => t.name?.startsWith(prefix)),
2458
+ ...result.tools,
2459
+ ],
2460
+ commands: [
2461
+ ...reject(prev.mcp.commands, c => commandBelongsToServer(c, serverName)),
2462
+ ...result.commands,
2463
+ ],
2464
+ resources: result.resources && result.resources.length > 0
2465
+ ? { ...prev.mcp.resources, [serverName]: result.resources }
2466
+ : omit(prev.mcp.resources, serverName),
2467
+ },
2468
+ }));
2469
+ if (result.client.type === 'connected') {
2470
+ registerElicitationHandlers([result.client]);
2471
+ reregisterChannelHandlerAfterReconnect(result.client);
2472
+ sendControlResponseSuccess(message);
2473
+ }
2474
+ else {
2475
+ const errorMessage = result.client.type === 'failed'
2476
+ ? (result.client.error ?? 'Connection failed')
2477
+ : `Server status: ${result.client.type}`;
2478
+ sendControlResponseError(message, errorMessage);
2479
+ }
2480
+ }
2481
+ }
2482
+ else if (message.request.subtype === 'channel_enable') {
2483
+ const currentAppState = getAppState();
2484
+ handleChannelEnable(message.request_id, message.request.serverName,
2485
+ // Pool spread matches mcp_status — all three client sources.
2486
+ [
2487
+ ...currentAppState.mcp.clients,
2488
+ ...sdkClients,
2489
+ ...dynamicMcpState.clients,
2490
+ ], output);
2491
+ }
2492
+ else if (message.request.subtype === 'mcp_authenticate') {
2493
+ const { serverName } = message.request;
2494
+ const currentAppState = getAppState();
2495
+ const config = getMcpConfigByName(serverName) ??
2496
+ mcpClients.find(c => c.name === serverName)?.config ??
2497
+ currentAppState.mcp.clients.find(c => c.name === serverName)
2498
+ ?.config ??
2499
+ null;
2500
+ if (!config) {
2501
+ sendControlResponseError(message, `Server not found: ${serverName}`);
2502
+ }
2503
+ else if (config.type !== 'sse' && config.type !== 'http') {
2504
+ sendControlResponseError(message, `Server type "${config.type}" does not support OAuth authentication`);
2505
+ }
2506
+ else {
2507
+ try {
2508
+ // Abort any previous in-flight OAuth flow for this server
2509
+ activeOAuthFlows.get(serverName)?.abort();
2510
+ const controller = new AbortController();
2511
+ activeOAuthFlows.set(serverName, controller);
2512
+ // Capture the auth URL from the callback
2513
+ let resolveAuthUrl;
2514
+ const authUrlPromise = new Promise(resolve => {
2515
+ resolveAuthUrl = resolve;
2516
+ });
2517
+ // Start the OAuth flow in the background
2518
+ const oauthPromise = performMCPOAuthFlow(serverName, config, url => resolveAuthUrl(url), controller.signal, {
2519
+ skipBrowserOpen: true,
2520
+ onWaitingForCallback: submit => {
2521
+ oauthCallbackSubmitters.set(serverName, submit);
2522
+ },
2523
+ });
2524
+ // Wait for the auth URL (or the flow to complete without needing redirect)
2525
+ const authUrl = await Promise.race([
2526
+ authUrlPromise,
2527
+ oauthPromise.then(() => null),
2528
+ ]);
2529
+ if (authUrl) {
2530
+ sendControlResponseSuccess(message, {
2531
+ authUrl,
2532
+ requiresUserAction: true,
2533
+ });
2534
+ }
2535
+ else {
2536
+ sendControlResponseSuccess(message, {
2537
+ requiresUserAction: false,
2538
+ });
2539
+ }
2540
+ // Store auth-only promise for mcp_oauth_callback_url handler.
2541
+ // Don't swallow errors — the callback handler needs to detect
2542
+ // auth failures and report them to the caller.
2543
+ oauthAuthPromises.set(serverName, oauthPromise);
2544
+ // Handle background completion — reconnect after auth.
2545
+ // When manual callback is used, skip the reconnect here;
2546
+ // the extension's handleAuthDone → mcp_reconnect handles it
2547
+ // (which also updates dynamicMcpState for tool registration).
2548
+ const fullFlowPromise = oauthPromise
2549
+ .then(async () => {
2550
+ // Don't reconnect if the server was disabled during the OAuth flow
2551
+ if (isMcpServerDisabled(serverName)) {
2552
+ return;
2553
+ }
2554
+ // Skip reconnect if the manual callback path was used —
2555
+ // handleAuthDone will do it via mcp_reconnect (which
2556
+ // updates dynamicMcpState for tool registration).
2557
+ if (oauthManualCallbackUsed.has(serverName)) {
2558
+ return;
2559
+ }
2560
+ // Reconnect the server after successful auth
2561
+ const result = await reconnectMcpServerImpl(serverName, config);
2562
+ const prefix = getMcpPrefix(serverName);
2563
+ setAppState(prev => ({
2564
+ ...prev,
2565
+ mcp: {
2566
+ ...prev.mcp,
2567
+ clients: prev.mcp.clients.map(c => c.name === serverName ? result.client : c),
2568
+ tools: [
2569
+ ...reject(prev.mcp.tools, t => t.name?.startsWith(prefix)),
2570
+ ...result.tools,
2571
+ ],
2572
+ commands: [
2573
+ ...reject(prev.mcp.commands, c => commandBelongsToServer(c, serverName)),
2574
+ ...result.commands,
2575
+ ],
2576
+ resources: result.resources && result.resources.length > 0
2577
+ ? {
2578
+ ...prev.mcp.resources,
2579
+ [serverName]: result.resources,
2580
+ }
2581
+ : omit(prev.mcp.resources, serverName),
2582
+ },
2583
+ }));
2584
+ // Also update dynamicMcpState so run() picks up the new tools
2585
+ // on the next turn (run() reads dynamicMcpState, not appState)
2586
+ dynamicMcpState = {
2587
+ ...dynamicMcpState,
2588
+ clients: [
2589
+ ...dynamicMcpState.clients.filter(c => c.name !== serverName),
2590
+ result.client,
2591
+ ],
2592
+ tools: [
2593
+ ...dynamicMcpState.tools.filter(t => !t.name?.startsWith(prefix)),
2594
+ ...result.tools,
2595
+ ],
2596
+ };
2597
+ })
2598
+ .catch(error => {
2599
+ logForDebugging(`MCP OAuth failed for ${serverName}: ${error}`, { level: 'error' });
2600
+ })
2601
+ .finally(() => {
2602
+ // Clean up only if this is still the active flow
2603
+ if (activeOAuthFlows.get(serverName) === controller) {
2604
+ activeOAuthFlows.delete(serverName);
2605
+ oauthCallbackSubmitters.delete(serverName);
2606
+ oauthManualCallbackUsed.delete(serverName);
2607
+ oauthAuthPromises.delete(serverName);
2608
+ }
2609
+ });
2610
+ void fullFlowPromise;
2611
+ }
2612
+ catch (error) {
2613
+ sendControlResponseError(message, errorMessage(error));
2614
+ }
2615
+ }
2616
+ }
2617
+ else if (message.request.subtype === 'mcp_oauth_callback_url') {
2618
+ const { serverName, callbackUrl } = message.request;
2619
+ const submit = oauthCallbackSubmitters.get(serverName);
2620
+ if (submit) {
2621
+ // Validate the callback URL before submitting. The submit
2622
+ // callback in auth.ts silently ignores URLs missing a code
2623
+ // param, which would leave the auth promise unresolved and
2624
+ // block the control message loop until timeout.
2625
+ let hasCodeOrError = false;
2626
+ try {
2627
+ const parsed = new URL(callbackUrl);
2628
+ hasCodeOrError =
2629
+ parsed.searchParams.has('code') ||
2630
+ parsed.searchParams.has('error');
2631
+ }
2632
+ catch {
2633
+ // Invalid URL
2634
+ }
2635
+ if (!hasCodeOrError) {
2636
+ sendControlResponseError(message, 'Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.');
2637
+ }
2638
+ else {
2639
+ oauthManualCallbackUsed.add(serverName);
2640
+ submit(callbackUrl);
2641
+ // Wait for auth (token exchange) to complete before responding.
2642
+ // Reconnect is handled by the extension via handleAuthDone →
2643
+ // mcp_reconnect (which updates dynamicMcpState for tools).
2644
+ const authPromise = oauthAuthPromises.get(serverName);
2645
+ if (authPromise) {
2646
+ try {
2647
+ await authPromise;
2648
+ sendControlResponseSuccess(message);
2649
+ }
2650
+ catch (error) {
2651
+ sendControlResponseError(message, error instanceof Error
2652
+ ? error.message
2653
+ : 'OAuth authentication failed');
2654
+ }
2655
+ }
2656
+ else {
2657
+ sendControlResponseSuccess(message);
2658
+ }
2659
+ }
2660
+ }
2661
+ else {
2662
+ sendControlResponseError(message, `No active OAuth flow for server: ${serverName}`);
2663
+ }
2664
+ }
2665
+ else if (message.request.subtype === 'claude_authenticate') {
2666
+ // Anthropic OAuth over the control channel. The SDK client owns
2667
+ // the user's browser (we're headless in -p mode); we hand back
2668
+ // both URLs and wait. Automatic URL → localhost listener catches
2669
+ // the redirect if the browser is on this host; manual URL → the
2670
+ // success page shows "code#state" for claude_oauth_callback.
2671
+ const { loginWithClaudeAi } = message.request;
2672
+ // Clean up any prior flow. cleanup() closes the localhost listener
2673
+ // and nulls the manual resolver. The prior `flow` promise is left
2674
+ // pending (AuthCodeListener.close() does not reject) but its object
2675
+ // graph becomes unreachable once the server handle is released and
2676
+ // is GC'd — no fd or port is held.
2677
+ claudeOAuth?.service.cleanup();
2678
+ logEvent('thaddeus_oauth_flow_start', {
2679
+ loginWithClaudeAi: loginWithClaudeAi ?? true,
2680
+ });
2681
+ const service = new OAuthService();
2682
+ let urlResolver;
2683
+ const urlPromise = new Promise(resolve => {
2684
+ urlResolver = resolve;
2685
+ });
2686
+ const flow = service
2687
+ .startOAuthFlow(async (manualUrl, automaticUrl) => {
2688
+ // automaticUrl is always defined when skipBrowserOpen is set;
2689
+ // the signature is optional only for the existing single-arg callers.
2690
+ urlResolver({ manualUrl, automaticUrl: automaticUrl });
2691
+ }, {
2692
+ loginWithClaudeAi: loginWithClaudeAi ?? true,
2693
+ skipBrowserOpen: true,
2694
+ })
2695
+ .then(async (tokens) => {
2696
+ // installOAuthTokens: performLogout (clear stale state) →
2697
+ // store profile → saveOAuthTokensIfNeeded → clearOAuthTokenCache
2698
+ // → clearAuthRelatedCaches. After this resolves, the memoized
2699
+ // getClaudeAIOAuthTokens in this process is invalidated; the
2700
+ // next API call re-reads keychain/file and works. No respawn.
2701
+ await installOAuthTokens(tokens);
2702
+ logEvent('thaddeus_oauth_success', {
2703
+ loginWithClaudeAi: loginWithClaudeAi ?? true,
2704
+ });
2705
+ })
2706
+ .finally(() => {
2707
+ service.cleanup();
2708
+ if (claudeOAuth?.service === service) {
2709
+ claudeOAuth = null;
2710
+ }
2711
+ });
2712
+ claudeOAuth = { service, flow };
2713
+ // Attach the rejection handler before awaiting so a synchronous
2714
+ // startOAuthFlow failure doesn't surface as an unhandled rejection.
2715
+ // The claude_oauth_callback handler re-awaits flow for the manual
2716
+ // path and surfaces the real error to the client.
2717
+ void flow.catch(err => logForDebugging(`claude_authenticate flow ended: ${err}`, {
2718
+ level: 'info',
2719
+ }));
2720
+ try {
2721
+ // Race against flow: if startOAuthFlow rejects before calling
2722
+ // the authURLHandler (e.g. AuthCodeListener.start() fails with
2723
+ // EACCES or fd exhaustion), urlPromise would pend forever and
2724
+ // wedge the stdin loop. flow resolving first is unreachable in
2725
+ // practice (it's suspended on the same urls we're waiting for).
2726
+ const { manualUrl, automaticUrl } = await Promise.race([
2727
+ urlPromise,
2728
+ flow.then(() => {
2729
+ throw new Error('OAuth flow completed without producing auth URLs');
2730
+ }),
2731
+ ]);
2732
+ sendControlResponseSuccess(message, {
2733
+ manualUrl,
2734
+ automaticUrl,
2735
+ });
2736
+ }
2737
+ catch (error) {
2738
+ sendControlResponseError(message, errorMessage(error));
2739
+ }
2740
+ }
2741
+ else if (message.request.subtype === 'claude_oauth_callback' ||
2742
+ message.request.subtype === 'claude_oauth_wait_for_completion') {
2743
+ if (!claudeOAuth) {
2744
+ sendControlResponseError(message, 'No active claude_authenticate flow');
2745
+ }
2746
+ else {
2747
+ // Inject the manual code synchronously — must happen in stdin
2748
+ // message order so a subsequent claude_authenticate doesn't
2749
+ // replace the service before this code lands.
2750
+ if (message.request.subtype === 'claude_oauth_callback') {
2751
+ claudeOAuth.service.handleManualAuthCodeInput({
2752
+ authorizationCode: message.request.authorizationCode,
2753
+ state: message.request.state,
2754
+ });
2755
+ }
2756
+ // Detach the await — the stdin reader is serial and blocking
2757
+ // here deadlocks claude_oauth_wait_for_completion: flow may
2758
+ // only resolve via a future claude_oauth_callback on stdin,
2759
+ // which can't be read while we're parked. Capture the binding;
2760
+ // claudeOAuth is nulled in flow's own .finally.
2761
+ const { flow } = claudeOAuth;
2762
+ void flow.then(() => {
2763
+ const accountInfo = getAccountInformation();
2764
+ sendControlResponseSuccess(message, {
2765
+ account: {
2766
+ email: accountInfo?.email,
2767
+ organization: accountInfo?.organization,
2768
+ subscriptionType: accountInfo?.subscription,
2769
+ tokenSource: accountInfo?.tokenSource,
2770
+ apiKeySource: accountInfo?.apiKeySource,
2771
+ apiProvider: getAPIProvider(),
2772
+ },
2773
+ });
2774
+ }, (error) => sendControlResponseError(message, errorMessage(error)));
2775
+ }
2776
+ }
2777
+ else if (message.request.subtype === 'mcp_clear_auth') {
2778
+ const { serverName } = message.request;
2779
+ const currentAppState = getAppState();
2780
+ const config = getMcpConfigByName(serverName) ??
2781
+ mcpClients.find(c => c.name === serverName)?.config ??
2782
+ currentAppState.mcp.clients.find(c => c.name === serverName)
2783
+ ?.config ??
2784
+ null;
2785
+ if (!config) {
2786
+ sendControlResponseError(message, `Server not found: ${serverName}`);
2787
+ }
2788
+ else if (config.type !== 'sse' && config.type !== 'http') {
2789
+ sendControlResponseError(message, `Cannot clear auth for server type "${config.type}"`);
2790
+ }
2791
+ else {
2792
+ await revokeServerTokens(serverName, config);
2793
+ const result = await reconnectMcpServerImpl(serverName, config);
2794
+ const prefix = getMcpPrefix(serverName);
2795
+ setAppState(prev => ({
2796
+ ...prev,
2797
+ mcp: {
2798
+ ...prev.mcp,
2799
+ clients: prev.mcp.clients.map(c => c.name === serverName ? result.client : c),
2800
+ tools: [
2801
+ ...reject(prev.mcp.tools, t => t.name?.startsWith(prefix)),
2802
+ ...result.tools,
2803
+ ],
2804
+ commands: [
2805
+ ...reject(prev.mcp.commands, c => commandBelongsToServer(c, serverName)),
2806
+ ...result.commands,
2807
+ ],
2808
+ resources: result.resources && result.resources.length > 0
2809
+ ? {
2810
+ ...prev.mcp.resources,
2811
+ [serverName]: result.resources,
2812
+ }
2813
+ : omit(prev.mcp.resources, serverName),
2814
+ },
2815
+ }));
2816
+ sendControlResponseSuccess(message, {});
2817
+ }
2818
+ }
2819
+ else if (message.request.subtype === 'apply_flag_settings') {
2820
+ // Snapshot the current model before applying — we need to detect
2821
+ // model switches so we can inject breadcrumbs and notify listeners.
2822
+ const prevModel = getMainLoopModel();
2823
+ // Merge the provided settings into the in-memory flag settings
2824
+ const existing = getFlagSettingsInline() ?? {};
2825
+ const incoming = message.request.settings;
2826
+ // Shallow-merge top-level keys; getSettingsForSource handles
2827
+ // the deep merge with file-based flag settings via mergeWith.
2828
+ // JSON serialization drops `undefined`, so callers use `null`
2829
+ // to signal "clear this key". Convert nulls to deletions so
2830
+ // SettingsSchema().safeParse() doesn't reject the whole object
2831
+ // (z.string().optional() accepts string | undefined, not null).
2832
+ const merged = { ...existing, ...incoming };
2833
+ for (const key of Object.keys(merged)) {
2834
+ if (merged[key] === null) {
2835
+ delete merged[key];
2836
+ }
2837
+ }
2838
+ setFlagSettingsInline(merged);
2839
+ // Route through notifyChange so fanOut() resets the settings cache
2840
+ // before listeners run. The subscriber at :392 calls
2841
+ // applySettingsChange for us. Pre-#20625 this was a direct
2842
+ // applySettingsChange() call that relied on its own internal reset —
2843
+ // now that the reset is centralized in fanOut, a direct call here
2844
+ // would read stale cached settings and silently drop the update.
2845
+ // Bonus: going through notifyChange also tells the other subscribers
2846
+ // (loadPluginHooks, sandbox-adapter) about the change, which the
2847
+ // previous direct call skipped.
2848
+ settingsChangeDetector.notifyChange('flagSettings');
2849
+ // If the incoming settings include a model change, update the
2850
+ // override so getMainLoopModel() reflects it. The override has
2851
+ // higher priority than the settings cascade in
2852
+ // getUserSpecifiedModelSetting(), so without this update,
2853
+ // getMainLoopModel() returns the stale override and the model
2854
+ // change is silently ignored (matching set_model at :2811).
2855
+ if ('model' in incoming) {
2856
+ if (incoming.model != null) {
2857
+ setMainLoopModelOverride(String(incoming.model));
2858
+ }
2859
+ else {
2860
+ setMainLoopModelOverride(undefined);
2861
+ }
2862
+ }
2863
+ // If the model changed, inject breadcrumbs so the model sees the
2864
+ // mid-conversation switch, and notify metadata listeners (CCR).
2865
+ const newModel = getMainLoopModel();
2866
+ if (newModel !== prevModel) {
2867
+ activeUserSpecifiedModel = newModel;
2868
+ const modelArg = incoming.model ? String(incoming.model) : 'default';
2869
+ notifySessionMetadataChanged({ model: newModel });
2870
+ injectModelSwitchBreadcrumbs(modelArg, newModel);
2871
+ }
2872
+ sendControlResponseSuccess(message);
2873
+ }
2874
+ else if (message.request.subtype === 'get_settings') {
2875
+ const currentAppState = getAppState();
2876
+ const model = getMainLoopModel();
2877
+ // modelSupportsEffort gate matches claude.ts — applied.effort must
2878
+ // mirror what actually goes to the API, not just what's configured.
2879
+ const effort = modelSupportsEffort(model)
2880
+ ? resolveAppliedEffort(model, currentAppState.effortValue)
2881
+ : undefined;
2882
+ sendControlResponseSuccess(message, {
2883
+ ...getSettingsWithSources(),
2884
+ applied: {
2885
+ model,
2886
+ // Numeric effort (ant-only) → null; SDK schema is string-level only.
2887
+ effort: typeof effort === 'string' ? effort : null,
2888
+ },
2889
+ });
2890
+ }
2891
+ else if (message.request.subtype === 'stop_task') {
2892
+ const { task_id: taskId } = message.request;
2893
+ try {
2894
+ await stopTask(taskId, {
2895
+ getAppState,
2896
+ setAppState,
2897
+ });
2898
+ sendControlResponseSuccess(message, {});
2899
+ }
2900
+ catch (error) {
2901
+ sendControlResponseError(message, errorMessage(error));
2902
+ }
2903
+ }
2904
+ else if (message.request.subtype === 'generate_session_title') {
2905
+ // Fire-and-forget so the Haiku call does not block the stdin loop
2906
+ // (which would delay processing of subsequent user messages /
2907
+ // interrupts for the duration of the API roundtrip).
2908
+ const { description, persist } = message.request;
2909
+ // Reuse the live controller only if it has not already been aborted
2910
+ // (e.g. by interrupt()); an aborted signal would cause queryHaiku to
2911
+ // immediately throw APIUserAbortError → {title: null}.
2912
+ const titleSignal = (abortController && !abortController.signal.aborted
2913
+ ? abortController
2914
+ : createAbortController()).signal;
2915
+ void (async () => {
2916
+ try {
2917
+ const title = await generateSessionTitle(description, titleSignal);
2918
+ if (title && persist) {
2919
+ try {
2920
+ saveAiGeneratedTitle(getSessionId(), title);
2921
+ }
2922
+ catch (e) {
2923
+ logError(e);
2924
+ }
2925
+ }
2926
+ sendControlResponseSuccess(message, { title });
2927
+ }
2928
+ catch (e) {
2929
+ // Unreachable in practice — generateSessionTitle wraps its
2930
+ // own body and returns null, saveAiGeneratedTitle is wrapped
2931
+ // above. Propagate (not swallow) so unexpected failures are
2932
+ // visible to the SDK caller (hostComms.ts catches and logs).
2933
+ sendControlResponseError(message, errorMessage(e));
2934
+ }
2935
+ })();
2936
+ }
2937
+ else if (message.request.subtype === 'side_question') {
2938
+ // Same fire-and-forget pattern as generate_session_title above —
2939
+ // the forked agent's API roundtrip must not block the stdin loop.
2940
+ //
2941
+ // The snapshot captured by stopHooks (for querySource === 'sdk')
2942
+ // holds the exact systemPrompt/userContext/systemContext/messages
2943
+ // sent on the last main-thread turn. Reusing them gives a byte-
2944
+ // identical prefix → prompt cache hit.
2945
+ //
2946
+ // Fallback (resume before first turn completes — no snapshot yet):
2947
+ // rebuild from scratch. buildSideQuestionFallbackParams mirrors
2948
+ // QueryEngine.ts:ask()'s system prompt assembly (including
2949
+ // --system-prompt / --append-system-prompt) so the rebuilt prefix
2950
+ // matches in the common case. May still miss the cache for
2951
+ // coordinator mode or memory-mechanics extras — acceptable, the
2952
+ // alternative is the side question failing entirely.
2953
+ const { question } = message.request;
2954
+ void (async () => {
2955
+ try {
2956
+ const saved = getLastCacheSafeParams();
2957
+ const cacheSafeParams = saved
2958
+ ? {
2959
+ ...saved,
2960
+ // If the last turn was interrupted, the snapshot holds an
2961
+ // already-aborted controller; createChildAbortController in
2962
+ // createSubagentContext would propagate it and the fork
2963
+ // would die before sending a request. The controller is
2964
+ // not part of the cache key — swapping in a fresh one is
2965
+ // safe. Same guard as generate_session_title above.
2966
+ toolUseContext: {
2967
+ ...saved.toolUseContext,
2968
+ abortController: createAbortController(),
2969
+ },
2970
+ }
2971
+ : await buildSideQuestionFallbackParams({
2972
+ tools: buildAllTools(getAppState()),
2973
+ commands: currentCommands,
2974
+ mcpClients: [
2975
+ ...getAppState().mcp.clients,
2976
+ ...sdkClients,
2977
+ ...dynamicMcpState.clients,
2978
+ ],
2979
+ messages: mutableMessages,
2980
+ readFileState,
2981
+ getAppState,
2982
+ setAppState,
2983
+ customSystemPrompt: options.systemPrompt,
2984
+ appendSystemPrompt: options.appendSystemPrompt,
2985
+ thinkingConfig: options.thinkingConfig,
2986
+ agents: currentAgents,
2987
+ });
2988
+ const result = await runSideQuestion({
2989
+ question,
2990
+ cacheSafeParams,
2991
+ });
2992
+ sendControlResponseSuccess(message, { response: result.response });
2993
+ }
2994
+ catch (e) {
2995
+ sendControlResponseError(message, errorMessage(e));
2996
+ }
2997
+ })();
2998
+ }
2999
+ else if ((feature('PROACTIVE') || feature('KAIROS')) &&
3000
+ message.request.subtype === 'set_proactive') {
3001
+ const req = message.request;
3002
+ if (req.enabled) {
3003
+ if (!proactiveModule.isProactiveActive()) {
3004
+ proactiveModule.activateProactive('command');
3005
+ scheduleProactiveTick();
3006
+ }
3007
+ }
3008
+ else {
3009
+ proactiveModule.deactivateProactive();
3010
+ }
3011
+ sendControlResponseSuccess(message);
3012
+ }
3013
+ else if (message.request.subtype === 'remote_control') {
3014
+ if (message.request.enabled) {
3015
+ if (bridgeHandle) {
3016
+ // Already connected
3017
+ sendControlResponseSuccess(message, {
3018
+ session_url: getRemoteSessionUrl(bridgeHandle.bridgeSessionId, bridgeHandle.sessionIngressUrl),
3019
+ connect_url: buildBridgeConnectUrl(bridgeHandle.environmentId, bridgeHandle.sessionIngressUrl),
3020
+ environment_id: bridgeHandle.environmentId,
3021
+ });
3022
+ }
3023
+ else {
3024
+ // initReplBridge surfaces gate-failure reasons via
3025
+ // onStateChange('failed', detail) before returning null.
3026
+ // Capture so the control-response error is actionable
3027
+ // ("/login", "disabled by your organization's policy", etc.)
3028
+ // instead of a generic "initialization failed".
3029
+ let bridgeFailureDetail;
3030
+ try {
3031
+ const { initReplBridge } = await import('src/bridge/initReplBridge.js');
3032
+ const handle = await initReplBridge({
3033
+ onInboundMessage(msg) {
3034
+ const fields = extractInboundMessageFields(msg);
3035
+ if (!fields)
3036
+ return;
3037
+ const { content, uuid } = fields;
3038
+ enqueue({
3039
+ value: content,
3040
+ mode: 'prompt',
3041
+ uuid,
3042
+ skipSlashCommands: true,
3043
+ });
3044
+ void run();
3045
+ },
3046
+ onPermissionResponse(response) {
3047
+ // Forward bridge permission responses into the
3048
+ // stdin processing loop so they resolve pending
3049
+ // permission requests from the SDK consumer.
3050
+ structuredIO.injectControlResponse(response);
3051
+ },
3052
+ onInterrupt() {
3053
+ abortController?.abort();
3054
+ },
3055
+ onSetModel(model) {
3056
+ const resolved = model === 'default' ? getDefaultMainLoopModel() : model;
3057
+ activeUserSpecifiedModel = resolved;
3058
+ setMainLoopModelOverride(resolved);
3059
+ },
3060
+ onSetMaxThinkingTokens(maxTokens) {
3061
+ if (maxTokens === null) {
3062
+ options.thinkingConfig = undefined;
3063
+ }
3064
+ else if (maxTokens === 0) {
3065
+ options.thinkingConfig = { type: 'disabled' };
3066
+ }
3067
+ else {
3068
+ options.thinkingConfig = {
3069
+ type: 'enabled',
3070
+ budgetTokens: maxTokens,
3071
+ };
3072
+ }
3073
+ },
3074
+ onStateChange(state, detail) {
3075
+ if (state === 'failed') {
3076
+ bridgeFailureDetail = detail;
3077
+ }
3078
+ logForDebugging(`[bridge:sdk] State change: ${state}${detail ? ` — ${detail}` : ''}`);
3079
+ output.enqueue({
3080
+ type: 'system',
3081
+ subtype: 'bridge_state',
3082
+ state,
3083
+ detail,
3084
+ uuid: randomUUID(),
3085
+ session_id: getSessionId(),
3086
+ });
3087
+ },
3088
+ initialMessages: mutableMessages.length > 0 ? mutableMessages : undefined,
3089
+ });
3090
+ if (!handle) {
3091
+ sendControlResponseError(message, bridgeFailureDetail ??
3092
+ 'Remote Control initialization failed');
3093
+ }
3094
+ else {
3095
+ bridgeHandle = handle;
3096
+ bridgeLastForwardedIndex = mutableMessages.length;
3097
+ // Forward permission requests to the bridge
3098
+ structuredIO.setOnControlRequestSent(request => {
3099
+ handle.sendControlRequest(request);
3100
+ });
3101
+ // Cancel stale bridge permission prompts when the SDK
3102
+ // consumer resolves a can_use_tool request first.
3103
+ structuredIO.setOnControlRequestResolved(requestId => {
3104
+ handle.sendControlCancelRequest(requestId);
3105
+ });
3106
+ sendControlResponseSuccess(message, {
3107
+ session_url: getRemoteSessionUrl(handle.bridgeSessionId, handle.sessionIngressUrl),
3108
+ connect_url: buildBridgeConnectUrl(handle.environmentId, handle.sessionIngressUrl),
3109
+ environment_id: handle.environmentId,
3110
+ });
3111
+ }
3112
+ }
3113
+ catch (err) {
3114
+ sendControlResponseError(message, errorMessage(err));
3115
+ }
3116
+ }
3117
+ }
3118
+ else {
3119
+ // Disable
3120
+ if (bridgeHandle) {
3121
+ structuredIO.setOnControlRequestSent(undefined);
3122
+ structuredIO.setOnControlRequestResolved(undefined);
3123
+ await bridgeHandle.teardown();
3124
+ bridgeHandle = null;
3125
+ }
3126
+ sendControlResponseSuccess(message);
3127
+ }
3128
+ }
3129
+ else {
3130
+ // Unknown control request subtype — send an error response so
3131
+ // the caller doesn't hang waiting for a reply that never comes.
3132
+ sendControlResponseError(message, `Unsupported control request subtype: ${message.request.subtype}`);
3133
+ }
3134
+ continue;
3135
+ }
3136
+ else if (message.type === 'control_response') {
3137
+ // Replay control_response messages when replay mode is enabled
3138
+ if (options.replayUserMessages) {
3139
+ output.enqueue(message);
3140
+ }
3141
+ continue;
3142
+ }
3143
+ else if (message.type === 'keep_alive') {
3144
+ // Silently ignore keep-alive messages
3145
+ continue;
3146
+ }
3147
+ else if (message.type === 'update_environment_variables') {
3148
+ // Handled in structuredIO.ts, but TypeScript needs the type guard
3149
+ continue;
3150
+ }
3151
+ else if (message.type === 'assistant' || message.type === 'system') {
3152
+ // History replay from bridge: inject into mutableMessages as
3153
+ // conversation context so the model sees prior turns.
3154
+ const internalMsgs = toInternalMessages([message]);
3155
+ mutableMessages.push(...internalMsgs);
3156
+ // Echo assistant messages back so CCR displays them
3157
+ if (message.type === 'assistant' && options.replayUserMessages) {
3158
+ output.enqueue(message);
3159
+ }
3160
+ continue;
3161
+ }
3162
+ // After handling control, keep-alive, env-var, assistant, and system
3163
+ // messages above, only user messages should remain.
3164
+ if (message.type !== 'user') {
3165
+ continue;
3166
+ }
3167
+ // First prompt message implicitly initializes if not already done.
3168
+ initialized = true;
3169
+ // Check for duplicate user message - skip if already processed
3170
+ if (message.uuid) {
3171
+ const sessionId = getSessionId();
3172
+ const existsInSession = await doesMessageExistInSession(sessionId, message.uuid);
3173
+ // Check both historical duplicates (from file) and runtime duplicates (this session)
3174
+ if (existsInSession || receivedMessageUuids.has(message.uuid)) {
3175
+ logForDebugging(`Skipping duplicate user message: ${message.uuid}`);
3176
+ // Send acknowledgment for duplicate message if replay mode is enabled
3177
+ if (options.replayUserMessages) {
3178
+ logForDebugging(`Sending acknowledgment for duplicate user message: ${message.uuid}`);
3179
+ output.enqueue({
3180
+ type: 'user',
3181
+ message: message.message,
3182
+ session_id: sessionId,
3183
+ parent_tool_use_id: null,
3184
+ uuid: message.uuid,
3185
+ timestamp: message.timestamp,
3186
+ isReplay: true,
3187
+ });
3188
+ }
3189
+ // Historical dup = transcript already has this turn's output, so it
3190
+ // ran but its lifecycle was never closed (interrupted before ack).
3191
+ // Runtime dups don't need this — the original enqueue path closes them.
3192
+ if (existsInSession) {
3193
+ notifyCommandLifecycle(message.uuid, 'completed');
3194
+ }
3195
+ // Don't enqueue duplicate messages for execution
3196
+ continue;
3197
+ }
3198
+ // Track this UUID to prevent runtime duplicates
3199
+ trackReceivedMessageUuid(message.uuid);
3200
+ }
3201
+ enqueue({
3202
+ mode: 'prompt',
3203
+ // file_attachments rides the protobuf catchall from the web composer.
3204
+ // Same-ref no-op when absent (no 'file_attachments' key).
3205
+ value: await resolveAndPrepend(message, message.message.content),
3206
+ uuid: message.uuid,
3207
+ priority: message.priority,
3208
+ });
3209
+ // Increment prompt count for attribution tracking and save snapshot
3210
+ // The snapshot persists promptCount so it survives compaction
3211
+ if (feature('COMMIT_ATTRIBUTION')) {
3212
+ setAppState(prev => ({
3213
+ ...prev,
3214
+ attribution: incrementPromptCount(prev.attribution, snapshot => {
3215
+ void recordAttributionSnapshot(snapshot).catch(error => {
3216
+ logForDebugging(`Attribution: Failed to save snapshot: ${error}`);
3217
+ });
3218
+ }),
3219
+ }));
3220
+ }
3221
+ void run();
3222
+ }
3223
+ inputClosed = true;
3224
+ cronScheduler?.stop();
3225
+ // Deactivate proactive mode so no timers/listeners keep the process alive
3226
+ if ((feature('PROACTIVE') || feature('KAIROS')) && proactiveModule?.isProactiveActive()) {
3227
+ proactiveModule.deactivateProactive();
3228
+ }
3229
+ if (!running) {
3230
+ // If a push-suggestion is in-flight, wait for it to emit before closing
3231
+ // the output stream (5 s safety timeout to prevent hanging).
3232
+ if (suggestionState.inflightPromise) {
3233
+ await Promise.race([suggestionState.inflightPromise, sleep(5000)]);
3234
+ }
3235
+ suggestionState.abortController?.abort();
3236
+ suggestionState.abortController = null;
3237
+ await finalizePendingAsyncHooks();
3238
+ unsubscribeSkillChanges();
3239
+ unsubscribeAuthStatus?.();
3240
+ statusListeners.delete(rateLimitListener);
3241
+ output.done();
3242
+ }
3243
+ })();
3244
+ return output;
3245
+ }
3246
+ /**
3247
+ * Creates a CanUseToolFn that incorporates a custom permission prompt tool.
3248
+ * This function converts the permissionPromptTool into a CanUseToolFn that can be used in ask.tsx
3249
+ */
3250
+ export function createCanUseToolWithPermissionPrompt(permissionPromptTool) {
3251
+ const canUseTool = async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => {
3252
+ const mainPermissionResult = forceDecision ??
3253
+ (await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId));
3254
+ // If the tool is allowed or denied, return the result
3255
+ if (mainPermissionResult.behavior === 'allow' ||
3256
+ mainPermissionResult.behavior === 'deny') {
3257
+ return mainPermissionResult;
3258
+ }
3259
+ // Race the permission prompt tool against the abort signal.
3260
+ //
3261
+ // Why we need this: The permission prompt tool may block indefinitely waiting
3262
+ // for user input (e.g., via stdin or a UI dialog). If the user triggers an
3263
+ // interrupt (Ctrl+C), we need to detect it even while the tool is blocked.
3264
+ // Without this race, the abort check would only run AFTER the tool completes,
3265
+ // which may never happen if the tool is waiting for input that will never come.
3266
+ //
3267
+ // The second check (combinedSignal.aborted) handles a race condition where
3268
+ // abort fires after Promise.race resolves but before we reach this check.
3269
+ const { signal: combinedSignal, cleanup: cleanupAbortListener } = createCombinedAbortSignal(toolUseContext.abortController.signal);
3270
+ // Check if already aborted before starting the race
3271
+ if (combinedSignal.aborted) {
3272
+ cleanupAbortListener();
3273
+ return {
3274
+ behavior: 'deny',
3275
+ message: 'Permission prompt was aborted.',
3276
+ decisionReason: {
3277
+ type: 'permissionPromptTool',
3278
+ permissionPromptToolName: tool.name,
3279
+ toolResult: undefined,
3280
+ },
3281
+ };
3282
+ }
3283
+ const abortPromise = new Promise(resolve => {
3284
+ combinedSignal.addEventListener('abort', () => resolve('aborted'), {
3285
+ once: true,
3286
+ });
3287
+ });
3288
+ const toolCallPromise = permissionPromptTool.call({
3289
+ tool_name: tool.name,
3290
+ input,
3291
+ tool_use_id: toolUseId,
3292
+ }, toolUseContext, canUseTool, assistantMessage);
3293
+ const raceResult = await Promise.race([toolCallPromise, abortPromise]);
3294
+ cleanupAbortListener();
3295
+ if (raceResult === 'aborted' || combinedSignal.aborted) {
3296
+ return {
3297
+ behavior: 'deny',
3298
+ message: 'Permission prompt was aborted.',
3299
+ decisionReason: {
3300
+ type: 'permissionPromptTool',
3301
+ permissionPromptToolName: tool.name,
3302
+ toolResult: undefined,
3303
+ },
3304
+ };
3305
+ }
3306
+ // TypeScript narrowing: after the abort check, raceResult must be ToolResult
3307
+ const result = raceResult;
3308
+ const permissionToolResultBlockParam = permissionPromptTool.mapToolResultToToolResultBlockParam(result.data, '1');
3309
+ if (!permissionToolResultBlockParam.content ||
3310
+ !Array.isArray(permissionToolResultBlockParam.content) ||
3311
+ !permissionToolResultBlockParam.content[0] ||
3312
+ permissionToolResultBlockParam.content[0].type !== 'text' ||
3313
+ typeof permissionToolResultBlockParam.content[0].text !== 'string') {
3314
+ throw new Error('Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.');
3315
+ }
3316
+ return permissionPromptToolResultToPermissionDecision(permissionToolOutputSchema().parse(safeParseJSON(permissionToolResultBlockParam.content[0].text)), permissionPromptTool, input, toolUseContext);
3317
+ };
3318
+ return canUseTool;
3319
+ }
3320
+ // Exported for testing — regression: this used to crash at construction when
3321
+ // getMcpTools() was empty (before per-server connects populated appState).
3322
+ export function getCanUseToolFn(permissionPromptToolName, structuredIO, getMcpTools, onPermissionPrompt) {
3323
+ if (permissionPromptToolName === 'stdio') {
3324
+ return structuredIO.createCanUseTool(onPermissionPrompt);
3325
+ }
3326
+ if (!permissionPromptToolName) {
3327
+ return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => forceDecision ??
3328
+ (await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId));
3329
+ }
3330
+ // Lazy lookup: MCP connects are per-server incremental in print mode, so
3331
+ // the tool may not be in appState yet at init time. Resolve on first call
3332
+ // (first permission prompt), by which point connects have had time to finish.
3333
+ let resolved = null;
3334
+ return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => {
3335
+ if (!resolved) {
3336
+ const mcpTools = getMcpTools();
3337
+ const permissionPromptTool = mcpTools.find(t => toolMatchesName(t, permissionPromptToolName));
3338
+ if (!permissionPromptTool) {
3339
+ const error = `Error: MCP tool ${permissionPromptToolName} (passed via --permission-prompt-tool) not found. Available MCP tools: ${mcpTools.map(t => t.name).join(', ') || 'none'}`;
3340
+ process.stderr.write(`${error}\n`);
3341
+ gracefulShutdownSync(1);
3342
+ throw new Error(error);
3343
+ }
3344
+ if (!permissionPromptTool.inputJSONSchema) {
3345
+ const error = `Error: tool ${permissionPromptToolName} (passed via --permission-prompt-tool) must be an MCP tool`;
3346
+ process.stderr.write(`${error}\n`);
3347
+ gracefulShutdownSync(1);
3348
+ throw new Error(error);
3349
+ }
3350
+ resolved = createCanUseToolWithPermissionPrompt(permissionPromptTool);
3351
+ }
3352
+ return resolved(tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision);
3353
+ };
3354
+ }
3355
+ async function handleInitializeRequest(request, requestId, initialized, output, commands, modelInfos, structuredIO, enableAuthStatus, options, agents, getAppState) {
3356
+ if (initialized) {
3357
+ output.enqueue({
3358
+ type: 'control_response',
3359
+ response: {
3360
+ subtype: 'error',
3361
+ error: 'Already initialized',
3362
+ request_id: requestId,
3363
+ pending_permission_requests: structuredIO.getPendingPermissionRequests(),
3364
+ },
3365
+ });
3366
+ return;
3367
+ }
3368
+ // Apply systemPrompt/appendSystemPrompt from stdin to avoid ARG_MAX limits
3369
+ if (request.systemPrompt !== undefined) {
3370
+ options.systemPrompt = request.systemPrompt;
3371
+ }
3372
+ if (request.appendSystemPrompt !== undefined) {
3373
+ options.appendSystemPrompt = request.appendSystemPrompt;
3374
+ }
3375
+ if (request.promptSuggestions !== undefined) {
3376
+ options.promptSuggestions = request.promptSuggestions;
3377
+ }
3378
+ // Merge agents from stdin to avoid ARG_MAX limits
3379
+ if (request.agents) {
3380
+ const stdinAgents = parseAgentsFromJson(request.agents, 'flagSettings');
3381
+ agents.push(...stdinAgents);
3382
+ }
3383
+ // Re-evaluate main thread agent after SDK agents are merged
3384
+ // This allows --agent to reference agents defined via SDK
3385
+ if (options.agent) {
3386
+ // If main.tsx already found this agent (filesystem-defined), it already
3387
+ // applied systemPrompt/model/initialPrompt. Skip to avoid double-apply.
3388
+ const alreadyResolved = getMainThreadAgentType() === options.agent;
3389
+ const mainThreadAgent = agents.find(a => a.agentType === options.agent);
3390
+ if (mainThreadAgent && !alreadyResolved) {
3391
+ // Update the main thread agent type in bootstrap state
3392
+ setMainThreadAgentType(mainThreadAgent.agentType);
3393
+ // Apply the agent's system prompt if user hasn't specified a custom one
3394
+ // SDK agents are always custom agents (not built-in), so getSystemPrompt() takes no args
3395
+ if (!options.systemPrompt && !isBuiltInAgent(mainThreadAgent)) {
3396
+ const agentSystemPrompt = mainThreadAgent.getSystemPrompt();
3397
+ if (agentSystemPrompt) {
3398
+ options.systemPrompt = agentSystemPrompt;
3399
+ }
3400
+ }
3401
+ // Apply the agent's model if user didn't specify one and agent has a model
3402
+ if (!options.userSpecifiedModel &&
3403
+ mainThreadAgent.model &&
3404
+ mainThreadAgent.model !== 'inherit') {
3405
+ const agentModel = parseUserSpecifiedModel(mainThreadAgent.model);
3406
+ setMainLoopModelOverride(agentModel);
3407
+ }
3408
+ // SDK-defined agents arrive via init, so main.tsx's lookup missed them.
3409
+ if (mainThreadAgent.initialPrompt) {
3410
+ structuredIO.prependUserMessage(mainThreadAgent.initialPrompt);
3411
+ }
3412
+ }
3413
+ else if (mainThreadAgent?.initialPrompt) {
3414
+ // Filesystem-defined agent (alreadyResolved by main.tsx). main.tsx
3415
+ // handles initialPrompt for the string inputPrompt case, but when
3416
+ // inputPrompt is an AsyncIterable (SDK stream-json), it can't
3417
+ // concatenate — fall back to prependUserMessage here.
3418
+ structuredIO.prependUserMessage(mainThreadAgent.initialPrompt);
3419
+ }
3420
+ }
3421
+ const settings = getSettings_DEPRECATED();
3422
+ const outputStyle = settings?.outputStyle || DEFAULT_OUTPUT_STYLE_NAME;
3423
+ const availableOutputStyles = await getAllOutputStyles(getCwd());
3424
+ // Get account information
3425
+ const accountInfo = getAccountInformation();
3426
+ if (request.hooks) {
3427
+ const hooks = {};
3428
+ for (const [event, matchers] of Object.entries(request.hooks)) {
3429
+ hooks[event] = matchers.map(matcher => {
3430
+ const callbacks = matcher.hookCallbackIds.map(callbackId => {
3431
+ return structuredIO.createHookCallback(callbackId, matcher.timeout);
3432
+ });
3433
+ return {
3434
+ matcher: matcher.matcher,
3435
+ hooks: callbacks,
3436
+ };
3437
+ });
3438
+ }
3439
+ registerHookCallbacks(hooks);
3440
+ }
3441
+ if (request.jsonSchema) {
3442
+ setInitJsonSchema(request.jsonSchema);
3443
+ }
3444
+ const initResponse = {
3445
+ commands: commands
3446
+ .filter(cmd => cmd.userInvocable !== false)
3447
+ .map(cmd => ({
3448
+ name: getCommandName(cmd),
3449
+ description: formatDescriptionWithSource(cmd),
3450
+ argumentHint: cmd.argumentHint || '',
3451
+ })),
3452
+ agents: agents.map(agent => ({
3453
+ name: agent.agentType,
3454
+ description: agent.whenToUse,
3455
+ // 'inherit' is an internal sentinel; normalize to undefined for the public API
3456
+ model: agent.model === 'inherit' ? undefined : agent.model,
3457
+ })),
3458
+ output_style: outputStyle,
3459
+ available_output_styles: Object.keys(availableOutputStyles),
3460
+ models: modelInfos,
3461
+ account: {
3462
+ email: accountInfo?.email,
3463
+ organization: accountInfo?.organization,
3464
+ subscriptionType: accountInfo?.subscription,
3465
+ tokenSource: accountInfo?.tokenSource,
3466
+ apiKeySource: accountInfo?.apiKeySource,
3467
+ // getAccountInformation() returns undefined under 3P providers, so the
3468
+ // other fields are all absent. apiProvider disambiguates "not logged
3469
+ // in" (firstParty + tokenSource:none) from "3P, login not applicable".
3470
+ apiProvider: getAPIProvider(),
3471
+ },
3472
+ pid: process.pid,
3473
+ };
3474
+ if (isFastModeEnabled() && isFastModeAvailable()) {
3475
+ const appState = getAppState();
3476
+ initResponse.fast_mode_state = getFastModeState(options.userSpecifiedModel ?? null, appState.fastMode);
3477
+ }
3478
+ output.enqueue({
3479
+ type: 'control_response',
3480
+ response: {
3481
+ subtype: 'success',
3482
+ request_id: requestId,
3483
+ response: initResponse,
3484
+ },
3485
+ });
3486
+ // After the initialize message, check the auth status-
3487
+ // This will get notified of changes, but we also want to send the
3488
+ // initial state.
3489
+ if (enableAuthStatus) {
3490
+ const authStatusManager = AwsAuthStatusManager.getInstance();
3491
+ const status = authStatusManager.getStatus();
3492
+ if (status) {
3493
+ output.enqueue({
3494
+ type: 'auth_status',
3495
+ isAuthenticating: status.isAuthenticating,
3496
+ output: status.output,
3497
+ error: status.error,
3498
+ uuid: randomUUID(),
3499
+ session_id: getSessionId(),
3500
+ });
3501
+ }
3502
+ }
3503
+ }
3504
+ async function handleRewindFiles(userMessageId, appState, setAppState, dryRun) {
3505
+ if (!fileHistoryEnabled()) {
3506
+ return { canRewind: false, error: 'File rewinding is not enabled.' };
3507
+ }
3508
+ if (!fileHistoryCanRestore(appState.fileHistory, userMessageId)) {
3509
+ return {
3510
+ canRewind: false,
3511
+ error: 'No file checkpoint found for this message.',
3512
+ };
3513
+ }
3514
+ if (dryRun) {
3515
+ const diffStats = await fileHistoryGetDiffStats(appState.fileHistory, userMessageId);
3516
+ return {
3517
+ canRewind: true,
3518
+ filesChanged: diffStats?.filesChanged,
3519
+ insertions: diffStats?.insertions,
3520
+ deletions: diffStats?.deletions,
3521
+ };
3522
+ }
3523
+ try {
3524
+ await fileHistoryRewind(updater => setAppState(prev => ({
3525
+ ...prev,
3526
+ fileHistory: updater(prev.fileHistory),
3527
+ })), userMessageId);
3528
+ }
3529
+ catch (error) {
3530
+ return {
3531
+ canRewind: false,
3532
+ error: `Failed to rewind: ${errorMessage(error)}`,
3533
+ };
3534
+ }
3535
+ return { canRewind: true };
3536
+ }
3537
+ function handleSetPermissionMode(request, requestId, toolPermissionContext, output) {
3538
+ // Check if trying to switch to bypassPermissions mode
3539
+ if (request.mode === 'bypassPermissions') {
3540
+ if (isBypassPermissionsModeDisabled()) {
3541
+ output.enqueue({
3542
+ type: 'control_response',
3543
+ response: {
3544
+ subtype: 'error',
3545
+ request_id: requestId,
3546
+ error: 'Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration',
3547
+ },
3548
+ });
3549
+ return toolPermissionContext;
3550
+ }
3551
+ if (!toolPermissionContext.isBypassPermissionsModeAvailable) {
3552
+ output.enqueue({
3553
+ type: 'control_response',
3554
+ response: {
3555
+ subtype: 'error',
3556
+ request_id: requestId,
3557
+ error: 'Cannot set permission mode to bypassPermissions because the session was not launched with --dangerously-skip-permissions',
3558
+ },
3559
+ });
3560
+ return toolPermissionContext;
3561
+ }
3562
+ }
3563
+ // Check if trying to switch to auto mode without the classifier gate
3564
+ if (feature('TRANSCRIPT_CLASSIFIER') &&
3565
+ request.mode === 'auto' &&
3566
+ !isAutoModeGateEnabled()) {
3567
+ const reason = getAutoModeUnavailableReason();
3568
+ output.enqueue({
3569
+ type: 'control_response',
3570
+ response: {
3571
+ subtype: 'error',
3572
+ request_id: requestId,
3573
+ error: reason
3574
+ ? `Cannot set permission mode to auto: ${getAutoModeUnavailableNotification(reason)}`
3575
+ : 'Cannot set permission mode to auto',
3576
+ },
3577
+ });
3578
+ return toolPermissionContext;
3579
+ }
3580
+ // Allow the mode switch
3581
+ output.enqueue({
3582
+ type: 'control_response',
3583
+ response: {
3584
+ subtype: 'success',
3585
+ request_id: requestId,
3586
+ response: {
3587
+ mode: request.mode,
3588
+ },
3589
+ },
3590
+ });
3591
+ return {
3592
+ ...transitionPermissionMode(toolPermissionContext.mode, request.mode, toolPermissionContext),
3593
+ mode: request.mode,
3594
+ };
3595
+ }
3596
+ /**
3597
+ * IDE-triggered channel enable. Derives the ChannelEntry from the connection's
3598
+ * pluginSource (IDE can't spoof kind/marketplace — we only take the server
3599
+ * name), appends it to session allowedChannels, and runs the full gate. On
3600
+ * gate failure, rolls back the append. On success, registers a notification
3601
+ * handler that enqueues channel messages at priority:'next' — drainCommandQueue
3602
+ * picks them up between turns.
3603
+ *
3604
+ * Intentionally does NOT register the claude/channel/permission handler that
3605
+ * useManageMCPConnections sets up for interactive mode. That handler resolves
3606
+ * a pending dialog inside handleInteractivePermission — but print.ts never
3607
+ * calls handleInteractivePermission. When SDK permission lands on 'ask', it
3608
+ * goes to the consumer's canUseTool callback over stdio; there is no CLI-side
3609
+ * dialog for a remote "yes tbxkq" to resolve. If an IDE wants channel-relayed
3610
+ * tool approval, that's IDE-side plumbing against its own pending-map. (Also
3611
+ * gated separately by thaddeus_harbor_permissions — not yet shipping on
3612
+ * interactive either.)
3613
+ */
3614
+ function handleChannelEnable(requestId, serverName, connectionPool, output) {
3615
+ const respondError = (error) => output.enqueue({
3616
+ type: 'control_response',
3617
+ response: { subtype: 'error', request_id: requestId, error },
3618
+ });
3619
+ if (!(feature('KAIROS') || feature('KAIROS_CHANNELS'))) {
3620
+ return respondError('channels feature not available in this build');
3621
+ }
3622
+ // Only a 'connected' client has .capabilities and .client to register the
3623
+ // handler on. The pool spread at the call site matches mcp_status.
3624
+ const connection = connectionPool.find(c => c.name === serverName && c.type === 'connected');
3625
+ if (!connection || connection.type !== 'connected') {
3626
+ return respondError(`server ${serverName} is not connected`);
3627
+ }
3628
+ const pluginSource = connection.config.pluginSource;
3629
+ const parsed = pluginSource ? parsePluginIdentifier(pluginSource) : undefined;
3630
+ if (!parsed?.marketplace) {
3631
+ // No pluginSource or @-less source — can never pass the {plugin,
3632
+ // marketplace}-keyed allowlist. Short-circuit with the same reason the
3633
+ // gate would produce.
3634
+ return respondError(`server ${serverName} is not plugin-sourced; channel_enable requires a marketplace plugin`);
3635
+ }
3636
+ const entry = {
3637
+ kind: 'plugin',
3638
+ name: parsed.name,
3639
+ marketplace: parsed.marketplace,
3640
+ };
3641
+ // Idempotency: don't double-append on repeat enable.
3642
+ const prior = getAllowedChannels();
3643
+ const already = prior.some(e => e.kind === 'plugin' &&
3644
+ e.name === entry.name &&
3645
+ e.marketplace === entry.marketplace);
3646
+ if (!already)
3647
+ setAllowedChannels([...prior, entry]);
3648
+ const gate = gateChannelServer(serverName, connection.capabilities, pluginSource);
3649
+ if (gate.action === 'skip') {
3650
+ // Rollback — only remove the entry we appended.
3651
+ if (!already)
3652
+ setAllowedChannels(prior);
3653
+ return respondError(gate.reason);
3654
+ }
3655
+ const pluginId = `${entry.name}@${entry.marketplace}`;
3656
+ logMCPDebug(serverName, 'Channel notifications registered');
3657
+ logEvent('thaddeus_mcp_channel_enable', { plugin: pluginId });
3658
+ // Identical enqueue shape to the interactive register block in
3659
+ // useManageMCPConnections. drainCommandQueue processes it between turns —
3660
+ // channel messages queue at priority 'next' and are seen by the model on
3661
+ // the turn after they arrive.
3662
+ connection.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => {
3663
+ const { content, meta } = notification.params;
3664
+ logMCPDebug(serverName, `notifications/claude/channel: ${content.slice(0, 80)}`);
3665
+ logEvent('thaddeus_mcp_channel_message', {
3666
+ content_length: content.length,
3667
+ meta_key_count: Object.keys(meta ?? {}).length,
3668
+ entry_kind: 'plugin',
3669
+ is_dev: false,
3670
+ plugin: pluginId,
3671
+ });
3672
+ enqueue({
3673
+ mode: 'prompt',
3674
+ value: wrapChannelMessage(serverName, content, meta),
3675
+ priority: 'next',
3676
+ isMeta: true,
3677
+ origin: { kind: 'channel', server: serverName },
3678
+ skipSlashCommands: true,
3679
+ });
3680
+ });
3681
+ output.enqueue({
3682
+ type: 'control_response',
3683
+ response: {
3684
+ subtype: 'success',
3685
+ request_id: requestId,
3686
+ response: undefined,
3687
+ },
3688
+ });
3689
+ }
3690
+ /**
3691
+ * Re-register the channel notification handler after mcp_reconnect /
3692
+ * mcp_toggle creates a new client. handleChannelEnable bound the handler to
3693
+ * the OLD client object; allowedChannels survives the reconnect but the
3694
+ * handler binding does not. Without this, channel messages silently drop
3695
+ * after a reconnect while the IDE still believes the channel is live.
3696
+ *
3697
+ * Mirrors the interactive CLI's onConnectionAttempt in
3698
+ * useManageMCPConnections, which re-gates on every new connection. Paired
3699
+ * with registerElicitationHandlers at the same call sites.
3700
+ *
3701
+ * No-op if the server was never channel-enabled: gateChannelServer calls
3702
+ * findChannelEntry internally and returns skip/session for an unlisted
3703
+ * server, so reconnecting a non-channel MCP server costs one feature-flag
3704
+ * check.
3705
+ */
3706
+ function reregisterChannelHandlerAfterReconnect(connection) {
3707
+ if (!(feature('KAIROS') || feature('KAIROS_CHANNELS')))
3708
+ return;
3709
+ if (connection.type !== 'connected')
3710
+ return;
3711
+ const gate = gateChannelServer(connection.name, connection.capabilities, connection.config.pluginSource);
3712
+ if (gate.action !== 'register')
3713
+ return;
3714
+ const entry = findChannelEntry(connection.name, getAllowedChannels());
3715
+ const pluginId = entry?.kind === 'plugin'
3716
+ ? `${entry.name}@${entry.marketplace}`
3717
+ : undefined;
3718
+ logMCPDebug(connection.name, 'Channel notifications re-registered after reconnect');
3719
+ connection.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => {
3720
+ const { content, meta } = notification.params;
3721
+ logMCPDebug(connection.name, `notifications/claude/channel: ${content.slice(0, 80)}`);
3722
+ logEvent('thaddeus_mcp_channel_message', {
3723
+ content_length: content.length,
3724
+ meta_key_count: Object.keys(meta ?? {}).length,
3725
+ entry_kind: entry?.kind,
3726
+ is_dev: entry?.dev ?? false,
3727
+ plugin: pluginId,
3728
+ });
3729
+ enqueue({
3730
+ mode: 'prompt',
3731
+ value: wrapChannelMessage(connection.name, content, meta),
3732
+ priority: 'next',
3733
+ isMeta: true,
3734
+ origin: { kind: 'channel', server: connection.name },
3735
+ skipSlashCommands: true,
3736
+ });
3737
+ });
3738
+ }
3739
+ /**
3740
+ * Emits an error message in the correct format based on outputFormat.
3741
+ * When using stream-json, writes JSON to stdout; otherwise writes plain text to stderr.
3742
+ */
3743
+ function emitLoadError(message, outputFormat) {
3744
+ if (outputFormat === 'stream-json') {
3745
+ const errorResult = {
3746
+ type: 'result',
3747
+ subtype: 'error_during_execution',
3748
+ duration_ms: 0,
3749
+ duration_api_ms: 0,
3750
+ is_error: true,
3751
+ num_turns: 0,
3752
+ stop_reason: null,
3753
+ session_id: getSessionId(),
3754
+ total_cost_usd: 0,
3755
+ usage: EMPTY_USAGE,
3756
+ modelUsage: {},
3757
+ permission_denials: [],
3758
+ uuid: randomUUID(),
3759
+ errors: [message],
3760
+ };
3761
+ process.stdout.write(jsonStringify(errorResult) + '\n');
3762
+ }
3763
+ else {
3764
+ process.stderr.write(message + '\n');
3765
+ }
3766
+ }
3767
+ /**
3768
+ * Removes an interrupted user message and its synthetic assistant sentinel
3769
+ * from the message array. Used during gateway-triggered restarts to clean up
3770
+ * the message history before re-enqueuing the interrupted prompt.
3771
+ *
3772
+ * @internal Exported for testing
3773
+ */
3774
+ export function removeInterruptedMessage(messages, interruptedUserMessage) {
3775
+ const idx = messages.findIndex(m => m.uuid === interruptedUserMessage.uuid);
3776
+ if (idx !== -1) {
3777
+ // Remove the user message and the sentinel that immediately follows it.
3778
+ // splice safely handles the case where idx is the last element.
3779
+ messages.splice(idx, 2);
3780
+ }
3781
+ }
3782
+ async function loadInitialMessages(setAppState, options) {
3783
+ const persistSession = !isSessionPersistenceDisabled();
3784
+ // Handle continue in print mode
3785
+ if (options.continue) {
3786
+ try {
3787
+ logEvent('thaddeus_continue_print', {});
3788
+ const result = await loadConversationForResume(undefined /* sessionId */, undefined /* file path */);
3789
+ if (result) {
3790
+ // Match coordinator mode to the resumed session's mode
3791
+ if (feature('COORDINATOR_MODE') && coordinatorModeModule) {
3792
+ const warning = coordinatorModeModule.matchSessionMode(result.mode);
3793
+ if (warning) {
3794
+ process.stderr.write(warning + '\n');
3795
+ // Refresh agent definitions to reflect the mode switch
3796
+ const { getAgentDefinitionsWithOverrides, getActiveAgentsFromList, } =
3797
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
3798
+ require('../tools/AgentTool/loadAgentsDir.js');
3799
+ getAgentDefinitionsWithOverrides.cache.clear?.();
3800
+ const freshAgentDefs = await getAgentDefinitionsWithOverrides(getCwd());
3801
+ setAppState(prev => ({
3802
+ ...prev,
3803
+ agentDefinitions: {
3804
+ ...freshAgentDefs,
3805
+ allAgents: freshAgentDefs.allAgents,
3806
+ activeAgents: getActiveAgentsFromList(freshAgentDefs.allAgents),
3807
+ },
3808
+ }));
3809
+ }
3810
+ }
3811
+ // Reuse the resumed session's ID
3812
+ if (!options.forkSession) {
3813
+ if (result.sessionId) {
3814
+ switchSession(asSessionId(result.sessionId), result.fullPath ? dirname(result.fullPath) : null);
3815
+ if (persistSession) {
3816
+ await resetSessionFilePointer();
3817
+ }
3818
+ }
3819
+ }
3820
+ restoreSessionStateFromLog(result, setAppState);
3821
+ // Restore session metadata so it's re-appended on exit via reAppendSessionMetadata
3822
+ restoreSessionMetadata(options.forkSession
3823
+ ? { ...result, worktreeSession: undefined }
3824
+ : result);
3825
+ // Write mode entry for the resumed session
3826
+ if (feature('COORDINATOR_MODE') && coordinatorModeModule) {
3827
+ saveMode(coordinatorModeModule.isCoordinatorMode()
3828
+ ? 'coordinator'
3829
+ : 'normal');
3830
+ }
3831
+ return {
3832
+ messages: result.messages,
3833
+ turnInterruptionState: result.turnInterruptionState,
3834
+ agentSetting: result.agentSetting,
3835
+ };
3836
+ }
3837
+ }
3838
+ catch (error) {
3839
+ logError(error);
3840
+ gracefulShutdownSync(1);
3841
+ return { messages: [] };
3842
+ }
3843
+ }
3844
+ // Handle teleport in print mode
3845
+ if (options.teleport) {
3846
+ try {
3847
+ if (!isPolicyAllowed('allow_remote_sessions')) {
3848
+ throw new Error("Remote sessions are disabled by your organization's policy.");
3849
+ }
3850
+ logEvent('thaddeus_teleport_print', {});
3851
+ if (typeof options.teleport !== 'string') {
3852
+ throw new Error('No session ID provided for teleport');
3853
+ }
3854
+ const { checkOutTeleportedSessionBranch, processMessagesForTeleportResume, teleportResumeCodeSession, validateGitState, } = await import('src/utils/teleport.js');
3855
+ await validateGitState();
3856
+ const teleportResult = await teleportResumeCodeSession(options.teleport);
3857
+ const { branchError } = await checkOutTeleportedSessionBranch(teleportResult.branch);
3858
+ return {
3859
+ messages: processMessagesForTeleportResume(teleportResult.log, branchError),
3860
+ };
3861
+ }
3862
+ catch (error) {
3863
+ logError(error);
3864
+ gracefulShutdownSync(1);
3865
+ return { messages: [] };
3866
+ }
3867
+ }
3868
+ // Handle resume in print mode (accepts session ID or URL)
3869
+ // URLs are [ANT-ONLY]
3870
+ if (options.resume) {
3871
+ try {
3872
+ logEvent('thaddeus_resume_print', {});
3873
+ // In print mode - we require a valid session ID, JSONL file or URL
3874
+ const parsedSessionId = parseSessionIdentifier(typeof options.resume === 'string' ? options.resume : '');
3875
+ if (!parsedSessionId) {
3876
+ let errorMessage = 'Error: --resume requires a valid session ID when used with --print. Usage: thaddeus -p --resume <session-id>';
3877
+ if (typeof options.resume === 'string') {
3878
+ errorMessage += `. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${options.resume}" is not a valid UUID`;
3879
+ }
3880
+ emitLoadError(errorMessage, options.outputFormat);
3881
+ gracefulShutdownSync(1);
3882
+ return { messages: [] };
3883
+ }
3884
+ // Hydrate local transcript from remote before loading
3885
+ if (isEnvTruthy(process.env.THADDEUS_USE_CCR_V2)) {
3886
+ // Await restore alongside hydration so SSE catchup lands on
3887
+ // restored state, not a fresh default.
3888
+ const [, metadata] = await Promise.all([
3889
+ hydrateFromCCRv2InternalEvents(parsedSessionId.sessionId),
3890
+ options.restoredWorkerState,
3891
+ ]);
3892
+ if (metadata) {
3893
+ setAppState(externalMetadataToAppState(metadata));
3894
+ if (typeof metadata.model === 'string') {
3895
+ setMainLoopModelOverride(metadata.model);
3896
+ }
3897
+ }
3898
+ }
3899
+ else if (parsedSessionId.isUrl &&
3900
+ parsedSessionId.ingressUrl &&
3901
+ isEnvTruthy(process.env.ENABLE_SESSION_PERSISTENCE)) {
3902
+ // v1: fetch session logs from Session Ingress
3903
+ await hydrateRemoteSession(parsedSessionId.sessionId, parsedSessionId.ingressUrl);
3904
+ }
3905
+ // Load the conversation with the specified session ID
3906
+ const result = await loadConversationForResume(parsedSessionId.sessionId, parsedSessionId.jsonlFile || undefined);
3907
+ // hydrateFromCCRv2InternalEvents writes an empty transcript file for
3908
+ // fresh sessions (writeFile(sessionFile, '') with zero events), so
3909
+ // loadConversationForResume returns {messages: []} not null. Treat
3910
+ // empty the same as null so SessionStart still fires.
3911
+ if (!result || result.messages.length === 0) {
3912
+ // For URL-based or CCR v2 resume, start with empty session (it was hydrated but empty)
3913
+ if (parsedSessionId.isUrl ||
3914
+ isEnvTruthy(process.env.THADDEUS_USE_CCR_V2)) {
3915
+ // Execute SessionStart hooks for startup since we're starting a new session
3916
+ return {
3917
+ messages: await (options.sessionStartHooksPromise ??
3918
+ processSessionStartHooks('startup')),
3919
+ };
3920
+ }
3921
+ else {
3922
+ emitLoadError(`No conversation found with session ID: ${parsedSessionId.sessionId}`, options.outputFormat);
3923
+ gracefulShutdownSync(1);
3924
+ return { messages: [] };
3925
+ }
3926
+ }
3927
+ // Handle resumeSessionAt feature
3928
+ if (options.resumeSessionAt) {
3929
+ const index = result.messages.findIndex(m => m.uuid === options.resumeSessionAt);
3930
+ if (index < 0) {
3931
+ emitLoadError(`No message found with message.uuid of: ${options.resumeSessionAt}`, options.outputFormat);
3932
+ gracefulShutdownSync(1);
3933
+ return { messages: [] };
3934
+ }
3935
+ result.messages = index >= 0 ? result.messages.slice(0, index + 1) : [];
3936
+ }
3937
+ // Match coordinator mode to the resumed session's mode
3938
+ if (feature('COORDINATOR_MODE') && coordinatorModeModule) {
3939
+ const warning = coordinatorModeModule.matchSessionMode(result.mode);
3940
+ if (warning) {
3941
+ process.stderr.write(warning + '\n');
3942
+ // Refresh agent definitions to reflect the mode switch
3943
+ const { getAgentDefinitionsWithOverrides, getActiveAgentsFromList } =
3944
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
3945
+ require('../tools/AgentTool/loadAgentsDir.js');
3946
+ getAgentDefinitionsWithOverrides.cache.clear?.();
3947
+ const freshAgentDefs = await getAgentDefinitionsWithOverrides(getCwd());
3948
+ setAppState(prev => ({
3949
+ ...prev,
3950
+ agentDefinitions: {
3951
+ ...freshAgentDefs,
3952
+ allAgents: freshAgentDefs.allAgents,
3953
+ activeAgents: getActiveAgentsFromList(freshAgentDefs.allAgents),
3954
+ },
3955
+ }));
3956
+ }
3957
+ }
3958
+ // Reuse the resumed session's ID
3959
+ if (!options.forkSession && result.sessionId) {
3960
+ switchSession(asSessionId(result.sessionId), result.fullPath ? dirname(result.fullPath) : null);
3961
+ if (persistSession) {
3962
+ await resetSessionFilePointer();
3963
+ }
3964
+ }
3965
+ restoreSessionStateFromLog(result, setAppState);
3966
+ // Restore session metadata so it's re-appended on exit via reAppendSessionMetadata
3967
+ restoreSessionMetadata(options.forkSession
3968
+ ? { ...result, worktreeSession: undefined }
3969
+ : result);
3970
+ // Write mode entry for the resumed session
3971
+ if (feature('COORDINATOR_MODE') && coordinatorModeModule) {
3972
+ saveMode(coordinatorModeModule.isCoordinatorMode() ? 'coordinator' : 'normal');
3973
+ }
3974
+ return {
3975
+ messages: result.messages,
3976
+ turnInterruptionState: result.turnInterruptionState,
3977
+ agentSetting: result.agentSetting,
3978
+ };
3979
+ }
3980
+ catch (error) {
3981
+ logError(error);
3982
+ const errorMessage = error instanceof Error
3983
+ ? `Failed to resume session: ${error.message}`
3984
+ : 'Failed to resume session with --print mode';
3985
+ emitLoadError(errorMessage, options.outputFormat);
3986
+ gracefulShutdownSync(1);
3987
+ return { messages: [] };
3988
+ }
3989
+ }
3990
+ // Join the SessionStart hooks promise kicked in main.tsx (or run fresh if
3991
+ // it wasn't kicked — e.g. --continue with no prior session falls through
3992
+ // here with sessionStartHooksPromise undefined because main.tsx guards on continue)
3993
+ return {
3994
+ messages: await (options.sessionStartHooksPromise ??
3995
+ processSessionStartHooks('startup')),
3996
+ };
3997
+ }
3998
+ function getStructuredIO(inputPrompt, options) {
3999
+ let inputStream;
4000
+ if (typeof inputPrompt === 'string') {
4001
+ if (inputPrompt.trim() !== '') {
4002
+ // Normalize to a streaming input.
4003
+ inputStream = fromArray([
4004
+ jsonStringify({
4005
+ type: 'user',
4006
+ session_id: '',
4007
+ message: {
4008
+ role: 'user',
4009
+ content: inputPrompt,
4010
+ },
4011
+ parent_tool_use_id: null,
4012
+ }),
4013
+ ]);
4014
+ }
4015
+ else {
4016
+ // Empty string - create empty stream
4017
+ inputStream = fromArray([]);
4018
+ }
4019
+ }
4020
+ else {
4021
+ inputStream = inputPrompt;
4022
+ }
4023
+ // Use RemoteIO if sdkUrl is provided, otherwise use regular StructuredIO
4024
+ return options.sdkUrl
4025
+ ? new RemoteIO(options.sdkUrl, inputStream, options.replayUserMessages)
4026
+ : new StructuredIO(inputStream, options.replayUserMessages);
4027
+ }
4028
+ /**
4029
+ * Handles unexpected permission responses by looking up the unresolved tool
4030
+ * call in the transcript and enqueuing it for execution.
4031
+ *
4032
+ * Returns true if a permission was enqueued, false otherwise.
4033
+ */
4034
+ export async function handleOrphanedPermissionResponse({ message, setAppState, onEnqueued, handledToolUseIds, }) {
4035
+ if (message.response.subtype === 'success' &&
4036
+ message.response.response?.toolUseID &&
4037
+ typeof message.response.response.toolUseID === 'string') {
4038
+ const permissionResult = message.response.response;
4039
+ const { toolUseID } = permissionResult;
4040
+ if (!toolUseID) {
4041
+ return false;
4042
+ }
4043
+ logForDebugging(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${toolUseID} request_id=${message.response.request_id}`);
4044
+ // Prevent re-processing the same orphaned tool_use. Without this guard,
4045
+ // duplicate control_response deliveries (e.g. from WebSocket reconnect)
4046
+ // cause the same tool to be executed multiple times, producing duplicate
4047
+ // tool_use IDs in the messages array and a 400 error from the API.
4048
+ // Once corrupted, every retry accumulates more duplicates.
4049
+ if (handledToolUseIds.has(toolUseID)) {
4050
+ logForDebugging(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${toolUseID} (already handled)`);
4051
+ return false;
4052
+ }
4053
+ const assistantMessage = await findUnresolvedToolUse(toolUseID);
4054
+ if (!assistantMessage) {
4055
+ logForDebugging(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${toolUseID} (already resolved in transcript)`);
4056
+ return false;
4057
+ }
4058
+ handledToolUseIds.add(toolUseID);
4059
+ logForDebugging(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${toolUseID} messageID=${assistantMessage.message.id}`);
4060
+ enqueue({
4061
+ mode: 'orphaned-permission',
4062
+ value: [],
4063
+ orphanedPermission: {
4064
+ permissionResult,
4065
+ assistantMessage,
4066
+ },
4067
+ });
4068
+ onEnqueued?.();
4069
+ return true;
4070
+ }
4071
+ return false;
4072
+ }
4073
+ /**
4074
+ * Converts a process transport config to a scoped config.
4075
+ * The types are structurally compatible, so we just add the scope.
4076
+ */
4077
+ function toScopedConfig(config) {
4078
+ // McpServerConfigForProcessTransport is a subset of McpServerConfig
4079
+ // (it excludes IDE-specific types like sse-ide and ws-ide)
4080
+ // Adding scope makes it a valid ScopedMcpServerConfig
4081
+ return { ...config, scope: 'dynamic' };
4082
+ }
4083
+ /**
4084
+ * Handles mcp_set_servers requests by processing both SDK and process-based servers.
4085
+ * SDK servers run in the SDK process; process-based servers are spawned by the CLI.
4086
+ *
4087
+ * Applies enterprise allowedMcpServers/deniedMcpServers policy — same filter as
4088
+ * --mcp-config (see filterMcpServersByPolicy call in main.tsx). Without this,
4089
+ * SDK V2 Query.setMcpServers() was a second policy bypass vector. Blocked servers
4090
+ * are reported in response.errors so the SDK consumer knows why they weren't added.
4091
+ */
4092
+ export async function handleMcpSetServers(servers, sdkState, dynamicState, setAppState) {
4093
+ // Enforce enterprise MCP policy on process-based servers (stdio/http/sse).
4094
+ // Mirrors the --mcp-config filter in main.tsx — both user-controlled injection
4095
+ // paths must have the same gate. type:'sdk' servers are exempt (SDK-managed,
4096
+ // CLI never spawns/connects for them — see filterMcpServersByPolicy jsdoc).
4097
+ // Blocked servers go into response.errors so the SDK caller sees why.
4098
+ const { allowed: allowedServers, blocked } = filterMcpServersByPolicy(servers);
4099
+ const policyErrors = {};
4100
+ for (const name of blocked) {
4101
+ policyErrors[name] =
4102
+ 'Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)';
4103
+ }
4104
+ // Separate SDK servers from process-based servers
4105
+ const sdkServers = {};
4106
+ const processServers = {};
4107
+ for (const [name, config] of Object.entries(allowedServers)) {
4108
+ if (config.type === 'sdk') {
4109
+ sdkServers[name] = config;
4110
+ }
4111
+ else {
4112
+ processServers[name] = config;
4113
+ }
4114
+ }
4115
+ // Handle SDK servers
4116
+ const currentSdkNames = new Set(Object.keys(sdkState.configs));
4117
+ const newSdkNames = new Set(Object.keys(sdkServers));
4118
+ const sdkAdded = [];
4119
+ const sdkRemoved = [];
4120
+ const newSdkConfigs = { ...sdkState.configs };
4121
+ let newSdkClients = [...sdkState.clients];
4122
+ let newSdkTools = [...sdkState.tools];
4123
+ // Remove SDK servers no longer in desired state
4124
+ for (const name of currentSdkNames) {
4125
+ if (!newSdkNames.has(name)) {
4126
+ const client = newSdkClients.find(c => c.name === name);
4127
+ if (client && client.type === 'connected') {
4128
+ await client.cleanup();
4129
+ }
4130
+ newSdkClients = newSdkClients.filter(c => c.name !== name);
4131
+ const prefix = `mcp__${name}__`;
4132
+ newSdkTools = newSdkTools.filter(t => !t.name.startsWith(prefix));
4133
+ delete newSdkConfigs[name];
4134
+ sdkRemoved.push(name);
4135
+ }
4136
+ }
4137
+ // Add new SDK servers as pending - they'll be upgraded to connected
4138
+ // when updateSdkMcp() runs on the next query
4139
+ for (const [name, config] of Object.entries(sdkServers)) {
4140
+ if (!currentSdkNames.has(name)) {
4141
+ newSdkConfigs[name] = config;
4142
+ const pendingClient = {
4143
+ type: 'pending',
4144
+ name,
4145
+ config: { ...config, scope: 'dynamic' },
4146
+ };
4147
+ newSdkClients = [...newSdkClients, pendingClient];
4148
+ sdkAdded.push(name);
4149
+ }
4150
+ }
4151
+ // Handle process-based servers
4152
+ const processResult = await reconcileMcpServers(processServers, dynamicState, setAppState);
4153
+ return {
4154
+ response: {
4155
+ added: [...sdkAdded, ...processResult.response.added],
4156
+ removed: [...sdkRemoved, ...processResult.response.removed],
4157
+ errors: { ...policyErrors, ...processResult.response.errors },
4158
+ },
4159
+ newSdkState: {
4160
+ configs: newSdkConfigs,
4161
+ clients: newSdkClients,
4162
+ tools: newSdkTools,
4163
+ },
4164
+ newDynamicState: processResult.newState,
4165
+ sdkServersChanged: sdkAdded.length > 0 || sdkRemoved.length > 0,
4166
+ };
4167
+ }
4168
+ /**
4169
+ * Reconciles the current set of dynamic MCP servers with a new desired state.
4170
+ * Handles additions, removals, and config changes.
4171
+ */
4172
+ export async function reconcileMcpServers(desiredConfigs, currentState, setAppState) {
4173
+ const currentNames = new Set(Object.keys(currentState.configs));
4174
+ const desiredNames = new Set(Object.keys(desiredConfigs));
4175
+ const toRemove = [...currentNames].filter(n => !desiredNames.has(n));
4176
+ const toAdd = [...desiredNames].filter(n => !currentNames.has(n));
4177
+ // Check for config changes (same name, different config)
4178
+ const toCheck = [...currentNames].filter(n => desiredNames.has(n));
4179
+ const toReplace = toCheck.filter(name => {
4180
+ const currentConfig = currentState.configs[name];
4181
+ const desiredConfigRaw = desiredConfigs[name];
4182
+ if (!currentConfig || !desiredConfigRaw)
4183
+ return true;
4184
+ const desiredConfig = toScopedConfig(desiredConfigRaw);
4185
+ return !areMcpConfigsEqual(currentConfig, desiredConfig);
4186
+ });
4187
+ const removed = [];
4188
+ const added = [];
4189
+ const errors = {};
4190
+ let newClients = [...currentState.clients];
4191
+ let newTools = [...currentState.tools];
4192
+ // Remove old servers (including ones being replaced)
4193
+ for (const name of [...toRemove, ...toReplace]) {
4194
+ const client = newClients.find(c => c.name === name);
4195
+ const config = currentState.configs[name];
4196
+ if (client && config) {
4197
+ if (client.type === 'connected') {
4198
+ try {
4199
+ await client.cleanup();
4200
+ }
4201
+ catch (e) {
4202
+ logError(e);
4203
+ }
4204
+ }
4205
+ // Clear the memoization cache
4206
+ await clearServerCache(name, config);
4207
+ }
4208
+ // Remove tools from this server
4209
+ const prefix = `mcp__${name}__`;
4210
+ newTools = newTools.filter(t => !t.name.startsWith(prefix));
4211
+ // Remove from clients list
4212
+ newClients = newClients.filter(c => c.name !== name);
4213
+ // Track removal (only for actually removed, not replaced)
4214
+ if (toRemove.includes(name)) {
4215
+ removed.push(name);
4216
+ }
4217
+ }
4218
+ // Add new servers (including replacements)
4219
+ for (const name of [...toAdd, ...toReplace]) {
4220
+ const config = desiredConfigs[name];
4221
+ if (!config)
4222
+ continue;
4223
+ const scopedConfig = toScopedConfig(config);
4224
+ // SDK servers are managed by the SDK process, not the CLI.
4225
+ // Just track them without trying to connect.
4226
+ if (config.type === 'sdk') {
4227
+ added.push(name);
4228
+ continue;
4229
+ }
4230
+ try {
4231
+ const client = await connectToServer(name, scopedConfig);
4232
+ newClients.push(client);
4233
+ if (client.type === 'connected') {
4234
+ const serverTools = await fetchToolsForClient(client);
4235
+ newTools.push(...serverTools);
4236
+ }
4237
+ else if (client.type === 'failed') {
4238
+ errors[name] = client.error || 'Connection failed';
4239
+ }
4240
+ added.push(name);
4241
+ }
4242
+ catch (e) {
4243
+ const err = toError(e);
4244
+ errors[name] = err.message;
4245
+ logError(err);
4246
+ }
4247
+ }
4248
+ // Build new configs
4249
+ const newConfigs = {};
4250
+ for (const name of desiredNames) {
4251
+ const config = desiredConfigs[name];
4252
+ if (config) {
4253
+ newConfigs[name] = toScopedConfig(config);
4254
+ }
4255
+ }
4256
+ const newState = {
4257
+ clients: newClients,
4258
+ tools: newTools,
4259
+ configs: newConfigs,
4260
+ };
4261
+ // Update AppState with the new tools
4262
+ setAppState(prev => {
4263
+ // Get all dynamic server names (current + new)
4264
+ const allDynamicServerNames = new Set([
4265
+ ...Object.keys(currentState.configs),
4266
+ ...Object.keys(newConfigs),
4267
+ ]);
4268
+ // Remove old dynamic tools
4269
+ const nonDynamicTools = prev.mcp.tools.filter(t => {
4270
+ for (const serverName of allDynamicServerNames) {
4271
+ if (t.name.startsWith(`mcp__${serverName}__`)) {
4272
+ return false;
4273
+ }
4274
+ }
4275
+ return true;
4276
+ });
4277
+ // Remove old dynamic clients
4278
+ const nonDynamicClients = prev.mcp.clients.filter(c => {
4279
+ return !allDynamicServerNames.has(c.name);
4280
+ });
4281
+ return {
4282
+ ...prev,
4283
+ mcp: {
4284
+ ...prev.mcp,
4285
+ tools: [...nonDynamicTools, ...newTools],
4286
+ clients: [...nonDynamicClients, ...newClients],
4287
+ },
4288
+ };
4289
+ });
4290
+ return {
4291
+ response: { added, removed, errors },
4292
+ newState,
4293
+ };
4294
+ }