@iaforged/context-code 1.0.63 → 1.0.67

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 (2000) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +637 -9
  3. package/context-bootstrap.js +28 -28
  4. package/package.json +169 -170
  5. package/dist/src/QueryEngine.js +0 -928
  6. package/dist/src/Task.js +0 -49
  7. package/dist/src/Tool.js +0 -56
  8. package/dist/src/assistant/AssistantSessionChooser.js +0 -16
  9. package/dist/src/assistant/index.js +0 -16
  10. package/dist/src/assistant/sessionDiscovery.js +0 -16
  11. package/dist/src/assistant/sessionHistory.js +0 -47
  12. package/dist/src/bootstrap/state.js +0 -1165
  13. package/dist/src/bridge/bridgeApi.js +0 -304
  14. package/dist/src/bridge/bridgeConfig.js +0 -39
  15. package/dist/src/bridge/bridgeDebug.js +0 -73
  16. package/dist/src/bridge/bridgeEnabled.js +0 -187
  17. package/dist/src/bridge/bridgeMain.js +0 -2289
  18. package/dist/src/bridge/bridgeMessaging.js +0 -353
  19. package/dist/src/bridge/bridgePermissionCallbacks.js +0 -10
  20. package/dist/src/bridge/bridgePointer.js +0 -175
  21. package/dist/src/bridge/bridgeStatusUtil.js +0 -105
  22. package/dist/src/bridge/bridgeUI.js +0 -412
  23. package/dist/src/bridge/capacityWake.js +0 -35
  24. package/dist/src/bridge/codeSessionApi.js +0 -111
  25. package/dist/src/bridge/createSession.js +0 -273
  26. package/dist/src/bridge/debugUtils.js +0 -115
  27. package/dist/src/bridge/envLessBridgeConfig.js +0 -121
  28. package/dist/src/bridge/flushGate.js +0 -65
  29. package/dist/src/bridge/inboundAttachments.js +0 -152
  30. package/dist/src/bridge/inboundMessages.js +0 -63
  31. package/dist/src/bridge/initReplBridge.js +0 -428
  32. package/dist/src/bridge/jwtUtils.js +0 -185
  33. package/dist/src/bridge/pollConfig.js +0 -85
  34. package/dist/src/bridge/pollConfigDefaults.js +0 -62
  35. package/dist/src/bridge/remoteBridgeCore.js +0 -712
  36. package/dist/src/bridge/replBridge.js +0 -1720
  37. package/dist/src/bridge/replBridgeHandle.js +0 -30
  38. package/dist/src/bridge/replBridgeTransport.js +0 -236
  39. package/dist/src/bridge/sessionIdCompat.js +0 -56
  40. package/dist/src/bridge/sessionRunner.js +0 -421
  41. package/dist/src/bridge/trustedDevice.js +0 -172
  42. package/dist/src/bridge/types.js +0 -9
  43. package/dist/src/bridge/workSecret.js +0 -99
  44. package/dist/src/buddy/CompanionSprite.js +0 -349
  45. package/dist/src/buddy/companion.js +0 -107
  46. package/dist/src/buddy/prompt.js +0 -33
  47. package/dist/src/buddy/sprites.js +0 -488
  48. package/dist/src/buddy/types.js +0 -90
  49. package/dist/src/buddy/useBuddyNotification.js +0 -90
  50. package/dist/src/cli/bg.js +0 -16
  51. package/dist/src/cli/exit.js +0 -30
  52. package/dist/src/cli/handlers/agents.js +0 -55
  53. package/dist/src/cli/handlers/ant.js +0 -16
  54. package/dist/src/cli/handlers/auth.js +0 -312
  55. package/dist/src/cli/handlers/autoMode.js +0 -128
  56. package/dist/src/cli/handlers/mcp.js +0 -334
  57. package/dist/src/cli/handlers/plugins.js +0 -634
  58. package/dist/src/cli/handlers/projects_bridge.js +0 -40
  59. package/dist/src/cli/handlers/templateJobs.js +0 -16
  60. package/dist/src/cli/handlers/util.js +0 -76
  61. package/dist/src/cli/ndjsonSafeStringify.js +0 -27
  62. package/dist/src/cli/print.js +0 -4225
  63. package/dist/src/cli/remoteIO.js +0 -208
  64. package/dist/src/cli/rollback.js +0 -16
  65. package/dist/src/cli/structuredIO.js +0 -644
  66. package/dist/src/cli/transports/HybridTransport.js +0 -233
  67. package/dist/src/cli/transports/SSETransport.js +0 -538
  68. package/dist/src/cli/transports/SerialBatchEventUploader.js +0 -224
  69. package/dist/src/cli/transports/Transport.js +0 -1
  70. package/dist/src/cli/transports/WebSocketTransport.js +0 -613
  71. package/dist/src/cli/transports/WorkerStateUploader.js +0 -88
  72. package/dist/src/cli/transports/ccrClient.js +0 -711
  73. package/dist/src/cli/transports/transportUtils.js +0 -39
  74. package/dist/src/cli/up.js +0 -16
  75. package/dist/src/cli/update.js +0 -315
  76. package/dist/src/commands/add-dir/add-dir.js +0 -121
  77. package/dist/src/commands/add-dir/index.js +0 -8
  78. package/dist/src/commands/add-dir/validation.js +0 -76
  79. package/dist/src/commands/advisor.js +0 -88
  80. package/dist/src/commands/agents/agents.js +0 -9
  81. package/dist/src/commands/agents/index.js +0 -7
  82. package/dist/src/commands/ant-trace/index.js +0 -1
  83. package/dist/src/commands/assistant/assistant.js +0 -16
  84. package/dist/src/commands/autofix-pr/index.js +0 -1
  85. package/dist/src/commands/backfill-sessions/index.js +0 -1
  86. package/dist/src/commands/branch/branch.js +0 -205
  87. package/dist/src/commands/branch/index.js +0 -11
  88. package/dist/src/commands/break-cache/index.js +0 -1
  89. package/dist/src/commands/bridge/bridge.js +0 -512
  90. package/dist/src/commands/bridge/index.js +0 -22
  91. package/dist/src/commands/bridge-kick.js +0 -179
  92. package/dist/src/commands/brief.js +0 -94
  93. package/dist/src/commands/btw/btw.js +0 -234
  94. package/dist/src/commands/btw/index.js +0 -9
  95. package/dist/src/commands/bughunter/index.js +0 -1
  96. package/dist/src/commands/chrome/chrome.js +0 -291
  97. package/dist/src/commands/chrome/index.js +0 -10
  98. package/dist/src/commands/clear/caches.js +0 -116
  99. package/dist/src/commands/clear/clear.js +0 -5
  100. package/dist/src/commands/clear/conversation.js +0 -191
  101. package/dist/src/commands/clear/index.js +0 -9
  102. package/dist/src/commands/color/color.js +0 -58
  103. package/dist/src/commands/color/index.js +0 -9
  104. package/dist/src/commands/commit-push-pr.js +0 -137
  105. package/dist/src/commands/commit.js +0 -80
  106. package/dist/src/commands/compact/compact.js +0 -196
  107. package/dist/src/commands/compact/index.js +0 -11
  108. package/dist/src/commands/config/config.js +0 -5
  109. package/dist/src/commands/config/index.js +0 -8
  110. package/dist/src/commands/context/context-noninteractive.js +0 -221
  111. package/dist/src/commands/context/context.js +0 -46
  112. package/dist/src/commands/context/index.js +0 -21
  113. package/dist/src/commands/copy/copy.js +0 -366
  114. package/dist/src/commands/copy/index.js +0 -7
  115. package/dist/src/commands/cost/cost.js +0 -21
  116. package/dist/src/commands/cost/index.js +0 -16
  117. package/dist/src/commands/createMovedToPluginCommand.js +0 -33
  118. package/dist/src/commands/ctx_viz/index.js +0 -1
  119. package/dist/src/commands/debug-tool-call/index.js +0 -1
  120. package/dist/src/commands/desktop/desktop.js +0 -5
  121. package/dist/src/commands/desktop/index.js +0 -22
  122. package/dist/src/commands/diff/diff.js +0 -5
  123. package/dist/src/commands/diff/index.js +0 -6
  124. package/dist/src/commands/doctor/doctor.js +0 -5
  125. package/dist/src/commands/doctor/index.js +0 -9
  126. package/dist/src/commands/effort/effort.js +0 -166
  127. package/dist/src/commands/effort/index.js +0 -11
  128. package/dist/src/commands/env/index.js +0 -1
  129. package/dist/src/commands/exit/exit.js +0 -31
  130. package/dist/src/commands/exit/index.js +0 -9
  131. package/dist/src/commands/export/export.js +0 -86
  132. package/dist/src/commands/export/index.js +0 -8
  133. package/dist/src/commands/extra-usage/extra-usage-core.js +0 -99
  134. package/dist/src/commands/extra-usage/extra-usage-noninteractive.js +0 -13
  135. package/dist/src/commands/extra-usage/extra-usage.js +0 -14
  136. package/dist/src/commands/extra-usage/index.js +0 -27
  137. package/dist/src/commands/fast/fast.js +0 -275
  138. package/dist/src/commands/fast/index.js +0 -20
  139. package/dist/src/commands/feedback/feedback.js +0 -10
  140. package/dist/src/commands/feedback/index.js +0 -20
  141. package/dist/src/commands/files/files.js +0 -11
  142. package/dist/src/commands/files/index.js +0 -9
  143. package/dist/src/commands/good-claude/index.js +0 -1
  144. package/dist/src/commands/heapdump/heapdump.js +0 -14
  145. package/dist/src/commands/heapdump/index.js +0 -9
  146. package/dist/src/commands/help/help.js +0 -5
  147. package/dist/src/commands/help/index.js +0 -7
  148. package/dist/src/commands/hooks/hooks.js +0 -11
  149. package/dist/src/commands/hooks/index.js +0 -8
  150. package/dist/src/commands/ide/ide.js +0 -615
  151. package/dist/src/commands/ide/index.js +0 -8
  152. package/dist/src/commands/init-verifiers.js +0 -258
  153. package/dist/src/commands/init.js +0 -249
  154. package/dist/src/commands/insights.js +0 -2555
  155. package/dist/src/commands/install-github-app/ApiKeyStep.js +0 -230
  156. package/dist/src/commands/install-github-app/CheckExistingSecretStep.js +0 -194
  157. package/dist/src/commands/install-github-app/CheckGitHubStep.js +0 -15
  158. package/dist/src/commands/install-github-app/ChooseRepoStep.js +0 -211
  159. package/dist/src/commands/install-github-app/CreatingStep.js +0 -52
  160. package/dist/src/commands/install-github-app/ErrorStep.js +0 -83
  161. package/dist/src/commands/install-github-app/ExistingWorkflowStep.js +0 -104
  162. package/dist/src/commands/install-github-app/InstallAppStep.js +0 -96
  163. package/dist/src/commands/install-github-app/OAuthFlowStep.js +0 -190
  164. package/dist/src/commands/install-github-app/SuccessStep.js +0 -93
  165. package/dist/src/commands/install-github-app/WarningsStep.js +0 -70
  166. package/dist/src/commands/install-github-app/index.js +0 -10
  167. package/dist/src/commands/install-github-app/install-github-app.js +0 -593
  168. package/dist/src/commands/install-github-app/setupGitHubActions.js +0 -227
  169. package/dist/src/commands/install-slack-app/index.js +0 -9
  170. package/dist/src/commands/install-slack-app/install-slack-app.js +0 -25
  171. package/dist/src/commands/install.js +0 -118
  172. package/dist/src/commands/issue/index.js +0 -1
  173. package/dist/src/commands/keybindings/index.js +0 -10
  174. package/dist/src/commands/keybindings/keybindings.js +0 -47
  175. package/dist/src/commands/login/index.js +0 -11
  176. package/dist/src/commands/login/login.js +0 -99
  177. package/dist/src/commands/login-openai/index.js +0 -7
  178. package/dist/src/commands/login-openai/login-openai.js +0 -54
  179. package/dist/src/commands/logout/index.js +0 -8
  180. package/dist/src/commands/logout/logout.js +0 -72
  181. package/dist/src/commands/mcp/addCommand.js +0 -183
  182. package/dist/src/commands/mcp/index.js +0 -9
  183. package/dist/src/commands/mcp/mcp.js +0 -78
  184. package/dist/src/commands/mcp/xaaIdpCommand.js +0 -193
  185. package/dist/src/commands/memory/index.js +0 -7
  186. package/dist/src/commands/memory/memory.js +0 -71
  187. package/dist/src/commands/mobile/index.js +0 -8
  188. package/dist/src/commands/mobile/mobile.js +0 -278
  189. package/dist/src/commands/mock-limits/index.js +0 -1
  190. package/dist/src/commands/model/index.js +0 -14
  191. package/dist/src/commands/model/model.js +0 -297
  192. package/dist/src/commands/oauth-refresh/index.js +0 -1
  193. package/dist/src/commands/onboarding/index.js +0 -1
  194. package/dist/src/commands/output-style/index.js +0 -8
  195. package/dist/src/commands/output-style/output-style.js +0 -6
  196. package/dist/src/commands/passes/index.js +0 -17
  197. package/dist/src/commands/passes/passes.js +0 -22
  198. package/dist/src/commands/perf-issue/index.js +0 -1
  199. package/dist/src/commands/permissions/index.js +0 -8
  200. package/dist/src/commands/permissions/permissions.js +0 -8
  201. package/dist/src/commands/plan/index.js +0 -8
  202. package/dist/src/commands/plan/plan.js +0 -115
  203. package/dist/src/commands/plugin/AddMarketplace.js +0 -95
  204. package/dist/src/commands/plugin/BrowseMarketplace.js +0 -576
  205. package/dist/src/commands/plugin/DiscoverPlugins.js +0 -613
  206. package/dist/src/commands/plugin/ManageMarketplaces.js +0 -582
  207. package/dist/src/commands/plugin/ManagePlugins.js +0 -1783
  208. package/dist/src/commands/plugin/PluginErrors.js +0 -124
  209. package/dist/src/commands/plugin/PluginOptionsDialog.js +0 -367
  210. package/dist/src/commands/plugin/PluginOptionsFlow.js +0 -97
  211. package/dist/src/commands/plugin/PluginSettings.js +0 -1042
  212. package/dist/src/commands/plugin/PluginTrustWarning.js +0 -34
  213. package/dist/src/commands/plugin/UnifiedInstalledCell.js +0 -615
  214. package/dist/src/commands/plugin/ValidatePlugin.js +0 -95
  215. package/dist/src/commands/plugin/index.js +0 -10
  216. package/dist/src/commands/plugin/parseArgs.js +0 -71
  217. package/dist/src/commands/plugin/plugin.js +0 -5
  218. package/dist/src/commands/plugin/pluginDetailsHelpers.js +0 -89
  219. package/dist/src/commands/plugin/usePagination.js +0 -89
  220. package/dist/src/commands/pr_comments/index.js +0 -49
  221. package/dist/src/commands/privacy-settings/index.js +0 -11
  222. package/dist/src/commands/privacy-settings/privacy-settings.js +0 -54
  223. package/dist/src/commands/profile/index.js +0 -9
  224. package/dist/src/commands/profile/profile.js +0 -426
  225. package/dist/src/commands/provider/index.js +0 -8
  226. package/dist/src/commands/provider/provider.js +0 -349
  227. package/dist/src/commands/rate-limit-options/index.js +0 -15
  228. package/dist/src/commands/rate-limit-options/rate-limit-options.js +0 -213
  229. package/dist/src/commands/release-notes/index.js +0 -8
  230. package/dist/src/commands/release-notes/release-notes.js +0 -38
  231. package/dist/src/commands/reload-plugins/index.js +0 -11
  232. package/dist/src/commands/reload-plugins/reload-plugins.js +0 -52
  233. package/dist/src/commands/remote-env/index.js +0 -12
  234. package/dist/src/commands/remote-env/remote-env.js +0 -5
  235. package/dist/src/commands/remote-setup/api.js +0 -155
  236. package/dist/src/commands/remote-setup/index.js +0 -15
  237. package/dist/src/commands/remote-setup/remote-setup.js +0 -149
  238. package/dist/src/commands/rename/generateSessionName.js +0 -58
  239. package/dist/src/commands/rename/index.js +0 -9
  240. package/dist/src/commands/rename/rename.js +0 -52
  241. package/dist/src/commands/reset-limits/index.js +0 -4
  242. package/dist/src/commands/resume/index.js +0 -9
  243. package/dist/src/commands/resume/resume.js +0 -239
  244. package/dist/src/commands/review/UltrareviewOverageDialog.js +0 -97
  245. package/dist/src/commands/review/reviewRemote.js +0 -259
  246. package/dist/src/commands/review/ultrareviewCommand.js +0 -57
  247. package/dist/src/commands/review/ultrareviewEnabled.js +0 -10
  248. package/dist/src/commands/review.js +0 -50
  249. package/dist/src/commands/rewind/index.js +0 -10
  250. package/dist/src/commands/rewind/rewind.js +0 -7
  251. package/dist/src/commands/sandbox-toggle/index.js +0 -41
  252. package/dist/src/commands/sandbox-toggle/sandbox-toggle.js +0 -72
  253. package/dist/src/commands/security-review.js +0 -231
  254. package/dist/src/commands/session/index.js +0 -13
  255. package/dist/src/commands/session/session.js +0 -142
  256. package/dist/src/commands/share/index.js +0 -1
  257. package/dist/src/commands/skills/index.js +0 -7
  258. package/dist/src/commands/skills/skills.js +0 -5
  259. package/dist/src/commands/stats/index.js +0 -7
  260. package/dist/src/commands/stats/stats.js +0 -5
  261. package/dist/src/commands/status/index.js +0 -8
  262. package/dist/src/commands/status/status.js +0 -5
  263. package/dist/src/commands/statusline.js +0 -22
  264. package/dist/src/commands/stickers/index.js +0 -8
  265. package/dist/src/commands/stickers/stickers.js +0 -14
  266. package/dist/src/commands/summary/index.js +0 -1
  267. package/dist/src/commands/tag/index.js +0 -9
  268. package/dist/src/commands/tag/tag.js +0 -215
  269. package/dist/src/commands/tasks/index.js +0 -8
  270. package/dist/src/commands/tasks/tasks.js +0 -5
  271. package/dist/src/commands/telegram/index.js +0 -9
  272. package/dist/src/commands/telegram/telegram.js +0 -118
  273. package/dist/src/commands/teleport/index.js +0 -1
  274. package/dist/src/commands/terminalSetup/index.js +0 -18
  275. package/dist/src/commands/terminalSetup/terminalSetup.js +0 -491
  276. package/dist/src/commands/theme/index.js +0 -7
  277. package/dist/src/commands/theme/theme.js +0 -50
  278. package/dist/src/commands/thinkback/index.js +0 -9
  279. package/dist/src/commands/thinkback/thinkback.js +0 -527
  280. package/dist/src/commands/thinkback-play/index.js +0 -13
  281. package/dist/src/commands/thinkback-play/thinkback-play.js +0 -34
  282. package/dist/src/commands/ultraplan.js +0 -418
  283. package/dist/src/commands/upgrade/index.js +0 -12
  284. package/dist/src/commands/upgrade/upgrade.js +0 -37
  285. package/dist/src/commands/usage/index.js +0 -7
  286. package/dist/src/commands/usage/usage.js +0 -5
  287. package/dist/src/commands/version.js +0 -18
  288. package/dist/src/commands/vim/index.js +0 -8
  289. package/dist/src/commands/vim/vim.js +0 -25
  290. package/dist/src/commands/voice/index.js +0 -14
  291. package/dist/src/commands/voice/voice.js +0 -130
  292. package/dist/src/commands/whatsapp/index.js +0 -9
  293. package/dist/src/commands/whatsapp/whatsapp.js +0 -326
  294. package/dist/src/commands.js +0 -646
  295. package/dist/src/components/AgentProgressLine.js +0 -111
  296. package/dist/src/components/App.js +0 -45
  297. package/dist/src/components/ApproveApiKey.js +0 -124
  298. package/dist/src/components/AutoModeOptInDialog.js +0 -140
  299. package/dist/src/components/AutoUpdater.js +0 -157
  300. package/dist/src/components/AutoUpdaterWrapper.js +0 -78
  301. package/dist/src/components/AwsAuthStatusBox.js +0 -88
  302. package/dist/src/components/BaseTextInput.js +0 -105
  303. package/dist/src/components/BashModeProgress.js +0 -48
  304. package/dist/src/components/BridgeDialog.js +0 -414
  305. package/dist/src/components/BypassPermissionsModeDialog.js +0 -87
  306. package/dist/src/components/ChannelDowngradeDialog.js +0 -100
  307. package/dist/src/components/ClaudeCodeHint/PluginHintMenu.js +0 -37
  308. package/dist/src/components/ClaudeInChromeOnboarding.js +0 -126
  309. package/dist/src/components/ClaudeMdExternalIncludesDialog.js +0 -137
  310. package/dist/src/components/ClickableImageRef.js +0 -64
  311. package/dist/src/components/CompactSummary.js +0 -119
  312. package/dist/src/components/ConfigurableShortcutHint.js +0 -34
  313. package/dist/src/components/ConsoleOAuthFlow.js +0 -756
  314. package/dist/src/components/ContextSuggestions.js +0 -43
  315. package/dist/src/components/ContextVisualization.js +0 -483
  316. package/dist/src/components/CoordinatorAgentStatus.js +0 -261
  317. package/dist/src/components/CostThresholdDialog.js +0 -48
  318. package/dist/src/components/CtrlOToExpand.js +0 -50
  319. package/dist/src/components/CustomSelect/SelectMulti.js +0 -149
  320. package/dist/src/components/CustomSelect/index.js +0 -2
  321. package/dist/src/components/CustomSelect/option-map.js +0 -32
  322. package/dist/src/components/CustomSelect/select-input-option.js +0 -426
  323. package/dist/src/components/CustomSelect/select-option.js +0 -23
  324. package/dist/src/components/CustomSelect/select.js +0 -518
  325. package/dist/src/components/CustomSelect/use-multi-select-state.js +0 -214
  326. package/dist/src/components/CustomSelect/use-select-input.js +0 -170
  327. package/dist/src/components/CustomSelect/use-select-navigation.js +0 -366
  328. package/dist/src/components/CustomSelect/use-select-state.js +0 -22
  329. package/dist/src/components/DesktopHandoff.js +0 -195
  330. package/dist/src/components/DesktopUpsell/DesktopUpsellStartup.js +0 -173
  331. package/dist/src/components/DevBar.js +0 -50
  332. package/dist/src/components/DevChannelsDialog.js +0 -103
  333. package/dist/src/components/DiagnosticsDisplay.js +0 -91
  334. package/dist/src/components/EffortCallout.js +0 -264
  335. package/dist/src/components/EffortIndicator.js +0 -29
  336. package/dist/src/components/ExitFlow.js +0 -40
  337. package/dist/src/components/ExportDialog.js +0 -101
  338. package/dist/src/components/FallbackToolUseErrorMessage.js +0 -115
  339. package/dist/src/components/FallbackToolUseRejectedMessage.js +0 -16
  340. package/dist/src/components/FastIcon.js +0 -42
  341. package/dist/src/components/Feedback.js +0 -439
  342. package/dist/src/components/FeedbackSurvey/FeedbackSurvey.js +0 -150
  343. package/dist/src/components/FeedbackSurvey/FeedbackSurveyView.js +0 -103
  344. package/dist/src/components/FeedbackSurvey/TranscriptSharePrompt.js +0 -83
  345. package/dist/src/components/FeedbackSurvey/submitTranscriptShare.js +0 -75
  346. package/dist/src/components/FeedbackSurvey/useDebouncedDigitInput.js +0 -51
  347. package/dist/src/components/FeedbackSurvey/useFeedbackSurvey.js +0 -258
  348. package/dist/src/components/FeedbackSurvey/useMemorySurvey.js +0 -191
  349. package/dist/src/components/FeedbackSurvey/usePostCompactSurvey.js +0 -202
  350. package/dist/src/components/FeedbackSurvey/useSurveyState.js +0 -80
  351. package/dist/src/components/FileEditToolDiff.js +0 -166
  352. package/dist/src/components/FileEditToolUpdatedMessage.js +0 -111
  353. package/dist/src/components/FileEditToolUseRejectedMessage.js +0 -157
  354. package/dist/src/components/FilePathLink.js +0 -34
  355. package/dist/src/components/FullscreenLayout.js +0 -578
  356. package/dist/src/components/GlobalSearchDialog.js +0 -339
  357. package/dist/src/components/HelpV2/Commands.js +0 -65
  358. package/dist/src/components/HelpV2/General.js +0 -24
  359. package/dist/src/components/HelpV2/HelpV2.js +0 -186
  360. package/dist/src/components/HighlightedCode/Fallback.js +0 -193
  361. package/dist/src/components/HighlightedCode.js +0 -184
  362. package/dist/src/components/HistorySearchDialog.js +0 -92
  363. package/dist/src/components/IdeAutoConnectDialog.js +0 -153
  364. package/dist/src/components/IdeOnboardingDialog.js +0 -174
  365. package/dist/src/components/IdeStatusIndicator.js +0 -49
  366. package/dist/src/components/IdleReturnDialog.js +0 -116
  367. package/dist/src/components/InterruptedByUser.js +0 -15
  368. package/dist/src/components/InvalidConfigDialog.js +0 -134
  369. package/dist/src/components/InvalidSettingsDialog.js +0 -84
  370. package/dist/src/components/KeybindingWarnings.js +0 -54
  371. package/dist/src/components/LanguagePicker.js +0 -84
  372. package/dist/src/components/LogSelector.js +0 -1579
  373. package/dist/src/components/LogoV2/AnimatedAsterisk.js +0 -42
  374. package/dist/src/components/LogoV2/AnimatedClawd.js +0 -111
  375. package/dist/src/components/LogoV2/ChannelsNotice.js +0 -258
  376. package/dist/src/components/LogoV2/Clawd.js +0 -5
  377. package/dist/src/components/LogoV2/CondensedLogo.js +0 -159
  378. package/dist/src/components/LogoV2/EmergencyTip.js +0 -47
  379. package/dist/src/components/LogoV2/Feed.js +0 -84
  380. package/dist/src/components/LogoV2/FeedColumn.js +0 -55
  381. package/dist/src/components/LogoV2/GuestPassesUpsell.js +0 -71
  382. package/dist/src/components/LogoV2/LogoV2.js +0 -565
  383. package/dist/src/components/LogoV2/Opus1mMergeNotice.js +0 -56
  384. package/dist/src/components/LogoV2/OverageCreditUpsell.js +0 -160
  385. package/dist/src/components/LogoV2/VoiceModeNotice.js +0 -70
  386. package/dist/src/components/LogoV2/WelcomeV2.js +0 -461
  387. package/dist/src/components/LogoV2/feedConfigs.js +0 -78
  388. package/dist/src/components/LspRecommendation/LspRecommendationMenu.js +0 -46
  389. package/dist/src/components/MCPServerApprovalDialog.js +0 -113
  390. package/dist/src/components/MCPServerDesktopImportDialog.js +0 -206
  391. package/dist/src/components/MCPServerDialogCopy.js +0 -15
  392. package/dist/src/components/MCPServerMultiselectDialog.js +0 -133
  393. package/dist/src/components/ManagedSettingsSecurityDialog/ManagedSettingsSecurityDialog.js +0 -149
  394. package/dist/src/components/ManagedSettingsSecurityDialog/utils.js +0 -105
  395. package/dist/src/components/Markdown.js +0 -217
  396. package/dist/src/components/MarkdownTable.js +0 -279
  397. package/dist/src/components/MemoryUsageIndicator.js +0 -27
  398. package/dist/src/components/Message.js +0 -566
  399. package/dist/src/components/MessageModel.js +0 -36
  400. package/dist/src/components/MessageResponse.js +0 -73
  401. package/dist/src/components/MessageRow.js +0 -346
  402. package/dist/src/components/MessageSelector.js +0 -743
  403. package/dist/src/components/MessageTimestamp.js +0 -57
  404. package/dist/src/components/Messages.js +0 -637
  405. package/dist/src/components/ModelPicker.js +0 -484
  406. package/dist/src/components/NativeAutoUpdater.js +0 -153
  407. package/dist/src/components/NotebookEditToolUseRejectedMessage.js +0 -83
  408. package/dist/src/components/OffscreenFreeze.js +0 -35
  409. package/dist/src/components/Onboarding.js +0 -174
  410. package/dist/src/components/OutputStylePicker.js +0 -102
  411. package/dist/src/components/PackageManagerAutoUpdater.js +0 -100
  412. package/dist/src/components/Passes/Passes.js +0 -113
  413. package/dist/src/components/PrBadge.js +0 -90
  414. package/dist/src/components/PressEnterToContinue.js +0 -15
  415. package/dist/src/components/PromptInput/HistorySearchInput.js +0 -44
  416. package/dist/src/components/PromptInput/IssueFlagBanner.js +0 -8
  417. package/dist/src/components/PromptInput/Notifications.js +0 -221
  418. package/dist/src/components/PromptInput/PromptInput.js +0 -1998
  419. package/dist/src/components/PromptInput/PromptInputFooter.js +0 -84
  420. package/dist/src/components/PromptInput/PromptInputFooterLeftSide.js +0 -409
  421. package/dist/src/components/PromptInput/PromptInputFooterSuggestions.js +0 -280
  422. package/dist/src/components/PromptInput/PromptInputHelpMenu.js +0 -379
  423. package/dist/src/components/PromptInput/PromptInputModeIndicator.js +0 -72
  424. package/dist/src/components/PromptInput/PromptInputQueuedCommands.js +0 -105
  425. package/dist/src/components/PromptInput/PromptInputStashNotice.js +0 -20
  426. package/dist/src/components/PromptInput/SandboxPromptFooterHint.js +0 -65
  427. package/dist/src/components/PromptInput/ShimmeredInput.js +0 -132
  428. package/dist/src/components/PromptInput/VoiceIndicator.js +0 -136
  429. package/dist/src/components/PromptInput/inputModes.js +0 -24
  430. package/dist/src/components/PromptInput/inputPaste.js +0 -62
  431. package/dist/src/components/PromptInput/useMaybeTruncateInput.js +0 -33
  432. package/dist/src/components/PromptInput/usePromptInputPlaceholder.js +0 -55
  433. package/dist/src/components/PromptInput/useShowFastIconHint.js +0 -23
  434. package/dist/src/components/PromptInput/useSwarmBanner.js +0 -112
  435. package/dist/src/components/PromptInput/utils.js +0 -50
  436. package/dist/src/components/QuickOpenDialog.js +0 -243
  437. package/dist/src/components/RemoteCallout.js +0 -53
  438. package/dist/src/components/RemoteEnvironmentDialog.js +0 -345
  439. package/dist/src/components/ResumeTask.js +0 -173
  440. package/dist/src/components/SandboxViolationExpandedView.js +0 -102
  441. package/dist/src/components/ScrollKeybindingHandler.js +0 -982
  442. package/dist/src/components/SearchBox.js +0 -55
  443. package/dist/src/components/SentryErrorBoundary.js +0 -16
  444. package/dist/src/components/SessionBackgroundHint.js +0 -104
  445. package/dist/src/components/SessionPreview.js +0 -200
  446. package/dist/src/components/Settings/Config.js +0 -1628
  447. package/dist/src/components/Settings/Settings.js +0 -129
  448. package/dist/src/components/Settings/Status.js +0 -230
  449. package/dist/src/components/Settings/Usage.js +0 -341
  450. package/dist/src/components/ShowInIDEPrompt.js +0 -151
  451. package/dist/src/components/SkillImprovementSurvey.js +0 -130
  452. package/dist/src/components/Spinner/FlashingChar.js +0 -51
  453. package/dist/src/components/Spinner/GlimmerMessage.js +0 -328
  454. package/dist/src/components/Spinner/ShimmerChar.js +0 -22
  455. package/dist/src/components/Spinner/SpinnerAnimationRow.js +0 -169
  456. package/dist/src/components/Spinner/SpinnerGlyph.js +0 -69
  457. package/dist/src/components/Spinner/TeammateSpinnerLine.js +0 -170
  458. package/dist/src/components/Spinner/TeammateSpinnerTree.js +0 -268
  459. package/dist/src/components/Spinner/index.js +0 -11
  460. package/dist/src/components/Spinner/teammateSelectHint.js +0 -1
  461. package/dist/src/components/Spinner/useShimmerAnimation.js +0 -22
  462. package/dist/src/components/Spinner/useStalledAnimation.js +0 -63
  463. package/dist/src/components/Spinner/utils.js +0 -77
  464. package/dist/src/components/Spinner.js +0 -470
  465. package/dist/src/components/Stats.js +0 -1000
  466. package/dist/src/components/StatusLine.js +0 -285
  467. package/dist/src/components/StatusNotices.js +0 -50
  468. package/dist/src/components/StructuredDiff/Fallback.js +0 -335
  469. package/dist/src/components/StructuredDiff/colorDiff.js +0 -26
  470. package/dist/src/components/StructuredDiff.js +0 -152
  471. package/dist/src/components/StructuredDiffList.js +0 -8
  472. package/dist/src/components/TagTabs.js +0 -100
  473. package/dist/src/components/TaskListV2.js +0 -333
  474. package/dist/src/components/TeammateViewHeader.js +0 -87
  475. package/dist/src/components/TeleportError.js +0 -191
  476. package/dist/src/components/TeleportProgress.js +0 -130
  477. package/dist/src/components/TeleportRepoMismatchDialog.js +0 -98
  478. package/dist/src/components/TeleportResumeWrapper.js +0 -158
  479. package/dist/src/components/TeleportStash.js +0 -82
  480. package/dist/src/components/TextInput.js +0 -108
  481. package/dist/src/components/ThemePicker.js +0 -330
  482. package/dist/src/components/ThinkingToggle.js +0 -153
  483. package/dist/src/components/TokenWarning.js +0 -172
  484. package/dist/src/components/ToolUseLoader.js +0 -34
  485. package/dist/src/components/TrustDialog/TrustDialog.js +0 -301
  486. package/dist/src/components/TrustDialog/utils.js +0 -199
  487. package/dist/src/components/ValidationErrorsList.js +0 -146
  488. package/dist/src/components/VimTextInput.js +0 -136
  489. package/dist/src/components/VirtualMessageList.js +0 -892
  490. package/dist/src/components/WorkflowMultiselectDialog.js +0 -118
  491. package/dist/src/components/WorktreeExitDialog.js +0 -222
  492. package/dist/src/components/agents/AgentDetail.js +0 -226
  493. package/dist/src/components/agents/AgentEditor.js +0 -146
  494. package/dist/src/components/agents/AgentNavigationFooter.js +0 -21
  495. package/dist/src/components/agents/AgentsList.js +0 -436
  496. package/dist/src/components/agents/AgentsMenu.js +0 -848
  497. package/dist/src/components/agents/ColorPicker.js +0 -110
  498. package/dist/src/components/agents/ModelSelector.js +0 -62
  499. package/dist/src/components/agents/SnapshotUpdateDialog.js +0 -16
  500. package/dist/src/components/agents/ToolSelector.js +0 -557
  501. package/dist/src/components/agents/agentFileUtils.js +0 -179
  502. package/dist/src/components/agents/generateAgent.js +0 -161
  503. package/dist/src/components/agents/new-agent-creation/CreateAgentWizard.js +0 -88
  504. package/dist/src/components/agents/new-agent-creation/wizard-steps/ColorStep.js +0 -80
  505. package/dist/src/components/agents/new-agent-creation/wizard-steps/ConfirmStep.js +0 -386
  506. package/dist/src/components/agents/new-agent-creation/wizard-steps/ConfirmStepWrapper.js +0 -63
  507. package/dist/src/components/agents/new-agent-creation/wizard-steps/DescriptionStep.js +0 -126
  508. package/dist/src/components/agents/new-agent-creation/wizard-steps/GenerateStep.js +0 -118
  509. package/dist/src/components/agents/new-agent-creation/wizard-steps/LocationStep.js +0 -79
  510. package/dist/src/components/agents/new-agent-creation/wizard-steps/MemoryStep.js +0 -107
  511. package/dist/src/components/agents/new-agent-creation/wizard-steps/MethodStep.js +0 -79
  512. package/dist/src/components/agents/new-agent-creation/wizard-steps/ModelStep.js +0 -48
  513. package/dist/src/components/agents/new-agent-creation/wizard-steps/PromptStep.js +0 -131
  514. package/dist/src/components/agents/new-agent-creation/wizard-steps/ToolsStep.js +0 -51
  515. package/dist/src/components/agents/new-agent-creation/wizard-steps/TypeStep.js +0 -100
  516. package/dist/src/components/agents/types.js +0 -4
  517. package/dist/src/components/agents/utils.js +0 -14
  518. package/dist/src/components/agents/validateAgent.js +0 -79
  519. package/dist/src/components/design-system/Byline.js +0 -72
  520. package/dist/src/components/design-system/Dialog.js +0 -116
  521. package/dist/src/components/design-system/Divider.js +0 -109
  522. package/dist/src/components/design-system/FuzzyPicker.js +0 -187
  523. package/dist/src/components/design-system/KeyboardShortcutHint.js +0 -67
  524. package/dist/src/components/design-system/ListItem.js +0 -183
  525. package/dist/src/components/design-system/LoadingState.js +0 -68
  526. package/dist/src/components/design-system/Pane.js +0 -68
  527. package/dist/src/components/design-system/ProgressBar.js +0 -62
  528. package/dist/src/components/design-system/Ratchet.js +0 -71
  529. package/dist/src/components/design-system/StatusIcon.js +0 -69
  530. package/dist/src/components/design-system/Tabs.js +0 -269
  531. package/dist/src/components/design-system/ThemeProvider.js +0 -137
  532. package/dist/src/components/design-system/ThemedBox.js +0 -125
  533. package/dist/src/components/design-system/ThemedText.js +0 -60
  534. package/dist/src/components/design-system/color.js +0 -22
  535. package/dist/src/components/diff/DiffDetailView.js +0 -284
  536. package/dist/src/components/diff/DiffDialog.js +0 -387
  537. package/dist/src/components/diff/DiffFileList.js +0 -291
  538. package/dist/src/components/grove/Grove.js +0 -483
  539. package/dist/src/components/hooks/HooksConfigMenu.js +0 -570
  540. package/dist/src/components/hooks/PromptDialog.js +0 -81
  541. package/dist/src/components/hooks/SelectEventMode.js +0 -117
  542. package/dist/src/components/hooks/SelectHookMode.js +0 -93
  543. package/dist/src/components/hooks/SelectMatcherMode.js +0 -124
  544. package/dist/src/components/hooks/ViewHookMode.js +0 -197
  545. package/dist/src/components/mcp/CapabilitiesSection.js +0 -55
  546. package/dist/src/components/mcp/ElicitationDialog.js +0 -945
  547. package/dist/src/components/mcp/MCPAgentServerMenu.js +0 -95
  548. package/dist/src/components/mcp/MCPListPanel.js +0 -504
  549. package/dist/src/components/mcp/MCPReconnect.js +0 -168
  550. package/dist/src/components/mcp/MCPRemoteServerMenu.js +0 -460
  551. package/dist/src/components/mcp/MCPSettings.js +0 -414
  552. package/dist/src/components/mcp/MCPStdioServerMenu.js +0 -95
  553. package/dist/src/components/mcp/MCPToolDetailView.js +0 -219
  554. package/dist/src/components/mcp/MCPToolListView.js +0 -136
  555. package/dist/src/components/mcp/McpParsingWarnings.js +0 -211
  556. package/dist/src/components/mcp/index.js +0 -8
  557. package/dist/src/components/mcp/types.js +0 -3
  558. package/dist/src/components/mcp/utils/reconnectHelpers.js +0 -35
  559. package/dist/src/components/memory/MemoryFileSelector.js +0 -455
  560. package/dist/src/components/memory/MemoryUpdateNotification.js +0 -42
  561. package/dist/src/components/messageActions.js +0 -418
  562. package/dist/src/components/messages/AdvisorMessage.js +0 -151
  563. package/dist/src/components/messages/AssistantRedactedThinkingMessage.js +0 -27
  564. package/dist/src/components/messages/AssistantTextMessage.js +0 -274
  565. package/dist/src/components/messages/AssistantThinkingMessage.js +0 -69
  566. package/dist/src/components/messages/AssistantToolUseMessage.js +0 -323
  567. package/dist/src/components/messages/AttachmentMessage.js +0 -418
  568. package/dist/src/components/messages/CollapsedReadSearchContent.js +0 -362
  569. package/dist/src/components/messages/CompactBoundaryMessage.js +0 -18
  570. package/dist/src/components/messages/GroupedToolUseContent.js +0 -37
  571. package/dist/src/components/messages/HighlightedThinkingText.js +0 -164
  572. package/dist/src/components/messages/HookProgressMessage.js +0 -110
  573. package/dist/src/components/messages/PlanApprovalMessage.js +0 -212
  574. package/dist/src/components/messages/RateLimitMessage.js +0 -149
  575. package/dist/src/components/messages/ShutdownMessage.js +0 -123
  576. package/dist/src/components/messages/SystemAPIErrorMessage.js +0 -135
  577. package/dist/src/components/messages/SystemTextMessage.js +0 -843
  578. package/dist/src/components/messages/TaskAssignmentMessage.js +0 -71
  579. package/dist/src/components/messages/UserAgentNotificationMessage.js +0 -77
  580. package/dist/src/components/messages/UserBashInputMessage.js +0 -51
  581. package/dist/src/components/messages/UserBashOutputMessage.js +0 -54
  582. package/dist/src/components/messages/UserChannelMessage.js +0 -129
  583. package/dist/src/components/messages/UserCommandMessage.js +0 -106
  584. package/dist/src/components/messages/UserImageMessage.js +0 -53
  585. package/dist/src/components/messages/UserLocalCommandOutputMessage.js +0 -169
  586. package/dist/src/components/messages/UserMemoryInputMessage.js +0 -72
  587. package/dist/src/components/messages/UserPlanMessage.js +0 -37
  588. package/dist/src/components/messages/UserPromptMessage.js +0 -63
  589. package/dist/src/components/messages/UserResourceUpdateMessage.js +0 -101
  590. package/dist/src/components/messages/UserTeammateMessage.js +0 -156
  591. package/dist/src/components/messages/UserTextMessage.js +0 -271
  592. package/dist/src/components/messages/UserToolResultMessage/RejectedPlanMessage.js +0 -27
  593. package/dist/src/components/messages/UserToolResultMessage/RejectedToolUseMessage.js +0 -16
  594. package/dist/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.js +0 -16
  595. package/dist/src/components/messages/UserToolResultMessage/UserToolErrorMessage.js +0 -91
  596. package/dist/src/components/messages/UserToolResultMessage/UserToolRejectMessage.js +0 -73
  597. package/dist/src/components/messages/UserToolResultMessage/UserToolResultMessage.js +0 -83
  598. package/dist/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.js +0 -58
  599. package/dist/src/components/messages/UserToolResultMessage/utils.js +0 -43
  600. package/dist/src/components/messages/nullRenderingAttachments.js +0 -58
  601. package/dist/src/components/messages/teamMemCollapsed.js +0 -142
  602. package/dist/src/components/messages/teamMemSaved.js +0 -17
  603. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/AskUserQuestionPermissionRequest.js +0 -654
  604. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/PreviewBox.js +0 -219
  605. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/PreviewQuestionView.js +0 -227
  606. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/QuestionNavigationBar.js +0 -174
  607. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/QuestionView.js +0 -444
  608. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/SubmitQuestionsView.js +0 -136
  609. package/dist/src/components/permissions/AskUserQuestionPermissionRequest/use-multiple-choice-state.js +0 -100
  610. package/dist/src/components/permissions/BashPermissionRequest/BashPermissionRequest.js +0 -404
  611. package/dist/src/components/permissions/BashPermissionRequest/bashToolUseOptions.js +0 -110
  612. package/dist/src/components/permissions/ComputerUseApproval/ComputerUseApproval.js +0 -448
  613. package/dist/src/components/permissions/EnterPlanModePermissionRequest/EnterPlanModePermissionRequest.js +0 -125
  614. package/dist/src/components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js +0 -650
  615. package/dist/src/components/permissions/FallbackPermissionRequest.js +0 -348
  616. package/dist/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.js +0 -184
  617. package/dist/src/components/permissions/FilePermissionDialog/FilePermissionDialog.js +0 -108
  618. package/dist/src/components/permissions/FilePermissionDialog/ideDiffConfig.js +0 -13
  619. package/dist/src/components/permissions/FilePermissionDialog/permissionOptions.js +0 -136
  620. package/dist/src/components/permissions/FilePermissionDialog/useFilePermissionDialog.js +0 -131
  621. package/dist/src/components/permissions/FilePermissionDialog/usePermissionHandler.js +0 -86
  622. package/dist/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.js +0 -163
  623. package/dist/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.js +0 -78
  624. package/dist/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +0 -112
  625. package/dist/src/components/permissions/NotebookEditPermissionRequest/NotebookEditPermissionRequest.js +0 -163
  626. package/dist/src/components/permissions/NotebookEditPermissionRequest/NotebookEditToolDiff.js +0 -217
  627. package/dist/src/components/permissions/PermissionDecisionDebugInfo.js +0 -466
  628. package/dist/src/components/permissions/PermissionDialog.js +0 -54
  629. package/dist/src/components/permissions/PermissionExplanation.js +0 -269
  630. package/dist/src/components/permissions/PermissionPrompt.js +0 -316
  631. package/dist/src/components/permissions/PermissionRequest.js +0 -160
  632. package/dist/src/components/permissions/PermissionRequestTitle.js +0 -57
  633. package/dist/src/components/permissions/PermissionRuleExplanation.js +0 -109
  634. package/dist/src/components/permissions/PowerShellPermissionRequest/PowerShellPermissionRequest.js +0 -178
  635. package/dist/src/components/permissions/PowerShellPermissionRequest/powershellToolUseOptions.js +0 -73
  636. package/dist/src/components/permissions/SandboxPermissionRequest.js +0 -161
  637. package/dist/src/components/permissions/SedEditPermissionRequest/SedEditPermissionRequest.js +0 -228
  638. package/dist/src/components/permissions/SkillPermissionRequest/SkillPermissionRequest.js +0 -384
  639. package/dist/src/components/permissions/WebFetchPermissionRequest/WebFetchPermissionRequest.js +0 -258
  640. package/dist/src/components/permissions/WorkerBadge.js +0 -43
  641. package/dist/src/components/permissions/WorkerPendingPermission.js +0 -106
  642. package/dist/src/components/permissions/hooks.js +0 -163
  643. package/dist/src/components/permissions/rules/AddPermissionRules.js +0 -170
  644. package/dist/src/components/permissions/rules/AddWorkspaceDirectory.js +0 -334
  645. package/dist/src/components/permissions/rules/PermissionRuleDescription.js +0 -77
  646. package/dist/src/components/permissions/rules/PermissionRuleInput.js +0 -135
  647. package/dist/src/components/permissions/rules/PermissionRuleList.js +0 -1189
  648. package/dist/src/components/permissions/rules/RecentDenialsTab.js +0 -204
  649. package/dist/src/components/permissions/rules/RemoveWorkspaceDirectory.js +0 -102
  650. package/dist/src/components/permissions/rules/WorkspaceTab.js +0 -132
  651. package/dist/src/components/permissions/shellPermissionHelpers.js +0 -111
  652. package/dist/src/components/permissions/useShellPermissionFeedback.js +0 -108
  653. package/dist/src/components/permissions/utils.js +0 -14
  654. package/dist/src/components/sandbox/SandboxConfigTab.js +0 -47
  655. package/dist/src/components/sandbox/SandboxDependenciesTab.js +0 -122
  656. package/dist/src/components/sandbox/SandboxDoctorSection.js +0 -46
  657. package/dist/src/components/sandbox/SandboxOverridesTab.js +0 -192
  658. package/dist/src/components/sandbox/SandboxSettings.js +0 -296
  659. package/dist/src/components/shell/ExpandShellOutputContext.js +0 -33
  660. package/dist/src/components/shell/OutputLine.js +0 -110
  661. package/dist/src/components/shell/ShellProgressMessage.js +0 -143
  662. package/dist/src/components/shell/ShellTimeDisplay.js +0 -71
  663. package/dist/src/components/skills/SkillsMenu.js +0 -238
  664. package/dist/src/components/tasks/AsyncAgentDetailDialog.js +0 -234
  665. package/dist/src/components/tasks/BackgroundTask.js +0 -363
  666. package/dist/src/components/tasks/BackgroundTaskStatus.js +0 -419
  667. package/dist/src/components/tasks/BackgroundTasksDialog.js +0 -496
  668. package/dist/src/components/tasks/DreamDetailDialog.js +0 -250
  669. package/dist/src/components/tasks/InProcessTeammateDetailDialog.js +0 -274
  670. package/dist/src/components/tasks/RemoteSessionDetailDialog.js +0 -868
  671. package/dist/src/components/tasks/RemoteSessionProgress.js +0 -249
  672. package/dist/src/components/tasks/ShellDetailDialog.js +0 -403
  673. package/dist/src/components/tasks/ShellProgress.js +0 -76
  674. package/dist/src/components/tasks/renderToolActivity.js +0 -28
  675. package/dist/src/components/tasks/taskStatusUtils.js +0 -94
  676. package/dist/src/components/teams/TeamStatus.js +0 -76
  677. package/dist/src/components/teams/TeamsDialog.js +0 -672
  678. package/dist/src/components/ui/OrderedList.js +0 -66
  679. package/dist/src/components/ui/OrderedListItem.js +0 -41
  680. package/dist/src/components/ui/TreeSelect.js +0 -300
  681. package/dist/src/components/wizard/WizardDialogLayout.js +0 -47
  682. package/dist/src/components/wizard/WizardNavigationFooter.js +0 -10
  683. package/dist/src/components/wizard/WizardProvider.js +0 -217
  684. package/dist/src/components/wizard/index.js +0 -4
  685. package/dist/src/components/wizard/useWizard.js +0 -9
  686. package/dist/src/constants/apiLimits.js +0 -81
  687. package/dist/src/constants/betas.js +0 -45
  688. package/dist/src/constants/common.js +0 -29
  689. package/dist/src/constants/cyberRiskInstruction.js +0 -24
  690. package/dist/src/constants/errorIds.js +0 -14
  691. package/dist/src/constants/figures.js +0 -38
  692. package/dist/src/constants/files.js +0 -150
  693. package/dist/src/constants/github-app.js +0 -139
  694. package/dist/src/constants/keys.js +0 -10
  695. package/dist/src/constants/messages.js +0 -1
  696. package/dist/src/constants/oauth.js +0 -221
  697. package/dist/src/constants/outputStyles.js +0 -162
  698. package/dist/src/constants/product.js +0 -56
  699. package/dist/src/constants/prompts.js +0 -752
  700. package/dist/src/constants/spinnerVerbs.js +0 -202
  701. package/dist/src/constants/system.js +0 -77
  702. package/dist/src/constants/systemPromptSections.js +0 -39
  703. package/dist/src/constants/toolLimits.js +0 -50
  704. package/dist/src/constants/tools.js +0 -103
  705. package/dist/src/constants/turnCompletionVerbs.js +0 -12
  706. package/dist/src/constants/xml.js +0 -73
  707. package/dist/src/context/QueuedMessageContext.js +0 -51
  708. package/dist/src/context/fpsMetrics.js +0 -22
  709. package/dist/src/context/mailbox.js +0 -35
  710. package/dist/src/context/modalContext.js +0 -34
  711. package/dist/src/context/notifications.js +0 -199
  712. package/dist/src/context/overlayContext.js +0 -149
  713. package/dist/src/context/promptOverlayContext.js +0 -118
  714. package/dist/src/context/stats.js +0 -207
  715. package/dist/src/context/voice.js +0 -74
  716. package/dist/src/context.js +0 -146
  717. package/dist/src/coordinator/coordinatorMode.js +0 -345
  718. package/dist/src/cost-tracker.js +0 -208
  719. package/dist/src/costHook.js +0 -17
  720. package/dist/src/daemon/main.js +0 -16
  721. package/dist/src/daemon/workerRegistry.js +0 -16
  722. package/dist/src/dialogLaunchers.js +0 -68
  723. package/dist/src/entrypoints/agentSdkTypes.js +0 -202
  724. package/dist/src/entrypoints/cli.js +0 -237
  725. package/dist/src/entrypoints/init.js +0 -265
  726. package/dist/src/entrypoints/mcp.js +0 -142
  727. package/dist/src/entrypoints/sandboxTypes.js +0 -112
  728. package/dist/src/entrypoints/sdk/controlSchemas.js +0 -452
  729. package/dist/src/entrypoints/sdk/controlTypes.js +0 -1
  730. package/dist/src/entrypoints/sdk/coreSchemas.js +0 -1331
  731. package/dist/src/entrypoints/sdk/coreTypes.generated.js +0 -1
  732. package/dist/src/entrypoints/sdk/coreTypes.js +0 -49
  733. package/dist/src/entrypoints/sdk/runtimeTypes.js +0 -1
  734. package/dist/src/entrypoints/sdk/toolTypes.js +0 -1
  735. package/dist/src/environment-runner/main.js +0 -16
  736. package/dist/src/history.js +0 -386
  737. package/dist/src/hooks/fileSuggestions.js +0 -635
  738. package/dist/src/hooks/notifs/useAutoModeUnavailableNotification.js +0 -47
  739. package/dist/src/hooks/notifs/useCanSwitchToExistingSubscription.js +0 -57
  740. package/dist/src/hooks/notifs/useDeprecationWarningNotification.js +0 -43
  741. package/dist/src/hooks/notifs/useFastModeNotification.js +0 -164
  742. package/dist/src/hooks/notifs/useIDEStatusIndicator.js +0 -174
  743. package/dist/src/hooks/notifs/useInstallMessages.js +0 -27
  744. package/dist/src/hooks/notifs/useLspInitializationNotification.js +0 -144
  745. package/dist/src/hooks/notifs/useMcpConnectivityStatus.js +0 -80
  746. package/dist/src/hooks/notifs/useModelMigrationNotifications.js +0 -53
  747. package/dist/src/hooks/notifs/useNpmDeprecationNotification.js +0 -24
  748. package/dist/src/hooks/notifs/usePluginAutoupdateNotification.js +0 -82
  749. package/dist/src/hooks/notifs/usePluginInstallationStatus.js +0 -127
  750. package/dist/src/hooks/notifs/useRateLimitWarningNotification.js +0 -118
  751. package/dist/src/hooks/notifs/useSettingsErrors.js +0 -64
  752. package/dist/src/hooks/notifs/useStartupNotification.js +0 -33
  753. package/dist/src/hooks/notifs/useTeammateShutdownNotification.js +0 -64
  754. package/dist/src/hooks/renderPlaceholder.js +0 -26
  755. package/dist/src/hooks/toolPermission/PermissionContext.js +0 -211
  756. package/dist/src/hooks/toolPermission/handlers/coordinatorHandler.js +0 -44
  757. package/dist/src/hooks/toolPermission/handlers/interactiveHandler.js +0 -397
  758. package/dist/src/hooks/toolPermission/handlers/swarmWorkerHandler.js +0 -108
  759. package/dist/src/hooks/toolPermission/permissionLogging.js +0 -145
  760. package/dist/src/hooks/unifiedSuggestions.js +0 -130
  761. package/dist/src/hooks/useAfterFirstRender.js +0 -12
  762. package/dist/src/hooks/useApiKeyVerification.js +0 -63
  763. package/dist/src/hooks/useArrowKeyHistory.js +0 -203
  764. package/dist/src/hooks/useAssistantHistory.js +0 -194
  765. package/dist/src/hooks/useAwaySummary.js +0 -105
  766. package/dist/src/hooks/useBackgroundTaskNavigation.js +0 -204
  767. package/dist/src/hooks/useBlink.js +0 -28
  768. package/dist/src/hooks/useCanUseTool.js +0 -192
  769. package/dist/src/hooks/useCancelRequest.js +0 -195
  770. package/dist/src/hooks/useChromeExtensionNotification.js +0 -49
  771. package/dist/src/hooks/useClaudeCodeHintRecommendation.js +0 -117
  772. package/dist/src/hooks/useClipboardImageHint.js +0 -59
  773. package/dist/src/hooks/useCommandKeybindings.js +0 -87
  774. package/dist/src/hooks/useCommandQueue.js +0 -10
  775. package/dist/src/hooks/useCopyOnSelect.js +0 -88
  776. package/dist/src/hooks/useDeferredHookMessages.js +0 -43
  777. package/dist/src/hooks/useDiffData.js +0 -69
  778. package/dist/src/hooks/useDiffInIDE.js +0 -252
  779. package/dist/src/hooks/useDirectConnect.js +0 -150
  780. package/dist/src/hooks/useDoublePress.js +0 -44
  781. package/dist/src/hooks/useDynamicConfig.js +0 -17
  782. package/dist/src/hooks/useElapsedTime.js +0 -25
  783. package/dist/src/hooks/useExitOnCtrlCD.js +0 -57
  784. package/dist/src/hooks/useExitOnCtrlCDWithKeybindings.js +0 -17
  785. package/dist/src/hooks/useFileHistorySnapshotInit.js +0 -14
  786. package/dist/src/hooks/useGlobalKeybindings.js +0 -215
  787. package/dist/src/hooks/useHistorySearch.js +0 -241
  788. package/dist/src/hooks/useIDEIntegration.js +0 -56
  789. package/dist/src/hooks/useIdeAtMentioned.js +0 -51
  790. package/dist/src/hooks/useIdeConnectionStatus.js +0 -21
  791. package/dist/src/hooks/useIdeLogging.js +0 -29
  792. package/dist/src/hooks/useIdeSelection.js +0 -106
  793. package/dist/src/hooks/useInboxPoller.js +0 -709
  794. package/dist/src/hooks/useInputBuffer.js +0 -73
  795. package/dist/src/hooks/useIssueFlagBanner.js +0 -115
  796. package/dist/src/hooks/useLogMessages.js +0 -98
  797. package/dist/src/hooks/useLspPluginRecommendation.js +0 -176
  798. package/dist/src/hooks/useMailboxBridge.js +0 -15
  799. package/dist/src/hooks/useMainLoopModel.js +0 -25
  800. package/dist/src/hooks/useManagePlugins.js +0 -261
  801. package/dist/src/hooks/useMemoryUsage.js +0 -28
  802. package/dist/src/hooks/useMergedClients.js +0 -11
  803. package/dist/src/hooks/useMergedCommands.js +0 -10
  804. package/dist/src/hooks/useMergedTools.js +0 -32
  805. package/dist/src/hooks/useMinDisplayTime.js +0 -26
  806. package/dist/src/hooks/useNotifyAfterTimeout.js +0 -51
  807. package/dist/src/hooks/useOfficialMarketplaceNotification.js +0 -46
  808. package/dist/src/hooks/usePasteHandler.js +0 -188
  809. package/dist/src/hooks/usePluginRecommendationBase.js +0 -101
  810. package/dist/src/hooks/usePrStatus.js +0 -91
  811. package/dist/src/hooks/usePromptSuggestion.js +0 -128
  812. package/dist/src/hooks/usePromptsFromClaudeInChrome.js +0 -66
  813. package/dist/src/hooks/useQueueProcessor.js +0 -46
  814. package/dist/src/hooks/useRemoteSession.js +0 -431
  815. package/dist/src/hooks/useReplBridge.js +0 -717
  816. package/dist/src/hooks/useSSHSession.js +0 -167
  817. package/dist/src/hooks/useScheduledTasks.js +0 -104
  818. package/dist/src/hooks/useSearchInput.js +0 -302
  819. package/dist/src/hooks/useSessionBackgrounding.js +0 -132
  820. package/dist/src/hooks/useSettings.js +0 -10
  821. package/dist/src/hooks/useSettingsChange.js +0 -13
  822. package/dist/src/hooks/useSkillImprovementSurvey.js +0 -69
  823. package/dist/src/hooks/useSkillsChange.js +0 -51
  824. package/dist/src/hooks/useSwarmInitialization.js +0 -67
  825. package/dist/src/hooks/useSwarmPermissionPoller.js +0 -215
  826. package/dist/src/hooks/useTaskListWatcher.js +0 -157
  827. package/dist/src/hooks/useTasksV2.js +0 -220
  828. package/dist/src/hooks/useTeammateViewAutoExit.js +0 -55
  829. package/dist/src/hooks/useTelegramMirror.js +0 -47
  830. package/dist/src/hooks/useTeleportResume.js +0 -81
  831. package/dist/src/hooks/useTerminalSize.js +0 -9
  832. package/dist/src/hooks/useTextInput.js +0 -397
  833. package/dist/src/hooks/useTimeout.js +0 -10
  834. package/dist/src/hooks/useTurnDiffs.js +0 -160
  835. package/dist/src/hooks/useTypeahead.js +0 -1392
  836. package/dist/src/hooks/useUpdateNotification.js +0 -22
  837. package/dist/src/hooks/useVimInput.js +0 -232
  838. package/dist/src/hooks/useVirtualScroll.js +0 -627
  839. package/dist/src/hooks/useVoice.js +0 -954
  840. package/dist/src/hooks/useVoiceEnabled.js +0 -21
  841. package/dist/src/hooks/useVoiceIntegration.js +0 -631
  842. package/dist/src/hooks/useWhatsAppMirror.js +0 -46
  843. package/dist/src/index.js +0 -18
  844. package/dist/src/ink/Ansi.js +0 -269
  845. package/dist/src/ink/bidi.js +0 -117
  846. package/dist/src/ink/clearTerminal.js +0 -58
  847. package/dist/src/ink/colorize.js +0 -198
  848. package/dist/src/ink/components/AlternateScreen.js +0 -74
  849. package/dist/src/ink/components/App.js +0 -558
  850. package/dist/src/ink/components/AppContext.js +0 -11
  851. package/dist/src/ink/components/Box.js +0 -153
  852. package/dist/src/ink/components/Button.js +0 -166
  853. package/dist/src/ink/components/ClockContext.js +0 -108
  854. package/dist/src/ink/components/CursorDeclarationContext.js +0 -3
  855. package/dist/src/ink/components/ErrorOverview.js +0 -49
  856. package/dist/src/ink/components/Link.js +0 -33
  857. package/dist/src/ink/components/Newline.js +0 -29
  858. package/dist/src/ink/components/NoSelect.js +0 -56
  859. package/dist/src/ink/components/RawAnsi.js +0 -45
  860. package/dist/src/ink/components/ScrollBox.js +0 -170
  861. package/dist/src/ink/components/Spacer.js +0 -19
  862. package/dist/src/ink/components/StdinContext.js +0 -16
  863. package/dist/src/ink/components/TerminalFocusContext.js +0 -45
  864. package/dist/src/ink/components/TerminalSizeContext.js +0 -3
  865. package/dist/src/ink/components/Text.js +0 -194
  866. package/dist/src/ink/constants.js +0 -2
  867. package/dist/src/ink/devtools.js +0 -16
  868. package/dist/src/ink/dom.js +0 -298
  869. package/dist/src/ink/events/click-event.js +0 -36
  870. package/dist/src/ink/events/dispatcher.js +0 -172
  871. package/dist/src/ink/events/emitter.js +0 -31
  872. package/dist/src/ink/events/event-handlers.js +0 -30
  873. package/dist/src/ink/events/event.js +0 -9
  874. package/dist/src/ink/events/focus-event.js +0 -16
  875. package/dist/src/ink/events/input-event.js +0 -161
  876. package/dist/src/ink/events/keyboard-event.js +0 -45
  877. package/dist/src/ink/events/terminal-event.js +0 -78
  878. package/dist/src/ink/events/terminal-focus-event.js +0 -15
  879. package/dist/src/ink/focus.js +0 -158
  880. package/dist/src/ink/frame.js +0 -30
  881. package/dist/src/ink/get-max-width.js +0 -23
  882. package/dist/src/ink/hit-test.js +0 -113
  883. package/dist/src/ink/hooks/use-animation-frame.js +0 -48
  884. package/dist/src/ink/hooks/use-app.js +0 -7
  885. package/dist/src/ink/hooks/use-declared-cursor.js +0 -60
  886. package/dist/src/ink/hooks/use-input.js +0 -70
  887. package/dist/src/ink/hooks/use-interval.js +0 -54
  888. package/dist/src/ink/hooks/use-search-highlight.js +0 -32
  889. package/dist/src/ink/hooks/use-selection.js +0 -60
  890. package/dist/src/ink/hooks/use-stdin.js +0 -7
  891. package/dist/src/ink/hooks/use-tab-status.js +0 -57
  892. package/dist/src/ink/hooks/use-terminal-focus.js +0 -15
  893. package/dist/src/ink/hooks/use-terminal-title.js +0 -29
  894. package/dist/src/ink/hooks/use-terminal-viewport.js +0 -77
  895. package/dist/src/ink/ink.js +0 -1644
  896. package/dist/src/ink/instances.js +0 -7
  897. package/dist/src/ink/layout/engine.js +0 -4
  898. package/dist/src/ink/layout/geometry.js +0 -61
  899. package/dist/src/ink/layout/node.js +0 -62
  900. package/dist/src/ink/layout/yoga.js +0 -237
  901. package/dist/src/ink/line-width-cache.js +0 -19
  902. package/dist/src/ink/log-update.js +0 -583
  903. package/dist/src/ink/measure-element.js +0 -8
  904. package/dist/src/ink/measure-text.js +0 -35
  905. package/dist/src/ink/node-cache.js +0 -30
  906. package/dist/src/ink/optimizer.js +0 -81
  907. package/dist/src/ink/output.js +0 -556
  908. package/dist/src/ink/parse-keypress.js +0 -695
  909. package/dist/src/ink/reconciler.js +0 -384
  910. package/dist/src/ink/render-border.js +0 -134
  911. package/dist/src/ink/render-node-to-output.js +0 -1216
  912. package/dist/src/ink/render-to-screen.js +0 -171
  913. package/dist/src/ink/renderer.js +0 -129
  914. package/dist/src/ink/root.js +0 -80
  915. package/dist/src/ink/screen.js +0 -1132
  916. package/dist/src/ink/searchHighlight.js +0 -78
  917. package/dist/src/ink/selection.js +0 -792
  918. package/dist/src/ink/squash-text-nodes.js +0 -56
  919. package/dist/src/ink/stringWidth.js +0 -200
  920. package/dist/src/ink/styles.js +0 -299
  921. package/dist/src/ink/supports-hyperlinks.js +0 -40
  922. package/dist/src/ink/tabstops.js +0 -39
  923. package/dist/src/ink/terminal-focus-state.js +0 -35
  924. package/dist/src/ink/terminal-querier.js +0 -173
  925. package/dist/src/ink/terminal.js +0 -208
  926. package/dist/src/ink/termio/ansi.js +0 -70
  927. package/dist/src/ink/termio/csi.js +0 -260
  928. package/dist/src/ink/termio/dec.js +0 -53
  929. package/dist/src/ink/termio/esc.js +0 -55
  930. package/dist/src/ink/termio/osc.js +0 -432
  931. package/dist/src/ink/termio/parser.js +0 -356
  932. package/dist/src/ink/termio/sgr.js +0 -292
  933. package/dist/src/ink/termio/tokenize.js +0 -264
  934. package/dist/src/ink/termio/types.js +0 -55
  935. package/dist/src/ink/termio.js +0 -24
  936. package/dist/src/ink/useTerminalNotification.js +0 -57
  937. package/dist/src/ink/warn.js +0 -10
  938. package/dist/src/ink/widest-line.js +0 -14
  939. package/dist/src/ink/wrap-text.js +0 -54
  940. package/dist/src/ink/wrapAnsi.js +0 -6
  941. package/dist/src/ink.js +0 -50
  942. package/dist/src/interactiveHelpers.js +0 -317
  943. package/dist/src/keybindings/KeybindingContext.js +0 -184
  944. package/dist/src/keybindings/KeybindingProviderSetup.js +0 -259
  945. package/dist/src/keybindings/defaultBindings.js +0 -333
  946. package/dist/src/keybindings/loadUserBindings.js +0 -393
  947. package/dist/src/keybindings/match.js +0 -111
  948. package/dist/src/keybindings/parser.js +0 -184
  949. package/dist/src/keybindings/reservedShortcuts.js +0 -109
  950. package/dist/src/keybindings/resolver.js +0 -182
  951. package/dist/src/keybindings/schema.js +0 -205
  952. package/dist/src/keybindings/shortcutFormat.js +0 -48
  953. package/dist/src/keybindings/template.js +0 -40
  954. package/dist/src/keybindings/useKeybinding.js +0 -161
  955. package/dist/src/keybindings/useShortcutDisplay.js +0 -43
  956. package/dist/src/keybindings/validate.js +0 -395
  957. package/dist/src/main.js +0 -4073
  958. package/dist/src/memdir/findRelevantMemories.js +0 -101
  959. package/dist/src/memdir/memdir.js +0 -408
  960. package/dist/src/memdir/memoryAge.js +0 -52
  961. package/dist/src/memdir/memoryScan.js +0 -65
  962. package/dist/src/memdir/memoryTypes.js +0 -260
  963. package/dist/src/memdir/paths.js +0 -236
  964. package/dist/src/memdir/teamMemPaths.js +0 -261
  965. package/dist/src/memdir/teamMemPrompts.js +0 -82
  966. package/dist/src/migrations/migrateAutoUpdatesToSettings.js +0 -47
  967. package/dist/src/migrations/migrateBypassPermissionsAcceptedToSettings.js +0 -32
  968. package/dist/src/migrations/migrateEnableAllProjectMcpServersToSettings.js +0 -83
  969. package/dist/src/migrations/migrateFennecToOpus.js +0 -39
  970. package/dist/src/migrations/migrateLegacyOpusToCurrent.js +0 -44
  971. package/dist/src/migrations/migrateOpusToOpus1m.js +0 -31
  972. package/dist/src/migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.js +0 -23
  973. package/dist/src/migrations/migrateSonnet1mToSonnet45.js +0 -38
  974. package/dist/src/migrations/migrateSonnet45ToSonnet46.js +0 -48
  975. package/dist/src/migrations/resetAutoModeOptInForDefaultOffer.js +0 -47
  976. package/dist/src/migrations/resetProToOpusDefault.js +0 -46
  977. package/dist/src/mirrors/shared.js +0 -186
  978. package/dist/src/moreright/useMoreRight.js +0 -13
  979. package/dist/src/native-ts/color-diff/index.js +0 -821
  980. package/dist/src/native-ts/file-index/index.js +0 -328
  981. package/dist/src/native-ts/yoga-layout/enums.js +0 -101
  982. package/dist/src/native-ts/yoga-layout/index.js +0 -2113
  983. package/dist/src/outputStyles/loadOutputStylesDir.js +0 -71
  984. package/dist/src/plugins/builtinPlugins.js +0 -132
  985. package/dist/src/plugins/bundled/index.js +0 -22
  986. package/dist/src/projectOnboardingState.js +0 -61
  987. package/dist/src/query/config.js +0 -17
  988. package/dist/src/query/deps.js +0 -12
  989. package/dist/src/query/stopHooks.js +0 -334
  990. package/dist/src/query/tokenBudget.js +0 -49
  991. package/dist/src/query.js +0 -1330
  992. package/dist/src/recovery/bunBundleShim.js +0 -11
  993. package/dist/src/remote/RemoteSessionManager.js +0 -195
  994. package/dist/src/remote/SessionsWebSocket.js +0 -305
  995. package/dist/src/remote/remotePermissionBridge.js +0 -70
  996. package/dist/src/remote/sdkMessageAdapter.js +0 -227
  997. package/dist/src/replLauncher.js +0 -6
  998. package/dist/src/schemas/hooks.js +0 -174
  999. package/dist/src/screens/Doctor.js +0 -580
  1000. package/dist/src/screens/REPL.js +0 -4434
  1001. package/dist/src/screens/ResumeConversation.js +0 -341
  1002. package/dist/src/self-hosted-runner/main.js +0 -16
  1003. package/dist/src/server/backends/dangerousBackend.js +0 -16
  1004. package/dist/src/server/connectHeadless.js +0 -16
  1005. package/dist/src/server/createDirectConnectSession.js +0 -62
  1006. package/dist/src/server/directConnectManager.js +0 -153
  1007. package/dist/src/server/lockfile.js +0 -16
  1008. package/dist/src/server/parseConnectUrl.js +0 -16
  1009. package/dist/src/server/server.js +0 -16
  1010. package/dist/src/server/serverBanner.js +0 -16
  1011. package/dist/src/server/serverLog.js +0 -16
  1012. package/dist/src/server/sessionManager.js +0 -16
  1013. package/dist/src/server/types.js +0 -7
  1014. package/dist/src/services/AgentSummary/agentSummary.js +0 -147
  1015. package/dist/src/services/MagicDocs/magicDocs.js +0 -193
  1016. package/dist/src/services/MagicDocs/prompts.js +0 -110
  1017. package/dist/src/services/PromptSuggestion/promptSuggestion.js +0 -402
  1018. package/dist/src/services/PromptSuggestion/speculation.js +0 -643
  1019. package/dist/src/services/SessionMemory/prompts.js +0 -254
  1020. package/dist/src/services/SessionMemory/sessionMemory.js +0 -358
  1021. package/dist/src/services/SessionMemory/sessionMemoryUtils.js +0 -157
  1022. package/dist/src/services/analytics/config.js +0 -33
  1023. package/dist/src/services/analytics/datadog.js +0 -259
  1024. package/dist/src/services/analytics/firstPartyEventLogger.js +0 -342
  1025. package/dist/src/services/analytics/firstPartyEventLoggingExporter.js +0 -594
  1026. package/dist/src/services/analytics/growthbook.js +0 -952
  1027. package/dist/src/services/analytics/index.js +0 -114
  1028. package/dist/src/services/analytics/metadata.js +0 -698
  1029. package/dist/src/services/analytics/sink.js +0 -95
  1030. package/dist/src/services/analytics/sinkKillswitch.js +0 -19
  1031. package/dist/src/services/api/adminRequests.js +0 -57
  1032. package/dist/src/services/api/bootstrap.js +0 -149
  1033. package/dist/src/services/api/claude.js +0 -2461
  1034. package/dist/src/services/api/client.js +0 -325
  1035. package/dist/src/services/api/dumpPrompts.js +0 -174
  1036. package/dist/src/services/api/emptyUsage.js +0 -20
  1037. package/dist/src/services/api/errorUtils.js +0 -203
  1038. package/dist/src/services/api/errors.js +0 -934
  1039. package/dist/src/services/api/filesApi.js +0 -523
  1040. package/dist/src/services/api/firstTokenDate.js +0 -49
  1041. package/dist/src/services/api/grove.js +0 -272
  1042. package/dist/src/services/api/index.js +0 -23
  1043. package/dist/src/services/api/logging.js +0 -484
  1044. package/dist/src/services/api/metricsOptOut.js +0 -127
  1045. package/dist/src/services/api/openai.js +0 -1187
  1046. package/dist/src/services/api/openrouter.js +0 -30
  1047. package/dist/src/services/api/overageCreditGrant.js +0 -123
  1048. package/dist/src/services/api/promptCacheBreakDetection.js +0 -510
  1049. package/dist/src/services/api/referral.js +0 -219
  1050. package/dist/src/services/api/sessionIngress.js +0 -358
  1051. package/dist/src/services/api/ultrareviewQuota.js +0 -29
  1052. package/dist/src/services/api/usage.js +0 -31
  1053. package/dist/src/services/api/withRetry.js +0 -599
  1054. package/dist/src/services/autoDream/autoDream.js +0 -244
  1055. package/dist/src/services/autoDream/config.js +0 -17
  1056. package/dist/src/services/autoDream/consolidationLock.js +0 -122
  1057. package/dist/src/services/autoDream/consolidationPrompt.js +0 -56
  1058. package/dist/src/services/awaySummary.js +0 -61
  1059. package/dist/src/services/claudeAiLimits.js +0 -331
  1060. package/dist/src/services/claudeAiLimitsHook.js +0 -15
  1061. package/dist/src/services/compact/apiMicrocompact.js +0 -97
  1062. package/dist/src/services/compact/autoCompact.js +0 -236
  1063. package/dist/src/services/compact/cachedMicrocompact.js +0 -16
  1064. package/dist/src/services/compact/compact.js +0 -1258
  1065. package/dist/src/services/compact/compactWarningHook.js +0 -12
  1066. package/dist/src/services/compact/compactWarningState.js +0 -15
  1067. package/dist/src/services/compact/grouping.js +0 -58
  1068. package/dist/src/services/compact/microCompact.js +0 -414
  1069. package/dist/src/services/compact/postCompactCleanup.js +0 -72
  1070. package/dist/src/services/compact/prompt.js +0 -327
  1071. package/dist/src/services/compact/sessionMemoryCompact.js +0 -467
  1072. package/dist/src/services/compact/timeBasedMCConfig.js +0 -11
  1073. package/dist/src/services/diagnosticTracking.js +0 -282
  1074. package/dist/src/services/extractMemories/extractMemories.js +0 -444
  1075. package/dist/src/services/extractMemories/prompts.js +0 -129
  1076. package/dist/src/services/internalLogging.js +0 -68
  1077. package/dist/src/services/lsp/LSPClient.js +0 -306
  1078. package/dist/src/services/lsp/LSPDiagnosticRegistry.js +0 -277
  1079. package/dist/src/services/lsp/LSPServerInstance.js +0 -390
  1080. package/dist/src/services/lsp/LSPServerManager.js +0 -305
  1081. package/dist/src/services/lsp/config.js +0 -57
  1082. package/dist/src/services/lsp/manager.js +0 -246
  1083. package/dist/src/services/lsp/passiveFeedback.js +0 -226
  1084. package/dist/src/services/mcp/InProcessTransport.js +0 -54
  1085. package/dist/src/services/mcp/MCPConnectionManager.js +0 -50
  1086. package/dist/src/services/mcp/SdkControlTransport.js +0 -115
  1087. package/dist/src/services/mcp/auth.js +0 -1882
  1088. package/dist/src/services/mcp/channelAllowlist.js +0 -57
  1089. package/dist/src/services/mcp/channelNotification.js +0 -236
  1090. package/dist/src/services/mcp/channelPermissions.js +0 -192
  1091. package/dist/src/services/mcp/claudeai.js +0 -123
  1092. package/dist/src/services/mcp/client.js +0 -2480
  1093. package/dist/src/services/mcp/config.js +0 -1277
  1094. package/dist/src/services/mcp/elicitationHandler.js +0 -192
  1095. package/dist/src/services/mcp/envExpansion.js +0 -30
  1096. package/dist/src/services/mcp/headersHelper.js +0 -94
  1097. package/dist/src/services/mcp/mcpStringUtils.js +0 -85
  1098. package/dist/src/services/mcp/normalization.js +0 -21
  1099. package/dist/src/services/mcp/oauthPort.js +0 -69
  1100. package/dist/src/services/mcp/officialRegistry.js +0 -54
  1101. package/dist/src/services/mcp/types.js +0 -94
  1102. package/dist/src/services/mcp/useManageMCPConnections.js +0 -820
  1103. package/dist/src/services/mcp/utils.js +0 -433
  1104. package/dist/src/services/mcp/vscodeSdkMcp.js +0 -69
  1105. package/dist/src/services/mcp/xaa.js +0 -342
  1106. package/dist/src/services/mcp/xaaIdpLogin.js +0 -377
  1107. package/dist/src/services/mcpServerApproval.js +0 -29
  1108. package/dist/src/services/mockRateLimits.js +0 -666
  1109. package/dist/src/services/notifier.js +0 -114
  1110. package/dist/src/services/oauth/auth-code-listener.js +0 -236
  1111. package/dist/src/services/oauth/client.js +0 -545
  1112. package/dist/src/services/oauth/crypto.js +0 -19
  1113. package/dist/src/services/oauth/getOauthProfile.js +0 -48
  1114. package/dist/src/services/oauth/index.js +0 -152
  1115. package/dist/src/services/oauth/types.js +0 -1
  1116. package/dist/src/services/plugins/PluginInstallationManager.js +0 -139
  1117. package/dist/src/services/plugins/pluginCliCommands.js +0 -230
  1118. package/dist/src/services/plugins/pluginOperations.js +0 -826
  1119. package/dist/src/services/policyLimits/index.js +0 -547
  1120. package/dist/src/services/policyLimits/types.js +0 -9
  1121. package/dist/src/services/preventSleep.js +0 -143
  1122. package/dist/src/services/rateLimitMessages.js +0 -271
  1123. package/dist/src/services/rateLimitMocking.js +0 -91
  1124. package/dist/src/services/remoteManagedSettings/index.js +0 -534
  1125. package/dist/src/services/remoteManagedSettings/securityCheck.js +0 -59
  1126. package/dist/src/services/remoteManagedSettings/syncCache.js +0 -90
  1127. package/dist/src/services/remoteManagedSettings/syncCacheState.js +0 -89
  1128. package/dist/src/services/remoteManagedSettings/types.js +0 -12
  1129. package/dist/src/services/settingsSync/index.js +0 -478
  1130. package/dist/src/services/settingsSync/types.js +0 -35
  1131. package/dist/src/services/teamMemorySync/index.js +0 -976
  1132. package/dist/src/services/teamMemorySync/secretScanner.js +0 -275
  1133. package/dist/src/services/teamMemorySync/teamMemSecretGuard.js +0 -35
  1134. package/dist/src/services/teamMemorySync/types.js +0 -47
  1135. package/dist/src/services/teamMemorySync/watcher.js +0 -326
  1136. package/dist/src/services/tips/tipHistory.js +0 -17
  1137. package/dist/src/services/tips/tipRegistry.js +0 -589
  1138. package/dist/src/services/tips/tipScheduler.js +0 -40
  1139. package/dist/src/services/tokenEstimation.js +0 -365
  1140. package/dist/src/services/toolUseSummary/toolUseSummaryGenerator.js +0 -87
  1141. package/dist/src/services/tools/StreamingToolExecutor.js +0 -413
  1142. package/dist/src/services/tools/toolExecution.js +0 -1218
  1143. package/dist/src/services/tools/toolHooks.js +0 -454
  1144. package/dist/src/services/tools/toolOrchestration.js +0 -110
  1145. package/dist/src/services/vcr.js +0 -291
  1146. package/dist/src/services/voice.js +0 -394
  1147. package/dist/src/services/voiceKeyterms.js +0 -94
  1148. package/dist/src/services/voiceStreamSTT.js +0 -406
  1149. package/dist/src/setup.js +0 -349
  1150. package/dist/src/skills/bundled/batch.js +0 -114
  1151. package/dist/src/skills/bundled/claudeApi.js +0 -145
  1152. package/dist/src/skills/bundled/claudeApiContent.js +0 -14
  1153. package/dist/src/skills/bundled/claudeInChrome.js +0 -27
  1154. package/dist/src/skills/bundled/debug.js +0 -99
  1155. package/dist/src/skills/bundled/index.js +0 -5
  1156. package/dist/src/skills/bundled/keybindings.js +0 -292
  1157. package/dist/src/skills/bundled/loop.js +0 -81
  1158. package/dist/src/skills/bundled/loremIpsum.js +0 -266
  1159. package/dist/src/skills/bundled/remember.js +0 -75
  1160. package/dist/src/skills/bundled/scheduleRemoteAgents.js +0 -373
  1161. package/dist/src/skills/bundled/simplify.js +0 -66
  1162. package/dist/src/skills/bundled/skillify.js +0 -184
  1163. package/dist/src/skills/bundled/stuck.js +0 -75
  1164. package/dist/src/skills/bundled/updateConfig.js +0 -463
  1165. package/dist/src/skills/bundled/verify.js +0 -25
  1166. package/dist/src/skills/bundled/verifyContent.js +0 -7
  1167. package/dist/src/skills/bundledSkills.js +0 -159
  1168. package/dist/src/skills/loadSkillsDir.js +0 -736
  1169. package/dist/src/skills/mcpSkillBuilders.js +0 -10
  1170. package/dist/src/ssh/createSSHSession.js +0 -16
  1171. package/dist/src/state/AppState.js +0 -184
  1172. package/dist/src/state/AppStateStore.js +0 -119
  1173. package/dist/src/state/onChangeAppState.js +0 -132
  1174. package/dist/src/state/selectors.js +0 -51
  1175. package/dist/src/state/store.js +0 -21
  1176. package/dist/src/state/teammateViewHelpers.js +0 -124
  1177. package/dist/src/tasks/DreamTask/DreamTask.js +0 -99
  1178. package/dist/src/tasks/InProcessTeammateTask/InProcessTeammateTask.js +0 -116
  1179. package/dist/src/tasks/InProcessTeammateTask/types.js +0 -35
  1180. package/dist/src/tasks/LocalAgentTask/LocalAgentTask.js +0 -507
  1181. package/dist/src/tasks/LocalMainSessionTask.js +0 -338
  1182. package/dist/src/tasks/LocalShellTask/LocalShellTask.js +0 -475
  1183. package/dist/src/tasks/LocalShellTask/guards.js +0 -9
  1184. package/dist/src/tasks/LocalShellTask/killShellTasks.js +0 -59
  1185. package/dist/src/tasks/RemoteAgentTask/RemoteAgentTask.js +0 -742
  1186. package/dist/src/tasks/pillLabel.js +0 -69
  1187. package/dist/src/tasks/stopTask.js +0 -67
  1188. package/dist/src/tasks/types.js +0 -18
  1189. package/dist/src/tasks.js +0 -39
  1190. package/dist/src/telegram/bridge.js +0 -334
  1191. package/dist/src/telegram/config.js +0 -57
  1192. package/dist/src/telegram/mirror.js +0 -91
  1193. package/dist/src/tools/AgentTool/AgentTool.js +0 -1222
  1194. package/dist/src/tools/AgentTool/UI.js +0 -592
  1195. package/dist/src/tools/AgentTool/agentColorManager.js +0 -43
  1196. package/dist/src/tools/AgentTool/agentDisplay.js +0 -72
  1197. package/dist/src/tools/AgentTool/agentMemory.js +0 -125
  1198. package/dist/src/tools/AgentTool/agentMemorySnapshot.js +0 -136
  1199. package/dist/src/tools/AgentTool/agentToolUtils.js +0 -456
  1200. package/dist/src/tools/AgentTool/built-in/claudeCodeGuideAgent.js +0 -175
  1201. package/dist/src/tools/AgentTool/built-in/exploreAgent.js +0 -76
  1202. package/dist/src/tools/AgentTool/built-in/generalPurposeAgent.js +0 -28
  1203. package/dist/src/tools/AgentTool/built-in/planAgent.js +0 -87
  1204. package/dist/src/tools/AgentTool/built-in/statuslineSetup.js +0 -140
  1205. package/dist/src/tools/AgentTool/built-in/verificationAgent.js +0 -146
  1206. package/dist/src/tools/AgentTool/builtInAgents.js +0 -58
  1207. package/dist/src/tools/AgentTool/constants.js +0 -11
  1208. package/dist/src/tools/AgentTool/forkSubagent.js +0 -177
  1209. package/dist/src/tools/AgentTool/loadAgentsDir.js +0 -497
  1210. package/dist/src/tools/AgentTool/prompt.js +0 -260
  1211. package/dist/src/tools/AgentTool/resumeAgent.js +0 -182
  1212. package/dist/src/tools/AgentTool/runAgent.js +0 -629
  1213. package/dist/src/tools/AskUserQuestionTool/AskUserQuestionTool.js +0 -237
  1214. package/dist/src/tools/AskUserQuestionTool/prompt.js +0 -38
  1215. package/dist/src/tools/BashTool/BashTool.js +0 -1008
  1216. package/dist/src/tools/BashTool/BashToolResultMessage.js +0 -168
  1217. package/dist/src/tools/BashTool/UI.js +0 -133
  1218. package/dist/src/tools/BashTool/bashCommandHelpers.js +0 -184
  1219. package/dist/src/tools/BashTool/bashPermissions.js +0 -2023
  1220. package/dist/src/tools/BashTool/bashSecurity.js +0 -2267
  1221. package/dist/src/tools/BashTool/commandSemantics.js +0 -105
  1222. package/dist/src/tools/BashTool/commentLabel.js +0 -14
  1223. package/dist/src/tools/BashTool/destructiveCommandWarning.js +0 -88
  1224. package/dist/src/tools/BashTool/modeValidation.js +0 -86
  1225. package/dist/src/tools/BashTool/pathValidation.js +0 -1080
  1226. package/dist/src/tools/BashTool/prompt.js +0 -333
  1227. package/dist/src/tools/BashTool/readOnlyValidation.js +0 -1794
  1228. package/dist/src/tools/BashTool/sedEditParser.js +0 -282
  1229. package/dist/src/tools/BashTool/sedValidation.js +0 -580
  1230. package/dist/src/tools/BashTool/shouldUseSandbox.js +0 -125
  1231. package/dist/src/tools/BashTool/toolName.js +0 -2
  1232. package/dist/src/tools/BashTool/utils.js +0 -180
  1233. package/dist/src/tools/BriefTool/BriefTool.js +0 -172
  1234. package/dist/src/tools/BriefTool/UI.js +0 -66
  1235. package/dist/src/tools/BriefTool/attachments.js +0 -86
  1236. package/dist/src/tools/BriefTool/prompt.js +0 -19
  1237. package/dist/src/tools/BriefTool/upload.js +0 -136
  1238. package/dist/src/tools/ConfigTool/ConfigTool.js +0 -398
  1239. package/dist/src/tools/ConfigTool/UI.js +0 -24
  1240. package/dist/src/tools/ConfigTool/constants.js +0 -1
  1241. package/dist/src/tools/ConfigTool/prompt.js +0 -82
  1242. package/dist/src/tools/ConfigTool/supportedSettings.js +0 -180
  1243. package/dist/src/tools/EnterPlanModeTool/EnterPlanModeTool.js +0 -98
  1244. package/dist/src/tools/EnterPlanModeTool/UI.js +0 -13
  1245. package/dist/src/tools/EnterPlanModeTool/constants.js +0 -1
  1246. package/dist/src/tools/EnterPlanModeTool/prompt.js +0 -164
  1247. package/dist/src/tools/EnterWorktreeTool/EnterWorktreeTool.js +0 -104
  1248. package/dist/src/tools/EnterWorktreeTool/UI.js +0 -8
  1249. package/dist/src/tools/EnterWorktreeTool/constants.js +0 -1
  1250. package/dist/src/tools/EnterWorktreeTool/prompt.js +0 -30
  1251. package/dist/src/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js +0 -385
  1252. package/dist/src/tools/ExitPlanModeTool/UI.js +0 -31
  1253. package/dist/src/tools/ExitPlanModeTool/constants.js +0 -2
  1254. package/dist/src/tools/ExitPlanModeTool/prompt.js +0 -27
  1255. package/dist/src/tools/ExitWorktreeTool/ExitWorktreeTool.js +0 -257
  1256. package/dist/src/tools/ExitWorktreeTool/UI.js +0 -9
  1257. package/dist/src/tools/ExitWorktreeTool/constants.js +0 -1
  1258. package/dist/src/tools/ExitWorktreeTool/prompt.js +0 -32
  1259. package/dist/src/tools/FileEditTool/FileEditTool.js +0 -480
  1260. package/dist/src/tools/FileEditTool/UI.js +0 -201
  1261. package/dist/src/tools/FileEditTool/constants.js +0 -7
  1262. package/dist/src/tools/FileEditTool/prompt.js +0 -24
  1263. package/dist/src/tools/FileEditTool/types.js +0 -50
  1264. package/dist/src/tools/FileEditTool/utils.js +0 -579
  1265. package/dist/src/tools/FileReadTool/FileReadTool.js +0 -889
  1266. package/dist/src/tools/FileReadTool/UI.js +0 -125
  1267. package/dist/src/tools/FileReadTool/imageProcessor.js +0 -46
  1268. package/dist/src/tools/FileReadTool/limits.js +0 -70
  1269. package/dist/src/tools/FileReadTool/prompt.js +0 -31
  1270. package/dist/src/tools/FileWriteTool/FileWriteTool.js +0 -341
  1271. package/dist/src/tools/FileWriteTool/UI.js +0 -338
  1272. package/dist/src/tools/FileWriteTool/prompt.js +0 -15
  1273. package/dist/src/tools/GlobTool/GlobTool.js +0 -161
  1274. package/dist/src/tools/GlobTool/UI.js +0 -39
  1275. package/dist/src/tools/GlobTool/prompt.js +0 -6
  1276. package/dist/src/tools/GrepTool/GrepTool.js +0 -439
  1277. package/dist/src/tools/GrepTool/UI.js +0 -154
  1278. package/dist/src/tools/GrepTool/prompt.js +0 -16
  1279. package/dist/src/tools/LSPTool/LSPTool.js +0 -660
  1280. package/dist/src/tools/LSPTool/UI.js +0 -204
  1281. package/dist/src/tools/LSPTool/formatters.js +0 -445
  1282. package/dist/src/tools/LSPTool/prompt.js +0 -20
  1283. package/dist/src/tools/LSPTool/schemas.js +0 -197
  1284. package/dist/src/tools/LSPTool/symbolContext.js +0 -75
  1285. package/dist/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +0 -100
  1286. package/dist/src/tools/ListMcpResourcesTool/UI.js +0 -16
  1287. package/dist/src/tools/ListMcpResourcesTool/prompt.js +0 -18
  1288. package/dist/src/tools/MCPTool/MCPTool.js +0 -60
  1289. package/dist/src/tools/MCPTool/UI.js +0 -342
  1290. package/dist/src/tools/MCPTool/classifyForCollapse.js +0 -597
  1291. package/dist/src/tools/MCPTool/prompt.js +0 -3
  1292. package/dist/src/tools/McpAuthTool/McpAuthTool.js +0 -162
  1293. package/dist/src/tools/NotebookEditTool/NotebookEditTool.js +0 -421
  1294. package/dist/src/tools/NotebookEditTool/UI.js +0 -40
  1295. package/dist/src/tools/NotebookEditTool/constants.js +0 -2
  1296. package/dist/src/tools/NotebookEditTool/prompt.js +0 -2
  1297. package/dist/src/tools/PowerShellTool/PowerShellTool.js +0 -899
  1298. package/dist/src/tools/PowerShellTool/UI.js +0 -57
  1299. package/dist/src/tools/PowerShellTool/clmTypes.js +0 -207
  1300. package/dist/src/tools/PowerShellTool/commandSemantics.js +0 -115
  1301. package/dist/src/tools/PowerShellTool/commonParameters.js +0 -27
  1302. package/dist/src/tools/PowerShellTool/destructiveCommandWarning.js +0 -92
  1303. package/dist/src/tools/PowerShellTool/gitSafety.js +0 -185
  1304. package/dist/src/tools/PowerShellTool/modeValidation.js +0 -357
  1305. package/dist/src/tools/PowerShellTool/pathValidation.js +0 -1712
  1306. package/dist/src/tools/PowerShellTool/powershellPermissions.js +0 -1351
  1307. package/dist/src/tools/PowerShellTool/powershellSecurity.js +0 -942
  1308. package/dist/src/tools/PowerShellTool/prompt.js +0 -132
  1309. package/dist/src/tools/PowerShellTool/readOnlyValidation.js +0 -1633
  1310. package/dist/src/tools/PowerShellTool/toolName.js +0 -2
  1311. package/dist/src/tools/REPLTool/constants.js +0 -43
  1312. package/dist/src/tools/REPLTool/primitiveTools.js +0 -36
  1313. package/dist/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +0 -112
  1314. package/dist/src/tools/ReadMcpResourceTool/UI.js +0 -23
  1315. package/dist/src/tools/ReadMcpResourceTool/prompt.js +0 -15
  1316. package/dist/src/tools/RemoteTriggerTool/RemoteTriggerTool.js +0 -142
  1317. package/dist/src/tools/RemoteTriggerTool/UI.js +0 -11
  1318. package/dist/src/tools/RemoteTriggerTool/prompt.js +0 -12
  1319. package/dist/src/tools/ScheduleCronTool/CronCreateTool.js +0 -120
  1320. package/dist/src/tools/ScheduleCronTool/CronDeleteTool.js +0 -74
  1321. package/dist/src/tools/ScheduleCronTool/CronListTool.js +0 -77
  1322. package/dist/src/tools/ScheduleCronTool/UI.js +0 -28
  1323. package/dist/src/tools/ScheduleCronTool/prompt.js +0 -115
  1324. package/dist/src/tools/SendMessageTool/SendMessageTool.js +0 -675
  1325. package/dist/src/tools/SendMessageTool/UI.js +0 -23
  1326. package/dist/src/tools/SendMessageTool/constants.js +0 -1
  1327. package/dist/src/tools/SendMessageTool/prompt.js +0 -47
  1328. package/dist/src/tools/SkillTool/SkillTool.js +0 -827
  1329. package/dist/src/tools/SkillTool/UI.js +0 -60
  1330. package/dist/src/tools/SkillTool/constants.js +0 -1
  1331. package/dist/src/tools/SkillTool/prompt.js +0 -184
  1332. package/dist/src/tools/SleepTool/prompt.js +0 -14
  1333. package/dist/src/tools/SyntheticOutputTool/SyntheticOutputTool.js +0 -138
  1334. package/dist/src/tools/TaskCreateTool/TaskCreateTool.js +0 -104
  1335. package/dist/src/tools/TaskCreateTool/constants.js +0 -1
  1336. package/dist/src/tools/TaskCreateTool/prompt.js +0 -52
  1337. package/dist/src/tools/TaskGetTool/TaskGetTool.js +0 -106
  1338. package/dist/src/tools/TaskGetTool/constants.js +0 -1
  1339. package/dist/src/tools/TaskGetTool/prompt.js +0 -23
  1340. package/dist/src/tools/TaskListTool/TaskListTool.js +0 -89
  1341. package/dist/src/tools/TaskListTool/constants.js +0 -1
  1342. package/dist/src/tools/TaskListTool/prompt.js +0 -44
  1343. package/dist/src/tools/TaskOutputTool/TaskOutputTool.js +0 -535
  1344. package/dist/src/tools/TaskOutputTool/constants.js +0 -1
  1345. package/dist/src/tools/TaskStopTool/TaskStopTool.js +0 -110
  1346. package/dist/src/tools/TaskStopTool/UI.js +0 -30
  1347. package/dist/src/tools/TaskStopTool/prompt.js +0 -7
  1348. package/dist/src/tools/TaskUpdateTool/TaskUpdateTool.js +0 -301
  1349. package/dist/src/tools/TaskUpdateTool/constants.js +0 -1
  1350. package/dist/src/tools/TaskUpdateTool/prompt.js +0 -76
  1351. package/dist/src/tools/TeamCreateTool/TeamCreateTool.js +0 -177
  1352. package/dist/src/tools/TeamCreateTool/UI.js +0 -4
  1353. package/dist/src/tools/TeamCreateTool/constants.js +0 -1
  1354. package/dist/src/tools/TeamCreateTool/prompt.js +0 -113
  1355. package/dist/src/tools/TeamDeleteTool/TeamDeleteTool.js +0 -102
  1356. package/dist/src/tools/TeamDeleteTool/UI.js +0 -13
  1357. package/dist/src/tools/TeamDeleteTool/constants.js +0 -1
  1358. package/dist/src/tools/TeamDeleteTool/prompt.js +0 -16
  1359. package/dist/src/tools/TodoWriteTool/TodoWriteTool.js +0 -99
  1360. package/dist/src/tools/TodoWriteTool/constants.js +0 -1
  1361. package/dist/src/tools/TodoWriteTool/prompt.js +0 -181
  1362. package/dist/src/tools/ToolSearchTool/ToolSearchTool.js +0 -357
  1363. package/dist/src/tools/ToolSearchTool/constants.js +0 -1
  1364. package/dist/src/tools/ToolSearchTool/prompt.js +0 -99
  1365. package/dist/src/tools/TungstenTool/TungstenLiveMonitor.js +0 -7
  1366. package/dist/src/tools/TungstenTool/TungstenTool.js +0 -3
  1367. package/dist/src/tools/WebFetchTool/UI.js +0 -30
  1368. package/dist/src/tools/WebFetchTool/WebFetchTool.js +0 -246
  1369. package/dist/src/tools/WebFetchTool/preapproved.js +0 -155
  1370. package/dist/src/tools/WebFetchTool/prompt.js +0 -39
  1371. package/dist/src/tools/WebFetchTool/utils.js +0 -381
  1372. package/dist/src/tools/WebSearchTool/UI.js +0 -66
  1373. package/dist/src/tools/WebSearchTool/WebSearchTool.js +0 -352
  1374. package/dist/src/tools/WebSearchTool/prompt.js +0 -32
  1375. package/dist/src/tools/WorkflowTool/constants.js +0 -2
  1376. package/dist/src/tools/shared/gitOperationTracking.js +0 -220
  1377. package/dist/src/tools/shared/spawnMultiAgent.js +0 -805
  1378. package/dist/src/tools/testing/TestingPermissionTool.js +0 -72
  1379. package/dist/src/tools/utils.js +0 -24
  1380. package/dist/src/tools.js +0 -332
  1381. package/dist/src/types/command.js +0 -10
  1382. package/dist/src/types/connectorText.js +0 -2
  1383. package/dist/src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.js +0 -673
  1384. package/dist/src/types/generated/events_mono/common/v1/auth.js +0 -49
  1385. package/dist/src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.js +0 -147
  1386. package/dist/src/types/generated/google/protobuf/timestamp.js +0 -38
  1387. package/dist/src/types/hooks.js +0 -153
  1388. package/dist/src/types/ids.js +0 -27
  1389. package/dist/src/types/logs.js +0 -11
  1390. package/dist/src/types/message.js +0 -1
  1391. package/dist/src/types/permissions.js +0 -25
  1392. package/dist/src/types/plugin.js +0 -72
  1393. package/dist/src/types/textInputTypes.js +0 -20
  1394. package/dist/src/types/utils.js +0 -5
  1395. package/dist/src/upstreamproxy/relay.js +0 -346
  1396. package/dist/src/upstreamproxy/upstreamproxy.js +0 -236
  1397. package/dist/src/utils/CircularBuffer.js +0 -75
  1398. package/dist/src/utils/Cursor.js +0 -1229
  1399. package/dist/src/utils/QueryGuard.js +0 -115
  1400. package/dist/src/utils/Shell.js +0 -374
  1401. package/dist/src/utils/ShellCommand.js +0 -338
  1402. package/dist/src/utils/abortController.js +0 -74
  1403. package/dist/src/utils/activityManager.js +0 -127
  1404. package/dist/src/utils/advisor.js +0 -77
  1405. package/dist/src/utils/agentContext.js +0 -91
  1406. package/dist/src/utils/agentId.js +0 -83
  1407. package/dist/src/utils/agentSwarmsEnabled.js +0 -37
  1408. package/dist/src/utils/agenticSessionSearch.js +0 -255
  1409. package/dist/src/utils/analyzeContext.js +0 -848
  1410. package/dist/src/utils/ansiToPng.js +0 -259
  1411. package/dist/src/utils/ansiToSvg.js +0 -207
  1412. package/dist/src/utils/api.js +0 -555
  1413. package/dist/src/utils/apiPreconnect.js +0 -62
  1414. package/dist/src/utils/appleTerminalBackup.js +0 -95
  1415. package/dist/src/utils/argumentSubstitution.js +0 -114
  1416. package/dist/src/utils/array.js +0 -12
  1417. package/dist/src/utils/asciicast.js +0 -200
  1418. package/dist/src/utils/attachments.js +0 -2514
  1419. package/dist/src/utils/attribution.js +0 -308
  1420. package/dist/src/utils/attributionHooks.js +0 -16
  1421. package/dist/src/utils/attributionTrailer.js +0 -16
  1422. package/dist/src/utils/auth.js +0 -2020
  1423. package/dist/src/utils/authFileDescriptor.js +0 -152
  1424. package/dist/src/utils/authPortable.js +0 -14
  1425. package/dist/src/utils/autoModeDenials.js +0 -15
  1426. package/dist/src/utils/autoRunIssue.js +0 -112
  1427. package/dist/src/utils/autoUpdater.js +0 -461
  1428. package/dist/src/utils/aws.js +0 -44
  1429. package/dist/src/utils/awsAuthStatusManager.js +0 -66
  1430. package/dist/src/utils/background/remote/preconditions.js +0 -175
  1431. package/dist/src/utils/background/remote/remoteSession.js +0 -53
  1432. package/dist/src/utils/backgroundHousekeeping.js +0 -66
  1433. package/dist/src/utils/bash/ParsedCommand.js +0 -241
  1434. package/dist/src/utils/bash/ShellSnapshot.js +0 -489
  1435. package/dist/src/utils/bash/ast.js +0 -2590
  1436. package/dist/src/utils/bash/bashParser.js +0 -4355
  1437. package/dist/src/utils/bash/bashPipeCommand.js +0 -249
  1438. package/dist/src/utils/bash/commands.js +0 -1131
  1439. package/dist/src/utils/bash/heredoc.js +0 -647
  1440. package/dist/src/utils/bash/parser.js +0 -195
  1441. package/dist/src/utils/bash/prefix.js +0 -154
  1442. package/dist/src/utils/bash/registry.js +0 -23
  1443. package/dist/src/utils/bash/shellCompletion.js +0 -196
  1444. package/dist/src/utils/bash/shellPrefix.js +0 -25
  1445. package/dist/src/utils/bash/shellQuote.js +0 -253
  1446. package/dist/src/utils/bash/shellQuoting.js +0 -106
  1447. package/dist/src/utils/bash/specs/alias.js +0 -11
  1448. package/dist/src/utils/bash/specs/index.js +0 -16
  1449. package/dist/src/utils/bash/specs/nohup.js +0 -10
  1450. package/dist/src/utils/bash/specs/pyright.js +0 -88
  1451. package/dist/src/utils/bash/specs/sleep.js +0 -10
  1452. package/dist/src/utils/bash/specs/srun.js +0 -28
  1453. package/dist/src/utils/bash/specs/time.js +0 -10
  1454. package/dist/src/utils/bash/specs/timeout.js +0 -17
  1455. package/dist/src/utils/bash/treeSitterAnalysis.js +0 -407
  1456. package/dist/src/utils/betas.js +0 -332
  1457. package/dist/src/utils/billing.js +0 -54
  1458. package/dist/src/utils/binaryCheck.js +0 -40
  1459. package/dist/src/utils/browser.js +0 -58
  1460. package/dist/src/utils/bufferedWriter.js +0 -77
  1461. package/dist/src/utils/bundledMode.js +0 -19
  1462. package/dist/src/utils/caCerts.js +0 -93
  1463. package/dist/src/utils/caCertsConfig.js +0 -77
  1464. package/dist/src/utils/cachePaths.js +0 -28
  1465. package/dist/src/utils/ccshareResume.js +0 -16
  1466. package/dist/src/utils/classifierApprovals.js +0 -66
  1467. package/dist/src/utils/classifierApprovalsHook.js +0 -10
  1468. package/dist/src/utils/claudeCodeHints.js +0 -142
  1469. package/dist/src/utils/claudeDesktop.js +0 -108
  1470. package/dist/src/utils/claudeInChrome/chromeNativeHost.js +0 -416
  1471. package/dist/src/utils/claudeInChrome/common.js +0 -466
  1472. package/dist/src/utils/claudeInChrome/mcpServer.js +0 -237
  1473. package/dist/src/utils/claudeInChrome/prompt.js +0 -79
  1474. package/dist/src/utils/claudeInChrome/setup.js +0 -320
  1475. package/dist/src/utils/claudeInChrome/setupPortable.js +0 -172
  1476. package/dist/src/utils/claudeInChrome/toolRendering.js +0 -234
  1477. package/dist/src/utils/claudemd.js +0 -1054
  1478. package/dist/src/utils/cleanup.js +0 -514
  1479. package/dist/src/utils/cleanupRegistry.js +0 -22
  1480. package/dist/src/utils/cliArgs.js +0 -53
  1481. package/dist/src/utils/cliHighlight.js +0 -45
  1482. package/dist/src/utils/codeIndexing.js +0 -149
  1483. package/dist/src/utils/collapseBackgroundBashNotifications.js +0 -70
  1484. package/dist/src/utils/collapseHookSummaries.js +0 -48
  1485. package/dist/src/utils/collapseReadSearch.js +0 -871
  1486. package/dist/src/utils/collapseTeammateShutdowns.js +0 -44
  1487. package/dist/src/utils/combinedAbortSignal.js +0 -40
  1488. package/dist/src/utils/commandLifecycle.js +0 -7
  1489. package/dist/src/utils/commitAttribution.js +0 -720
  1490. package/dist/src/utils/completionCache.js +0 -138
  1491. package/dist/src/utils/computerUse/appNames.js +0 -170
  1492. package/dist/src/utils/computerUse/cleanup.js +0 -66
  1493. package/dist/src/utils/computerUse/common.js +0 -56
  1494. package/dist/src/utils/computerUse/computerUseLock.js +0 -183
  1495. package/dist/src/utils/computerUse/drainRunLoop.js +0 -71
  1496. package/dist/src/utils/computerUse/escHotkey.js +0 -53
  1497. package/dist/src/utils/computerUse/executor.js +0 -480
  1498. package/dist/src/utils/computerUse/gates.js +0 -55
  1499. package/dist/src/utils/computerUse/hostAdapter.js +0 -62
  1500. package/dist/src/utils/computerUse/inputLoader.js +0 -27
  1501. package/dist/src/utils/computerUse/mcpServer.js +0 -84
  1502. package/dist/src/utils/computerUse/setup.js +0 -42
  1503. package/dist/src/utils/computerUse/swiftLoader.js +0 -20
  1504. package/dist/src/utils/computerUse/toolRendering.js +0 -100
  1505. package/dist/src/utils/computerUse/wrapper.js +0 -318
  1506. package/dist/src/utils/concurrentSessions.js +0 -179
  1507. package/dist/src/utils/config.js +0 -1084
  1508. package/dist/src/utils/configConstants.js +0 -18
  1509. package/dist/src/utils/contentArray.js +0 -45
  1510. package/dist/src/utils/context.js +0 -185
  1511. package/dist/src/utils/contextAnalysis.js +0 -171
  1512. package/dist/src/utils/contextSuggestions.js +0 -158
  1513. package/dist/src/utils/controlMessageCompat.js +0 -31
  1514. package/dist/src/utils/conversationRecovery.js +0 -436
  1515. package/dist/src/utils/cron.js +0 -260
  1516. package/dist/src/utils/cronJitterConfig.js +0 -62
  1517. package/dist/src/utils/cronScheduler.js +0 -388
  1518. package/dist/src/utils/cronTasks.js +0 -328
  1519. package/dist/src/utils/cronTasksLock.js +0 -159
  1520. package/dist/src/utils/crossProjectResume.js +0 -46
  1521. package/dist/src/utils/crypto.js +0 -13
  1522. package/dist/src/utils/cwd.js +0 -29
  1523. package/dist/src/utils/databaseMcp/common.js +0 -48
  1524. package/dist/src/utils/databaseMcp/mcpServer.js +0 -2
  1525. package/dist/src/utils/databaseMcp/server/connection.js +0 -243
  1526. package/dist/src/utils/databaseMcp/server/index.js +0 -1442
  1527. package/dist/src/utils/databaseMcp/server/queries.js +0 -683
  1528. package/dist/src/utils/databaseMcp/server/types.js +0 -7
  1529. package/dist/src/utils/databaseMcp/setup.js +0 -28
  1530. package/dist/src/utils/debug.js +0 -220
  1531. package/dist/src/utils/debugFilter.js +0 -125
  1532. package/dist/src/utils/deepLink/banner.js +0 -103
  1533. package/dist/src/utils/deepLink/parseDeepLink.js +0 -138
  1534. package/dist/src/utils/deepLink/protocolHandler.js +0 -119
  1535. package/dist/src/utils/deepLink/registerProtocol.js +0 -291
  1536. package/dist/src/utils/deepLink/terminalLauncher.js +0 -455
  1537. package/dist/src/utils/deepLink/terminalPreference.js +0 -51
  1538. package/dist/src/utils/desktopDeepLink.js +0 -208
  1539. package/dist/src/utils/detectRepository.js +0 -157
  1540. package/dist/src/utils/diagLogs.js +0 -74
  1541. package/dist/src/utils/diff.js +0 -108
  1542. package/dist/src/utils/directMemberMessage.js +0 -34
  1543. package/dist/src/utils/displayTags.js +0 -46
  1544. package/dist/src/utils/doctorContextWarnings.js +0 -179
  1545. package/dist/src/utils/doctorDiagnostic.js +0 -495
  1546. package/dist/src/utils/dxt/helpers.js +0 -64
  1547. package/dist/src/utils/dxt/zip.js +0 -167
  1548. package/dist/src/utils/earlyInput.js +0 -166
  1549. package/dist/src/utils/editor.js +0 -163
  1550. package/dist/src/utils/effort.js +0 -278
  1551. package/dist/src/utils/embeddedTools.js +0 -26
  1552. package/dist/src/utils/env.js +0 -358
  1553. package/dist/src/utils/envDynamic.js +0 -130
  1554. package/dist/src/utils/envUtils.js +0 -154
  1555. package/dist/src/utils/envValidation.js +0 -26
  1556. package/dist/src/utils/errorLogSink.js +0 -197
  1557. package/dist/src/utils/errors.js +0 -207
  1558. package/dist/src/utils/eventLoopStallDetector.js +0 -16
  1559. package/dist/src/utils/exampleCommands.js +0 -165
  1560. package/dist/src/utils/execFileNoThrow.js +0 -93
  1561. package/dist/src/utils/execFileNoThrowPortable.js +0 -111
  1562. package/dist/src/utils/execSyncWrapper.js +0 -68
  1563. package/dist/src/utils/exportRenderer.js +0 -71
  1564. package/dist/src/utils/extraUsage.js +0 -19
  1565. package/dist/src/utils/fastMode.js +0 -393
  1566. package/dist/src/utils/file.js +0 -467
  1567. package/dist/src/utils/fileHistory.js +0 -851
  1568. package/dist/src/utils/fileOperationAnalytics.js +0 -45
  1569. package/dist/src/utils/filePersistence/filePersistence.js +0 -212
  1570. package/dist/src/utils/filePersistence/outputsScanner.js +0 -104
  1571. package/dist/src/utils/filePersistence/types.js +0 -5
  1572. package/dist/src/utils/fileRead.js +0 -81
  1573. package/dist/src/utils/fileReadCache.js +0 -78
  1574. package/dist/src/utils/fileStateCache.js +0 -99
  1575. package/dist/src/utils/findExecutable.js +0 -13
  1576. package/dist/src/utils/fingerprint.js +0 -59
  1577. package/dist/src/utils/forkedAgent.js +0 -410
  1578. package/dist/src/utils/format.js +0 -238
  1579. package/dist/src/utils/formatBriefTimestamp.js +0 -72
  1580. package/dist/src/utils/fpsTracker.js +0 -34
  1581. package/dist/src/utils/frontmatterParser.js +0 -260
  1582. package/dist/src/utils/fsOperations.js +0 -834
  1583. package/dist/src/utils/fullscreen.js +0 -194
  1584. package/dist/src/utils/generatedFiles.js +0 -122
  1585. package/dist/src/utils/generators.js +0 -67
  1586. package/dist/src/utils/genericProcessUtils.js +0 -155
  1587. package/dist/src/utils/getWorktreePaths.js +0 -56
  1588. package/dist/src/utils/getWorktreePathsPortable.js +0 -23
  1589. package/dist/src/utils/ghPrStatus.js +0 -71
  1590. package/dist/src/utils/git/gitConfigParser.js +0 -226
  1591. package/dist/src/utils/git/gitFilesystem.js +0 -606
  1592. package/dist/src/utils/git/gitignore.js +0 -84
  1593. package/dist/src/utils/git.js +0 -725
  1594. package/dist/src/utils/gitDiff.js +0 -395
  1595. package/dist/src/utils/gitSettings.js +0 -18
  1596. package/dist/src/utils/github/ghAuthStatus.js +0 -23
  1597. package/dist/src/utils/githubRepoPathMapping.js +0 -135
  1598. package/dist/src/utils/glob.js +0 -90
  1599. package/dist/src/utils/gracefulShutdown.js +0 -447
  1600. package/dist/src/utils/groupToolUses.js +0 -126
  1601. package/dist/src/utils/handlePromptSubmit.js +0 -398
  1602. package/dist/src/utils/hash.js +0 -46
  1603. package/dist/src/utils/headlessProfiler.js +0 -147
  1604. package/dist/src/utils/heapDumpService.js +0 -202
  1605. package/dist/src/utils/heatmap.js +0 -151
  1606. package/dist/src/utils/highlightMatch.js +0 -28
  1607. package/dist/src/utils/hooks/AsyncHookRegistry.js +0 -187
  1608. package/dist/src/utils/hooks/apiQueryHookHelper.js +0 -77
  1609. package/dist/src/utils/hooks/execAgentHook.js +0 -257
  1610. package/dist/src/utils/hooks/execHttpHook.js +0 -184
  1611. package/dist/src/utils/hooks/execPromptHook.js +0 -171
  1612. package/dist/src/utils/hooks/fileChangedWatcher.js +0 -161
  1613. package/dist/src/utils/hooks/hookEvents.js +0 -111
  1614. package/dist/src/utils/hooks/hookHelpers.js +0 -60
  1615. package/dist/src/utils/hooks/hooksConfigManager.js +0 -323
  1616. package/dist/src/utils/hooks/hooksConfigSnapshot.js +0 -114
  1617. package/dist/src/utils/hooks/hooksSettings.js +0 -204
  1618. package/dist/src/utils/hooks/postSamplingHooks.js +0 -39
  1619. package/dist/src/utils/hooks/registerFrontmatterHooks.js +0 -47
  1620. package/dist/src/utils/hooks/registerSkillHooks.js +0 -40
  1621. package/dist/src/utils/hooks/sessionHooks.js +0 -252
  1622. package/dist/src/utils/hooks/skillImprovement.js +0 -211
  1623. package/dist/src/utils/hooks/ssrfGuard.js +0 -258
  1624. package/dist/src/utils/hooks.js +0 -3668
  1625. package/dist/src/utils/horizontalScroll.js +0 -108
  1626. package/dist/src/utils/http.js +0 -121
  1627. package/dist/src/utils/hyperlink.js +0 -28
  1628. package/dist/src/utils/iTermBackup.js +0 -48
  1629. package/dist/src/utils/ide.js +0 -1198
  1630. package/dist/src/utils/idePathConversion.js +0 -66
  1631. package/dist/src/utils/idleTimeout.js +0 -44
  1632. package/dist/src/utils/imagePaste.js +0 -329
  1633. package/dist/src/utils/imageResizer.js +0 -664
  1634. package/dist/src/utils/imageStore.js +0 -150
  1635. package/dist/src/utils/imageValidation.js +0 -92
  1636. package/dist/src/utils/immediateCommand.js +0 -12
  1637. package/dist/src/utils/inProcessTeammateHelpers.js +0 -71
  1638. package/dist/src/utils/ink.js +0 -20
  1639. package/dist/src/utils/intl.js +0 -83
  1640. package/dist/src/utils/jetbrains.js +0 -152
  1641. package/dist/src/utils/json.js +0 -295
  1642. package/dist/src/utils/jsonRead.js +0 -14
  1643. package/dist/src/utils/keyboardShortcuts.js +0 -11
  1644. package/dist/src/utils/lazySchema.js +0 -8
  1645. package/dist/src/utils/listSessionsImpl.js +0 -332
  1646. package/dist/src/utils/localInstaller.js +0 -131
  1647. package/dist/src/utils/lockfile.js +0 -22
  1648. package/dist/src/utils/log.js +0 -280
  1649. package/dist/src/utils/logoV2Utils.js +0 -288
  1650. package/dist/src/utils/mailbox.js +0 -50
  1651. package/dist/src/utils/managedEnv.js +0 -160
  1652. package/dist/src/utils/managedEnvConstants.js +0 -187
  1653. package/dist/src/utils/markdown.js +0 -300
  1654. package/dist/src/utils/markdownConfigLoader.js +0 -480
  1655. package/dist/src/utils/mcp/dateTimeParser.js +0 -102
  1656. package/dist/src/utils/mcp/elicitationValidation.js +0 -259
  1657. package/dist/src/utils/mcpInstructionsDelta.js +0 -97
  1658. package/dist/src/utils/mcpOutputStorage.js +0 -159
  1659. package/dist/src/utils/mcpValidation.js +0 -165
  1660. package/dist/src/utils/mcpWebSocketTransport.js +0 -180
  1661. package/dist/src/utils/memoize.js +0 -205
  1662. package/dist/src/utils/memory/types.js +0 -9
  1663. package/dist/src/utils/memory/versions.js +0 -7
  1664. package/dist/src/utils/memoryFileDetection.js +0 -247
  1665. package/dist/src/utils/messagePredicates.js +0 -6
  1666. package/dist/src/utils/messageQueueManager.js +0 -430
  1667. package/dist/src/utils/messages/mappers.js +0 -240
  1668. package/dist/src/utils/messages/systemInit.js +0 -74
  1669. package/dist/src/utils/messages.js +0 -4273
  1670. package/dist/src/utils/model/agent.js +0 -128
  1671. package/dist/src/utils/model/aliases.js +0 -21
  1672. package/dist/src/utils/model/antModels.js +0 -25
  1673. package/dist/src/utils/model/bedrock.js +0 -220
  1674. package/dist/src/utils/model/check1mAccess.js +0 -64
  1675. package/dist/src/utils/model/configs.js +0 -93
  1676. package/dist/src/utils/model/contextWindowUpgradeCheck.js +0 -41
  1677. package/dist/src/utils/model/deprecation.js +0 -72
  1678. package/dist/src/utils/model/model.js +0 -635
  1679. package/dist/src/utils/model/modelAllowlist.js +0 -148
  1680. package/dist/src/utils/model/modelCapabilities.js +0 -107
  1681. package/dist/src/utils/model/modelOptions.js +0 -627
  1682. package/dist/src/utils/model/modelStrings.js +0 -144
  1683. package/dist/src/utils/model/modelSupportOverrides.js +0 -40
  1684. package/dist/src/utils/model/openrouter.js +0 -51
  1685. package/dist/src/utils/model/providerBaseUrls.js +0 -77
  1686. package/dist/src/utils/model/providerCatalog.js +0 -81
  1687. package/dist/src/utils/model/providerModels.js +0 -334
  1688. package/dist/src/utils/model/providerProfiles.js +0 -392
  1689. package/dist/src/utils/model/providerProfilesDb.js +0 -556
  1690. package/dist/src/utils/model/providerSwitch.js +0 -68
  1691. package/dist/src/utils/model/providers.js +0 -199
  1692. package/dist/src/utils/model/validateModel.js +0 -257
  1693. package/dist/src/utils/modelCost.js +0 -160
  1694. package/dist/src/utils/modifiers.js +0 -35
  1695. package/dist/src/utils/mtls.js +0 -134
  1696. package/dist/src/utils/nativeInstaller/download.js +0 -370
  1697. package/dist/src/utils/nativeInstaller/index.js +0 -8
  1698. package/dist/src/utils/nativeInstaller/installer.js +0 -1396
  1699. package/dist/src/utils/nativeInstaller/packageManagers.js +0 -258
  1700. package/dist/src/utils/nativeInstaller/pidLock.js +0 -347
  1701. package/dist/src/utils/notebook.js +0 -176
  1702. package/dist/src/utils/objectGroupBy.js +0 -15
  1703. package/dist/src/utils/pasteStore.js +0 -93
  1704. package/dist/src/utils/path.js +0 -140
  1705. package/dist/src/utils/pdf.js +0 -236
  1706. package/dist/src/utils/pdfUtils.js +0 -61
  1707. package/dist/src/utils/peerAddress.js +0 -20
  1708. package/dist/src/utils/permissions/PermissionMode.js +0 -95
  1709. package/dist/src/utils/permissions/PermissionPromptToolResultSchema.js +0 -85
  1710. package/dist/src/utils/permissions/PermissionResult.js +0 -11
  1711. package/dist/src/utils/permissions/PermissionRule.js +0 -19
  1712. package/dist/src/utils/permissions/PermissionUpdate.js +0 -268
  1713. package/dist/src/utils/permissions/PermissionUpdateSchema.js +0 -61
  1714. package/dist/src/utils/permissions/autoModeState.js +0 -34
  1715. package/dist/src/utils/permissions/bashClassifier.js +0 -30
  1716. package/dist/src/utils/permissions/bypassPermissionsKillswitch.js +0 -115
  1717. package/dist/src/utils/permissions/classifierDecision.js +0 -88
  1718. package/dist/src/utils/permissions/classifierShared.js +0 -28
  1719. package/dist/src/utils/permissions/dangerousPatterns.js +0 -78
  1720. package/dist/src/utils/permissions/denialTracking.js +0 -34
  1721. package/dist/src/utils/permissions/filesystem.js +0 -1411
  1722. package/dist/src/utils/permissions/getNextPermissionMode.js +0 -74
  1723. package/dist/src/utils/permissions/pathValidation.js +0 -351
  1724. package/dist/src/utils/permissions/permissionExplainer.js +0 -188
  1725. package/dist/src/utils/permissions/permissionRuleParser.js +0 -177
  1726. package/dist/src/utils/permissions/permissionSetup.js +0 -1164
  1727. package/dist/src/utils/permissions/permissions.js +0 -1065
  1728. package/dist/src/utils/permissions/permissionsLoader.js +0 -217
  1729. package/dist/src/utils/permissions/shadowedRuleDetection.js +0 -149
  1730. package/dist/src/utils/permissions/shellRuleMatching.js +0 -174
  1731. package/dist/src/utils/permissions/yoloClassifier.js +0 -1195
  1732. package/dist/src/utils/planModeV2.js +0 -75
  1733. package/dist/src/utils/plans.js +0 -334
  1734. package/dist/src/utils/platform.js +0 -122
  1735. package/dist/src/utils/plugins/addDirPluginSettings.js +0 -53
  1736. package/dist/src/utils/plugins/cacheUtils.js +0 -174
  1737. package/dist/src/utils/plugins/dependencyResolver.js +0 -244
  1738. package/dist/src/utils/plugins/fetchTelemetry.js +0 -108
  1739. package/dist/src/utils/plugins/gitAvailability.js +0 -65
  1740. package/dist/src/utils/plugins/headlessPluginInstall.js +0 -136
  1741. package/dist/src/utils/plugins/hintRecommendation.js +0 -136
  1742. package/dist/src/utils/plugins/installCounts.js +0 -218
  1743. package/dist/src/utils/plugins/installedPluginsManager.js +0 -1003
  1744. package/dist/src/utils/plugins/loadPluginAgents.js +0 -219
  1745. package/dist/src/utils/plugins/loadPluginCommands.js +0 -595
  1746. package/dist/src/utils/plugins/loadPluginHooks.js +0 -239
  1747. package/dist/src/utils/plugins/loadPluginOutputStyles.js +0 -112
  1748. package/dist/src/utils/plugins/lspPluginIntegration.js +0 -293
  1749. package/dist/src/utils/plugins/lspRecommendation.js +0 -278
  1750. package/dist/src/utils/plugins/managedPlugins.js +0 -26
  1751. package/dist/src/utils/plugins/marketplaceHelpers.js +0 -470
  1752. package/dist/src/utils/plugins/marketplaceManager.js +0 -1939
  1753. package/dist/src/utils/plugins/mcpPluginIntegration.js +0 -465
  1754. package/dist/src/utils/plugins/mcpbHandler.js +0 -708
  1755. package/dist/src/utils/plugins/officialMarketplace.js +0 -21
  1756. package/dist/src/utils/plugins/officialMarketplaceGcs.js +0 -195
  1757. package/dist/src/utils/plugins/officialMarketplaceStartupCheck.js +0 -338
  1758. package/dist/src/utils/plugins/orphanedPluginFilter.js +0 -96
  1759. package/dist/src/utils/plugins/parseMarketplaceInput.js +0 -143
  1760. package/dist/src/utils/plugins/performStartupChecks.js +0 -66
  1761. package/dist/src/utils/plugins/pluginAutoupdate.js +0 -210
  1762. package/dist/src/utils/plugins/pluginBlocklist.js +0 -93
  1763. package/dist/src/utils/plugins/pluginDirectories.js +0 -170
  1764. package/dist/src/utils/plugins/pluginFlagging.js +0 -173
  1765. package/dist/src/utils/plugins/pluginIdentifier.js +0 -78
  1766. package/dist/src/utils/plugins/pluginInstallationHelpers.js +0 -400
  1767. package/dist/src/utils/plugins/pluginLoader.js +0 -2426
  1768. package/dist/src/utils/plugins/pluginOptionsStorage.js +0 -311
  1769. package/dist/src/utils/plugins/pluginPolicy.js +0 -18
  1770. package/dist/src/utils/plugins/pluginStartupCheck.js +0 -261
  1771. package/dist/src/utils/plugins/pluginVersioning.js +0 -128
  1772. package/dist/src/utils/plugins/reconciler.js +0 -181
  1773. package/dist/src/utils/plugins/refresh.js +0 -162
  1774. package/dist/src/utils/plugins/schemas.js +0 -1283
  1775. package/dist/src/utils/plugins/validatePlugin.js +0 -765
  1776. package/dist/src/utils/plugins/walkPluginMarkdown.js +0 -49
  1777. package/dist/src/utils/plugins/zipCache.js +0 -346
  1778. package/dist/src/utils/plugins/zipCacheAdapters.js +0 -133
  1779. package/dist/src/utils/postCommitAttribution.js +0 -16
  1780. package/dist/src/utils/powershell/dangerousCmdlets.js +0 -174
  1781. package/dist/src/utils/powershell/parser.js +0 -1357
  1782. package/dist/src/utils/powershell/staticPrefix.js +0 -277
  1783. package/dist/src/utils/preflightChecks.js +0 -147
  1784. package/dist/src/utils/privacyLevel.js +0 -49
  1785. package/dist/src/utils/process.js +0 -56
  1786. package/dist/src/utils/processUserInput/processBashCommand.js +0 -119
  1787. package/dist/src/utils/processUserInput/processSlashCommand.js +0 -845
  1788. package/dist/src/utils/processUserInput/processTextPrompt.js +0 -68
  1789. package/dist/src/utils/processUserInput/processUserInput.js +0 -326
  1790. package/dist/src/utils/profilerBase.js +0 -29
  1791. package/dist/src/utils/promptCategory.js +0 -39
  1792. package/dist/src/utils/promptEditor.js +0 -151
  1793. package/dist/src/utils/promptShellExecution.js +0 -119
  1794. package/dist/src/utils/proxy.js +0 -347
  1795. package/dist/src/utils/queryContext.js +0 -110
  1796. package/dist/src/utils/queryHelpers.js +0 -436
  1797. package/dist/src/utils/queryProfiler.js +0 -242
  1798. package/dist/src/utils/queueProcessor.js +0 -70
  1799. package/dist/src/utils/readEditContext.js +0 -176
  1800. package/dist/src/utils/readFileInRange.js +0 -278
  1801. package/dist/src/utils/releaseNotes.js +0 -304
  1802. package/dist/src/utils/renderOptions.js +0 -67
  1803. package/dist/src/utils/ripgrep.js +0 -540
  1804. package/dist/src/utils/sandbox/sandbox-adapter.js +0 -749
  1805. package/dist/src/utils/sandbox/sandbox-ui-utils.js +0 -11
  1806. package/dist/src/utils/sanitization.js +0 -72
  1807. package/dist/src/utils/screenshotClipboard.js +0 -89
  1808. package/dist/src/utils/sdkEventQueue.js +0 -49
  1809. package/dist/src/utils/sdkHeapDumpMonitor.js +0 -16
  1810. package/dist/src/utils/secureStorage/fallbackStorage.js +0 -59
  1811. package/dist/src/utils/secureStorage/index.js +0 -14
  1812. package/dist/src/utils/secureStorage/keychainPrefetch.js +0 -91
  1813. package/dist/src/utils/secureStorage/macOsKeychainHelpers.js +0 -91
  1814. package/dist/src/utils/secureStorage/macOsKeychainStorage.js +0 -192
  1815. package/dist/src/utils/secureStorage/plainTextStorage.js +0 -81
  1816. package/dist/src/utils/secureStorage/secureStoreDefs.js +0 -1
  1817. package/dist/src/utils/secureStorage/sqliteStorage.js +0 -217
  1818. package/dist/src/utils/secureStorage/types.js +0 -1
  1819. package/dist/src/utils/semanticBoolean.js +0 -23
  1820. package/dist/src/utils/semanticNumber.js +0 -34
  1821. package/dist/src/utils/semver.js +0 -53
  1822. package/dist/src/utils/sequential.js +0 -43
  1823. package/dist/src/utils/sessionActivity.js +0 -120
  1824. package/dist/src/utils/sessionDataUploader.js +0 -16
  1825. package/dist/src/utils/sessionEnvVars.js +0 -18
  1826. package/dist/src/utils/sessionEnvironment.js +0 -131
  1827. package/dist/src/utils/sessionFileAccessHooks.js +0 -207
  1828. package/dist/src/utils/sessionIngressAuth.js +0 -113
  1829. package/dist/src/utils/sessionRestore.js +0 -359
  1830. package/dist/src/utils/sessionStart.js +0 -165
  1831. package/dist/src/utils/sessionState.js +0 -76
  1832. package/dist/src/utils/sessionStorage.js +0 -4162
  1833. package/dist/src/utils/sessionStoragePortable.js +0 -665
  1834. package/dist/src/utils/sessionTitle.js +0 -120
  1835. package/dist/src/utils/sessionUrl.js +0 -50
  1836. package/dist/src/utils/set.js +0 -50
  1837. package/dist/src/utils/settings/allErrors.js +0 -29
  1838. package/dist/src/utils/settings/applySettingsChange.js +0 -65
  1839. package/dist/src/utils/settings/changeDetector.js +0 -409
  1840. package/dist/src/utils/settings/constants.js +0 -166
  1841. package/dist/src/utils/settings/internalWrites.js +0 -33
  1842. package/dist/src/utils/settings/managedPath.js +0 -29
  1843. package/dist/src/utils/settings/mdm/constants.js +0 -62
  1844. package/dist/src/utils/settings/mdm/rawRead.js +0 -97
  1845. package/dist/src/utils/settings/mdm/settings.js +0 -254
  1846. package/dist/src/utils/settings/permissionValidation.js +0 -224
  1847. package/dist/src/utils/settings/pluginOnlyPolicy.js +0 -53
  1848. package/dist/src/utils/settings/schemaOutput.js +0 -7
  1849. package/dist/src/utils/settings/settings.js +0 -791
  1850. package/dist/src/utils/settings/settingsCache.js +0 -47
  1851. package/dist/src/utils/settings/toolValidationConfig.js +0 -76
  1852. package/dist/src/utils/settings/types.js +0 -846
  1853. package/dist/src/utils/settings/validateEditTool.js +0 -34
  1854. package/dist/src/utils/settings/validation.js +0 -192
  1855. package/dist/src/utils/settings/validationTips.js +0 -111
  1856. package/dist/src/utils/shell/bashProvider.js +0 -202
  1857. package/dist/src/utils/shell/outputLimits.js +0 -7
  1858. package/dist/src/utils/shell/powershellDetection.js +0 -96
  1859. package/dist/src/utils/shell/powershellProvider.js +0 -104
  1860. package/dist/src/utils/shell/prefix.js +0 -246
  1861. package/dist/src/utils/shell/readOnlyCommandValidation.js +0 -1776
  1862. package/dist/src/utils/shell/resolveDefaultShell.js +0 -13
  1863. package/dist/src/utils/shell/shellProvider.js +0 -2
  1864. package/dist/src/utils/shell/shellToolUtils.js +0 -21
  1865. package/dist/src/utils/shell/specPrefix.js +0 -198
  1866. package/dist/src/utils/shellConfig.js +0 -136
  1867. package/dist/src/utils/sideQuery.js +0 -195
  1868. package/dist/src/utils/sideQuestion.js +0 -121
  1869. package/dist/src/utils/signal.js +0 -34
  1870. package/dist/src/utils/sinks.js +0 -15
  1871. package/dist/src/utils/skills/skillChangeDetector.js +0 -264
  1872. package/dist/src/utils/slashCommandParsing.js +0 -46
  1873. package/dist/src/utils/sleep.js +0 -72
  1874. package/dist/src/utils/sliceAnsi.js +0 -74
  1875. package/dist/src/utils/slowOperations.js +0 -323
  1876. package/dist/src/utils/standaloneAgent.js +0 -20
  1877. package/dist/src/utils/startupProfiler.js +0 -158
  1878. package/dist/src/utils/staticRender.js +0 -103
  1879. package/dist/src/utils/stats.js +0 -802
  1880. package/dist/src/utils/statsCache.js +0 -330
  1881. package/dist/src/utils/status.js +0 -544
  1882. package/dist/src/utils/statusNoticeDefinitions.js +0 -112
  1883. package/dist/src/utils/statusNoticeHelpers.js +0 -15
  1884. package/dist/src/utils/stream.js +0 -73
  1885. package/dist/src/utils/streamJsonStdoutGuard.js +0 -107
  1886. package/dist/src/utils/streamlinedTransform.js +0 -162
  1887. package/dist/src/utils/stringUtils.js +0 -202
  1888. package/dist/src/utils/subprocessEnv.js +0 -87
  1889. package/dist/src/utils/suggestions/commandSuggestions.js +0 -458
  1890. package/dist/src/utils/suggestions/directoryCompletion.js +0 -191
  1891. package/dist/src/utils/suggestions/shellHistoryCompletion.js +0 -95
  1892. package/dist/src/utils/suggestions/skillUsageTracking.js +0 -50
  1893. package/dist/src/utils/suggestions/slackChannelSuggestions.js +0 -169
  1894. package/dist/src/utils/swarm/It2SetupPrompt.js +0 -386
  1895. package/dist/src/utils/swarm/backends/ITermBackend.js +0 -276
  1896. package/dist/src/utils/swarm/backends/InProcessBackend.js +0 -237
  1897. package/dist/src/utils/swarm/backends/PaneBackendExecutor.js +0 -250
  1898. package/dist/src/utils/swarm/backends/TmuxBackend.js +0 -574
  1899. package/dist/src/utils/swarm/backends/detection.js +0 -112
  1900. package/dist/src/utils/swarm/backends/it2Setup.js +0 -185
  1901. package/dist/src/utils/swarm/backends/registry.js +0 -369
  1902. package/dist/src/utils/swarm/backends/teammateModeSnapshot.js +0 -68
  1903. package/dist/src/utils/swarm/backends/types.js +0 -9
  1904. package/dist/src/utils/swarm/constants.js +0 -29
  1905. package/dist/src/utils/swarm/inProcessRunner.js +0 -1021
  1906. package/dist/src/utils/swarm/leaderPermissionBridge.js +0 -31
  1907. package/dist/src/utils/swarm/permissionSync.js +0 -667
  1908. package/dist/src/utils/swarm/reconnection.js +0 -82
  1909. package/dist/src/utils/swarm/spawnInProcess.js +0 -218
  1910. package/dist/src/utils/swarm/spawnUtils.js +0 -123
  1911. package/dist/src/utils/swarm/teamHelpers.js +0 -484
  1912. package/dist/src/utils/swarm/teammateInit.js +0 -87
  1913. package/dist/src/utils/swarm/teammateLayoutManager.js +0 -82
  1914. package/dist/src/utils/swarm/teammateModel.js +0 -9
  1915. package/dist/src/utils/swarm/teammatePromptAddendum.js +0 -17
  1916. package/dist/src/utils/systemDirectories.js +0 -51
  1917. package/dist/src/utils/systemPrompt.js +0 -90
  1918. package/dist/src/utils/systemPromptType.js +0 -9
  1919. package/dist/src/utils/systemTheme.js +0 -108
  1920. package/dist/src/utils/systemThemeWatcher.js +0 -16
  1921. package/dist/src/utils/taggedId.js +0 -49
  1922. package/dist/src/utils/task/TaskOutput.js +0 -320
  1923. package/dist/src/utils/task/diskOutput.js +0 -387
  1924. package/dist/src/utils/task/framework.js +0 -236
  1925. package/dist/src/utils/task/outputFormatting.js +0 -24
  1926. package/dist/src/utils/task/sdkProgress.js +0 -24
  1927. package/dist/src/utils/tasks.js +0 -672
  1928. package/dist/src/utils/teamDiscovery.js +0 -48
  1929. package/dist/src/utils/teamMemoryOps.js +0 -67
  1930. package/dist/src/utils/teammate.js +0 -237
  1931. package/dist/src/utils/teammateContext.js +0 -56
  1932. package/dist/src/utils/teammateMailbox.js +0 -793
  1933. package/dist/src/utils/telemetry/betaSessionTracing.js +0 -371
  1934. package/dist/src/utils/telemetry/bigqueryExporter.js +0 -178
  1935. package/dist/src/utils/telemetry/events.js +0 -57
  1936. package/dist/src/utils/telemetry/instrumentation.js +0 -617
  1937. package/dist/src/utils/telemetry/logger.js +0 -25
  1938. package/dist/src/utils/telemetry/perfettoTracing.js +0 -882
  1939. package/dist/src/utils/telemetry/pluginTelemetry.js +0 -157
  1940. package/dist/src/utils/telemetry/sessionTracing.js +0 -693
  1941. package/dist/src/utils/telemetry/skillLoadedEvent.js +0 -26
  1942. package/dist/src/utils/telemetryAttributes.js +0 -57
  1943. package/dist/src/utils/teleport/api.js +0 -299
  1944. package/dist/src/utils/teleport/environmentSelection.js +0 -55
  1945. package/dist/src/utils/teleport/environments.js +0 -84
  1946. package/dist/src/utils/teleport/gitBundle.js +0 -192
  1947. package/dist/src/utils/teleport.js +0 -1041
  1948. package/dist/src/utils/tempfile.js +0 -26
  1949. package/dist/src/utils/terminal.js +0 -105
  1950. package/dist/src/utils/terminalPanel.js +0 -155
  1951. package/dist/src/utils/textHighlighting.js +0 -113
  1952. package/dist/src/utils/theme.js +0 -525
  1953. package/dist/src/utils/thinking.js +0 -130
  1954. package/dist/src/utils/timeouts.js +0 -35
  1955. package/dist/src/utils/tmuxSocket.js +0 -373
  1956. package/dist/src/utils/todo/types.js +0 -9
  1957. package/dist/src/utils/tokenBudget.js +0 -62
  1958. package/dist/src/utils/tokens.js +0 -223
  1959. package/dist/src/utils/toolErrors.js +0 -101
  1960. package/dist/src/utils/toolPool.js +0 -63
  1961. package/dist/src/utils/toolResultStorage.js +0 -769
  1962. package/dist/src/utils/toolSchemaCache.js +0 -7
  1963. package/dist/src/utils/toolSearch.js +0 -551
  1964. package/dist/src/utils/transcriptSearch.js +0 -200
  1965. package/dist/src/utils/treeify.js +0 -111
  1966. package/dist/src/utils/truncate.js +0 -164
  1967. package/dist/src/utils/udsClient.js +0 -16
  1968. package/dist/src/utils/udsMessaging.js +0 -16
  1969. package/dist/src/utils/ultraplan/ccrSession.js +0 -264
  1970. package/dist/src/utils/ultraplan/keyword.js +0 -122
  1971. package/dist/src/utils/ultraplan/prompt.txt +0 -1
  1972. package/dist/src/utils/unaryLogging.js +0 -16
  1973. package/dist/src/utils/undercover.js +0 -89
  1974. package/dist/src/utils/user.js +0 -138
  1975. package/dist/src/utils/userAgent.js +0 -13
  1976. package/dist/src/utils/userPromptKeywords.js +0 -21
  1977. package/dist/src/utils/uuid.js +0 -22
  1978. package/dist/src/utils/warningHandler.js +0 -97
  1979. package/dist/src/utils/which.js +0 -75
  1980. package/dist/src/utils/windowsPaths.js +0 -146
  1981. package/dist/src/utils/withResolvers.js +0 -13
  1982. package/dist/src/utils/words.js +0 -793
  1983. package/dist/src/utils/workloadContext.js +0 -42
  1984. package/dist/src/utils/worktree.js +0 -1142
  1985. package/dist/src/utils/worktreeModeEnabled.js +0 -11
  1986. package/dist/src/utils/xdg.js +0 -52
  1987. package/dist/src/utils/xml.js +0 -15
  1988. package/dist/src/utils/yaml.js +0 -16
  1989. package/dist/src/utils/zodToJsonSchema.js +0 -19
  1990. package/dist/src/vim/motions.js +0 -73
  1991. package/dist/src/vim/operators.js +0 -401
  1992. package/dist/src/vim/textObjects.js +0 -153
  1993. package/dist/src/vim/transitions.js +0 -340
  1994. package/dist/src/vim/types.js +0 -93
  1995. package/dist/src/voice/voiceModeEnabled.js +0 -48
  1996. package/dist/src/whatsapp/bridge.js +0 -267
  1997. package/dist/src/whatsapp/config.js +0 -128
  1998. package/dist/src/whatsapp/markdown.js +0 -37
  1999. package/dist/src/whatsapp/mirror.js +0 -74
  2000. package/dist/src/whatsapp/session.js +0 -142
@@ -1,4225 +0,0 @@
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
- }