@iaforged/context-code 1.0.63 → 1.0.65

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 +633 -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,3668 +0,0 @@
1
- // biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
2
- /**
3
- * Hooks are user-defined shell commands that can be executed at various points
4
- * in Context Code's lifecycle.
5
- */
6
- import { basename } from 'path';
7
- import { spawn } from 'child_process';
8
- import { pathExists } from './file.js';
9
- import { wrapSpawn } from './ShellCommand.js';
10
- import { TaskOutput } from './task/TaskOutput.js';
11
- import { getCwd } from './cwd.js';
12
- import { randomUUID } from 'crypto';
13
- import { formatShellPrefixCommand } from './bash/shellPrefix.js';
14
- import { getHookEnvFilePath, invalidateSessionEnvCache, } from './sessionEnvironment.js';
15
- import { subprocessEnv } from './subprocessEnv.js';
16
- import { getPlatform } from './platform.js';
17
- import { findGitBashPath, windowsPathToPosixPath } from './windowsPaths.js';
18
- import { getCachedPowerShellPath } from './shell/powershellDetection.js';
19
- import { DEFAULT_HOOK_SHELL } from './shell/shellProvider.js';
20
- import { buildPowerShellArgs } from './shell/powershellProvider.js';
21
- import { loadPluginOptions, substituteUserConfigVariables, } from './plugins/pluginOptionsStorage.js';
22
- import { getPluginDataDir } from './plugins/pluginDirectories.js';
23
- import { getSessionId, getProjectRoot, getIsNonInteractiveSession, getRegisteredHooks, getStatsStore, addToTurnHookDuration, getOriginalCwd, getMainThreadAgentType, } from '../bootstrap/state.js';
24
- import { checkHasTrustDialogAccepted } from './config.js';
25
- import { getHooksConfigFromSnapshot, shouldAllowManagedHooksOnly, shouldDisableAllHooksIncludingManaged, } from './hooks/hooksConfigSnapshot.js';
26
- import { getTranscriptPathForSession, getAgentTranscriptPath, } from './sessionStorage.js';
27
- import { getSettings_DEPRECATED, getSettingsForSource, } from './settings/settings.js';
28
- import { logEvent, } from '../services/analytics/index.js';
29
- import { logOTelEvent } from './telemetry/events.js';
30
- import { ALLOWED_OFFICIAL_MARKETPLACE_NAMES } from './plugins/schemas.js';
31
- import { startHookSpan, endHookSpan, isBetaTracingEnabled, } from './telemetry/sessionTracing.js';
32
- import { hookJSONOutputSchema, promptRequestSchema, isAsyncHookJSONOutput, isSyncHookJSONOutput, } from '../types/hooks.js';
33
- import chalk from 'chalk';
34
- import { getHookDisplayText } from './hooks/hooksSettings.js';
35
- import { logForDebugging } from './debug.js';
36
- import { logForDiagnosticsNoPII } from './diagLogs.js';
37
- import { firstLineOf } from './stringUtils.js';
38
- import { normalizeLegacyToolName, getLegacyToolNames, permissionRuleValueFromString, } from './permissions/permissionRuleParser.js';
39
- import { logError } from './log.js';
40
- import { createCombinedAbortSignal } from './combinedAbortSignal.js';
41
- import { registerPendingAsyncHook } from './hooks/AsyncHookRegistry.js';
42
- import { enqueuePendingNotification } from './messageQueueManager.js';
43
- import { extractTextContent, getLastAssistantMessage, wrapInSystemReminder, } from './messages.js';
44
- import { emitHookStarted, emitHookResponse, startHookProgressInterval, } from './hooks/hookEvents.js';
45
- import { createAttachmentMessage } from './attachments.js';
46
- import { all } from './generators.js';
47
- import { findToolByName } from '../Tool.js';
48
- import { execPromptHook } from './hooks/execPromptHook.js';
49
- import { execAgentHook } from './hooks/execAgentHook.js';
50
- import { execHttpHook } from './hooks/execHttpHook.js';
51
- import { getSessionHooks, getSessionFunctionHooks, getSessionHookCallback, clearSessionHooks, } from './hooks/sessionHooks.js';
52
- import { jsonStringify, jsonParse } from './slowOperations.js';
53
- import { isEnvTruthy } from './envUtils.js';
54
- import { errorMessage, getErrnoCode } from './errors.js';
55
- const TOOL_HOOK_EXECUTION_TIMEOUT_MS = 10 * 60 * 1000;
56
- /**
57
- * SessionEnd hooks run during shutdown/clear and need a much tighter bound
58
- * than TOOL_HOOK_EXECUTION_TIMEOUT_MS. This value is used by callers as both
59
- * the per-hook default timeout AND the overall AbortSignal cap (hooks run in
60
- * parallel, so one value suffices). Overridable via env var for users whose
61
- * teardown scripts need more time.
62
- */
63
- const SESSION_END_HOOK_TIMEOUT_MS_DEFAULT = 1500;
64
- export function getSessionEndHookTimeoutMs() {
65
- const raw = process.env.CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS;
66
- const parsed = raw ? parseInt(raw, 10) : NaN;
67
- return Number.isFinite(parsed) && parsed > 0
68
- ? parsed
69
- : SESSION_END_HOOK_TIMEOUT_MS_DEFAULT;
70
- }
71
- function executeInBackground({ processId, hookId, shellCommand, asyncResponse, hookEvent, hookName, command, asyncRewake, pluginId, }) {
72
- if (asyncRewake) {
73
- // asyncRewake hooks bypass the registry entirely. On completion, if exit
74
- // code 2 (blocking error), enqueue as a task-notification so it wakes the
75
- // model via useQueueProcessor (idle) or gets injected mid-query via
76
- // queued_command attachments (busy).
77
- //
78
- // NOTE: We deliberately do NOT call shellCommand.background() here, because
79
- // it calls taskOutput.spillToDisk() which breaks in-memory stdout/stderr
80
- // capture (getStderr() returns '' in disk mode). The StreamWrappers stay
81
- // attached and pipe data into the in-memory TaskOutput buffers. The abort
82
- // handler already no-ops on 'interrupt' reason (user submitted a new
83
- // message), so the hook survives new prompts. A hard cancel (Escape) WILL
84
- // kill the hook via the abort handler, which is the desired behavior.
85
- void shellCommand.result.then(async (result) => {
86
- // result resolves on 'exit', but stdio 'data' events may still be
87
- // pending. Yield to I/O so the StreamWrapper data handlers drain into
88
- // TaskOutput before we read it.
89
- await new Promise(resolve => setImmediate(resolve));
90
- const stdout = await shellCommand.taskOutput.getStdout();
91
- const stderr = shellCommand.taskOutput.getStderr();
92
- shellCommand.cleanup();
93
- emitHookResponse({
94
- hookId,
95
- hookName,
96
- hookEvent,
97
- output: stdout + stderr,
98
- stdout,
99
- stderr,
100
- exitCode: result.code,
101
- outcome: result.code === 0 ? 'success' : 'error',
102
- });
103
- if (result.code === 2) {
104
- enqueuePendingNotification({
105
- value: wrapInSystemReminder(`Stop hook blocking error from command "${hookName}": ${stderr || stdout}`),
106
- mode: 'task-notification',
107
- });
108
- }
109
- });
110
- return true;
111
- }
112
- // TaskOutput on the ShellCommand accumulates data — no stream listeners needed
113
- if (!shellCommand.background(processId)) {
114
- return false;
115
- }
116
- registerPendingAsyncHook({
117
- processId,
118
- hookId,
119
- asyncResponse,
120
- hookEvent,
121
- hookName,
122
- command,
123
- shellCommand,
124
- pluginId,
125
- });
126
- return true;
127
- }
128
- /**
129
- * Checks if a hook should be skipped due to lack of workspace trust.
130
- *
131
- * ALL hooks require workspace trust because they execute arbitrary commands from
132
- * .claude/settings.json. This is a defense-in-depth security measure.
133
- *
134
- * Context: Hooks are captured via captureHooksConfigSnapshot() before the trust
135
- * dialog is shown. While most hooks won't execute until after trust is established
136
- * through normal program flow, enforcing trust for ALL hooks prevents:
137
- * - Future bugs where a hook might accidentally execute before trust
138
- * - Any codepath that might trigger hooks before trust dialog
139
- * - Security issues from hook execution in untrusted workspaces
140
- *
141
- * Historical vulnerabilities that prompted this check:
142
- * - SessionEnd hooks executing when user declines trust dialog
143
- * - SubagentStop hooks executing when subagent completes before trust
144
- *
145
- * @returns true if hook should be skipped, false if it should execute
146
- */
147
- export function shouldSkipHookDueToTrust() {
148
- // In non-interactive mode (SDK), trust is implicit - always execute
149
- const isInteractive = !getIsNonInteractiveSession();
150
- if (!isInteractive) {
151
- return false;
152
- }
153
- // In interactive mode, ALL hooks require trust
154
- const hasTrust = checkHasTrustDialogAccepted();
155
- return !hasTrust;
156
- }
157
- /**
158
- * Creates the base hook input that's common to all hook types
159
- */
160
- export function createBaseHookInput(permissionMode, sessionId,
161
- // Typed narrowly (not ToolUseContext) so callers can pass toolUseContext
162
- // directly via structural typing without this function depending on Tool.ts.
163
- agentInfo) {
164
- const resolvedSessionId = sessionId ?? getSessionId();
165
- // agent_type: subagent's type (from toolUseContext) takes precedence over
166
- // the session's --agent flag. Hooks use agent_id presence to distinguish
167
- // subagent calls from main-thread calls in a --agent session.
168
- const resolvedAgentType = agentInfo?.agentType ?? getMainThreadAgentType();
169
- return {
170
- session_id: resolvedSessionId,
171
- transcript_path: getTranscriptPathForSession(resolvedSessionId),
172
- cwd: getCwd(),
173
- permission_mode: permissionMode,
174
- agent_id: agentInfo?.agentId,
175
- agent_type: resolvedAgentType,
176
- };
177
- }
178
- /**
179
- * Parse and validate a JSON string against the hook output Zod schema.
180
- * Returns the validated output or formatted validation errors.
181
- */
182
- function validateHookJson(jsonString) {
183
- const parsed = jsonParse(jsonString);
184
- const validation = hookJSONOutputSchema().safeParse(parsed);
185
- if (validation.success) {
186
- logForDebugging('Successfully parsed and validated hook JSON output');
187
- return { json: validation.data };
188
- }
189
- const errors = validation.error.issues
190
- .map(err => ` - ${err.path.join('.')}: ${err.message}`)
191
- .join('\n');
192
- return {
193
- validationError: `Hook JSON output validation failed:\n${errors}\n\nThe hook's output was: ${jsonStringify(parsed, null, 2)}`,
194
- };
195
- }
196
- function parseHookOutput(stdout) {
197
- const trimmed = stdout.trim();
198
- if (!trimmed.startsWith('{')) {
199
- logForDebugging('Hook output does not start with {, treating as plain text');
200
- return { plainText: stdout };
201
- }
202
- try {
203
- const result = validateHookJson(trimmed);
204
- if ('json' in result) {
205
- return result;
206
- }
207
- // For command hooks, include the schema hint in the error message
208
- const errorMessage = `${result.validationError}\n\nExpected schema:\n${jsonStringify({
209
- continue: 'boolean (optional)',
210
- suppressOutput: 'boolean (optional)',
211
- stopReason: 'string (optional)',
212
- decision: '"approve" | "block" (optional)',
213
- reason: 'string (optional)',
214
- systemMessage: 'string (optional)',
215
- permissionDecision: '"allow" | "deny" | "ask" (optional)',
216
- hookSpecificOutput: {
217
- 'for PreToolUse': {
218
- hookEventName: '"PreToolUse"',
219
- permissionDecision: '"allow" | "deny" | "ask" (optional)',
220
- permissionDecisionReason: 'string (optional)',
221
- updatedInput: 'object (optional) - Modified tool input to use',
222
- },
223
- 'for UserPromptSubmit': {
224
- hookEventName: '"UserPromptSubmit"',
225
- additionalContext: 'string (required)',
226
- },
227
- 'for PostToolUse': {
228
- hookEventName: '"PostToolUse"',
229
- additionalContext: 'string (optional)',
230
- },
231
- },
232
- }, null, 2)}`;
233
- logForDebugging(errorMessage);
234
- return { plainText: stdout, validationError: errorMessage };
235
- }
236
- catch (e) {
237
- logForDebugging(`Failed to parse hook output as JSON: ${e}`);
238
- return { plainText: stdout };
239
- }
240
- }
241
- function parseHttpHookOutput(body) {
242
- const trimmed = body.trim();
243
- if (trimmed === '') {
244
- const validation = hookJSONOutputSchema().safeParse({});
245
- if (validation.success) {
246
- logForDebugging('HTTP hook returned empty body, treating as empty JSON object');
247
- return { json: validation.data };
248
- }
249
- }
250
- if (!trimmed.startsWith('{')) {
251
- const validationError = `HTTP hook must return JSON, but got non-JSON response body: ${trimmed.length > 200 ? trimmed.slice(0, 200) + '\u2026' : trimmed}`;
252
- logForDebugging(validationError);
253
- return { validationError };
254
- }
255
- try {
256
- const result = validateHookJson(trimmed);
257
- if ('json' in result) {
258
- return result;
259
- }
260
- logForDebugging(result.validationError);
261
- return result;
262
- }
263
- catch (e) {
264
- const validationError = `HTTP hook must return valid JSON, but parsing failed: ${e}`;
265
- logForDebugging(validationError);
266
- return { validationError };
267
- }
268
- }
269
- function processHookJSONOutput({ json, command, hookName, toolUseID, hookEvent, expectedHookEvent, stdout, stderr, exitCode, durationMs, }) {
270
- const result = {};
271
- // At this point we know it's a sync response
272
- const syncJson = json;
273
- // Handle common elements
274
- if (syncJson.continue === false) {
275
- result.preventContinuation = true;
276
- if (syncJson.stopReason) {
277
- result.stopReason = syncJson.stopReason;
278
- }
279
- }
280
- if (json.decision) {
281
- switch (json.decision) {
282
- case 'approve':
283
- result.permissionBehavior = 'allow';
284
- break;
285
- case 'block':
286
- result.permissionBehavior = 'deny';
287
- result.blockingError = {
288
- blockingError: json.reason || 'Blocked by hook',
289
- command,
290
- };
291
- break;
292
- default:
293
- // Handle unknown decision types as errors
294
- throw new Error(`Unknown hook decision type: ${json.decision}. Valid types are: approve, block`);
295
- }
296
- }
297
- // Handle systemMessage field
298
- if (json.systemMessage) {
299
- result.systemMessage = json.systemMessage;
300
- }
301
- // Handle PreToolUse specific
302
- if (json.hookSpecificOutput?.hookEventName === 'PreToolUse' &&
303
- json.hookSpecificOutput.permissionDecision) {
304
- switch (json.hookSpecificOutput.permissionDecision) {
305
- case 'allow':
306
- result.permissionBehavior = 'allow';
307
- break;
308
- case 'deny':
309
- result.permissionBehavior = 'deny';
310
- result.blockingError = {
311
- blockingError: json.reason || 'Blocked by hook',
312
- command,
313
- };
314
- break;
315
- case 'ask':
316
- result.permissionBehavior = 'ask';
317
- break;
318
- default:
319
- // Handle unknown decision types as errors
320
- throw new Error(`Unknown hook permissionDecision type: ${json.hookSpecificOutput.permissionDecision}. Valid types are: allow, deny, ask`);
321
- }
322
- }
323
- if (result.permissionBehavior !== undefined && json.reason !== undefined) {
324
- result.hookPermissionDecisionReason = json.reason;
325
- }
326
- // Handle hookSpecificOutput
327
- if (json.hookSpecificOutput) {
328
- // Validate hook event name matches expected if provided
329
- if (expectedHookEvent &&
330
- json.hookSpecificOutput.hookEventName !== expectedHookEvent) {
331
- throw new Error(`Hook returned incorrect event name: expected '${expectedHookEvent}' but got '${json.hookSpecificOutput.hookEventName}'. Full stdout: ${jsonStringify(json, null, 2)}`);
332
- }
333
- switch (json.hookSpecificOutput.hookEventName) {
334
- case 'PreToolUse':
335
- // Override with more specific permission decision if provided
336
- if (json.hookSpecificOutput.permissionDecision) {
337
- switch (json.hookSpecificOutput.permissionDecision) {
338
- case 'allow':
339
- result.permissionBehavior = 'allow';
340
- break;
341
- case 'deny':
342
- result.permissionBehavior = 'deny';
343
- result.blockingError = {
344
- blockingError: json.hookSpecificOutput.permissionDecisionReason ||
345
- json.reason ||
346
- 'Blocked by hook',
347
- command,
348
- };
349
- break;
350
- case 'ask':
351
- result.permissionBehavior = 'ask';
352
- break;
353
- }
354
- }
355
- result.hookPermissionDecisionReason =
356
- json.hookSpecificOutput.permissionDecisionReason;
357
- // Extract updatedInput if provided
358
- if (json.hookSpecificOutput.updatedInput) {
359
- result.updatedInput = json.hookSpecificOutput.updatedInput;
360
- }
361
- // Extract additionalContext if provided
362
- result.additionalContext = json.hookSpecificOutput.additionalContext;
363
- break;
364
- case 'UserPromptSubmit':
365
- result.additionalContext = json.hookSpecificOutput.additionalContext;
366
- break;
367
- case 'SessionStart':
368
- result.additionalContext = json.hookSpecificOutput.additionalContext;
369
- result.initialUserMessage = json.hookSpecificOutput.initialUserMessage;
370
- if ('watchPaths' in json.hookSpecificOutput &&
371
- json.hookSpecificOutput.watchPaths) {
372
- result.watchPaths = json.hookSpecificOutput.watchPaths;
373
- }
374
- break;
375
- case 'Setup':
376
- result.additionalContext = json.hookSpecificOutput.additionalContext;
377
- break;
378
- case 'SubagentStart':
379
- result.additionalContext = json.hookSpecificOutput.additionalContext;
380
- break;
381
- case 'PostToolUse':
382
- result.additionalContext = json.hookSpecificOutput.additionalContext;
383
- // Extract updatedMCPToolOutput if provided
384
- if (json.hookSpecificOutput.updatedMCPToolOutput) {
385
- result.updatedMCPToolOutput =
386
- json.hookSpecificOutput.updatedMCPToolOutput;
387
- }
388
- break;
389
- case 'PostToolUseFailure':
390
- result.additionalContext = json.hookSpecificOutput.additionalContext;
391
- break;
392
- case 'PermissionDenied':
393
- result.retry = json.hookSpecificOutput.retry;
394
- break;
395
- case 'PermissionRequest':
396
- // Extract the permission request decision
397
- if (json.hookSpecificOutput.decision) {
398
- result.permissionRequestResult = json.hookSpecificOutput.decision;
399
- // Also update permissionBehavior for consistency
400
- result.permissionBehavior =
401
- json.hookSpecificOutput.decision.behavior === 'allow'
402
- ? 'allow'
403
- : 'deny';
404
- if (json.hookSpecificOutput.decision.behavior === 'allow' &&
405
- json.hookSpecificOutput.decision.updatedInput) {
406
- result.updatedInput = json.hookSpecificOutput.decision.updatedInput;
407
- }
408
- }
409
- break;
410
- case 'Elicitation':
411
- if (json.hookSpecificOutput.action) {
412
- result.elicitationResponse = {
413
- action: json.hookSpecificOutput.action,
414
- content: json.hookSpecificOutput.content,
415
- };
416
- if (json.hookSpecificOutput.action === 'decline') {
417
- result.blockingError = {
418
- blockingError: json.reason || 'Elicitation denied by hook',
419
- command,
420
- };
421
- }
422
- }
423
- break;
424
- case 'ElicitationResult':
425
- if (json.hookSpecificOutput.action) {
426
- result.elicitationResultResponse = {
427
- action: json.hookSpecificOutput.action,
428
- content: json.hookSpecificOutput.content,
429
- };
430
- if (json.hookSpecificOutput.action === 'decline') {
431
- result.blockingError = {
432
- blockingError: json.reason || 'Elicitation result blocked by hook',
433
- command,
434
- };
435
- }
436
- }
437
- break;
438
- }
439
- }
440
- return {
441
- ...result,
442
- message: result.blockingError
443
- ? createAttachmentMessage({
444
- type: 'hook_blocking_error',
445
- hookName,
446
- toolUseID,
447
- hookEvent,
448
- blockingError: result.blockingError,
449
- })
450
- : createAttachmentMessage({
451
- type: 'hook_success',
452
- hookName,
453
- toolUseID,
454
- hookEvent,
455
- // JSON-output hooks inject context via additionalContext →
456
- // hook_additional_context, not this field. Empty content suppresses
457
- // the trivial "X hook success: Success" system-reminder that
458
- // otherwise pollutes every turn (messages.ts:3577 skips on '').
459
- content: '',
460
- stdout,
461
- stderr,
462
- exitCode,
463
- command,
464
- durationMs,
465
- }),
466
- };
467
- }
468
- /**
469
- * Execute a command-based hook using bash or PowerShell.
470
- *
471
- * Shell resolution: hook.shell → 'bash'. PowerShell hooks spawn pwsh
472
- * with -NoProfile -NonInteractive -Command and skip bash-specific prep
473
- * (POSIX path conversion, .sh auto-prepend, CLAUDE_CODE_SHELL_PREFIX).
474
- * See docs/design/ps-shell-selection.md §5.1.
475
- */
476
- async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hookId, hookIndex, pluginRoot, pluginId, skillRoot, forceSyncExecution, requestPrompt) {
477
- // Gated to once-per-session events to keep diag_log volume bounded.
478
- // started/completed live inside the try/finally so setup-path throws
479
- // don't orphan a started marker — that'd be indistinguishable from a hang.
480
- const shouldEmitDiag = hookEvent === 'SessionStart' ||
481
- hookEvent === 'Setup' ||
482
- hookEvent === 'SessionEnd';
483
- const diagStartMs = Date.now();
484
- let diagExitCode;
485
- let diagAborted = false;
486
- const isWindows = getPlatform() === 'windows';
487
- // --
488
- // Per-hook shell selection (phase 1 of docs/design/ps-shell-selection.md).
489
- // Resolution order: hook.shell → DEFAULT_HOOK_SHELL. The defaultShell
490
- // fallback (settings.defaultShell) is phase 2 — not wired yet.
491
- //
492
- // The bash path is the historical default and stays unchanged. The
493
- // PowerShell path deliberately skips the Windows-specific bash
494
- // accommodations (cygpath conversion, .sh auto-prepend, POSIX-quoted
495
- // SHELL_PREFIX).
496
- const shellType = hook.shell ?? DEFAULT_HOOK_SHELL;
497
- const isPowerShell = shellType === 'powershell';
498
- // --
499
- // Windows bash path: hooks run via Git Bash (Cygwin), NOT cmd.exe.
500
- //
501
- // This means every path we put into env vars or substitute into the command
502
- // string MUST be a POSIX path (/c/Users/foo), not a Windows path
503
- // (C:\Users\foo or C:/Users/foo). Git Bash cannot resolve Windows paths.
504
- //
505
- // windowsPathToPosixPath() is pure-JS regex conversion (no cygpath shell-out):
506
- // C:\Users\foo -> /c/Users/foo, UNC preserved, slashes flipped. Memoized
507
- // (LRU-500) so repeated calls are cheap.
508
- //
509
- // PowerShell path: use native paths — skip the conversion entirely.
510
- // PowerShell expects Windows paths on Windows (and native paths on
511
- // Unix where pwsh is also available).
512
- const toHookPath = isWindows && !isPowerShell
513
- ? (p) => windowsPathToPosixPath(p)
514
- : (p) => p;
515
- // Set CLAUDE_PROJECT_DIR to the stable project root (not the worktree path).
516
- // getProjectRoot() is never updated when entering a worktree, so hooks that
517
- // reference $CLAUDE_PROJECT_DIR always resolve relative to the real repo root.
518
- const projectDir = getProjectRoot();
519
- // Substitute ${CLAUDE_PLUGIN_ROOT} and ${user_config.X} in the command string.
520
- // Order matches MCP/LSP (plugin vars FIRST, then user config) so a user-
521
- // entered value containing the literal text ${CLAUDE_PLUGIN_ROOT} is treated
522
- // as opaque — not re-interpreted as a template.
523
- let command = hook.command;
524
- let pluginOpts;
525
- if (pluginRoot) {
526
- // Plugin directory gone (orphan GC race, concurrent session deleted it):
527
- // throw so callers yield a non-blocking error. Running would fail — and
528
- // `python3 <missing>.py` exits 2, the hook protocol's "block" code, which
529
- // bricks UserPromptSubmit/Stop until restart. The pre-check is necessary
530
- // because exit-2-from-missing-script is indistinguishable from an
531
- // intentional block after spawn.
532
- if (!(await pathExists(pluginRoot))) {
533
- throw new Error(`Plugin directory does not exist: ${pluginRoot}` +
534
- (pluginId ? ` (${pluginId} — run /plugin to reinstall)` : ''));
535
- }
536
- // Inline both ROOT and DATA substitution instead of calling
537
- // substitutePluginVariables(). That helper normalizes \ → / on Windows
538
- // unconditionally — correct for bash (toHookPath already produced /c/...
539
- // so it's a no-op) but wrong for PS where toHookPath is identity and we
540
- // want native C:\... backslashes. Inlining also lets us use the function-
541
- // form .replace() so paths containing $ aren't mangled by $-pattern
542
- // interpretation (rare but possible: \\server\c$\plugin).
543
- const rootPath = toHookPath(pluginRoot);
544
- command = command.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => rootPath);
545
- if (pluginId) {
546
- const dataPath = toHookPath(getPluginDataDir(pluginId));
547
- command = command.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g, () => dataPath);
548
- }
549
- if (pluginId) {
550
- pluginOpts = loadPluginOptions(pluginId);
551
- // Throws if a referenced key is missing — that means the hook uses a key
552
- // that's either not declared in manifest.userConfig or not yet configured.
553
- // Caught upstream like any other hook exec failure.
554
- command = substituteUserConfigVariables(command, pluginOpts);
555
- }
556
- }
557
- // On Windows (bash only), auto-prepend `bash` for .sh scripts so they
558
- // execute instead of opening in the default file handler. PowerShell
559
- // runs .ps1 files natively — no prepend needed.
560
- if (isWindows && !isPowerShell && command.trim().match(/\.sh(\s|$|")/)) {
561
- if (!command.trim().startsWith('bash ')) {
562
- command = `bash ${command}`;
563
- }
564
- }
565
- // CLAUDE_CODE_SHELL_PREFIX wraps the command via POSIX quoting
566
- // (formatShellPrefixCommand uses shell-quote). This makes no sense for
567
- // PowerShell — see design §8.1. For now PS hooks ignore the prefix;
568
- // a CLAUDE_CODE_PS_SHELL_PREFIX (or shell-aware prefix) is a follow-up.
569
- const finalCommand = !isPowerShell && process.env.CLAUDE_CODE_SHELL_PREFIX
570
- ? formatShellPrefixCommand(process.env.CLAUDE_CODE_SHELL_PREFIX, command)
571
- : command;
572
- const hookTimeoutMs = hook.timeout
573
- ? hook.timeout * 1000
574
- : TOOL_HOOK_EXECUTION_TIMEOUT_MS;
575
- // Build env vars — all paths go through toHookPath for Windows POSIX conversion
576
- const envVars = {
577
- ...subprocessEnv(),
578
- CLAUDE_PROJECT_DIR: toHookPath(projectDir),
579
- };
580
- // Plugin and skill hooks both set CLAUDE_PLUGIN_ROOT (skills use the same
581
- // name for consistency — skills can migrate to plugins without code changes)
582
- if (pluginRoot) {
583
- envVars.CLAUDE_PLUGIN_ROOT = toHookPath(pluginRoot);
584
- if (pluginId) {
585
- envVars.CLAUDE_PLUGIN_DATA = toHookPath(getPluginDataDir(pluginId));
586
- }
587
- }
588
- // Expose plugin options as env vars too, so hooks can read them without
589
- // ${user_config.X} in the command string. Sensitive values included — hooks
590
- // run the user's own code, same trust boundary as reading keychain directly.
591
- if (pluginOpts) {
592
- for (const [key, value] of Object.entries(pluginOpts)) {
593
- // Sanitize non-identifier chars (bash can't ref $FOO-BAR). The schema
594
- // at schemas.ts:611 now constrains keys to /^[A-Za-z_]\w*$/ so this is
595
- // belt-and-suspenders, but cheap insurance if someone bypasses the schema.
596
- const envKey = key.replace(/[^A-Za-z0-9_]/g, '_').toUpperCase();
597
- envVars[`CLAUDE_PLUGIN_OPTION_${envKey}`] = String(value);
598
- }
599
- }
600
- if (skillRoot) {
601
- envVars.CLAUDE_PLUGIN_ROOT = toHookPath(skillRoot);
602
- }
603
- // CLAUDE_ENV_FILE points to a .sh file that the hook writes env var
604
- // definitions into; getSessionEnvironmentScript() concatenates them and
605
- // bashProvider injects the content into bash commands. A PS hook would
606
- // naturally write PS syntax ($env:FOO = 'bar'), which bash can't parse.
607
- // Skip for PS — consistent with how .sh prepend and SHELL_PREFIX are
608
- // already bash-only above.
609
- if (!isPowerShell &&
610
- (hookEvent === 'SessionStart' ||
611
- hookEvent === 'Setup' ||
612
- hookEvent === 'CwdChanged' ||
613
- hookEvent === 'FileChanged') &&
614
- hookIndex !== undefined) {
615
- envVars.CLAUDE_ENV_FILE = await getHookEnvFilePath(hookEvent, hookIndex);
616
- }
617
- // When agent worktrees are removed, getCwd() may return a deleted path via
618
- // AsyncLocalStorage. Validate before spawning since spawn() emits async
619
- // 'error' events for missing cwd rather than throwing synchronously.
620
- const hookCwd = getCwd();
621
- const safeCwd = (await pathExists(hookCwd)) ? hookCwd : getOriginalCwd();
622
- if (safeCwd !== hookCwd) {
623
- logForDebugging(`Hooks: cwd ${hookCwd} not found, falling back to original cwd`, { level: 'warn' });
624
- }
625
- // --
626
- // Spawn. Two completely separate paths:
627
- //
628
- // Bash: spawn(cmd, [], { shell: <gitBashPath | true> }) — the shell
629
- // option makes Node pass the whole string to the shell for parsing.
630
- //
631
- // PowerShell: spawn(pwshPath, ['-NoProfile', '-NonInteractive',
632
- // '-Command', cmd]) — explicit argv, no shell option. -NoProfile
633
- // skips user profile scripts (faster, deterministic).
634
- // -NonInteractive fails fast instead of prompting.
635
- //
636
- // The Git Bash hard-exit in findGitBashPath() is still in place for
637
- // bash hooks. PowerShell hooks never call it, so a Windows user with
638
- // only pwsh and shell: 'powershell' on every hook could in theory run
639
- // without Git Bash — but init.ts still calls setShellIfWindows() on
640
- // startup, which will exit first. Relaxing that is phase 1 of the
641
- // design's implementation order (separate PR).
642
- let child;
643
- if (shellType === 'powershell') {
644
- const pwshPath = await getCachedPowerShellPath();
645
- if (!pwshPath) {
646
- throw new Error(`Hook "${hook.command}" has shell: 'powershell' but no PowerShell ` +
647
- `executable (pwsh or powershell) was found on PATH. Install ` +
648
- `PowerShell, or remove "shell": "powershell" to use bash.`);
649
- }
650
- child = spawn(pwshPath, buildPowerShellArgs(finalCommand), {
651
- env: envVars,
652
- cwd: safeCwd,
653
- // Prevent visible console window on Windows (no-op on other platforms)
654
- windowsHide: true,
655
- });
656
- }
657
- else {
658
- // On Windows, use Git Bash explicitly (cmd.exe can't run bash syntax).
659
- // On other platforms, shell: true uses /bin/sh.
660
- const shell = isWindows ? findGitBashPath() : true;
661
- child = spawn(finalCommand, [], {
662
- env: envVars,
663
- cwd: safeCwd,
664
- shell,
665
- // Prevent visible console window on Windows (no-op on other platforms)
666
- windowsHide: true,
667
- });
668
- }
669
- // Hooks use pipe mode — stdout must be streamed into JS so we can parse
670
- // the first response line to detect async hooks ({"async": true}).
671
- const hookTaskOutput = new TaskOutput(`hook_${child.pid}`, null);
672
- const shellCommand = wrapSpawn(child, signal, hookTimeoutMs, hookTaskOutput);
673
- // Track whether shellCommand ownership was transferred (e.g., to async hook registry)
674
- let shellCommandTransferred = false;
675
- // Track whether stdin has already been written (to avoid "write after end" errors)
676
- let stdinWritten = false;
677
- if ((hook.async || hook.asyncRewake) && !forceSyncExecution) {
678
- const processId = `async_hook_${child.pid}`;
679
- logForDebugging(`Hooks: Config-based async hook, backgrounding process ${processId}`);
680
- // Write stdin before backgrounding so the hook receives its input.
681
- // The trailing newline matches the sync path (L1000). Without it,
682
- // bash `read -r line` returns exit 1 (EOF before delimiter) — the
683
- // variable IS populated but `if read -r line; then ...` skips the
684
- // branch. See gh-30509 / CC-161.
685
- child.stdin.write(jsonInput + '\n', 'utf8');
686
- child.stdin.end();
687
- stdinWritten = true;
688
- const backgrounded = executeInBackground({
689
- processId,
690
- hookId,
691
- shellCommand,
692
- asyncResponse: { async: true, asyncTimeout: hookTimeoutMs },
693
- hookEvent,
694
- hookName,
695
- command: hook.command,
696
- asyncRewake: hook.asyncRewake,
697
- pluginId,
698
- });
699
- if (backgrounded) {
700
- return {
701
- stdout: '',
702
- stderr: '',
703
- output: '',
704
- status: 0,
705
- backgrounded: true,
706
- };
707
- }
708
- }
709
- let stdout = '';
710
- let stderr = '';
711
- let output = '';
712
- // Set up output data collection with explicit UTF-8 encoding
713
- child.stdout.setEncoding('utf8');
714
- child.stderr.setEncoding('utf8');
715
- let initialResponseChecked = false;
716
- let asyncResolve = null;
717
- const childIsAsyncPromise = new Promise(resolve => {
718
- asyncResolve = resolve;
719
- });
720
- // Track trimmed prompt-request lines we processed so we can strip them
721
- // from final stdout by content match (no index tracking → no index drift)
722
- const processedPromptLines = new Set();
723
- // Serialize async prompt handling so responses are sent in order
724
- let promptChain = Promise.resolve();
725
- // Line buffer for detecting prompt requests in streaming output
726
- let lineBuffer = '';
727
- child.stdout.on('data', data => {
728
- stdout += data;
729
- output += data;
730
- // When requestPrompt is provided, parse stdout line-by-line for prompt requests
731
- if (requestPrompt) {
732
- lineBuffer += data;
733
- const lines = lineBuffer.split('\n');
734
- lineBuffer = lines.pop() ?? ''; // last element is an incomplete line
735
- for (const line of lines) {
736
- const trimmed = line.trim();
737
- if (!trimmed)
738
- continue;
739
- try {
740
- const parsed = jsonParse(trimmed);
741
- const validation = promptRequestSchema().safeParse(parsed);
742
- if (validation.success) {
743
- processedPromptLines.add(trimmed);
744
- logForDebugging(`Hooks: Detected prompt request from hook: ${trimmed}`);
745
- // Chain the async handling to serialize prompt responses
746
- const promptReq = validation.data;
747
- const reqPrompt = requestPrompt;
748
- promptChain = promptChain.then(async () => {
749
- try {
750
- const response = await reqPrompt(promptReq);
751
- child.stdin.write(jsonStringify(response) + '\n', 'utf8');
752
- }
753
- catch (err) {
754
- logForDebugging(`Hooks: Prompt request handling failed: ${err}`);
755
- // User cancelled or prompt failed — close stdin so the hook
756
- // process doesn't hang waiting for input
757
- child.stdin.destroy();
758
- }
759
- });
760
- continue;
761
- }
762
- }
763
- catch {
764
- // Not JSON, just a normal line
765
- }
766
- }
767
- }
768
- // Check for async response on first line of output. The async protocol is:
769
- // hook emits {"async":true,...} as its FIRST line, then its normal output.
770
- // We must parse ONLY the first line — if the process is fast and writes more
771
- // before this 'data' event fires, parsing the full accumulated stdout fails
772
- // and an async hook blocks for its full duration instead of backgrounding.
773
- if (!initialResponseChecked) {
774
- const firstLine = firstLineOf(stdout).trim();
775
- if (!firstLine.includes('}'))
776
- return;
777
- initialResponseChecked = true;
778
- logForDebugging(`Hooks: Checking first line for async: ${firstLine}`);
779
- try {
780
- const parsed = jsonParse(firstLine);
781
- logForDebugging(`Hooks: Parsed initial response: ${jsonStringify(parsed)}`);
782
- if (isAsyncHookJSONOutput(parsed) && !forceSyncExecution) {
783
- const processId = `async_hook_${child.pid}`;
784
- logForDebugging(`Hooks: Detected async hook, backgrounding process ${processId}`);
785
- const backgrounded = executeInBackground({
786
- processId,
787
- hookId,
788
- shellCommand,
789
- asyncResponse: parsed,
790
- hookEvent,
791
- hookName,
792
- command: hook.command,
793
- pluginId,
794
- });
795
- if (backgrounded) {
796
- shellCommandTransferred = true;
797
- asyncResolve?.({
798
- stdout,
799
- stderr,
800
- output,
801
- status: 0,
802
- });
803
- }
804
- }
805
- else if (isAsyncHookJSONOutput(parsed) && forceSyncExecution) {
806
- logForDebugging(`Hooks: Detected async hook but forceSyncExecution is true, waiting for completion`);
807
- }
808
- else {
809
- logForDebugging(`Hooks: Initial response is not async, continuing normal processing`);
810
- }
811
- }
812
- catch (e) {
813
- logForDebugging(`Hooks: Failed to parse initial response as JSON: ${e}`);
814
- }
815
- }
816
- });
817
- child.stderr.on('data', data => {
818
- stderr += data;
819
- output += data;
820
- });
821
- const stopProgressInterval = startHookProgressInterval({
822
- hookId,
823
- hookName,
824
- hookEvent,
825
- getOutput: async () => ({ stdout, stderr, output }),
826
- });
827
- // Wait for stdout and stderr streams to finish before considering output complete
828
- // This prevents a race condition where 'close' fires before all 'data' events are processed
829
- const stdoutEndPromise = new Promise(resolve => {
830
- child.stdout.on('end', () => resolve());
831
- });
832
- const stderrEndPromise = new Promise(resolve => {
833
- child.stderr.on('end', () => resolve());
834
- });
835
- // Write to stdin, making sure to handle EPIPE errors that can happen when
836
- // the hook command exits before reading all input.
837
- // Note: EPIPE handling is difficult to set up in testing since Bun and Node
838
- // have different behaviors.
839
- // TODO: Add tests for EPIPE handling.
840
- // Skip if stdin was already written (e.g., by config-based async hook path)
841
- const stdinWritePromise = stdinWritten
842
- ? Promise.resolve()
843
- : new Promise((resolve, reject) => {
844
- child.stdin.on('error', err => {
845
- // When requestPrompt is provided, stdin stays open for prompt responses.
846
- // EPIPE errors from later writes (after process exits) are expected -- suppress them.
847
- if (!requestPrompt) {
848
- reject(err);
849
- }
850
- else {
851
- logForDebugging(`Hooks: stdin error during prompt flow (likely process exited): ${err}`);
852
- }
853
- });
854
- // Explicitly specify UTF-8 encoding to ensure proper handling of Unicode characters
855
- child.stdin.write(jsonInput + '\n', 'utf8');
856
- // When requestPrompt is provided, keep stdin open for prompt responses
857
- if (!requestPrompt) {
858
- child.stdin.end();
859
- }
860
- resolve();
861
- });
862
- // Create promise for child process error
863
- const childErrorPromise = new Promise((_, reject) => {
864
- child.on('error', reject);
865
- });
866
- // Create promise for child process close - but only resolve after streams end
867
- // to ensure all output has been collected
868
- const childClosePromise = new Promise(resolve => {
869
- let exitCode = null;
870
- child.on('close', code => {
871
- exitCode = code ?? 1;
872
- // Wait for both streams to end before resolving with the final output
873
- void Promise.all([stdoutEndPromise, stderrEndPromise]).then(() => {
874
- // Strip lines we processed as prompt requests so parseHookOutput
875
- // only sees the final hook result. Content-matching against the set
876
- // of actually-processed lines means prompt JSON can never leak
877
- // through (fail-closed), regardless of line positioning.
878
- const finalStdout = processedPromptLines.size === 0
879
- ? stdout
880
- : stdout
881
- .split('\n')
882
- .filter(line => !processedPromptLines.has(line.trim()))
883
- .join('\n');
884
- resolve({
885
- stdout: finalStdout,
886
- stderr,
887
- output,
888
- status: exitCode,
889
- aborted: signal.aborted,
890
- });
891
- });
892
- });
893
- });
894
- // Race between stdin write, async detection, and process completion
895
- try {
896
- if (shouldEmitDiag) {
897
- logForDiagnosticsNoPII('info', 'hook_spawn_started', {
898
- hook_event_name: hookEvent,
899
- index: hookIndex,
900
- });
901
- }
902
- await Promise.race([stdinWritePromise, childErrorPromise]);
903
- // Wait for any pending prompt responses before resolving
904
- const result = await Promise.race([
905
- childIsAsyncPromise,
906
- childClosePromise,
907
- childErrorPromise,
908
- ]);
909
- // Ensure all queued prompt responses have been sent
910
- await promptChain;
911
- diagExitCode = result.status;
912
- diagAborted = result.aborted ?? false;
913
- return result;
914
- }
915
- catch (error) {
916
- // Handle errors from stdin write or child process
917
- const code = getErrnoCode(error);
918
- diagExitCode = 1;
919
- if (code === 'EPIPE') {
920
- logForDebugging('EPIPE error while writing to hook stdin (hook command likely closed early)');
921
- const errMsg = 'Hook command closed stdin before hook input was fully written (EPIPE)';
922
- return {
923
- stdout: '',
924
- stderr: errMsg,
925
- output: errMsg,
926
- status: 1,
927
- };
928
- }
929
- else if (code === 'ABORT_ERR') {
930
- diagAborted = true;
931
- return {
932
- stdout: '',
933
- stderr: 'Hook cancelled',
934
- output: 'Hook cancelled',
935
- status: 1,
936
- aborted: true,
937
- };
938
- }
939
- else {
940
- const errorMsg = errorMessage(error);
941
- const errOutput = `Error occurred while executing hook command: ${errorMsg}`;
942
- return {
943
- stdout: '',
944
- stderr: errOutput,
945
- output: errOutput,
946
- status: 1,
947
- };
948
- }
949
- }
950
- finally {
951
- if (shouldEmitDiag) {
952
- logForDiagnosticsNoPII('info', 'hook_spawn_completed', {
953
- hook_event_name: hookEvent,
954
- index: hookIndex,
955
- duration_ms: Date.now() - diagStartMs,
956
- exit_code: diagExitCode,
957
- aborted: diagAborted,
958
- });
959
- }
960
- stopProgressInterval();
961
- // Clean up stream resources unless ownership was transferred (e.g., to async hook registry)
962
- if (!shellCommandTransferred) {
963
- shellCommand.cleanup();
964
- }
965
- }
966
- }
967
- /**
968
- * Check if a match query matches a hook matcher pattern
969
- * @param matchQuery The query to match (e.g., 'Write', 'Edit', 'Bash')
970
- * @param matcher The matcher pattern - can be:
971
- * - Simple string for exact match (e.g., 'Write')
972
- * - Pipe-separated list for multiple exact matches (e.g., 'Write|Edit')
973
- * - Regex pattern (e.g., '^Write.*', '.*', '^(Write|Edit)$')
974
- * @returns true if the query matches the pattern
975
- */
976
- function matchesPattern(matchQuery, matcher) {
977
- if (!matcher || matcher === '*') {
978
- return true;
979
- }
980
- // Check if it's a simple string or pipe-separated list (no regex special chars except |)
981
- if (/^[a-zA-Z0-9_|]+$/.test(matcher)) {
982
- // Handle pipe-separated exact matches
983
- if (matcher.includes('|')) {
984
- const patterns = matcher
985
- .split('|')
986
- .map(p => normalizeLegacyToolName(p.trim()));
987
- return patterns.includes(matchQuery);
988
- }
989
- // Simple exact match
990
- return matchQuery === normalizeLegacyToolName(matcher);
991
- }
992
- // Otherwise treat as regex
993
- try {
994
- const regex = new RegExp(matcher);
995
- if (regex.test(matchQuery)) {
996
- return true;
997
- }
998
- // Also test against legacy names so patterns like "^Task$" still match
999
- for (const legacyName of getLegacyToolNames(matchQuery)) {
1000
- if (regex.test(legacyName)) {
1001
- return true;
1002
- }
1003
- }
1004
- return false;
1005
- }
1006
- catch {
1007
- // If the regex is invalid, log error and return false
1008
- logForDebugging(`Invalid regex pattern in hook matcher: ${matcher}`);
1009
- return false;
1010
- }
1011
- }
1012
- /**
1013
- * Prepare a matcher for hook `if` conditions. Expensive work (tool lookup,
1014
- * Zod validation, tree-sitter parsing for Bash) happens once here; the
1015
- * returned closure is called per hook. Returns undefined for non-tool events.
1016
- */
1017
- async function prepareIfConditionMatcher(hookInput, tools) {
1018
- if (hookInput.hook_event_name !== 'PreToolUse' &&
1019
- hookInput.hook_event_name !== 'PostToolUse' &&
1020
- hookInput.hook_event_name !== 'PostToolUseFailure' &&
1021
- hookInput.hook_event_name !== 'PermissionRequest') {
1022
- return undefined;
1023
- }
1024
- const toolName = normalizeLegacyToolName(hookInput.tool_name);
1025
- const tool = tools && findToolByName(tools, hookInput.tool_name);
1026
- const input = tool?.inputSchema.safeParse(hookInput.tool_input);
1027
- const patternMatcher = input?.success && tool?.preparePermissionMatcher
1028
- ? await tool.preparePermissionMatcher(input.data)
1029
- : undefined;
1030
- return ifCondition => {
1031
- const parsed = permissionRuleValueFromString(ifCondition);
1032
- if (normalizeLegacyToolName(parsed.toolName) !== toolName) {
1033
- return false;
1034
- }
1035
- if (!parsed.ruleContent) {
1036
- return true;
1037
- }
1038
- return patternMatcher ? patternMatcher(parsed.ruleContent) : false;
1039
- };
1040
- }
1041
- function isInternalHook(matched) {
1042
- return matched.hook.type === 'callback' && matched.hook.internal === true;
1043
- }
1044
- /**
1045
- * Build a dedup key for a matched hook, namespaced by source context.
1046
- *
1047
- * Settings-file hooks (no pluginRoot/skillRoot) share the '' prefix so the
1048
- * same command defined in user/project/local still collapses to one — the
1049
- * original intent of the dedup. Plugin/skill hooks get their root as the
1050
- * prefix, so two plugins sharing an unexpanded `${CLAUDE_PLUGIN_ROOT}/hook.sh`
1051
- * template don't collapse: after expansion they point to different files.
1052
- */
1053
- function hookDedupKey(m, payload) {
1054
- return `${m.pluginRoot ?? m.skillRoot ?? ''}\0${payload}`;
1055
- }
1056
- /**
1057
- * Build a map of {sanitizedPluginName: hookCount} from matched hooks.
1058
- * Only logs actual names for official marketplace plugins; others become 'third-party'.
1059
- */
1060
- function getPluginHookCounts(hooks) {
1061
- const pluginHooks = hooks.filter(h => h.pluginId);
1062
- if (pluginHooks.length === 0) {
1063
- return undefined;
1064
- }
1065
- const counts = {};
1066
- for (const h of pluginHooks) {
1067
- const atIndex = h.pluginId.lastIndexOf('@');
1068
- const isOfficial = atIndex > 0 &&
1069
- ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(h.pluginId.slice(atIndex + 1));
1070
- const key = isOfficial ? h.pluginId : 'third-party';
1071
- counts[key] = (counts[key] || 0) + 1;
1072
- }
1073
- return counts;
1074
- }
1075
- /**
1076
- * Build a map of {hookType: count} from matched hooks.
1077
- */
1078
- function getHookTypeCounts(hooks) {
1079
- const counts = {};
1080
- for (const h of hooks) {
1081
- counts[h.hook.type] = (counts[h.hook.type] || 0) + 1;
1082
- }
1083
- return counts;
1084
- }
1085
- function getHooksConfig(appState, sessionId, hookEvent) {
1086
- // HookMatcher is a zod-stripped {matcher, hooks} so snapshot matchers can be
1087
- // pushed directly without re-wrapping.
1088
- const hooks = [...(getHooksConfigFromSnapshot()?.[hookEvent] ?? [])];
1089
- // Check if only managed hooks should run (used for both registered and session hooks)
1090
- const managedOnly = shouldAllowManagedHooksOnly();
1091
- // Process registered hooks (SDK callbacks and plugin native hooks)
1092
- const registeredHooks = getRegisteredHooks()?.[hookEvent];
1093
- if (registeredHooks) {
1094
- for (const matcher of registeredHooks) {
1095
- // Skip plugin hooks when restricted to managed hooks only
1096
- // Plugin hooks have pluginRoot set, SDK callbacks do not
1097
- if (managedOnly && 'pluginRoot' in matcher) {
1098
- continue;
1099
- }
1100
- hooks.push(matcher);
1101
- }
1102
- }
1103
- // Merge session hooks for the current session only
1104
- // Function hooks (like structured output enforcement) must be scoped to their session
1105
- // to prevent hooks from one agent leaking to another (e.g., verification agent to main agent)
1106
- // Skip session hooks entirely when allowManagedHooksOnly is set —
1107
- // this prevents frontmatter hooks from agents/skills from bypassing the policy.
1108
- // strictPluginOnlyCustomization does NOT block here — it gates at the
1109
- // REGISTRATION sites (runAgent.ts:526 for agent frontmatter hooks) where
1110
- // agentDefinition.source is known. A blanket block here would also kill
1111
- // plugin-provided agents' frontmatter hooks, which is too broad.
1112
- // Also skip if appState not provided (for backwards compatibility)
1113
- if (!managedOnly && appState !== undefined) {
1114
- const sessionHooks = getSessionHooks(appState, sessionId, hookEvent).get(hookEvent);
1115
- if (sessionHooks) {
1116
- // SessionDerivedHookMatcher already includes optional skillRoot
1117
- for (const matcher of sessionHooks) {
1118
- hooks.push(matcher);
1119
- }
1120
- }
1121
- // Merge session function hooks separately (can't be persisted to HookMatcher format)
1122
- const sessionFunctionHooks = getSessionFunctionHooks(appState, sessionId, hookEvent).get(hookEvent);
1123
- if (sessionFunctionHooks) {
1124
- for (const matcher of sessionFunctionHooks) {
1125
- hooks.push(matcher);
1126
- }
1127
- }
1128
- }
1129
- return hooks;
1130
- }
1131
- /**
1132
- * Lightweight existence check for hooks on a given event. Mirrors the sources
1133
- * assembled by getHooksConfig() but stops at the first hit without building
1134
- * the full merged config.
1135
- *
1136
- * Intentionally over-approximates: returns true if any matcher exists for the
1137
- * event, even if managed-only filtering or pattern matching would later
1138
- * discard it. A false positive just means we proceed to the full matching
1139
- * path; a false negative would skip a hook, so we err on the side of true.
1140
- *
1141
- * Used to skip createBaseHookInput (getTranscriptPathForSession path joins)
1142
- * and getMatchingHooks on hot paths where hooks are typically unconfigured.
1143
- * See hasInstructionsLoadedHook / hasWorktreeCreateHook for the same pattern.
1144
- */
1145
- function hasHookForEvent(hookEvent, appState, sessionId) {
1146
- const snap = getHooksConfigFromSnapshot()?.[hookEvent];
1147
- if (snap && snap.length > 0)
1148
- return true;
1149
- const reg = getRegisteredHooks()?.[hookEvent];
1150
- if (reg && reg.length > 0)
1151
- return true;
1152
- if (appState?.sessionHooks.get(sessionId)?.hooks[hookEvent])
1153
- return true;
1154
- return false;
1155
- }
1156
- /**
1157
- * Get hook commands that match the given query
1158
- * @param appState The current app state (optional for backwards compatibility)
1159
- * @param sessionId The current session ID (main session or agent ID)
1160
- * @param hookEvent The hook event
1161
- * @param hookInput The hook input for matching
1162
- * @returns Array of matched hooks with optional plugin context
1163
- */
1164
- export async function getMatchingHooks(appState, sessionId, hookEvent, hookInput, tools) {
1165
- try {
1166
- const hookMatchers = getHooksConfig(appState, sessionId, hookEvent);
1167
- // If you change the criteria below, then you must change
1168
- // src/utils/hooks/hooksConfigManager.ts as well.
1169
- let matchQuery = undefined;
1170
- switch (hookInput.hook_event_name) {
1171
- case 'PreToolUse':
1172
- case 'PostToolUse':
1173
- case 'PostToolUseFailure':
1174
- case 'PermissionRequest':
1175
- case 'PermissionDenied':
1176
- matchQuery = hookInput.tool_name;
1177
- break;
1178
- case 'SessionStart':
1179
- matchQuery = hookInput.source;
1180
- break;
1181
- case 'Setup':
1182
- matchQuery = hookInput.trigger;
1183
- break;
1184
- case 'PreCompact':
1185
- case 'PostCompact':
1186
- matchQuery = hookInput.trigger;
1187
- break;
1188
- case 'Notification':
1189
- matchQuery = hookInput.notification_type;
1190
- break;
1191
- case 'SessionEnd':
1192
- matchQuery = hookInput.reason;
1193
- break;
1194
- case 'StopFailure':
1195
- matchQuery = hookInput.error;
1196
- break;
1197
- case 'SubagentStart':
1198
- matchQuery = hookInput.agent_type;
1199
- break;
1200
- case 'SubagentStop':
1201
- matchQuery = hookInput.agent_type;
1202
- break;
1203
- case 'TeammateIdle':
1204
- case 'TaskCreated':
1205
- case 'TaskCompleted':
1206
- break;
1207
- case 'Elicitation':
1208
- matchQuery = hookInput.mcp_server_name;
1209
- break;
1210
- case 'ElicitationResult':
1211
- matchQuery = hookInput.mcp_server_name;
1212
- break;
1213
- case 'ConfigChange':
1214
- matchQuery = hookInput.source;
1215
- break;
1216
- case 'InstructionsLoaded':
1217
- matchQuery = hookInput.load_reason;
1218
- break;
1219
- case 'FileChanged':
1220
- matchQuery = basename(hookInput.file_path);
1221
- break;
1222
- default:
1223
- break;
1224
- }
1225
- logForDebugging(`Getting matching hook commands for ${hookEvent} with query: ${matchQuery}`, { level: 'verbose' });
1226
- logForDebugging(`Found ${hookMatchers.length} hook matchers in settings`, {
1227
- level: 'verbose',
1228
- });
1229
- // Extract hooks with their plugin context (if any)
1230
- const filteredMatchers = matchQuery
1231
- ? hookMatchers.filter(matcher => !matcher.matcher || matchesPattern(matchQuery, matcher.matcher))
1232
- : hookMatchers;
1233
- const matchedHooks = filteredMatchers.flatMap(matcher => {
1234
- // Check if this is a PluginHookMatcher (has pluginRoot) or SkillHookMatcher (has skillRoot)
1235
- const pluginRoot = 'pluginRoot' in matcher ? matcher.pluginRoot : undefined;
1236
- const pluginId = 'pluginId' in matcher ? matcher.pluginId : undefined;
1237
- const skillRoot = 'skillRoot' in matcher ? matcher.skillRoot : undefined;
1238
- const hookSource = pluginRoot
1239
- ? 'pluginName' in matcher
1240
- ? `plugin:${matcher.pluginName}`
1241
- : 'plugin'
1242
- : skillRoot
1243
- ? 'skillName' in matcher
1244
- ? `skill:${matcher.skillName}`
1245
- : 'skill'
1246
- : 'settings';
1247
- return matcher.hooks.map(hook => ({
1248
- hook,
1249
- pluginRoot,
1250
- pluginId,
1251
- skillRoot,
1252
- hookSource,
1253
- }));
1254
- });
1255
- // Deduplicate hooks by command/prompt/url within the same source context.
1256
- // Key is namespaced by pluginRoot/skillRoot (see hookDedupKey above) so
1257
- // cross-plugin template collisions don't drop hooks (gh-29724).
1258
- //
1259
- // Note: new Map(entries) keeps the LAST entry on key collision, not first.
1260
- // For settings hooks this means the last-merged scope wins; for
1261
- // same-plugin duplicates the pluginRoot is identical so it doesn't matter.
1262
- // Fast-path: callback/function hooks don't need dedup (each is unique).
1263
- // Skip the 6-pass filter + 4×Map + 4×Array.from below when all hooks are
1264
- // callback/function — the common case for internal hooks like
1265
- // sessionFileAccessHooks/attributionHooks (44x faster in microbench).
1266
- if (matchedHooks.every(m => m.hook.type === 'callback' || m.hook.type === 'function')) {
1267
- return matchedHooks;
1268
- }
1269
- // Helper to extract the `if` condition from a hook for dedup keys.
1270
- // Hooks with different `if` conditions are distinct even if otherwise identical.
1271
- const getIfCondition = (hook) => hook.if ?? '';
1272
- const uniqueCommandHooks = Array.from(new Map(matchedHooks
1273
- .filter((m) => m.hook.type === 'command')
1274
- // shell is part of identity: {command:'echo x', shell:'bash'}
1275
- // and {command:'echo x', shell:'powershell'} are distinct hooks,
1276
- // not duplicates. Default to 'bash' so legacy configs (no shell
1277
- // field) still dedup against explicit shell:'bash'.
1278
- .map(m => [
1279
- hookDedupKey(m, `${m.hook.shell ?? DEFAULT_HOOK_SHELL}\0${m.hook.command}\0${getIfCondition(m.hook)}`),
1280
- m,
1281
- ])).values());
1282
- const uniquePromptHooks = Array.from(new Map(matchedHooks
1283
- .filter(m => m.hook.type === 'prompt')
1284
- .map(m => [
1285
- hookDedupKey(m, `${m.hook.prompt}\0${getIfCondition(m.hook)}`),
1286
- m,
1287
- ])).values());
1288
- const uniqueAgentHooks = Array.from(new Map(matchedHooks
1289
- .filter(m => m.hook.type === 'agent')
1290
- .map(m => [
1291
- hookDedupKey(m, `${m.hook.prompt}\0${getIfCondition(m.hook)}`),
1292
- m,
1293
- ])).values());
1294
- const uniqueHttpHooks = Array.from(new Map(matchedHooks
1295
- .filter(m => m.hook.type === 'http')
1296
- .map(m => [
1297
- hookDedupKey(m, `${m.hook.url}\0${getIfCondition(m.hook)}`),
1298
- m,
1299
- ])).values());
1300
- const callbackHooks = matchedHooks.filter(m => m.hook.type === 'callback');
1301
- // Function hooks don't need deduplication - each callback is unique
1302
- const functionHooks = matchedHooks.filter(m => m.hook.type === 'function');
1303
- const uniqueHooks = [
1304
- ...uniqueCommandHooks,
1305
- ...uniquePromptHooks,
1306
- ...uniqueAgentHooks,
1307
- ...uniqueHttpHooks,
1308
- ...callbackHooks,
1309
- ...functionHooks,
1310
- ];
1311
- // Filter hooks based on their `if` condition. This allows hooks to specify
1312
- // conditions like "Bash(git *)" to only run for git commands, avoiding
1313
- // process spawning overhead for non-matching commands.
1314
- const hasIfCondition = uniqueHooks.some(h => (h.hook.type === 'command' ||
1315
- h.hook.type === 'prompt' ||
1316
- h.hook.type === 'agent' ||
1317
- h.hook.type === 'http') &&
1318
- h.hook.if);
1319
- const ifMatcher = hasIfCondition
1320
- ? await prepareIfConditionMatcher(hookInput, tools)
1321
- : undefined;
1322
- const ifFilteredHooks = uniqueHooks.filter(h => {
1323
- if (h.hook.type !== 'command' &&
1324
- h.hook.type !== 'prompt' &&
1325
- h.hook.type !== 'agent' &&
1326
- h.hook.type !== 'http') {
1327
- return true;
1328
- }
1329
- const ifCondition = h.hook.if;
1330
- if (!ifCondition) {
1331
- return true;
1332
- }
1333
- if (!ifMatcher) {
1334
- logForDebugging(`Hook if condition "${ifCondition}" cannot be evaluated for non-tool event ${hookInput.hook_event_name}`);
1335
- return false;
1336
- }
1337
- if (ifMatcher(ifCondition)) {
1338
- return true;
1339
- }
1340
- logForDebugging(`Skipping hook due to if condition "${ifCondition}" not matching`);
1341
- return false;
1342
- });
1343
- // HTTP hooks are not supported for SessionStart/Setup events. In headless
1344
- // mode the sandbox ask callback deadlocks because the structuredInput
1345
- // consumer hasn't started yet when these hooks fire.
1346
- const filteredHooks = hookEvent === 'SessionStart' || hookEvent === 'Setup'
1347
- ? ifFilteredHooks.filter(h => {
1348
- if (h.hook.type === 'http') {
1349
- logForDebugging(`Skipping HTTP hook ${h.hook.url} — HTTP hooks are not supported for ${hookEvent}`);
1350
- return false;
1351
- }
1352
- return true;
1353
- })
1354
- : ifFilteredHooks;
1355
- logForDebugging(`Matched ${filteredHooks.length} unique hooks for query "${matchQuery || 'no match query'}" (${matchedHooks.length} before deduplication)`, { level: 'verbose' });
1356
- return filteredHooks;
1357
- }
1358
- catch {
1359
- return [];
1360
- }
1361
- }
1362
- /**
1363
- * Format a list of blocking errors from a PreTool hook's configured commands.
1364
- * @param hookName The name of the hook (e.g., 'PreToolUse:Write', 'PreToolUse:Edit', 'PreToolUse:Bash')
1365
- * @param blockingErrors Array of blocking errors from hooks
1366
- * @returns Formatted blocking message
1367
- */
1368
- export function getPreToolHookBlockingMessage(hookName, blockingError) {
1369
- return `${hookName} hook error: ${blockingError.blockingError}`;
1370
- }
1371
- /**
1372
- * Format a list of blocking errors from a Stop hook's configured commands.
1373
- * @param blockingErrors Array of blocking errors from hooks
1374
- * @returns Formatted message to give feedback to the model
1375
- */
1376
- export function getStopHookMessage(blockingError) {
1377
- return `Stop hook feedback:\n${blockingError.blockingError}`;
1378
- }
1379
- /**
1380
- * Format a blocking error from a TeammateIdle hook.
1381
- * @param blockingError The blocking error from the hook
1382
- * @returns Formatted message to give feedback to the model
1383
- */
1384
- export function getTeammateIdleHookMessage(blockingError) {
1385
- return `TeammateIdle hook feedback:\n${blockingError.blockingError}`;
1386
- }
1387
- /**
1388
- * Format a blocking error from a TaskCreated hook.
1389
- * @param blockingError The blocking error from the hook
1390
- * @returns Formatted message to give feedback to the model
1391
- */
1392
- export function getTaskCreatedHookMessage(blockingError) {
1393
- return `TaskCreated hook feedback:\n${blockingError.blockingError}`;
1394
- }
1395
- /**
1396
- * Format a blocking error from a TaskCompleted hook.
1397
- * @param blockingError The blocking error from the hook
1398
- * @returns Formatted message to give feedback to the model
1399
- */
1400
- export function getTaskCompletedHookMessage(blockingError) {
1401
- return `TaskCompleted hook feedback:\n${blockingError.blockingError}`;
1402
- }
1403
- /**
1404
- * Format a list of blocking errors from a UserPromptSubmit hook's configured commands.
1405
- * @param blockingErrors Array of blocking errors from hooks
1406
- * @returns Formatted blocking message
1407
- */
1408
- export function getUserPromptSubmitHookBlockingMessage(blockingError) {
1409
- return `UserPromptSubmit operation blocked by hook:\n${blockingError.blockingError}`;
1410
- }
1411
- /**
1412
- * Common logic for executing hooks
1413
- * @param hookInput The structured hook input that will be validated and converted to JSON
1414
- * @param toolUseID The ID for tracking this hook execution
1415
- * @param matchQuery The query to match against hook matchers
1416
- * @param signal Optional AbortSignal to cancel hook execution
1417
- * @param timeoutMs Optional timeout in milliseconds for hook execution
1418
- * @param toolUseContext Optional ToolUseContext for prompt-based hooks (required if using prompt hooks)
1419
- * @param messages Optional conversation history for prompt/function hooks
1420
- * @returns Async generator that yields progress messages and hook results
1421
- */
1422
- async function* executeHooks({ hookInput, toolUseID, matchQuery, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, toolUseContext, messages, forceSyncExecution, requestPrompt, toolInputSummary, }) {
1423
- if (shouldDisableAllHooksIncludingManaged()) {
1424
- return;
1425
- }
1426
- if (isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)) {
1427
- return;
1428
- }
1429
- const hookEvent = hookInput.hook_event_name;
1430
- const hookName = matchQuery ? `${hookEvent}:${matchQuery}` : hookEvent;
1431
- // Bind the prompt callback to this hook's name and tool input summary so the UI can display context
1432
- const boundRequestPrompt = requestPrompt?.(hookName, toolInputSummary);
1433
- // SECURITY: ALL hooks require workspace trust in interactive mode
1434
- // This centralized check prevents RCE vulnerabilities for all current and future hooks
1435
- if (shouldSkipHookDueToTrust()) {
1436
- logForDebugging(`Skipping ${hookName} hook execution - workspace trust not accepted`);
1437
- return;
1438
- }
1439
- const appState = toolUseContext ? toolUseContext.getAppState() : undefined;
1440
- // Use the agent's session ID if available, otherwise fall back to main session
1441
- const sessionId = toolUseContext?.agentId ?? getSessionId();
1442
- const matchingHooks = await getMatchingHooks(appState, sessionId, hookEvent, hookInput, toolUseContext?.options?.tools);
1443
- if (matchingHooks.length === 0) {
1444
- return;
1445
- }
1446
- if (signal?.aborted) {
1447
- return;
1448
- }
1449
- const userHooks = matchingHooks.filter(h => !isInternalHook(h));
1450
- if (userHooks.length > 0) {
1451
- const pluginHookCounts = getPluginHookCounts(userHooks);
1452
- const hookTypeCounts = getHookTypeCounts(userHooks);
1453
- logEvent(`tengu_run_hook`, {
1454
- hookName: hookName,
1455
- numCommands: userHooks.length,
1456
- hookTypeCounts: jsonStringify(hookTypeCounts),
1457
- ...(pluginHookCounts && {
1458
- pluginHookCounts: jsonStringify(pluginHookCounts),
1459
- }),
1460
- });
1461
- }
1462
- else {
1463
- // Fast-path: all hooks are internal callbacks (sessionFileAccessHooks,
1464
- // attributionHooks). These return {} and don't use the abort signal, so we
1465
- // can skip span/progress/abortSignal/processHookJSONOutput/resultLoop.
1466
- // Measured: 6.01µs → ~1.8µs per PostToolUse hit (-70%).
1467
- const batchStartTime = Date.now();
1468
- const context = toolUseContext
1469
- ? {
1470
- getAppState: toolUseContext.getAppState,
1471
- updateAttributionState: toolUseContext.updateAttributionState,
1472
- }
1473
- : undefined;
1474
- for (const [i, { hook }] of matchingHooks.entries()) {
1475
- if (hook.type === 'callback') {
1476
- await hook.callback(hookInput, toolUseID, signal, i, context);
1477
- }
1478
- }
1479
- const totalDurationMs = Date.now() - batchStartTime;
1480
- getStatsStore()?.observe('hook_duration_ms', totalDurationMs);
1481
- addToTurnHookDuration(totalDurationMs);
1482
- logEvent(`tengu_repl_hook_finished`, {
1483
- hookName: hookName,
1484
- numCommands: matchingHooks.length,
1485
- numSuccess: matchingHooks.length,
1486
- numBlocking: 0,
1487
- numNonBlockingError: 0,
1488
- numCancelled: 0,
1489
- totalDurationMs,
1490
- });
1491
- return;
1492
- }
1493
- // Collect hook definitions for beta tracing telemetry
1494
- const hookDefinitionsJson = isBetaTracingEnabled()
1495
- ? jsonStringify(getHookDefinitionsForTelemetry(matchingHooks))
1496
- : '[]';
1497
- // Log hook execution start to OTEL (only for beta tracing)
1498
- if (isBetaTracingEnabled()) {
1499
- void logOTelEvent('hook_execution_start', {
1500
- hook_event: hookEvent,
1501
- hook_name: hookName,
1502
- num_hooks: String(matchingHooks.length),
1503
- managed_only: String(shouldAllowManagedHooksOnly()),
1504
- hook_definitions: hookDefinitionsJson,
1505
- hook_source: shouldAllowManagedHooksOnly() ? 'policySettings' : 'merged',
1506
- });
1507
- }
1508
- // Start hook span for beta tracing
1509
- const hookSpan = startHookSpan(hookEvent, hookName, matchingHooks.length, hookDefinitionsJson);
1510
- // Yield progress messages for each hook before execution
1511
- for (const { hook } of matchingHooks) {
1512
- yield {
1513
- message: {
1514
- type: 'progress',
1515
- data: {
1516
- type: 'hook_progress',
1517
- hookEvent,
1518
- hookName,
1519
- command: getHookDisplayText(hook),
1520
- ...(hook.type === 'prompt' && { promptText: hook.prompt }),
1521
- ...('statusMessage' in hook &&
1522
- hook.statusMessage != null && {
1523
- statusMessage: hook.statusMessage,
1524
- }),
1525
- },
1526
- parentToolUseID: toolUseID,
1527
- toolUseID,
1528
- timestamp: new Date().toISOString(),
1529
- uuid: randomUUID(),
1530
- },
1531
- };
1532
- }
1533
- // Track wall-clock time for the entire hook batch
1534
- const batchStartTime = Date.now();
1535
- // Lazy-once stringify of hookInput. Shared across all command/prompt/agent/http
1536
- // hooks in this batch (hookInput is never mutated). Callback/function hooks
1537
- // return before reaching this, so batches with only those pay no stringify cost.
1538
- let jsonInputResult;
1539
- function getJsonInput() {
1540
- if (jsonInputResult !== undefined) {
1541
- return jsonInputResult;
1542
- }
1543
- try {
1544
- return (jsonInputResult = { ok: true, value: jsonStringify(hookInput) });
1545
- }
1546
- catch (error) {
1547
- logError(Error(`Failed to stringify hook ${hookName} input`, { cause: error }));
1548
- return (jsonInputResult = { ok: false, error });
1549
- }
1550
- }
1551
- // Run all hooks in parallel with individual timeouts
1552
- const hookPromises = matchingHooks.map(async function* ({ hook, pluginRoot, pluginId, skillRoot }, hookIndex) {
1553
- if (hook.type === 'callback') {
1554
- const callbackTimeoutMs = hook.timeout ? hook.timeout * 1000 : timeoutMs;
1555
- const { signal: abortSignal, cleanup } = createCombinedAbortSignal(signal, { timeoutMs: callbackTimeoutMs });
1556
- yield executeHookCallback({
1557
- toolUseID,
1558
- hook,
1559
- hookEvent,
1560
- hookInput,
1561
- signal: abortSignal,
1562
- hookIndex,
1563
- toolUseContext,
1564
- }).finally(cleanup);
1565
- return;
1566
- }
1567
- if (hook.type === 'function') {
1568
- if (!messages) {
1569
- yield {
1570
- message: createAttachmentMessage({
1571
- type: 'hook_error_during_execution',
1572
- hookName,
1573
- toolUseID,
1574
- hookEvent,
1575
- content: 'Messages not provided for function hook',
1576
- }),
1577
- outcome: 'non_blocking_error',
1578
- hook,
1579
- };
1580
- return;
1581
- }
1582
- // Function hooks only come from session storage with callback embedded
1583
- yield executeFunctionHook({
1584
- hook,
1585
- messages,
1586
- hookName,
1587
- toolUseID,
1588
- hookEvent,
1589
- timeoutMs,
1590
- signal,
1591
- });
1592
- return;
1593
- }
1594
- // Command and prompt hooks need jsonInput
1595
- const commandTimeoutMs = hook.timeout ? hook.timeout * 1000 : timeoutMs;
1596
- const { signal: abortSignal, cleanup } = createCombinedAbortSignal(signal, {
1597
- timeoutMs: commandTimeoutMs,
1598
- });
1599
- const hookId = randomUUID();
1600
- const hookStartMs = Date.now();
1601
- const hookCommand = getHookDisplayText(hook);
1602
- try {
1603
- const jsonInputRes = getJsonInput();
1604
- if (!jsonInputRes.ok) {
1605
- yield {
1606
- message: createAttachmentMessage({
1607
- type: 'hook_error_during_execution',
1608
- hookName,
1609
- toolUseID,
1610
- hookEvent,
1611
- content: `Failed to prepare hook input: ${errorMessage(jsonInputRes.error)}`,
1612
- command: hookCommand,
1613
- durationMs: Date.now() - hookStartMs,
1614
- }),
1615
- outcome: 'non_blocking_error',
1616
- hook,
1617
- };
1618
- cleanup();
1619
- return;
1620
- }
1621
- const jsonInput = jsonInputRes.value;
1622
- if (hook.type === 'prompt') {
1623
- if (!toolUseContext) {
1624
- throw new Error('ToolUseContext is required for prompt hooks. This is a bug.');
1625
- }
1626
- const promptResult = await execPromptHook(hook, hookName, hookEvent, jsonInput, abortSignal, toolUseContext, messages, toolUseID);
1627
- // Inject timing fields for hook visibility
1628
- if (promptResult.message?.type === 'attachment') {
1629
- const att = promptResult.message.attachment;
1630
- if (att.type === 'hook_success' ||
1631
- att.type === 'hook_non_blocking_error') {
1632
- att.command = hookCommand;
1633
- att.durationMs = Date.now() - hookStartMs;
1634
- }
1635
- }
1636
- yield promptResult;
1637
- cleanup?.();
1638
- return;
1639
- }
1640
- if (hook.type === 'agent') {
1641
- if (!toolUseContext) {
1642
- throw new Error('ToolUseContext is required for agent hooks. This is a bug.');
1643
- }
1644
- if (!messages) {
1645
- throw new Error('Messages are required for agent hooks. This is a bug.');
1646
- }
1647
- const agentResult = await execAgentHook(hook, hookName, hookEvent, jsonInput, abortSignal, toolUseContext, toolUseID, messages, 'agent_type' in hookInput
1648
- ? hookInput.agent_type
1649
- : undefined);
1650
- // Inject timing fields for hook visibility
1651
- if (agentResult.message?.type === 'attachment') {
1652
- const att = agentResult.message.attachment;
1653
- if (att.type === 'hook_success' ||
1654
- att.type === 'hook_non_blocking_error') {
1655
- att.command = hookCommand;
1656
- att.durationMs = Date.now() - hookStartMs;
1657
- }
1658
- }
1659
- yield agentResult;
1660
- cleanup?.();
1661
- return;
1662
- }
1663
- if (hook.type === 'http') {
1664
- emitHookStarted(hookId, hookName, hookEvent);
1665
- // execHttpHook manages its own timeout internally via hook.timeout or
1666
- // DEFAULT_HTTP_HOOK_TIMEOUT_MS, so pass the parent signal directly
1667
- // to avoid double-stacking timeouts with abortSignal.
1668
- const httpResult = await execHttpHook(hook, hookEvent, jsonInput, signal);
1669
- cleanup?.();
1670
- if (httpResult.aborted) {
1671
- emitHookResponse({
1672
- hookId,
1673
- hookName,
1674
- hookEvent,
1675
- output: 'Hook cancelled',
1676
- stdout: '',
1677
- stderr: '',
1678
- exitCode: undefined,
1679
- outcome: 'cancelled',
1680
- });
1681
- yield {
1682
- message: createAttachmentMessage({
1683
- type: 'hook_cancelled',
1684
- hookName,
1685
- toolUseID,
1686
- hookEvent,
1687
- }),
1688
- outcome: 'cancelled',
1689
- hook,
1690
- };
1691
- return;
1692
- }
1693
- if (httpResult.error || !httpResult.ok) {
1694
- const stderr = httpResult.error || `HTTP ${httpResult.statusCode} from ${hook.url}`;
1695
- emitHookResponse({
1696
- hookId,
1697
- hookName,
1698
- hookEvent,
1699
- output: stderr,
1700
- stdout: '',
1701
- stderr,
1702
- exitCode: httpResult.statusCode,
1703
- outcome: 'error',
1704
- });
1705
- yield {
1706
- message: createAttachmentMessage({
1707
- type: 'hook_non_blocking_error',
1708
- hookName,
1709
- toolUseID,
1710
- hookEvent,
1711
- stderr,
1712
- stdout: '',
1713
- exitCode: httpResult.statusCode ?? 0,
1714
- }),
1715
- outcome: 'non_blocking_error',
1716
- hook,
1717
- };
1718
- return;
1719
- }
1720
- // HTTP hooks must return JSON — parse and validate through Zod
1721
- const { json: httpJson, validationError: httpValidationError } = parseHttpHookOutput(httpResult.body);
1722
- if (httpValidationError) {
1723
- emitHookResponse({
1724
- hookId,
1725
- hookName,
1726
- hookEvent,
1727
- output: httpResult.body,
1728
- stdout: httpResult.body,
1729
- stderr: `JSON validation failed: ${httpValidationError}`,
1730
- exitCode: httpResult.statusCode,
1731
- outcome: 'error',
1732
- });
1733
- yield {
1734
- message: createAttachmentMessage({
1735
- type: 'hook_non_blocking_error',
1736
- hookName,
1737
- toolUseID,
1738
- hookEvent,
1739
- stderr: `JSON validation failed: ${httpValidationError}`,
1740
- stdout: httpResult.body,
1741
- exitCode: httpResult.statusCode ?? 0,
1742
- }),
1743
- outcome: 'non_blocking_error',
1744
- hook,
1745
- };
1746
- return;
1747
- }
1748
- if (httpJson && isAsyncHookJSONOutput(httpJson)) {
1749
- // Async response: treat as success (no further processing)
1750
- emitHookResponse({
1751
- hookId,
1752
- hookName,
1753
- hookEvent,
1754
- output: httpResult.body,
1755
- stdout: httpResult.body,
1756
- stderr: '',
1757
- exitCode: httpResult.statusCode,
1758
- outcome: 'success',
1759
- });
1760
- yield {
1761
- outcome: 'success',
1762
- hook,
1763
- };
1764
- return;
1765
- }
1766
- if (httpJson) {
1767
- const processed = processHookJSONOutput({
1768
- json: httpJson,
1769
- command: hook.url,
1770
- hookName,
1771
- toolUseID,
1772
- hookEvent,
1773
- expectedHookEvent: hookEvent,
1774
- stdout: httpResult.body,
1775
- stderr: '',
1776
- exitCode: httpResult.statusCode,
1777
- });
1778
- emitHookResponse({
1779
- hookId,
1780
- hookName,
1781
- hookEvent,
1782
- output: httpResult.body,
1783
- stdout: httpResult.body,
1784
- stderr: '',
1785
- exitCode: httpResult.statusCode,
1786
- outcome: 'success',
1787
- });
1788
- yield {
1789
- ...processed,
1790
- outcome: 'success',
1791
- hook,
1792
- };
1793
- return;
1794
- }
1795
- return;
1796
- }
1797
- emitHookStarted(hookId, hookName, hookEvent);
1798
- const result = await execCommandHook(hook, hookEvent, hookName, jsonInput, abortSignal, hookId, hookIndex, pluginRoot, pluginId, skillRoot, forceSyncExecution, boundRequestPrompt);
1799
- cleanup?.();
1800
- const durationMs = Date.now() - hookStartMs;
1801
- if (result.backgrounded) {
1802
- yield {
1803
- outcome: 'success',
1804
- hook,
1805
- };
1806
- return;
1807
- }
1808
- if (result.aborted) {
1809
- emitHookResponse({
1810
- hookId,
1811
- hookName,
1812
- hookEvent,
1813
- output: result.output,
1814
- stdout: result.stdout,
1815
- stderr: result.stderr,
1816
- exitCode: result.status,
1817
- outcome: 'cancelled',
1818
- });
1819
- yield {
1820
- message: createAttachmentMessage({
1821
- type: 'hook_cancelled',
1822
- hookName,
1823
- toolUseID,
1824
- hookEvent,
1825
- command: hookCommand,
1826
- durationMs,
1827
- }),
1828
- outcome: 'cancelled',
1829
- hook,
1830
- };
1831
- return;
1832
- }
1833
- // Try JSON parsing first
1834
- const { json, plainText, validationError } = parseHookOutput(result.stdout);
1835
- if (validationError) {
1836
- emitHookResponse({
1837
- hookId,
1838
- hookName,
1839
- hookEvent,
1840
- output: result.output,
1841
- stdout: result.stdout,
1842
- stderr: `JSON validation failed: ${validationError}`,
1843
- exitCode: 1,
1844
- outcome: 'error',
1845
- });
1846
- yield {
1847
- message: createAttachmentMessage({
1848
- type: 'hook_non_blocking_error',
1849
- hookName,
1850
- toolUseID,
1851
- hookEvent,
1852
- stderr: `JSON validation failed: ${validationError}`,
1853
- stdout: result.stdout,
1854
- exitCode: 1,
1855
- command: hookCommand,
1856
- durationMs,
1857
- }),
1858
- outcome: 'non_blocking_error',
1859
- hook,
1860
- };
1861
- return;
1862
- }
1863
- if (json) {
1864
- // Async responses were already backgrounded during execution
1865
- if (isAsyncHookJSONOutput(json)) {
1866
- yield {
1867
- outcome: 'success',
1868
- hook,
1869
- };
1870
- return;
1871
- }
1872
- // Process JSON output
1873
- const processed = processHookJSONOutput({
1874
- json,
1875
- command: hookCommand,
1876
- hookName,
1877
- toolUseID,
1878
- hookEvent,
1879
- expectedHookEvent: hookEvent,
1880
- stdout: result.stdout,
1881
- stderr: result.stderr,
1882
- exitCode: result.status,
1883
- durationMs,
1884
- });
1885
- // Handle suppressOutput (skip for async responses)
1886
- if (isSyncHookJSONOutput(json) &&
1887
- !json.suppressOutput &&
1888
- plainText &&
1889
- result.status === 0) {
1890
- // Still show non-JSON output if not suppressed
1891
- const content = `${chalk.bold(hookName)} completed`;
1892
- emitHookResponse({
1893
- hookId,
1894
- hookName,
1895
- hookEvent,
1896
- output: result.output,
1897
- stdout: result.stdout,
1898
- stderr: result.stderr,
1899
- exitCode: result.status,
1900
- outcome: 'success',
1901
- });
1902
- yield {
1903
- ...processed,
1904
- message: processed.message ||
1905
- createAttachmentMessage({
1906
- type: 'hook_success',
1907
- hookName,
1908
- toolUseID,
1909
- hookEvent,
1910
- content,
1911
- stdout: result.stdout,
1912
- stderr: result.stderr,
1913
- exitCode: result.status,
1914
- command: hookCommand,
1915
- durationMs,
1916
- }),
1917
- outcome: 'success',
1918
- hook,
1919
- };
1920
- return;
1921
- }
1922
- emitHookResponse({
1923
- hookId,
1924
- hookName,
1925
- hookEvent,
1926
- output: result.output,
1927
- stdout: result.stdout,
1928
- stderr: result.stderr,
1929
- exitCode: result.status,
1930
- outcome: result.status === 0 ? 'success' : 'error',
1931
- });
1932
- yield {
1933
- ...processed,
1934
- outcome: 'success',
1935
- hook,
1936
- };
1937
- return;
1938
- }
1939
- // Fall back to existing logic for non-JSON output
1940
- if (result.status === 0) {
1941
- emitHookResponse({
1942
- hookId,
1943
- hookName,
1944
- hookEvent,
1945
- output: result.output,
1946
- stdout: result.stdout,
1947
- stderr: result.stderr,
1948
- exitCode: result.status,
1949
- outcome: 'success',
1950
- });
1951
- yield {
1952
- message: createAttachmentMessage({
1953
- type: 'hook_success',
1954
- hookName,
1955
- toolUseID,
1956
- hookEvent,
1957
- content: result.stdout.trim(),
1958
- stdout: result.stdout,
1959
- stderr: result.stderr,
1960
- exitCode: result.status,
1961
- command: hookCommand,
1962
- durationMs,
1963
- }),
1964
- outcome: 'success',
1965
- hook,
1966
- };
1967
- return;
1968
- }
1969
- // Hooks with exit code 2 provide blocking feedback
1970
- if (result.status === 2) {
1971
- emitHookResponse({
1972
- hookId,
1973
- hookName,
1974
- hookEvent,
1975
- output: result.output,
1976
- stdout: result.stdout,
1977
- stderr: result.stderr,
1978
- exitCode: result.status,
1979
- outcome: 'error',
1980
- });
1981
- yield {
1982
- blockingError: {
1983
- blockingError: `[${hook.command}]: ${result.stderr || 'No stderr output'}`,
1984
- command: hook.command,
1985
- },
1986
- outcome: 'blocking',
1987
- hook,
1988
- };
1989
- return;
1990
- }
1991
- // Any other non-zero exit code is a non-critical error that should just
1992
- // be shown to the user.
1993
- emitHookResponse({
1994
- hookId,
1995
- hookName,
1996
- hookEvent,
1997
- output: result.output,
1998
- stdout: result.stdout,
1999
- stderr: result.stderr,
2000
- exitCode: result.status,
2001
- outcome: 'error',
2002
- });
2003
- yield {
2004
- message: createAttachmentMessage({
2005
- type: 'hook_non_blocking_error',
2006
- hookName,
2007
- toolUseID,
2008
- hookEvent,
2009
- stderr: `Failed with non-blocking status code: ${result.stderr.trim() || 'No stderr output'}`,
2010
- stdout: result.stdout,
2011
- exitCode: result.status,
2012
- command: hookCommand,
2013
- durationMs,
2014
- }),
2015
- outcome: 'non_blocking_error',
2016
- hook,
2017
- };
2018
- return;
2019
- }
2020
- catch (error) {
2021
- // Clean up on error
2022
- cleanup?.();
2023
- const errorMessage = error instanceof Error ? error.message : String(error);
2024
- emitHookResponse({
2025
- hookId,
2026
- hookName,
2027
- hookEvent,
2028
- output: `Failed to run: ${errorMessage}`,
2029
- stdout: '',
2030
- stderr: `Failed to run: ${errorMessage}`,
2031
- exitCode: 1,
2032
- outcome: 'error',
2033
- });
2034
- yield {
2035
- message: createAttachmentMessage({
2036
- type: 'hook_non_blocking_error',
2037
- hookName,
2038
- toolUseID,
2039
- hookEvent,
2040
- stderr: `Failed to run: ${errorMessage}`,
2041
- stdout: '',
2042
- exitCode: 1,
2043
- command: hookCommand,
2044
- durationMs: Date.now() - hookStartMs,
2045
- }),
2046
- outcome: 'non_blocking_error',
2047
- hook,
2048
- };
2049
- return;
2050
- }
2051
- });
2052
- // Track outcomes for logging
2053
- const outcomes = {
2054
- success: 0,
2055
- blocking: 0,
2056
- non_blocking_error: 0,
2057
- cancelled: 0,
2058
- };
2059
- let permissionBehavior;
2060
- // Run all hooks in parallel and wait for all to complete
2061
- for await (const result of all(hookPromises)) {
2062
- outcomes[result.outcome]++;
2063
- // Check for preventContinuation early
2064
- if (result.preventContinuation) {
2065
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) requested preventContinuation`);
2066
- yield {
2067
- preventContinuation: true,
2068
- stopReason: result.stopReason,
2069
- };
2070
- }
2071
- // Handle different result types
2072
- if (result.blockingError) {
2073
- yield {
2074
- blockingError: result.blockingError,
2075
- };
2076
- }
2077
- if (result.message) {
2078
- yield { message: result.message };
2079
- }
2080
- // Yield system message separately if present
2081
- if (result.systemMessage) {
2082
- yield {
2083
- message: createAttachmentMessage({
2084
- type: 'hook_system_message',
2085
- content: result.systemMessage,
2086
- hookName,
2087
- toolUseID,
2088
- hookEvent,
2089
- }),
2090
- };
2091
- }
2092
- // Collect additional context from hooks
2093
- if (result.additionalContext) {
2094
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) provided additionalContext (${result.additionalContext.length} chars)`);
2095
- yield {
2096
- additionalContexts: [result.additionalContext],
2097
- };
2098
- }
2099
- if (result.initialUserMessage) {
2100
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) provided initialUserMessage (${result.initialUserMessage.length} chars)`);
2101
- yield {
2102
- initialUserMessage: result.initialUserMessage,
2103
- };
2104
- }
2105
- if (result.watchPaths && result.watchPaths.length > 0) {
2106
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) provided ${result.watchPaths.length} watchPaths`);
2107
- yield {
2108
- watchPaths: result.watchPaths,
2109
- };
2110
- }
2111
- // Yield updatedMCPToolOutput if provided (from PostToolUse hooks)
2112
- if (result.updatedMCPToolOutput) {
2113
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) replaced MCP tool output`);
2114
- yield {
2115
- updatedMCPToolOutput: result.updatedMCPToolOutput,
2116
- };
2117
- }
2118
- // Check for permission behavior with precedence: deny > ask > allow
2119
- if (result.permissionBehavior) {
2120
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) returned permissionDecision: ${result.permissionBehavior}${result.hookPermissionDecisionReason ? ` (reason: ${result.hookPermissionDecisionReason})` : ''}`);
2121
- // Apply precedence rules
2122
- switch (result.permissionBehavior) {
2123
- case 'deny':
2124
- // deny always takes precedence
2125
- permissionBehavior = 'deny';
2126
- break;
2127
- case 'ask':
2128
- // ask takes precedence over allow but not deny
2129
- if (permissionBehavior !== 'deny') {
2130
- permissionBehavior = 'ask';
2131
- }
2132
- break;
2133
- case 'allow':
2134
- // allow only if no other behavior set
2135
- if (!permissionBehavior) {
2136
- permissionBehavior = 'allow';
2137
- }
2138
- break;
2139
- case 'passthrough':
2140
- // passthrough doesn't set permission behavior
2141
- break;
2142
- }
2143
- }
2144
- // Yield permission behavior and updatedInput if provided (from allow or ask behavior)
2145
- if (permissionBehavior !== undefined) {
2146
- const updatedInput = result.updatedInput &&
2147
- (result.permissionBehavior === 'allow' ||
2148
- result.permissionBehavior === 'ask')
2149
- ? result.updatedInput
2150
- : undefined;
2151
- if (updatedInput) {
2152
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) modified tool input keys: [${Object.keys(updatedInput).join(', ')}]`);
2153
- }
2154
- yield {
2155
- permissionBehavior,
2156
- hookPermissionDecisionReason: result.hookPermissionDecisionReason,
2157
- hookSource: matchingHooks.find(m => m.hook === result.hook)?.hookSource,
2158
- updatedInput,
2159
- };
2160
- }
2161
- // Yield updatedInput separately for passthrough case (no permission decision)
2162
- // This allows hooks to modify input without making a permission decision
2163
- // Note: Check result.permissionBehavior (this hook's behavior), not the aggregated permissionBehavior
2164
- if (result.updatedInput && result.permissionBehavior === undefined) {
2165
- logForDebugging(`Hook ${hookEvent} (${getHookDisplayText(result.hook)}) modified tool input keys: [${Object.keys(result.updatedInput).join(', ')}]`);
2166
- yield {
2167
- updatedInput: result.updatedInput,
2168
- };
2169
- }
2170
- // Yield permission request result if provided (from PermissionRequest hooks)
2171
- if (result.permissionRequestResult) {
2172
- yield {
2173
- permissionRequestResult: result.permissionRequestResult,
2174
- };
2175
- }
2176
- // Yield retry flag if provided (from PermissionDenied hooks)
2177
- if (result.retry) {
2178
- yield {
2179
- retry: result.retry,
2180
- };
2181
- }
2182
- // Yield elicitation response if provided (from Elicitation hooks)
2183
- if (result.elicitationResponse) {
2184
- yield {
2185
- elicitationResponse: result.elicitationResponse,
2186
- };
2187
- }
2188
- // Yield elicitation result response if provided (from ElicitationResult hooks)
2189
- if (result.elicitationResultResponse) {
2190
- yield {
2191
- elicitationResultResponse: result.elicitationResultResponse,
2192
- };
2193
- }
2194
- // Invoke session hook callback if this is a command/prompt/function hook (not a callback hook)
2195
- if (appState && result.hook.type !== 'callback') {
2196
- const sessionId = getSessionId();
2197
- // Use empty string as matcher when matchQuery is undefined (e.g., for Stop hooks)
2198
- const matcher = matchQuery ?? '';
2199
- const hookEntry = getSessionHookCallback(appState, sessionId, hookEvent, matcher, result.hook);
2200
- // Invoke onHookSuccess only on success outcome
2201
- if (hookEntry?.onHookSuccess && result.outcome === 'success') {
2202
- try {
2203
- hookEntry.onHookSuccess(result.hook, result);
2204
- }
2205
- catch (error) {
2206
- logError(Error('Session hook success callback failed', { cause: error }));
2207
- }
2208
- }
2209
- }
2210
- }
2211
- const totalDurationMs = Date.now() - batchStartTime;
2212
- getStatsStore()?.observe('hook_duration_ms', totalDurationMs);
2213
- addToTurnHookDuration(totalDurationMs);
2214
- logEvent(`tengu_repl_hook_finished`, {
2215
- hookName: hookName,
2216
- numCommands: matchingHooks.length,
2217
- numSuccess: outcomes.success,
2218
- numBlocking: outcomes.blocking,
2219
- numNonBlockingError: outcomes.non_blocking_error,
2220
- numCancelled: outcomes.cancelled,
2221
- totalDurationMs,
2222
- });
2223
- // Log hook execution completion to OTEL (only for beta tracing)
2224
- if (isBetaTracingEnabled()) {
2225
- const hookDefinitionsComplete = getHookDefinitionsForTelemetry(matchingHooks);
2226
- void logOTelEvent('hook_execution_complete', {
2227
- hook_event: hookEvent,
2228
- hook_name: hookName,
2229
- num_hooks: String(matchingHooks.length),
2230
- num_success: String(outcomes.success),
2231
- num_blocking: String(outcomes.blocking),
2232
- num_non_blocking_error: String(outcomes.non_blocking_error),
2233
- num_cancelled: String(outcomes.cancelled),
2234
- managed_only: String(shouldAllowManagedHooksOnly()),
2235
- hook_definitions: jsonStringify(hookDefinitionsComplete),
2236
- hook_source: shouldAllowManagedHooksOnly() ? 'policySettings' : 'merged',
2237
- });
2238
- }
2239
- // End hook span for beta tracing
2240
- endHookSpan(hookSpan, {
2241
- numSuccess: outcomes.success,
2242
- numBlocking: outcomes.blocking,
2243
- numNonBlockingError: outcomes.non_blocking_error,
2244
- numCancelled: outcomes.cancelled,
2245
- });
2246
- }
2247
- export function hasBlockingResult(results) {
2248
- return results.some(r => r.blocked);
2249
- }
2250
- /**
2251
- * Execute hooks outside of the REPL (e.g. notifications, session end)
2252
- *
2253
- * Unlike executeHooks() which yields messages that are exposed to the model as
2254
- * system messages, this function only logs errors via logForDebugging (visible
2255
- * with --debug). Callers that need to surface errors to users should handle
2256
- * the returned results appropriately (e.g. executeSessionEndHooks writes to
2257
- * stderr during shutdown).
2258
- *
2259
- * @param getAppState Optional function to get the current app state (for session hooks)
2260
- * @param hookInput The structured hook input that will be validated and converted to JSON
2261
- * @param matchQuery The query to match against hook matchers
2262
- * @param signal Optional AbortSignal to cancel hook execution
2263
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2264
- * @returns Array of HookOutsideReplResult objects containing command, succeeded, and output
2265
- */
2266
- async function executeHooksOutsideREPL({ getAppState, hookInput, matchQuery, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, }) {
2267
- if (isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)) {
2268
- return [];
2269
- }
2270
- const hookEvent = hookInput.hook_event_name;
2271
- const hookName = matchQuery ? `${hookEvent}:${matchQuery}` : hookEvent;
2272
- if (shouldDisableAllHooksIncludingManaged()) {
2273
- logForDebugging(`Skipping hooks for ${hookName} due to 'disableAllHooks' managed setting`);
2274
- return [];
2275
- }
2276
- // SECURITY: ALL hooks require workspace trust in interactive mode
2277
- // This centralized check prevents RCE vulnerabilities for all current and future hooks
2278
- if (shouldSkipHookDueToTrust()) {
2279
- logForDebugging(`Skipping ${hookName} hook execution - workspace trust not accepted`);
2280
- return [];
2281
- }
2282
- const appState = getAppState ? getAppState() : undefined;
2283
- // Use main session ID for outside-REPL hooks
2284
- const sessionId = getSessionId();
2285
- const matchingHooks = await getMatchingHooks(appState, sessionId, hookEvent, hookInput);
2286
- if (matchingHooks.length === 0) {
2287
- return [];
2288
- }
2289
- if (signal?.aborted) {
2290
- return [];
2291
- }
2292
- const userHooks = matchingHooks.filter(h => !isInternalHook(h));
2293
- if (userHooks.length > 0) {
2294
- const pluginHookCounts = getPluginHookCounts(userHooks);
2295
- const hookTypeCounts = getHookTypeCounts(userHooks);
2296
- logEvent(`tengu_run_hook`, {
2297
- hookName: hookName,
2298
- numCommands: userHooks.length,
2299
- hookTypeCounts: jsonStringify(hookTypeCounts),
2300
- ...(pluginHookCounts && {
2301
- pluginHookCounts: jsonStringify(pluginHookCounts),
2302
- }),
2303
- });
2304
- }
2305
- // Validate and stringify the hook input
2306
- let jsonInput;
2307
- try {
2308
- jsonInput = jsonStringify(hookInput);
2309
- }
2310
- catch (error) {
2311
- logError(error);
2312
- return [];
2313
- }
2314
- // Run all hooks in parallel with individual timeouts
2315
- const hookPromises = matchingHooks.map(async ({ hook, pluginRoot, pluginId }, hookIndex) => {
2316
- // Handle callback hooks
2317
- if (hook.type === 'callback') {
2318
- const callbackTimeoutMs = hook.timeout ? hook.timeout * 1000 : timeoutMs;
2319
- const { signal: abortSignal, cleanup } = createCombinedAbortSignal(signal, { timeoutMs: callbackTimeoutMs });
2320
- try {
2321
- const toolUseID = randomUUID();
2322
- const json = await hook.callback(hookInput, toolUseID, abortSignal, hookIndex);
2323
- cleanup?.();
2324
- if (isAsyncHookJSONOutput(json)) {
2325
- logForDebugging(`${hookName} [callback] returned async response, returning empty output`);
2326
- return {
2327
- command: 'callback',
2328
- succeeded: true,
2329
- output: '',
2330
- blocked: false,
2331
- };
2332
- }
2333
- const output = hookEvent === 'WorktreeCreate' &&
2334
- isSyncHookJSONOutput(json) &&
2335
- json.hookSpecificOutput?.hookEventName === 'WorktreeCreate'
2336
- ? json.hookSpecificOutput.worktreePath
2337
- : json.systemMessage || '';
2338
- const blocked = isSyncHookJSONOutput(json) && json.decision === 'block';
2339
- logForDebugging(`${hookName} [callback] completed successfully`);
2340
- return {
2341
- command: 'callback',
2342
- succeeded: true,
2343
- output,
2344
- blocked,
2345
- };
2346
- }
2347
- catch (error) {
2348
- cleanup?.();
2349
- const errorMessage = error instanceof Error ? error.message : String(error);
2350
- logForDebugging(`${hookName} [callback] failed to run: ${errorMessage}`, { level: 'error' });
2351
- return {
2352
- command: 'callback',
2353
- succeeded: false,
2354
- output: errorMessage,
2355
- blocked: false,
2356
- };
2357
- }
2358
- }
2359
- // TODO: Implement prompt stop hooks outside REPL
2360
- if (hook.type === 'prompt') {
2361
- return {
2362
- command: hook.prompt,
2363
- succeeded: false,
2364
- output: 'Prompt stop hooks are not yet supported outside REPL',
2365
- blocked: false,
2366
- };
2367
- }
2368
- // TODO: Implement agent stop hooks outside REPL
2369
- if (hook.type === 'agent') {
2370
- return {
2371
- command: hook.prompt,
2372
- succeeded: false,
2373
- output: 'Agent stop hooks are not yet supported outside REPL',
2374
- blocked: false,
2375
- };
2376
- }
2377
- // Function hooks require messages array (only available in REPL context)
2378
- // For -p mode Stop hooks, use executeStopHooks which supports function hooks
2379
- if (hook.type === 'function') {
2380
- logError(new Error(`Function hook reached executeHooksOutsideREPL for ${hookEvent}. Function hooks should only be used in REPL context (Stop hooks).`));
2381
- return {
2382
- command: 'function',
2383
- succeeded: false,
2384
- output: 'Internal error: function hook executed outside REPL context',
2385
- blocked: false,
2386
- };
2387
- }
2388
- // Handle HTTP hooks (no toolUseContext needed - just HTTP POST).
2389
- // execHttpHook handles its own timeout internally via hook.timeout or
2390
- // DEFAULT_HTTP_HOOK_TIMEOUT_MS, so we pass signal directly.
2391
- if (hook.type === 'http') {
2392
- try {
2393
- const httpResult = await execHttpHook(hook, hookEvent, jsonInput, signal);
2394
- if (httpResult.aborted) {
2395
- logForDebugging(`${hookName} [${hook.url}] cancelled`);
2396
- return {
2397
- command: hook.url,
2398
- succeeded: false,
2399
- output: 'Hook cancelled',
2400
- blocked: false,
2401
- };
2402
- }
2403
- if (httpResult.error || !httpResult.ok) {
2404
- const errMsg = httpResult.error ||
2405
- `HTTP ${httpResult.statusCode} from ${hook.url}`;
2406
- logForDebugging(`${hookName} [${hook.url}] failed: ${errMsg}`, {
2407
- level: 'error',
2408
- });
2409
- return {
2410
- command: hook.url,
2411
- succeeded: false,
2412
- output: errMsg,
2413
- blocked: false,
2414
- };
2415
- }
2416
- // HTTP hooks must return JSON — parse and validate through Zod
2417
- const { json: httpJson, validationError: httpValidationError } = parseHttpHookOutput(httpResult.body);
2418
- if (httpValidationError) {
2419
- throw new Error(httpValidationError);
2420
- }
2421
- if (httpJson && !isAsyncHookJSONOutput(httpJson)) {
2422
- logForDebugging(`Parsed JSON output from HTTP hook: ${jsonStringify(httpJson)}`, { level: 'verbose' });
2423
- }
2424
- const jsonBlocked = httpJson &&
2425
- !isAsyncHookJSONOutput(httpJson) &&
2426
- isSyncHookJSONOutput(httpJson) &&
2427
- httpJson.decision === 'block';
2428
- // WorktreeCreate's consumer reads `output` as the bare filesystem
2429
- // path. Command hooks provide it via stdout; http hooks provide it
2430
- // via hookSpecificOutput.worktreePath. Without worktreePath, emit ''
2431
- // so the consumer's length filter skips it instead of treating the
2432
- // raw '{}' body as a path.
2433
- const output = hookEvent === 'WorktreeCreate'
2434
- ? httpJson &&
2435
- isSyncHookJSONOutput(httpJson) &&
2436
- httpJson.hookSpecificOutput?.hookEventName === 'WorktreeCreate'
2437
- ? httpJson.hookSpecificOutput.worktreePath
2438
- : ''
2439
- : httpResult.body;
2440
- return {
2441
- command: hook.url,
2442
- succeeded: true,
2443
- output,
2444
- blocked: !!jsonBlocked,
2445
- };
2446
- }
2447
- catch (error) {
2448
- const errorMessage = error instanceof Error ? error.message : String(error);
2449
- logForDebugging(`${hookName} [${hook.url}] failed to run: ${errorMessage}`, { level: 'error' });
2450
- return {
2451
- command: hook.url,
2452
- succeeded: false,
2453
- output: errorMessage,
2454
- blocked: false,
2455
- };
2456
- }
2457
- }
2458
- // Handle command hooks
2459
- const commandTimeoutMs = hook.timeout ? hook.timeout * 1000 : timeoutMs;
2460
- const { signal: abortSignal, cleanup } = createCombinedAbortSignal(signal, { timeoutMs: commandTimeoutMs });
2461
- try {
2462
- const result = await execCommandHook(hook, hookEvent, hookName, jsonInput, abortSignal, randomUUID(), hookIndex, pluginRoot, pluginId);
2463
- // Clear timeout if hook completes
2464
- cleanup?.();
2465
- if (result.aborted) {
2466
- logForDebugging(`${hookName} [${hook.command}] cancelled`);
2467
- return {
2468
- command: hook.command,
2469
- succeeded: false,
2470
- output: 'Hook cancelled',
2471
- blocked: false,
2472
- };
2473
- }
2474
- logForDebugging(`${hookName} [${hook.command}] completed with status ${result.status}`);
2475
- // Parse JSON for any messages to print out.
2476
- const { json, validationError } = parseHookOutput(result.stdout);
2477
- if (validationError) {
2478
- // Validation error is logged via logForDebugging and returned in output
2479
- throw new Error(validationError);
2480
- }
2481
- if (json && !isAsyncHookJSONOutput(json)) {
2482
- logForDebugging(`Parsed JSON output from hook: ${jsonStringify(json)}`, { level: 'verbose' });
2483
- }
2484
- // Blocked if exit code 2 or JSON decision: 'block'
2485
- const jsonBlocked = json &&
2486
- !isAsyncHookJSONOutput(json) &&
2487
- isSyncHookJSONOutput(json) &&
2488
- json.decision === 'block';
2489
- const blocked = result.status === 2 || !!jsonBlocked;
2490
- // For successful hooks (exit code 0), use stdout; for failed hooks, use stderr
2491
- const output = result.status === 0 ? result.stdout || '' : result.stderr || '';
2492
- const watchPaths = json &&
2493
- isSyncHookJSONOutput(json) &&
2494
- json.hookSpecificOutput &&
2495
- 'watchPaths' in json.hookSpecificOutput
2496
- ? json.hookSpecificOutput.watchPaths
2497
- : undefined;
2498
- const systemMessage = json && isSyncHookJSONOutput(json) ? json.systemMessage : undefined;
2499
- return {
2500
- command: hook.command,
2501
- succeeded: result.status === 0,
2502
- output,
2503
- blocked,
2504
- watchPaths,
2505
- systemMessage,
2506
- };
2507
- }
2508
- catch (error) {
2509
- // Clean up on error
2510
- cleanup?.();
2511
- const errorMessage = error instanceof Error ? error.message : String(error);
2512
- logForDebugging(`${hookName} [${hook.command}] failed to run: ${errorMessage}`, { level: 'error' });
2513
- return {
2514
- command: hook.command,
2515
- succeeded: false,
2516
- output: errorMessage,
2517
- blocked: false,
2518
- };
2519
- }
2520
- });
2521
- // Wait for all hooks to complete and collect results
2522
- return await Promise.all(hookPromises);
2523
- }
2524
- /**
2525
- * Execute pre-tool hooks if configured
2526
- * @param toolName The name of the tool (e.g., 'Write', 'Edit', 'Bash')
2527
- * @param toolUseID The ID of the tool use
2528
- * @param toolInput The input that will be passed to the tool
2529
- * @param permissionMode Optional permission mode from toolPermissionContext
2530
- * @param signal Optional AbortSignal to cancel hook execution
2531
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2532
- * @param toolUseContext Optional ToolUseContext for prompt-based hooks
2533
- * @returns Async generator that yields progress messages and returns blocking errors
2534
- */
2535
- export async function* executePreToolHooks(toolName, toolUseID, toolInput, toolUseContext, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, requestPrompt, toolInputSummary) {
2536
- const appState = toolUseContext.getAppState();
2537
- const sessionId = toolUseContext.agentId ?? getSessionId();
2538
- if (!hasHookForEvent('PreToolUse', appState, sessionId)) {
2539
- return;
2540
- }
2541
- logForDebugging(`executePreToolHooks called for tool: ${toolName}`, {
2542
- level: 'verbose',
2543
- });
2544
- const hookInput = {
2545
- ...createBaseHookInput(permissionMode, undefined, toolUseContext),
2546
- hook_event_name: 'PreToolUse',
2547
- tool_name: toolName,
2548
- tool_input: toolInput,
2549
- tool_use_id: toolUseID,
2550
- };
2551
- yield* executeHooks({
2552
- hookInput,
2553
- toolUseID,
2554
- matchQuery: toolName,
2555
- signal,
2556
- timeoutMs,
2557
- toolUseContext,
2558
- requestPrompt,
2559
- toolInputSummary,
2560
- });
2561
- }
2562
- /**
2563
- * Execute post-tool hooks if configured
2564
- * @param toolName The name of the tool (e.g., 'Write', 'Edit', 'Bash')
2565
- * @param toolUseID The ID of the tool use
2566
- * @param toolInput The input that was passed to the tool
2567
- * @param toolResponse The response from the tool
2568
- * @param toolUseContext ToolUseContext for prompt-based hooks
2569
- * @param permissionMode Optional permission mode from toolPermissionContext
2570
- * @param signal Optional AbortSignal to cancel hook execution
2571
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2572
- * @returns Async generator that yields progress messages and blocking errors for automated feedback
2573
- */
2574
- export async function* executePostToolHooks(toolName, toolUseID, toolInput, toolResponse, toolUseContext, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2575
- const hookInput = {
2576
- ...createBaseHookInput(permissionMode, undefined, toolUseContext),
2577
- hook_event_name: 'PostToolUse',
2578
- tool_name: toolName,
2579
- tool_input: toolInput,
2580
- tool_response: toolResponse,
2581
- tool_use_id: toolUseID,
2582
- };
2583
- yield* executeHooks({
2584
- hookInput,
2585
- toolUseID,
2586
- matchQuery: toolName,
2587
- signal,
2588
- timeoutMs,
2589
- toolUseContext,
2590
- });
2591
- }
2592
- /**
2593
- * Execute post-tool-use-failure hooks if configured
2594
- * @param toolName The name of the tool (e.g., 'Write', 'Edit', 'Bash')
2595
- * @param toolUseID The ID of the tool use
2596
- * @param toolInput The input that was passed to the tool
2597
- * @param error The error message from the failed tool call
2598
- * @param toolUseContext ToolUseContext for prompt-based hooks
2599
- * @param isInterrupt Whether the tool was interrupted by user
2600
- * @param permissionMode Optional permission mode from toolPermissionContext
2601
- * @param signal Optional AbortSignal to cancel hook execution
2602
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2603
- * @returns Async generator that yields progress messages and blocking errors
2604
- */
2605
- export async function* executePostToolUseFailureHooks(toolName, toolUseID, toolInput, error, toolUseContext, isInterrupt, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2606
- const appState = toolUseContext.getAppState();
2607
- const sessionId = toolUseContext.agentId ?? getSessionId();
2608
- if (!hasHookForEvent('PostToolUseFailure', appState, sessionId)) {
2609
- return;
2610
- }
2611
- const hookInput = {
2612
- ...createBaseHookInput(permissionMode, undefined, toolUseContext),
2613
- hook_event_name: 'PostToolUseFailure',
2614
- tool_name: toolName,
2615
- tool_input: toolInput,
2616
- tool_use_id: toolUseID,
2617
- error,
2618
- is_interrupt: isInterrupt,
2619
- };
2620
- yield* executeHooks({
2621
- hookInput,
2622
- toolUseID,
2623
- matchQuery: toolName,
2624
- signal,
2625
- timeoutMs,
2626
- toolUseContext,
2627
- });
2628
- }
2629
- export async function* executePermissionDeniedHooks(toolName, toolUseID, toolInput, reason, toolUseContext, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2630
- const appState = toolUseContext.getAppState();
2631
- const sessionId = toolUseContext.agentId ?? getSessionId();
2632
- if (!hasHookForEvent('PermissionDenied', appState, sessionId)) {
2633
- return;
2634
- }
2635
- const hookInput = {
2636
- ...createBaseHookInput(permissionMode, undefined, toolUseContext),
2637
- hook_event_name: 'PermissionDenied',
2638
- tool_name: toolName,
2639
- tool_input: toolInput,
2640
- tool_use_id: toolUseID,
2641
- reason,
2642
- };
2643
- yield* executeHooks({
2644
- hookInput,
2645
- toolUseID,
2646
- matchQuery: toolName,
2647
- signal,
2648
- timeoutMs,
2649
- toolUseContext,
2650
- });
2651
- }
2652
- /**
2653
- * Execute notification hooks if configured
2654
- * @param notificationData The notification data to pass to hooks
2655
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2656
- * @returns Promise that resolves when all hooks complete
2657
- */
2658
- export async function executeNotificationHooks(notificationData, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2659
- const { message, title, notificationType } = notificationData;
2660
- const hookInput = {
2661
- ...createBaseHookInput(undefined),
2662
- hook_event_name: 'Notification',
2663
- message,
2664
- title,
2665
- notification_type: notificationType,
2666
- };
2667
- await executeHooksOutsideREPL({
2668
- hookInput,
2669
- timeoutMs,
2670
- matchQuery: notificationType,
2671
- });
2672
- }
2673
- export async function executeStopFailureHooks(lastMessage, toolUseContext, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2674
- const appState = toolUseContext?.getAppState();
2675
- // executeHooksOutsideREPL hardcodes main sessionId (:2738). Agent frontmatter
2676
- // hooks (registerFrontmatterHooks) key by agentId; gating with agentId here
2677
- // would pass the gate but fail execution. Align gate with execution.
2678
- const sessionId = getSessionId();
2679
- if (!hasHookForEvent('StopFailure', appState, sessionId))
2680
- return;
2681
- const lastAssistantText = extractTextContent(lastMessage.message.content, '\n').trim() || undefined;
2682
- // Some createAssistantAPIErrorMessage call sites omit `error` (e.g.
2683
- // image-size at errors.ts:431). Default to 'unknown' so matcher filtering
2684
- // at getMatchingHooks:1525 always applies.
2685
- const error = lastMessage.error ?? 'unknown';
2686
- const hookInput = {
2687
- ...createBaseHookInput(undefined, undefined, toolUseContext),
2688
- hook_event_name: 'StopFailure',
2689
- error,
2690
- error_details: lastMessage.errorDetails,
2691
- last_assistant_message: lastAssistantText,
2692
- };
2693
- await executeHooksOutsideREPL({
2694
- getAppState: toolUseContext?.getAppState,
2695
- hookInput,
2696
- timeoutMs,
2697
- matchQuery: error,
2698
- });
2699
- }
2700
- /**
2701
- * Execute stop hooks if configured
2702
- * @param toolUseContext ToolUseContext for prompt-based hooks
2703
- * @param permissionMode permission mode from toolPermissionContext
2704
- * @param signal AbortSignal to cancel hook execution
2705
- * @param stopHookActive Whether this call is happening within another stop hook
2706
- * @param isSubagent Whether the current execution context is a subagent
2707
- * @param messages Optional conversation history for prompt/function hooks
2708
- * @returns Async generator that yields progress messages and blocking errors
2709
- */
2710
- export async function* executeStopHooks(permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, stopHookActive = false, subagentId, toolUseContext, messages, agentType, requestPrompt) {
2711
- const hookEvent = subagentId ? 'SubagentStop' : 'Stop';
2712
- const appState = toolUseContext?.getAppState();
2713
- const sessionId = toolUseContext?.agentId ?? getSessionId();
2714
- if (!hasHookForEvent(hookEvent, appState, sessionId)) {
2715
- return;
2716
- }
2717
- // Extract text content from the last assistant message so hooks can
2718
- // inspect the final response without reading the transcript file.
2719
- const lastAssistantMessage = messages
2720
- ? getLastAssistantMessage(messages)
2721
- : undefined;
2722
- const lastAssistantText = lastAssistantMessage
2723
- ? extractTextContent(lastAssistantMessage.message.content, '\n').trim() ||
2724
- undefined
2725
- : undefined;
2726
- const hookInput = subagentId
2727
- ? {
2728
- ...createBaseHookInput(permissionMode),
2729
- hook_event_name: 'SubagentStop',
2730
- stop_hook_active: stopHookActive,
2731
- agent_id: subagentId,
2732
- agent_transcript_path: getAgentTranscriptPath(subagentId),
2733
- agent_type: agentType ?? '',
2734
- last_assistant_message: lastAssistantText,
2735
- }
2736
- : {
2737
- ...createBaseHookInput(permissionMode),
2738
- hook_event_name: 'Stop',
2739
- stop_hook_active: stopHookActive,
2740
- last_assistant_message: lastAssistantText,
2741
- };
2742
- // Trust check is now centralized in executeHooks()
2743
- yield* executeHooks({
2744
- hookInput,
2745
- toolUseID: randomUUID(),
2746
- signal,
2747
- timeoutMs,
2748
- toolUseContext,
2749
- messages,
2750
- requestPrompt,
2751
- });
2752
- }
2753
- /**
2754
- * Execute TeammateIdle hooks when a teammate is about to go idle.
2755
- * If a hook blocks (exit code 2), the teammate should continue working instead of going idle.
2756
- * @param teammateName The name of the teammate going idle
2757
- * @param teamName The team this teammate belongs to
2758
- * @param permissionMode Optional permission mode
2759
- * @param signal Optional AbortSignal to cancel hook execution
2760
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2761
- * @returns Async generator that yields progress messages and blocking errors
2762
- */
2763
- export async function* executeTeammateIdleHooks(teammateName, teamName, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2764
- const hookInput = {
2765
- ...createBaseHookInput(permissionMode),
2766
- hook_event_name: 'TeammateIdle',
2767
- teammate_name: teammateName,
2768
- team_name: teamName,
2769
- };
2770
- yield* executeHooks({
2771
- hookInput,
2772
- toolUseID: randomUUID(),
2773
- signal,
2774
- timeoutMs,
2775
- });
2776
- }
2777
- /**
2778
- * Execute TaskCreated hooks when a task is being created.
2779
- * If a hook blocks (exit code 2), the task creation should be prevented and feedback returned.
2780
- * @param taskId The ID of the task being created
2781
- * @param taskSubject The subject/title of the task
2782
- * @param taskDescription Optional description of the task
2783
- * @param teammateName Optional name of the teammate creating the task
2784
- * @param teamName Optional team name
2785
- * @param permissionMode Optional permission mode
2786
- * @param signal Optional AbortSignal to cancel hook execution
2787
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2788
- * @param toolUseContext Optional ToolUseContext for resolving appState and sessionId
2789
- * @returns Async generator that yields progress messages and blocking errors
2790
- */
2791
- export async function* executeTaskCreatedHooks(taskId, taskSubject, taskDescription, teammateName, teamName, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, toolUseContext) {
2792
- const hookInput = {
2793
- ...createBaseHookInput(permissionMode),
2794
- hook_event_name: 'TaskCreated',
2795
- task_id: taskId,
2796
- task_subject: taskSubject,
2797
- task_description: taskDescription,
2798
- teammate_name: teammateName,
2799
- team_name: teamName,
2800
- };
2801
- yield* executeHooks({
2802
- hookInput,
2803
- toolUseID: randomUUID(),
2804
- signal,
2805
- timeoutMs,
2806
- toolUseContext,
2807
- });
2808
- }
2809
- /**
2810
- * Execute TaskCompleted hooks when a task is being marked as completed.
2811
- * If a hook blocks (exit code 2), the task completion should be prevented and feedback returned.
2812
- * @param taskId The ID of the task being completed
2813
- * @param taskSubject The subject/title of the task
2814
- * @param taskDescription Optional description of the task
2815
- * @param teammateName Optional name of the teammate completing the task
2816
- * @param teamName Optional team name
2817
- * @param permissionMode Optional permission mode
2818
- * @param signal Optional AbortSignal to cancel hook execution
2819
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2820
- * @param toolUseContext Optional ToolUseContext for resolving appState and sessionId
2821
- * @returns Async generator that yields progress messages and blocking errors
2822
- */
2823
- export async function* executeTaskCompletedHooks(taskId, taskSubject, taskDescription, teammateName, teamName, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, toolUseContext) {
2824
- const hookInput = {
2825
- ...createBaseHookInput(permissionMode),
2826
- hook_event_name: 'TaskCompleted',
2827
- task_id: taskId,
2828
- task_subject: taskSubject,
2829
- task_description: taskDescription,
2830
- teammate_name: teammateName,
2831
- team_name: teamName,
2832
- };
2833
- yield* executeHooks({
2834
- hookInput,
2835
- toolUseID: randomUUID(),
2836
- signal,
2837
- timeoutMs,
2838
- toolUseContext,
2839
- });
2840
- }
2841
- /**
2842
- * Execute start hooks if configured
2843
- * @param prompt The user prompt that will be passed to the tool
2844
- * @param permissionMode Permission mode from toolPermissionContext
2845
- * @param toolUseContext ToolUseContext for prompt-based hooks
2846
- * @returns Async generator that yields progress messages and hook results
2847
- */
2848
- export async function* executeUserPromptSubmitHooks(prompt, permissionMode, toolUseContext, requestPrompt) {
2849
- const appState = toolUseContext.getAppState();
2850
- const sessionId = toolUseContext.agentId ?? getSessionId();
2851
- if (!hasHookForEvent('UserPromptSubmit', appState, sessionId)) {
2852
- return;
2853
- }
2854
- const hookInput = {
2855
- ...createBaseHookInput(permissionMode),
2856
- hook_event_name: 'UserPromptSubmit',
2857
- prompt,
2858
- };
2859
- yield* executeHooks({
2860
- hookInput,
2861
- toolUseID: randomUUID(),
2862
- signal: toolUseContext.abortController.signal,
2863
- timeoutMs: TOOL_HOOK_EXECUTION_TIMEOUT_MS,
2864
- toolUseContext,
2865
- requestPrompt,
2866
- });
2867
- }
2868
- /**
2869
- * Execute session start hooks if configured
2870
- * @param source The source of the session start (startup, resume, clear)
2871
- * @param sessionId Optional The session id to use as hook input
2872
- * @param agentType Optional The agent type (from --agent flag) running this session
2873
- * @param model Optional The model being used for this session
2874
- * @param signal Optional AbortSignal to cancel hook execution
2875
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2876
- * @returns Async generator that yields progress messages and hook results
2877
- */
2878
- export async function* executeSessionStartHooks(source, sessionId, agentType, model, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, forceSyncExecution) {
2879
- const hookInput = {
2880
- ...createBaseHookInput(undefined, sessionId),
2881
- hook_event_name: 'SessionStart',
2882
- source,
2883
- agent_type: agentType,
2884
- model,
2885
- };
2886
- yield* executeHooks({
2887
- hookInput,
2888
- toolUseID: randomUUID(),
2889
- matchQuery: source,
2890
- signal,
2891
- timeoutMs,
2892
- forceSyncExecution,
2893
- });
2894
- }
2895
- /**
2896
- * Execute setup hooks if configured
2897
- * @param trigger The trigger type ('init' or 'maintenance')
2898
- * @param signal Optional AbortSignal to cancel hook execution
2899
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2900
- * @param forceSyncExecution If true, async hooks will not be backgrounded
2901
- * @returns Async generator that yields progress messages and hook results
2902
- */
2903
- export async function* executeSetupHooks(trigger, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, forceSyncExecution) {
2904
- const hookInput = {
2905
- ...createBaseHookInput(undefined),
2906
- hook_event_name: 'Setup',
2907
- trigger,
2908
- };
2909
- yield* executeHooks({
2910
- hookInput,
2911
- toolUseID: randomUUID(),
2912
- matchQuery: trigger,
2913
- signal,
2914
- timeoutMs,
2915
- forceSyncExecution,
2916
- });
2917
- }
2918
- /**
2919
- * Execute subagent start hooks if configured
2920
- * @param agentId The unique identifier for the subagent
2921
- * @param agentType The type/name of the subagent being started
2922
- * @param signal Optional AbortSignal to cancel hook execution
2923
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2924
- * @returns Async generator that yields progress messages and hook results
2925
- */
2926
- export async function* executeSubagentStartHooks(agentId, agentType, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2927
- const hookInput = {
2928
- ...createBaseHookInput(undefined),
2929
- hook_event_name: 'SubagentStart',
2930
- agent_id: agentId,
2931
- agent_type: agentType,
2932
- };
2933
- yield* executeHooks({
2934
- hookInput,
2935
- toolUseID: randomUUID(),
2936
- matchQuery: agentType,
2937
- signal,
2938
- timeoutMs,
2939
- });
2940
- }
2941
- /**
2942
- * Execute pre-compact hooks if configured
2943
- * @param compactData The compact data to pass to hooks
2944
- * @param signal Optional AbortSignal to cancel hook execution
2945
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2946
- * @returns Object with optional newCustomInstructions and userDisplayMessage
2947
- */
2948
- export async function executePreCompactHooks(compactData, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
2949
- const hookInput = {
2950
- ...createBaseHookInput(undefined),
2951
- hook_event_name: 'PreCompact',
2952
- trigger: compactData.trigger,
2953
- custom_instructions: compactData.customInstructions,
2954
- };
2955
- const results = await executeHooksOutsideREPL({
2956
- hookInput,
2957
- matchQuery: compactData.trigger,
2958
- signal,
2959
- timeoutMs,
2960
- });
2961
- if (results.length === 0) {
2962
- return {};
2963
- }
2964
- // Extract custom instructions from successful hooks with non-empty output
2965
- const successfulOutputs = results
2966
- .filter(result => result.succeeded && result.output.trim().length > 0)
2967
- .map(result => result.output.trim());
2968
- // Build user display messages with command info
2969
- const displayMessages = [];
2970
- for (const result of results) {
2971
- if (result.succeeded) {
2972
- if (result.output.trim()) {
2973
- displayMessages.push(`PreCompact [${result.command}] completed successfully: ${result.output.trim()}`);
2974
- }
2975
- else {
2976
- displayMessages.push(`PreCompact [${result.command}] completed successfully`);
2977
- }
2978
- }
2979
- else {
2980
- if (result.output.trim()) {
2981
- displayMessages.push(`PreCompact [${result.command}] failed: ${result.output.trim()}`);
2982
- }
2983
- else {
2984
- displayMessages.push(`PreCompact [${result.command}] failed`);
2985
- }
2986
- }
2987
- }
2988
- return {
2989
- newCustomInstructions: successfulOutputs.length > 0 ? successfulOutputs.join('\n\n') : undefined,
2990
- userDisplayMessage: displayMessages.length > 0 ? displayMessages.join('\n') : undefined,
2991
- };
2992
- }
2993
- /**
2994
- * Execute post-compact hooks if configured
2995
- * @param compactData The compact data to pass to hooks, including the summary
2996
- * @param signal Optional AbortSignal to cancel hook execution
2997
- * @param timeoutMs Optional timeout in milliseconds for hook execution
2998
- * @returns Object with optional userDisplayMessage
2999
- */
3000
- export async function executePostCompactHooks(compactData, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
3001
- const hookInput = {
3002
- ...createBaseHookInput(undefined),
3003
- hook_event_name: 'PostCompact',
3004
- trigger: compactData.trigger,
3005
- compact_summary: compactData.compactSummary,
3006
- };
3007
- const results = await executeHooksOutsideREPL({
3008
- hookInput,
3009
- matchQuery: compactData.trigger,
3010
- signal,
3011
- timeoutMs,
3012
- });
3013
- if (results.length === 0) {
3014
- return {};
3015
- }
3016
- const displayMessages = [];
3017
- for (const result of results) {
3018
- if (result.succeeded) {
3019
- if (result.output.trim()) {
3020
- displayMessages.push(`PostCompact [${result.command}] completed successfully: ${result.output.trim()}`);
3021
- }
3022
- else {
3023
- displayMessages.push(`PostCompact [${result.command}] completed successfully`);
3024
- }
3025
- }
3026
- else {
3027
- if (result.output.trim()) {
3028
- displayMessages.push(`PostCompact [${result.command}] failed: ${result.output.trim()}`);
3029
- }
3030
- else {
3031
- displayMessages.push(`PostCompact [${result.command}] failed`);
3032
- }
3033
- }
3034
- }
3035
- return {
3036
- userDisplayMessage: displayMessages.length > 0 ? displayMessages.join('\n') : undefined,
3037
- };
3038
- }
3039
- /**
3040
- * Execute session end hooks if configured
3041
- * @param reason The reason for ending the session
3042
- * @param options Optional parameters including app state functions and signal
3043
- * @returns Promise that resolves when all hooks complete
3044
- */
3045
- export async function executeSessionEndHooks(reason, options) {
3046
- const { getAppState, setAppState, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, } = options || {};
3047
- const hookInput = {
3048
- ...createBaseHookInput(undefined),
3049
- hook_event_name: 'SessionEnd',
3050
- reason,
3051
- };
3052
- const results = await executeHooksOutsideREPL({
3053
- getAppState,
3054
- hookInput,
3055
- matchQuery: reason,
3056
- signal,
3057
- timeoutMs,
3058
- });
3059
- // During shutdown, Ink is unmounted so we can write directly to stderr
3060
- for (const result of results) {
3061
- if (!result.succeeded && result.output) {
3062
- process.stderr.write(`SessionEnd hook [${result.command}] failed: ${result.output}\n`);
3063
- }
3064
- }
3065
- // Clear session hooks after execution
3066
- if (setAppState) {
3067
- const sessionId = getSessionId();
3068
- clearSessionHooks(setAppState, sessionId);
3069
- }
3070
- }
3071
- /**
3072
- * Execute permission request hooks if configured
3073
- * These hooks are called when a permission dialog would be displayed to the user.
3074
- * Hooks can approve or deny the permission request programmatically.
3075
- * @param toolName The name of the tool requesting permission
3076
- * @param toolUseID The ID of the tool use
3077
- * @param toolInput The input that would be passed to the tool
3078
- * @param toolUseContext ToolUseContext for the request
3079
- * @param permissionMode Optional permission mode from toolPermissionContext
3080
- * @param permissionSuggestions Optional permission suggestions (the "always allow" options)
3081
- * @param signal Optional AbortSignal to cancel hook execution
3082
- * @param timeoutMs Optional timeout in milliseconds for hook execution
3083
- * @returns Async generator that yields progress messages and returns aggregated result
3084
- */
3085
- export async function* executePermissionRequestHooks(toolName, toolUseID, toolInput, toolUseContext, permissionMode, permissionSuggestions, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, requestPrompt, toolInputSummary) {
3086
- logForDebugging(`executePermissionRequestHooks called for tool: ${toolName}`);
3087
- const hookInput = {
3088
- ...createBaseHookInput(permissionMode, undefined, toolUseContext),
3089
- hook_event_name: 'PermissionRequest',
3090
- tool_name: toolName,
3091
- tool_input: toolInput,
3092
- permission_suggestions: permissionSuggestions,
3093
- };
3094
- yield* executeHooks({
3095
- hookInput,
3096
- toolUseID,
3097
- matchQuery: toolName,
3098
- signal,
3099
- timeoutMs,
3100
- toolUseContext,
3101
- requestPrompt,
3102
- toolInputSummary,
3103
- });
3104
- }
3105
- /**
3106
- * Execute config change hooks when configuration files change during a session.
3107
- * Fired by file watchers when settings, skills, or commands change on disk.
3108
- * Enables enterprise admins to audit/log configuration changes for security.
3109
- *
3110
- * Policy settings are enterprise-managed and must never be blockable by hooks.
3111
- * Hooks still fire (for audit logging) but blocking results are ignored — callers
3112
- * will always see an empty result for policy sources.
3113
- *
3114
- * @param source The type of config that changed
3115
- * @param filePath Optional path to the changed file
3116
- * @param timeoutMs Optional timeout in milliseconds for hook execution
3117
- */
3118
- export async function executeConfigChangeHooks(source, filePath, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
3119
- const hookInput = {
3120
- ...createBaseHookInput(undefined),
3121
- hook_event_name: 'ConfigChange',
3122
- source,
3123
- file_path: filePath,
3124
- };
3125
- const results = await executeHooksOutsideREPL({
3126
- hookInput,
3127
- timeoutMs,
3128
- matchQuery: source,
3129
- });
3130
- // Policy settings are enterprise-managed — hooks fire for audit logging
3131
- // but must never block policy changes from being applied
3132
- if (source === 'policy_settings') {
3133
- return results.map(r => ({ ...r, blocked: false }));
3134
- }
3135
- return results;
3136
- }
3137
- async function executeEnvHooks(hookInput, timeoutMs) {
3138
- const results = await executeHooksOutsideREPL({ hookInput, timeoutMs });
3139
- if (results.length > 0) {
3140
- invalidateSessionEnvCache();
3141
- }
3142
- const watchPaths = results.flatMap(r => r.watchPaths ?? []);
3143
- const systemMessages = results
3144
- .map(r => r.systemMessage)
3145
- .filter((m) => !!m);
3146
- return { results, watchPaths, systemMessages };
3147
- }
3148
- export function executeCwdChangedHooks(oldCwd, newCwd, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
3149
- const hookInput = {
3150
- ...createBaseHookInput(undefined),
3151
- hook_event_name: 'CwdChanged',
3152
- old_cwd: oldCwd,
3153
- new_cwd: newCwd,
3154
- };
3155
- return executeEnvHooks(hookInput, timeoutMs);
3156
- }
3157
- export function executeFileChangedHooks(filePath, event, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS) {
3158
- const hookInput = {
3159
- ...createBaseHookInput(undefined),
3160
- hook_event_name: 'FileChanged',
3161
- file_path: filePath,
3162
- event,
3163
- };
3164
- return executeEnvHooks(hookInput, timeoutMs);
3165
- }
3166
- /**
3167
- * Check if InstructionsLoaded hooks are configured (without executing them).
3168
- * Callers should check this before invoking executeInstructionsLoadedHooks to avoid
3169
- * building hook inputs for every instruction file when no hook is configured.
3170
- *
3171
- * Checks both settings-file hooks (getHooksConfigFromSnapshot) and registered
3172
- * hooks (plugin hooks + SDK callback hooks via registerHookCallbacks). Session-
3173
- * derived hooks (structured output enforcement etc.) are internal and not checked.
3174
- */
3175
- export function hasInstructionsLoadedHook() {
3176
- const snapshotHooks = getHooksConfigFromSnapshot()?.['InstructionsLoaded'];
3177
- if (snapshotHooks && snapshotHooks.length > 0)
3178
- return true;
3179
- const registeredHooks = getRegisteredHooks()?.['InstructionsLoaded'];
3180
- if (registeredHooks && registeredHooks.length > 0)
3181
- return true;
3182
- return false;
3183
- }
3184
- /**
3185
- * Execute InstructionsLoaded hooks when an instruction file (CLAUDE.md or
3186
- * .claude/rules/*.md) is loaded into context. Fire-and-forget — this hook is
3187
- * for observability/audit only and does not support blocking.
3188
- *
3189
- * Dispatch sites:
3190
- * - Eager load at session start (getMemoryFiles in claudemd.ts)
3191
- * - Eager reload after compaction (getMemoryFiles cache cleared by
3192
- * runPostCompactCleanup; next call reports load_reason: 'compact')
3193
- * - Lazy load when Claude touches a file that triggers nested CLAUDE.md or
3194
- * conditional rules with paths: frontmatter (memoryFilesToAttachments in
3195
- * attachments.ts)
3196
- */
3197
- export async function executeInstructionsLoadedHooks(filePath, memoryType, loadReason, options) {
3198
- const { globs, triggerFilePath, parentFilePath, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, } = options ?? {};
3199
- const hookInput = {
3200
- ...createBaseHookInput(undefined),
3201
- hook_event_name: 'InstructionsLoaded',
3202
- file_path: filePath,
3203
- memory_type: memoryType,
3204
- load_reason: loadReason,
3205
- globs,
3206
- trigger_file_path: triggerFilePath,
3207
- parent_file_path: parentFilePath,
3208
- };
3209
- await executeHooksOutsideREPL({
3210
- hookInput,
3211
- timeoutMs,
3212
- matchQuery: loadReason,
3213
- });
3214
- }
3215
- /**
3216
- * Parse elicitation-specific fields from a HookOutsideReplResult.
3217
- * Mirrors the relevant branches of processHookJSONOutput for Elicitation
3218
- * and ElicitationResult hook events.
3219
- */
3220
- function parseElicitationHookOutput(result, expectedEventName) {
3221
- // Exit code 2 = blocking (same as executeHooks path)
3222
- if (result.blocked && !result.succeeded) {
3223
- return {
3224
- blockingError: {
3225
- blockingError: result.output || `Elicitation blocked by hook`,
3226
- command: result.command,
3227
- },
3228
- };
3229
- }
3230
- if (!result.output.trim()) {
3231
- return {};
3232
- }
3233
- // Try to parse JSON output for structured elicitation response
3234
- const trimmed = result.output.trim();
3235
- if (!trimmed.startsWith('{')) {
3236
- return {};
3237
- }
3238
- try {
3239
- const parsed = hookJSONOutputSchema().parse(JSON.parse(trimmed));
3240
- if (isAsyncHookJSONOutput(parsed)) {
3241
- return {};
3242
- }
3243
- if (!isSyncHookJSONOutput(parsed)) {
3244
- return {};
3245
- }
3246
- // Check for top-level decision: 'block' (exit code 0 + JSON block)
3247
- if (parsed.decision === 'block' || result.blocked) {
3248
- return {
3249
- blockingError: {
3250
- blockingError: parsed.reason || 'Elicitation blocked by hook',
3251
- command: result.command,
3252
- },
3253
- };
3254
- }
3255
- const specific = parsed.hookSpecificOutput;
3256
- if (!specific || specific.hookEventName !== expectedEventName) {
3257
- return {};
3258
- }
3259
- if (!specific.action) {
3260
- return {};
3261
- }
3262
- const response = {
3263
- action: specific.action,
3264
- content: specific.content,
3265
- };
3266
- const out = { response };
3267
- if (specific.action === 'decline') {
3268
- out.blockingError = {
3269
- blockingError: parsed.reason ||
3270
- (expectedEventName === 'Elicitation'
3271
- ? 'Elicitation denied by hook'
3272
- : 'Elicitation result blocked by hook'),
3273
- command: result.command,
3274
- };
3275
- }
3276
- return out;
3277
- }
3278
- catch {
3279
- return {};
3280
- }
3281
- }
3282
- export async function executeElicitationHooks({ serverName, message, requestedSchema, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, mode, url, elicitationId, }) {
3283
- const hookInput = {
3284
- ...createBaseHookInput(permissionMode),
3285
- hook_event_name: 'Elicitation',
3286
- mcp_server_name: serverName,
3287
- message,
3288
- mode,
3289
- url,
3290
- elicitation_id: elicitationId,
3291
- requested_schema: requestedSchema,
3292
- };
3293
- const results = await executeHooksOutsideREPL({
3294
- hookInput,
3295
- matchQuery: serverName,
3296
- signal,
3297
- timeoutMs,
3298
- });
3299
- let elicitationResponse;
3300
- let blockingError;
3301
- for (const result of results) {
3302
- const parsed = parseElicitationHookOutput(result, 'Elicitation');
3303
- if (parsed.blockingError) {
3304
- blockingError = parsed.blockingError;
3305
- }
3306
- if (parsed.response) {
3307
- elicitationResponse = parsed.response;
3308
- }
3309
- }
3310
- return { elicitationResponse, blockingError };
3311
- }
3312
- export async function executeElicitationResultHooks({ serverName, action, content, permissionMode, signal, timeoutMs = TOOL_HOOK_EXECUTION_TIMEOUT_MS, mode, elicitationId, }) {
3313
- const hookInput = {
3314
- ...createBaseHookInput(permissionMode),
3315
- hook_event_name: 'ElicitationResult',
3316
- mcp_server_name: serverName,
3317
- elicitation_id: elicitationId,
3318
- mode,
3319
- action,
3320
- content,
3321
- };
3322
- const results = await executeHooksOutsideREPL({
3323
- hookInput,
3324
- matchQuery: serverName,
3325
- signal,
3326
- timeoutMs,
3327
- });
3328
- let elicitationResultResponse;
3329
- let blockingError;
3330
- for (const result of results) {
3331
- const parsed = parseElicitationHookOutput(result, 'ElicitationResult');
3332
- if (parsed.blockingError) {
3333
- blockingError = parsed.blockingError;
3334
- }
3335
- if (parsed.response) {
3336
- elicitationResultResponse = parsed.response;
3337
- }
3338
- }
3339
- return { elicitationResultResponse, blockingError };
3340
- }
3341
- /**
3342
- * Execute status line command if configured
3343
- * @param statusLineInput The structured status input that will be converted to JSON
3344
- * @param signal Optional AbortSignal to cancel hook execution
3345
- * @param timeoutMs Optional timeout in milliseconds for hook execution
3346
- * @returns The status line text to display, or undefined if no command configured
3347
- */
3348
- export async function executeStatusLineCommand(statusLineInput, signal, timeoutMs = 5000, // Short timeout for status line
3349
- logResult = false) {
3350
- // Check if all hooks (including statusLine) are disabled by managed settings
3351
- if (shouldDisableAllHooksIncludingManaged()) {
3352
- return undefined;
3353
- }
3354
- // SECURITY: ALL hooks require workspace trust in interactive mode
3355
- // This centralized check prevents RCE vulnerabilities for all current and future hooks
3356
- if (shouldSkipHookDueToTrust()) {
3357
- logForDebugging(`Skipping StatusLine command execution - workspace trust not accepted`);
3358
- return undefined;
3359
- }
3360
- // When disableAllHooks is set in non-managed settings, only managed statusLine runs
3361
- // (non-managed settings cannot disable managed commands, but non-managed commands are disabled)
3362
- let statusLine;
3363
- if (shouldAllowManagedHooksOnly()) {
3364
- statusLine = getSettingsForSource('policySettings')?.statusLine;
3365
- }
3366
- else {
3367
- statusLine = getSettings_DEPRECATED()?.statusLine;
3368
- }
3369
- if (!statusLine || statusLine.type !== 'command') {
3370
- return undefined;
3371
- }
3372
- // Use provided signal or create a default one
3373
- const abortSignal = signal || AbortSignal.timeout(timeoutMs);
3374
- try {
3375
- // Convert status input to JSON
3376
- const jsonInput = jsonStringify(statusLineInput);
3377
- const result = await execCommandHook(statusLine, 'StatusLine', 'statusLine', jsonInput, abortSignal, randomUUID());
3378
- if (result.aborted) {
3379
- return undefined;
3380
- }
3381
- // For successful hooks (exit code 0), use stdout
3382
- if (result.status === 0) {
3383
- // Trim and split output into lines, then join with newlines
3384
- const output = result.stdout
3385
- .trim()
3386
- .split('\n')
3387
- .flatMap(line => line.trim() || [])
3388
- .join('\n');
3389
- if (output) {
3390
- if (logResult) {
3391
- logForDebugging(`StatusLine [${statusLine.command}] completed with status ${result.status}`);
3392
- }
3393
- return output;
3394
- }
3395
- }
3396
- else if (logResult) {
3397
- logForDebugging(`StatusLine [${statusLine.command}] completed with status ${result.status}`, { level: 'warn' });
3398
- }
3399
- return undefined;
3400
- }
3401
- catch (error) {
3402
- logForDebugging(`Status hook failed: ${error}`, { level: 'error' });
3403
- return undefined;
3404
- }
3405
- }
3406
- /**
3407
- * Execute file suggestion command if configured
3408
- * @param fileSuggestionInput The structured input that will be converted to JSON
3409
- * @param signal Optional AbortSignal to cancel hook execution
3410
- * @param timeoutMs Optional timeout in milliseconds for hook execution
3411
- * @returns Array of file paths, or empty array if no command configured
3412
- */
3413
- export async function executeFileSuggestionCommand(fileSuggestionInput, signal, timeoutMs = 5000) {
3414
- // Check if all hooks are disabled by managed settings
3415
- if (shouldDisableAllHooksIncludingManaged()) {
3416
- return [];
3417
- }
3418
- // SECURITY: ALL hooks require workspace trust in interactive mode
3419
- // This centralized check prevents RCE vulnerabilities for all current and future hooks
3420
- if (shouldSkipHookDueToTrust()) {
3421
- logForDebugging(`Skipping FileSuggestion command execution - workspace trust not accepted`);
3422
- return [];
3423
- }
3424
- // When disableAllHooks is set in non-managed settings, only managed fileSuggestion runs
3425
- // (non-managed settings cannot disable managed commands, but non-managed commands are disabled)
3426
- let fileSuggestion;
3427
- if (shouldAllowManagedHooksOnly()) {
3428
- fileSuggestion = getSettingsForSource('policySettings')?.fileSuggestion;
3429
- }
3430
- else {
3431
- fileSuggestion = getSettings_DEPRECATED()?.fileSuggestion;
3432
- }
3433
- if (!fileSuggestion || fileSuggestion.type !== 'command') {
3434
- return [];
3435
- }
3436
- // Use provided signal or create a default one
3437
- const abortSignal = signal || AbortSignal.timeout(timeoutMs);
3438
- try {
3439
- const jsonInput = jsonStringify(fileSuggestionInput);
3440
- const hook = { type: 'command', command: fileSuggestion.command };
3441
- const result = await execCommandHook(hook, 'FileSuggestion', 'FileSuggestion', jsonInput, abortSignal, randomUUID());
3442
- if (result.aborted || result.status !== 0) {
3443
- return [];
3444
- }
3445
- return result.stdout
3446
- .split('\n')
3447
- .map(line => line.trim())
3448
- .filter(Boolean);
3449
- }
3450
- catch (error) {
3451
- logForDebugging(`File suggestion helper failed: ${error}`, {
3452
- level: 'error',
3453
- });
3454
- return [];
3455
- }
3456
- }
3457
- async function executeFunctionHook({ hook, messages, hookName, toolUseID, hookEvent, timeoutMs, signal, }) {
3458
- const callbackTimeoutMs = hook.timeout ?? timeoutMs;
3459
- const { signal: abortSignal, cleanup } = createCombinedAbortSignal(signal, {
3460
- timeoutMs: callbackTimeoutMs,
3461
- });
3462
- try {
3463
- // Check if already aborted
3464
- if (abortSignal.aborted) {
3465
- cleanup();
3466
- return {
3467
- outcome: 'cancelled',
3468
- hook,
3469
- };
3470
- }
3471
- // Execute callback with abort signal
3472
- const passed = await new Promise((resolve, reject) => {
3473
- // Handle abort signal
3474
- const onAbort = () => reject(new Error('Function hook cancelled'));
3475
- abortSignal.addEventListener('abort', onAbort);
3476
- // Execute callback
3477
- Promise.resolve(hook.callback(messages, abortSignal))
3478
- .then(result => {
3479
- abortSignal.removeEventListener('abort', onAbort);
3480
- resolve(result);
3481
- })
3482
- .catch(error => {
3483
- abortSignal.removeEventListener('abort', onAbort);
3484
- reject(error);
3485
- });
3486
- });
3487
- cleanup();
3488
- if (passed) {
3489
- return {
3490
- outcome: 'success',
3491
- hook,
3492
- };
3493
- }
3494
- return {
3495
- blockingError: {
3496
- blockingError: hook.errorMessage,
3497
- command: 'function',
3498
- },
3499
- outcome: 'blocking',
3500
- hook,
3501
- };
3502
- }
3503
- catch (error) {
3504
- cleanup();
3505
- // Handle cancellation
3506
- if (error instanceof Error &&
3507
- (error.message === 'Function hook cancelled' ||
3508
- error.name === 'AbortError')) {
3509
- return {
3510
- outcome: 'cancelled',
3511
- hook,
3512
- };
3513
- }
3514
- // Log for monitoring
3515
- logError(error);
3516
- return {
3517
- message: createAttachmentMessage({
3518
- type: 'hook_error_during_execution',
3519
- hookName,
3520
- toolUseID,
3521
- hookEvent,
3522
- content: error instanceof Error
3523
- ? error.message
3524
- : 'Function hook execution error',
3525
- }),
3526
- outcome: 'non_blocking_error',
3527
- hook,
3528
- };
3529
- }
3530
- }
3531
- async function executeHookCallback({ toolUseID, hook, hookEvent, hookInput, signal, hookIndex, toolUseContext, }) {
3532
- // Create context for callbacks that need state access
3533
- const context = toolUseContext
3534
- ? {
3535
- getAppState: toolUseContext.getAppState,
3536
- updateAttributionState: toolUseContext.updateAttributionState,
3537
- }
3538
- : undefined;
3539
- const json = await hook.callback(hookInput, toolUseID, signal, hookIndex, context);
3540
- if (isAsyncHookJSONOutput(json)) {
3541
- return {
3542
- outcome: 'success',
3543
- hook,
3544
- };
3545
- }
3546
- const processed = processHookJSONOutput({
3547
- json,
3548
- command: 'callback',
3549
- // TODO: If the hook came from a plugin, use the full path to the plugin for easier debugging
3550
- hookName: `${hookEvent}:Callback`,
3551
- toolUseID,
3552
- hookEvent,
3553
- expectedHookEvent: hookEvent,
3554
- // Callbacks don't have stdout/stderr/exitCode
3555
- stdout: undefined,
3556
- stderr: undefined,
3557
- exitCode: undefined,
3558
- });
3559
- return {
3560
- ...processed,
3561
- outcome: 'success',
3562
- hook,
3563
- };
3564
- }
3565
- /**
3566
- * Check if WorktreeCreate hooks are configured (without executing them).
3567
- *
3568
- * Checks both settings-file hooks (getHooksConfigFromSnapshot) and registered
3569
- * hooks (plugin hooks + SDK callback hooks via registerHookCallbacks).
3570
- *
3571
- * Must mirror the managedOnly filtering in getHooksConfig() — when
3572
- * shouldAllowManagedHooksOnly() is true, plugin hooks (pluginRoot set) are
3573
- * skipped at execution, so we must also skip them here. Otherwise this returns
3574
- * true but executeWorktreeCreateHook() finds no matching hooks and throws,
3575
- * blocking the git-worktree fallback.
3576
- */
3577
- export function hasWorktreeCreateHook() {
3578
- const snapshotHooks = getHooksConfigFromSnapshot()?.['WorktreeCreate'];
3579
- if (snapshotHooks && snapshotHooks.length > 0)
3580
- return true;
3581
- const registeredHooks = getRegisteredHooks()?.['WorktreeCreate'];
3582
- if (!registeredHooks || registeredHooks.length === 0)
3583
- return false;
3584
- // Mirror getHooksConfig(): skip plugin hooks in managed-only mode
3585
- const managedOnly = shouldAllowManagedHooksOnly();
3586
- return registeredHooks.some(matcher => !(managedOnly && 'pluginRoot' in matcher));
3587
- }
3588
- /**
3589
- * Execute WorktreeCreate hooks.
3590
- * Returns the worktree path from hook stdout.
3591
- * Throws if hooks fail or produce no output.
3592
- * Callers should check hasWorktreeCreateHook() before calling this.
3593
- */
3594
- export async function executeWorktreeCreateHook(name) {
3595
- const hookInput = {
3596
- ...createBaseHookInput(undefined),
3597
- hook_event_name: 'WorktreeCreate',
3598
- name,
3599
- };
3600
- const results = await executeHooksOutsideREPL({
3601
- hookInput,
3602
- timeoutMs: TOOL_HOOK_EXECUTION_TIMEOUT_MS,
3603
- });
3604
- // Find the first successful result with non-empty output
3605
- const successfulResult = results.find(r => r.succeeded && r.output.trim().length > 0);
3606
- if (!successfulResult) {
3607
- const failedOutputs = results
3608
- .filter(r => !r.succeeded)
3609
- .map(r => `${r.command}: ${r.output.trim() || 'no output'}`);
3610
- throw new Error(`WorktreeCreate hook failed: ${failedOutputs.join('; ') || 'no successful output'}`);
3611
- }
3612
- const worktreePath = successfulResult.output.trim();
3613
- return { worktreePath };
3614
- }
3615
- /**
3616
- * Execute WorktreeRemove hooks if configured.
3617
- * Returns true if hooks were configured and ran, false if no hooks are configured.
3618
- *
3619
- * Checks both settings-file hooks (getHooksConfigFromSnapshot) and registered
3620
- * hooks (plugin hooks + SDK callback hooks via registerHookCallbacks).
3621
- */
3622
- export async function executeWorktreeRemoveHook(worktreePath) {
3623
- const snapshotHooks = getHooksConfigFromSnapshot()?.['WorktreeRemove'];
3624
- const registeredHooks = getRegisteredHooks()?.['WorktreeRemove'];
3625
- const hasSnapshotHooks = snapshotHooks && snapshotHooks.length > 0;
3626
- const hasRegisteredHooks = registeredHooks && registeredHooks.length > 0;
3627
- if (!hasSnapshotHooks && !hasRegisteredHooks) {
3628
- return false;
3629
- }
3630
- const hookInput = {
3631
- ...createBaseHookInput(undefined),
3632
- hook_event_name: 'WorktreeRemove',
3633
- worktree_path: worktreePath,
3634
- };
3635
- const results = await executeHooksOutsideREPL({
3636
- hookInput,
3637
- timeoutMs: TOOL_HOOK_EXECUTION_TIMEOUT_MS,
3638
- });
3639
- if (results.length === 0) {
3640
- return false;
3641
- }
3642
- for (const result of results) {
3643
- if (!result.succeeded) {
3644
- logForDebugging(`WorktreeRemove hook failed [${result.command}]: ${result.output.trim()}`, { level: 'error' });
3645
- }
3646
- }
3647
- return true;
3648
- }
3649
- function getHookDefinitionsForTelemetry(matchedHooks) {
3650
- return matchedHooks.map(({ hook }) => {
3651
- if (hook.type === 'command') {
3652
- return { type: 'command', command: hook.command };
3653
- }
3654
- else if (hook.type === 'prompt') {
3655
- return { type: 'prompt', prompt: hook.prompt };
3656
- }
3657
- else if (hook.type === 'http') {
3658
- return { type: 'http', command: hook.url };
3659
- }
3660
- else if (hook.type === 'function') {
3661
- return { type: 'function', name: 'function' };
3662
- }
3663
- else if (hook.type === 'callback') {
3664
- return { type: 'callback', name: 'callback' };
3665
- }
3666
- return { type: 'unknown' };
3667
- });
3668
- }