@iaforged/context-code 1.0.72 → 1.0.74

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