thaddeus 1.0.26 → 1.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2082) hide show
  1. package/package.json +14 -5
  2. package/src/QueryEngine.js +926 -0
  3. package/src/Task.js +49 -0
  4. package/src/Tool.js +61 -0
  5. package/src/assistant/gate.js +5 -0
  6. package/src/assistant/index.js +106 -0
  7. package/src/assistant/sessionHistory.js +145 -0
  8. package/src/bootstrap/state.js +1163 -0
  9. package/src/bridge/bridgeApi.js +304 -0
  10. package/src/bridge/bridgeConfig.js +39 -0
  11. package/src/bridge/bridgeDebug.js +73 -0
  12. package/src/bridge/bridgeEnabled.js +185 -0
  13. package/src/bridge/bridgeMain.js +2289 -0
  14. package/src/bridge/bridgeMessaging.js +353 -0
  15. package/src/bridge/bridgePermissionCallbacks.js +10 -0
  16. package/src/bridge/bridgePointer.js +175 -0
  17. package/src/bridge/bridgeStatusUtil.js +105 -0
  18. package/src/bridge/bridgeUI.js +411 -0
  19. package/src/bridge/capacityWake.js +35 -0
  20. package/src/bridge/codeSessionApi.js +111 -0
  21. package/src/bridge/createSession.js +273 -0
  22. package/src/bridge/debugUtils.js +115 -0
  23. package/src/bridge/envLessBridgeConfig.js +120 -0
  24. package/src/bridge/flushGate.js +65 -0
  25. package/src/bridge/inboundAttachments.js +152 -0
  26. package/src/bridge/inboundMessages.js +63 -0
  27. package/src/bridge/initReplBridge.js +431 -0
  28. package/src/bridge/jwtUtils.js +185 -0
  29. package/src/bridge/peerSessions.js +5 -0
  30. package/src/bridge/pollConfig.js +85 -0
  31. package/src/bridge/pollConfigDefaults.js +62 -0
  32. package/src/bridge/remoteBridgeCore.js +712 -0
  33. package/src/bridge/replBridge.js +1719 -0
  34. package/src/bridge/replBridgeHandle.js +30 -0
  35. package/src/bridge/replBridgeTransport.js +236 -0
  36. package/src/bridge/sessionIdCompat.js +56 -0
  37. package/src/bridge/sessionRunner.js +421 -0
  38. package/src/bridge/trustedDevice.js +170 -0
  39. package/src/bridge/types.js +9 -0
  40. package/src/bridge/webhookSanitizer.js +6 -0
  41. package/src/bridge/workSecret.js +99 -0
  42. package/src/buddy/CompanionSprite.js +348 -0
  43. package/src/buddy/companion.js +107 -0
  44. package/src/buddy/prompt.js +33 -0
  45. package/src/buddy/sprites.js +488 -0
  46. package/src/buddy/types.js +90 -0
  47. package/src/buddy/useBuddyNotification.js +85 -0
  48. package/src/cli/bg.js +17 -0
  49. package/src/cli/exit.js +30 -0
  50. package/src/cli/handlers/agents.js +55 -0
  51. package/src/cli/handlers/auth.js +249 -0
  52. package/src/cli/handlers/autoMode.js +128 -0
  53. package/src/cli/handlers/mcp.js +335 -0
  54. package/src/cli/handlers/plugins.js +634 -0
  55. package/src/cli/handlers/templateJobs.js +19 -0
  56. package/src/cli/handlers/util.js +76 -0
  57. package/src/cli/ndjsonSafeStringify.js +27 -0
  58. package/src/cli/print.js +4294 -0
  59. package/src/cli/remoteIO.js +208 -0
  60. package/src/cli/structuredIO.js +644 -0
  61. package/src/cli/transports/HybridTransport.js +233 -0
  62. package/src/cli/transports/SSETransport.js +538 -0
  63. package/src/cli/transports/SerialBatchEventUploader.js +224 -0
  64. package/src/cli/transports/WebSocketTransport.js +613 -0
  65. package/src/cli/transports/WorkerStateUploader.js +88 -0
  66. package/src/cli/transports/ccrClient.js +711 -0
  67. package/src/cli/transports/transportUtils.js +39 -0
  68. package/src/cli/update.js +314 -0
  69. package/src/commandCenter/launch.js +39 -0
  70. package/src/commandCenter/phoneApi.js +168 -0
  71. package/src/commandCenter/phoneStore.js +159 -0
  72. package/src/commandCenter/reactorBus.js +130 -0
  73. package/src/commandCenter/server.js +288 -0
  74. package/src/commandCenter/server.ts +42 -7
  75. package/src/commandCenter/tunnel.js +199 -0
  76. package/src/commands/add-dir/add-dir.js +121 -0
  77. package/src/commands/add-dir/index.js +8 -0
  78. package/src/commands/add-dir/validation.js +76 -0
  79. package/src/commands/advisor.js +88 -0
  80. package/src/commands/agents/agents.js +10 -0
  81. package/src/commands/agents/index.js +7 -0
  82. package/src/commands/agents-platform/index.js +2 -0
  83. package/src/commands/assistant/index.js +86 -0
  84. package/src/commands/backup/index.js +31 -0
  85. package/src/commands/branch/branch.js +205 -0
  86. package/src/commands/branch/index.js +11 -0
  87. package/src/commands/bridge/bridge.js +513 -0
  88. package/src/commands/bridge/index.js +22 -0
  89. package/src/commands/bridge-kick.js +179 -0
  90. package/src/commands/brief.js +89 -0
  91. package/src/commands/btw/btw.js +235 -0
  92. package/src/commands/btw/index.js +9 -0
  93. package/src/commands/buddy/buddy.js +100 -0
  94. package/src/commands/buddy/index.js +11 -0
  95. package/src/commands/chrome/chrome.js +291 -0
  96. package/src/commands/chrome/index.js +10 -0
  97. package/src/commands/clear/caches.js +116 -0
  98. package/src/commands/clear/clear.js +5 -0
  99. package/src/commands/clear/conversation.js +189 -0
  100. package/src/commands/clear/index.js +9 -0
  101. package/src/commands/color/color.js +58 -0
  102. package/src/commands/color/index.js +9 -0
  103. package/src/commands/commit-push-pr.js +137 -0
  104. package/src/commands/commit.js +80 -0
  105. package/src/commands/compact/compact.js +194 -0
  106. package/src/commands/compact/index.js +11 -0
  107. package/src/commands/config/config.js +6 -0
  108. package/src/commands/config/index.js +8 -0
  109. package/src/commands/context/context-noninteractive.js +219 -0
  110. package/src/commands/context/context.js +45 -0
  111. package/src/commands/context/index.js +21 -0
  112. package/src/commands/coordinator.js +34 -0
  113. package/src/commands/copy/copy.js +366 -0
  114. package/src/commands/copy/index.js +7 -0
  115. package/src/commands/cost/cost.js +21 -0
  116. package/src/commands/cost/index.js +16 -0
  117. package/src/commands/createMovedToPluginCommand.js +33 -0
  118. package/src/commands/desktop/desktop.js +6 -0
  119. package/src/commands/desktop/index.js +22 -0
  120. package/src/commands/diff/diff.js +6 -0
  121. package/src/commands/diff/index.js +6 -0
  122. package/src/commands/doctor/doctor.js +6 -0
  123. package/src/commands/doctor/index.js +9 -0
  124. package/src/commands/effort/effort.js +166 -0
  125. package/src/commands/effort/index.js +11 -0
  126. package/src/commands/exit/exit.js +32 -0
  127. package/src/commands/exit/index.js +9 -0
  128. package/src/commands/export/export.js +87 -0
  129. package/src/commands/export/index.js +8 -0
  130. package/src/commands/extra-usage/extra-usage-core.js +99 -0
  131. package/src/commands/extra-usage/extra-usage-noninteractive.js +13 -0
  132. package/src/commands/extra-usage/extra-usage.js +15 -0
  133. package/src/commands/extra-usage/index.js +29 -0
  134. package/src/commands/fast/fast.js +276 -0
  135. package/src/commands/fast/index.js +19 -0
  136. package/src/commands/feedback/feedback.js +11 -0
  137. package/src/commands/feedback/index.js +20 -0
  138. package/src/commands/files/files.js +11 -0
  139. package/src/commands/files/index.js +9 -0
  140. package/src/commands/force-snip.js +19 -0
  141. package/src/commands/fork/index.js +67 -0
  142. package/src/commands/heapdump/heapdump.js +14 -0
  143. package/src/commands/heapdump/index.js +9 -0
  144. package/src/commands/help/help.js +6 -0
  145. package/src/commands/help/index.js +7 -0
  146. package/src/commands/hooks/hooks.js +12 -0
  147. package/src/commands/hooks/index.js +8 -0
  148. package/src/commands/ide/ide.js +615 -0
  149. package/src/commands/ide/index.js +8 -0
  150. package/src/commands/init-verifiers.js +258 -0
  151. package/src/commands/init.js +248 -0
  152. package/src/commands/insights.js +2554 -0
  153. package/src/commands/install-github-app/ApiKeyStep.js +230 -0
  154. package/src/commands/install-github-app/CheckExistingSecretStep.js +194 -0
  155. package/src/commands/install-github-app/CheckGitHubStep.js +16 -0
  156. package/src/commands/install-github-app/ChooseRepoStep.js +211 -0
  157. package/src/commands/install-github-app/CreatingStep.js +53 -0
  158. package/src/commands/install-github-app/ErrorStep.js +84 -0
  159. package/src/commands/install-github-app/ExistingWorkflowStep.js +105 -0
  160. package/src/commands/install-github-app/InstallAppStep.js +97 -0
  161. package/src/commands/install-github-app/OAuthFlowStep.js +190 -0
  162. package/src/commands/install-github-app/SuccessStep.js +94 -0
  163. package/src/commands/install-github-app/WarningsStep.js +71 -0
  164. package/src/commands/install-github-app/index.js +10 -0
  165. package/src/commands/install-github-app/install-github-app.js +593 -0
  166. package/src/commands/install-github-app/setupGitHubActions.js +227 -0
  167. package/src/commands/install-slack-app/index.js +9 -0
  168. package/src/commands/install-slack-app/install-slack-app.js +25 -0
  169. package/src/commands/install.js +198 -0
  170. package/src/commands/keybindings/index.js +10 -0
  171. package/src/commands/keybindings/keybindings.js +47 -0
  172. package/src/commands/login/index.js +21 -0
  173. package/src/commands/login/login.js +135 -0
  174. package/src/commands/logout/index.js +11 -0
  175. package/src/commands/logout/logout.js +75 -0
  176. package/src/commands/mcp/addCommand.js +183 -0
  177. package/src/commands/mcp/index.js +9 -0
  178. package/src/commands/mcp/mcp.js +78 -0
  179. package/src/commands/mcp/xaaIdpCommand.js +193 -0
  180. package/src/commands/memories/index.js +9 -0
  181. package/src/commands/memories/index.ts +12 -0
  182. package/src/commands/memories/memories.tsx +949 -0
  183. package/src/commands/memory/index.js +7 -0
  184. package/src/commands/memory/memory.js +71 -0
  185. package/src/commands/mobile/index.js +9 -0
  186. package/src/commands/mobile/mobile.js +279 -0
  187. package/src/commands/model/index.js +14 -0
  188. package/src/commands/model/model.js +284 -0
  189. package/src/commands/output-style/index.js +8 -0
  190. package/src/commands/output-style/output-style.js +6 -0
  191. package/src/commands/passes/index.js +17 -0
  192. package/src/commands/passes/passes.js +23 -0
  193. package/src/commands/peers/index.js +68 -0
  194. package/src/commands/permissions/index.js +8 -0
  195. package/src/commands/permissions/permissions.js +9 -0
  196. package/src/commands/plan/index.js +8 -0
  197. package/src/commands/plan/plan.js +116 -0
  198. package/src/commands/plugin/AddMarketplace.js +96 -0
  199. package/src/commands/plugin/BrowseMarketplace.js +582 -0
  200. package/src/commands/plugin/DiscoverPlugins.js +613 -0
  201. package/src/commands/plugin/ManageMarketplaces.js +583 -0
  202. package/src/commands/plugin/ManagePlugins.js +1783 -0
  203. package/src/commands/plugin/PluginErrors.js +124 -0
  204. package/src/commands/plugin/PluginOptionsDialog.js +367 -0
  205. package/src/commands/plugin/PluginOptionsFlow.js +97 -0
  206. package/src/commands/plugin/PluginSettings.js +1041 -0
  207. package/src/commands/plugin/PluginTrustWarning.js +35 -0
  208. package/src/commands/plugin/UnifiedInstalledCell.js +616 -0
  209. package/src/commands/plugin/ValidatePlugin.js +96 -0
  210. package/src/commands/plugin/index.js +10 -0
  211. package/src/commands/plugin/parseArgs.js +71 -0
  212. package/src/commands/plugin/plugin.js +6 -0
  213. package/src/commands/plugin/pluginDetailsHelpers.js +95 -0
  214. package/src/commands/plugin/usePagination.js +89 -0
  215. package/src/commands/pr_comments/index.js +49 -0
  216. package/src/commands/privacy-settings/index.js +11 -0
  217. package/src/commands/privacy-settings/privacy-settings.js +55 -0
  218. package/src/commands/proactive.js +29 -0
  219. package/src/commands/rate-limit-options/index.js +15 -0
  220. package/src/commands/rate-limit-options/rate-limit-options.js +213 -0
  221. package/src/commands/release-notes/index.js +8 -0
  222. package/src/commands/release-notes/release-notes.js +38 -0
  223. package/src/commands/reload-plugins/index.js +11 -0
  224. package/src/commands/reload-plugins/reload-plugins.js +52 -0
  225. package/src/commands/remote-env/index.js +12 -0
  226. package/src/commands/remote-env/remote-env.js +6 -0
  227. package/src/commands/remote-setup/api.js +155 -0
  228. package/src/commands/remote-setup/index.js +15 -0
  229. package/src/commands/remote-setup/remote-setup.js +150 -0
  230. package/src/commands/remoteControlServer/index.js +58 -0
  231. package/src/commands/rename/generateSessionName.js +58 -0
  232. package/src/commands/rename/index.js +9 -0
  233. package/src/commands/rename/rename.js +52 -0
  234. package/src/commands/resume/index.js +9 -0
  235. package/src/commands/resume/resume.js +239 -0
  236. package/src/commands/review/UltrareviewOverageDialog.js +97 -0
  237. package/src/commands/review/reviewRemote.js +259 -0
  238. package/src/commands/review/ultrareviewCommand.js +58 -0
  239. package/src/commands/review/ultrareviewEnabled.js +10 -0
  240. package/src/commands/review.js +53 -0
  241. package/src/commands/rewind/index.js +10 -0
  242. package/src/commands/rewind/rewind.js +7 -0
  243. package/src/commands/sandbox-toggle/index.js +41 -0
  244. package/src/commands/sandbox-toggle/sandbox-toggle.js +73 -0
  245. package/src/commands/security-review.js +231 -0
  246. package/src/commands/session/index.js +13 -0
  247. package/src/commands/session/session.js +143 -0
  248. package/src/commands/skills/index.js +7 -0
  249. package/src/commands/skills/skills.js +6 -0
  250. package/src/commands/speak.js +21 -0
  251. package/src/commands/start-business.js +1575 -0
  252. package/src/commands/start-business.ts +1581 -0
  253. package/src/commands/stats/index.js +7 -0
  254. package/src/commands/stats/stats.js +6 -0
  255. package/src/commands/status/index.js +8 -0
  256. package/src/commands/status/status.js +6 -0
  257. package/src/commands/statusline.js +22 -0
  258. package/src/commands/stickers/index.js +8 -0
  259. package/src/commands/stickers/stickers.js +14 -0
  260. package/src/commands/subscribe-pr.js +131 -0
  261. package/src/commands/tag/index.js +9 -0
  262. package/src/commands/tag/tag.js +215 -0
  263. package/src/commands/tasks/index.js +8 -0
  264. package/src/commands/tasks/tasks.js +6 -0
  265. package/src/commands/terminalSetup/index.js +18 -0
  266. package/src/commands/terminalSetup/terminalSetup.js +491 -0
  267. package/src/commands/thaddeus-usage/index.js +17 -0
  268. package/src/commands/theme/index.js +7 -0
  269. package/src/commands/theme/theme.js +51 -0
  270. package/src/commands/thinkback/index.js +9 -0
  271. package/src/commands/thinkback/thinkback.js +528 -0
  272. package/src/commands/thinkback-play/index.js +13 -0
  273. package/src/commands/thinkback-play/thinkback-play.js +34 -0
  274. package/src/commands/torch.js +122 -0
  275. package/src/commands/ultraplan.js +416 -0
  276. package/src/commands/upgrade/index.js +12 -0
  277. package/src/commands/upgrade/upgrade.js +38 -0
  278. package/src/commands/usage/index.js +7 -0
  279. package/src/commands/usage/usage.js +6 -0
  280. package/src/commands/version.js +17 -0
  281. package/src/commands/vim/index.js +8 -0
  282. package/src/commands/vim/vim.js +25 -0
  283. package/src/commands/voice/index.js +13 -0
  284. package/src/commands/voice/voice.js +44 -0
  285. package/src/commands/workflows/index.js +123 -0
  286. package/src/commands.js +614 -0
  287. package/src/commands.ts +4 -0
  288. package/src/components/AgentProgressLine.js +112 -0
  289. package/src/components/AntModelSwitchCallout.js +8 -0
  290. package/src/components/App.js +46 -0
  291. package/src/components/ApproveApiKey.js +125 -0
  292. package/src/components/AutoModeOptInDialog.js +140 -0
  293. package/src/components/AutoUpdater.js +156 -0
  294. package/src/components/AutoUpdaterWrapper.js +78 -0
  295. package/src/components/AwsAuthStatusBox.js +88 -0
  296. package/src/components/BaseTextInput.js +105 -0
  297. package/src/components/BashModeProgress.js +49 -0
  298. package/src/components/BridgeDialog.js +415 -0
  299. package/src/components/BypassPermissionsModeDialog.js +87 -0
  300. package/src/components/ChannelDowngradeDialog.js +101 -0
  301. package/src/components/ClaudeInChromeOnboarding.js +126 -0
  302. package/src/components/ClaudeMdExternalIncludesDialog.js +137 -0
  303. package/src/components/ClickableImageRef.js +65 -0
  304. package/src/components/CompactSummary.js +120 -0
  305. package/src/components/ConfigurableShortcutHint.js +35 -0
  306. package/src/components/ConsoleOAuthFlow.js +554 -0
  307. package/src/components/ContextSuggestions.js +44 -0
  308. package/src/components/ContextVisualization.js +482 -0
  309. package/src/components/CoordinatorAgentStatus.js +261 -0
  310. package/src/components/CostThresholdDialog.js +49 -0
  311. package/src/components/CtrlOToExpand.js +50 -0
  312. package/src/components/CustomSelect/SelectMulti.js +150 -0
  313. package/src/components/CustomSelect/index.js +2 -0
  314. package/src/components/CustomSelect/option-map.js +32 -0
  315. package/src/components/CustomSelect/select-input-option.js +426 -0
  316. package/src/components/CustomSelect/select-option.js +24 -0
  317. package/src/components/CustomSelect/select.js +518 -0
  318. package/src/components/CustomSelect/use-multi-select-state.js +214 -0
  319. package/src/components/CustomSelect/use-select-input.js +170 -0
  320. package/src/components/CustomSelect/use-select-navigation.js +366 -0
  321. package/src/components/CustomSelect/use-select-state.js +22 -0
  322. package/src/components/DesktopHandoff.js +195 -0
  323. package/src/components/DesktopUpsell/DesktopUpsellStartup.js +174 -0
  324. package/src/components/DevBar.js +51 -0
  325. package/src/components/DevChannelsDialog.js +104 -0
  326. package/src/components/DiagnosticsDisplay.js +91 -0
  327. package/src/components/EffortCallout.js +264 -0
  328. package/src/components/EffortIndicator.js +28 -0
  329. package/src/components/ExitFlow.js +41 -0
  330. package/src/components/ExportDialog.js +101 -0
  331. package/src/components/FallbackToolUseErrorMessage.js +116 -0
  332. package/src/components/FallbackToolUseRejectedMessage.js +17 -0
  333. package/src/components/FastIcon.js +43 -0
  334. package/src/components/Feedback.js +369 -0
  335. package/src/components/FeedbackSurvey/FeedbackSurvey.js +151 -0
  336. package/src/components/FeedbackSurvey/FeedbackSurveyView.js +104 -0
  337. package/src/components/FeedbackSurvey/TranscriptSharePrompt.js +84 -0
  338. package/src/components/FeedbackSurvey/submitTranscriptShare.js +10 -0
  339. package/src/components/FeedbackSurvey/useDebouncedDigitInput.js +51 -0
  340. package/src/components/FeedbackSurvey/useFeedbackSurvey.js +258 -0
  341. package/src/components/FeedbackSurvey/useFrustrationDetection.js +8 -0
  342. package/src/components/FeedbackSurvey/useMemorySurvey.js +191 -0
  343. package/src/components/FeedbackSurvey/usePostCompactSurvey.js +202 -0
  344. package/src/components/FeedbackSurvey/useSurveyState.js +80 -0
  345. package/src/components/FileEditToolDiff.js +167 -0
  346. package/src/components/FileEditToolUpdatedMessage.js +112 -0
  347. package/src/components/FileEditToolUseRejectedMessage.js +158 -0
  348. package/src/components/FilePathLink.js +35 -0
  349. package/src/components/FullscreenLayout.js +578 -0
  350. package/src/components/GlobalSearchDialog.js +340 -0
  351. package/src/components/HelpV2/Commands.js +66 -0
  352. package/src/components/HelpV2/General.js +25 -0
  353. package/src/components/HelpV2/HelpV2.js +186 -0
  354. package/src/components/HighlightedCode/Fallback.js +193 -0
  355. package/src/components/HighlightedCode.js +185 -0
  356. package/src/components/HistorySearchDialog.js +93 -0
  357. package/src/components/IdeAutoConnectDialog.js +154 -0
  358. package/src/components/IdeOnboardingDialog.js +175 -0
  359. package/src/components/IdeStatusIndicator.js +50 -0
  360. package/src/components/IdleReturnDialog.js +117 -0
  361. package/src/components/InterruptedByUser.js +16 -0
  362. package/src/components/InvalidConfigDialog.js +135 -0
  363. package/src/components/InvalidSettingsDialog.js +85 -0
  364. package/src/components/KeybindingWarnings.js +55 -0
  365. package/src/components/LanguagePicker.js +84 -0
  366. package/src/components/LogSelector.js +1579 -0
  367. package/src/components/LogoV2/AnimatedAsterisk.js +43 -0
  368. package/src/components/LogoV2/AnimatedClawd.js +64 -0
  369. package/src/components/LogoV2/ChannelsNotice.js +262 -0
  370. package/src/components/LogoV2/Clawd.js +33 -0
  371. package/src/components/LogoV2/CondensedLogo.js +160 -0
  372. package/src/components/LogoV2/EmergencyTip.js +48 -0
  373. package/src/components/LogoV2/Feed.js +85 -0
  374. package/src/components/LogoV2/FeedColumn.js +55 -0
  375. package/src/components/LogoV2/GuestPassesUpsell.js +71 -0
  376. package/src/components/LogoV2/LogoV2.js +565 -0
  377. package/src/components/LogoV2/Opus1mMergeNotice.js +57 -0
  378. package/src/components/LogoV2/OverageCreditUpsell.js +161 -0
  379. package/src/components/LogoV2/VoiceModeNotice.js +71 -0
  380. package/src/components/LogoV2/WelcomeV2.js +14 -0
  381. package/src/components/LogoV2/feedConfigs.js +79 -0
  382. package/src/components/LspRecommendation/LspRecommendationMenu.js +46 -0
  383. package/src/components/MCPServerApprovalDialog.js +114 -0
  384. package/src/components/MCPServerDesktopImportDialog.js +206 -0
  385. package/src/components/MCPServerDialogCopy.js +16 -0
  386. package/src/components/MCPServerMultiselectDialog.js +134 -0
  387. package/src/components/ManagedSettingsSecurityDialog/ManagedSettingsSecurityDialog.js +150 -0
  388. package/src/components/ManagedSettingsSecurityDialog/utils.js +105 -0
  389. package/src/components/Markdown.js +233 -0
  390. package/src/components/MarkdownTable.js +280 -0
  391. package/src/components/MemoryUsageIndicator.js +28 -0
  392. package/src/components/Message.js +564 -0
  393. package/src/components/MessageModel.js +37 -0
  394. package/src/components/MessageResponse.js +73 -0
  395. package/src/components/MessageRow.js +346 -0
  396. package/src/components/MessageSelector.js +744 -0
  397. package/src/components/MessageTimestamp.js +58 -0
  398. package/src/components/Messages.js +645 -0
  399. package/src/components/ModelPicker.js +452 -0
  400. package/src/components/NativeAutoUpdater.js +152 -0
  401. package/src/components/NotebookEditToolUseRejectedMessage.js +84 -0
  402. package/src/components/OffscreenFreeze.js +35 -0
  403. package/src/components/Onboarding.js +174 -0
  404. package/src/components/OutputStylePicker.js +103 -0
  405. package/src/components/PackageManagerAutoUpdater.js +99 -0
  406. package/src/components/Passes/Passes.js +114 -0
  407. package/src/components/PrBadge.js +91 -0
  408. package/src/components/PressEnterToContinue.js +16 -0
  409. package/src/components/PromptInput/HistorySearchInput.js +45 -0
  410. package/src/components/PromptInput/IssueFlagBanner.js +8 -0
  411. package/src/components/PromptInput/Notifications.js +220 -0
  412. package/src/components/PromptInput/PromptInput.js +2014 -0
  413. package/src/components/PromptInput/PromptInputFooter.js +85 -0
  414. package/src/components/PromptInput/PromptInputFooterLeftSide.js +408 -0
  415. package/src/components/PromptInput/PromptInputFooterSuggestions.js +281 -0
  416. package/src/components/PromptInput/PromptInputHelpMenu.js +380 -0
  417. package/src/components/PromptInput/PromptInputModeIndicator.js +73 -0
  418. package/src/components/PromptInput/PromptInputQueuedCommands.js +105 -0
  419. package/src/components/PromptInput/PromptInputStashNotice.js +21 -0
  420. package/src/components/PromptInput/SandboxPromptFooterHint.js +66 -0
  421. package/src/components/PromptInput/ShimmeredInput.js +133 -0
  422. package/src/components/PromptInput/VoiceIndicator.js +137 -0
  423. package/src/components/PromptInput/inputModes.js +24 -0
  424. package/src/components/PromptInput/inputPaste.js +62 -0
  425. package/src/components/PromptInput/useMaybeTruncateInput.js +33 -0
  426. package/src/components/PromptInput/usePromptInputPlaceholder.js +53 -0
  427. package/src/components/PromptInput/useShowFastIconHint.js +23 -0
  428. package/src/components/PromptInput/useSwarmBanner.js +112 -0
  429. package/src/components/PromptInput/utils.js +50 -0
  430. package/src/components/QuickOpenDialog.js +244 -0
  431. package/src/components/RemoteCallout.js +53 -0
  432. package/src/components/RemoteEnvironmentDialog.js +346 -0
  433. package/src/components/ResumeTask.js +173 -0
  434. package/src/components/SandboxViolationExpandedView.js +106 -0
  435. package/src/components/ScrollKeybindingHandler.js +982 -0
  436. package/src/components/SearchBox.js +56 -0
  437. package/src/components/SentryErrorBoundary.js +16 -0
  438. package/src/components/SessionBackgroundHint.js +105 -0
  439. package/src/components/SessionPreview.js +200 -0
  440. package/src/components/Settings/Config.js +1626 -0
  441. package/src/components/Settings/Settings.js +131 -0
  442. package/src/components/Settings/Status.js +230 -0
  443. package/src/components/Settings/Usage.js +341 -0
  444. package/src/components/ShowInIDEPrompt.js +152 -0
  445. package/src/components/SkillImprovementSurvey.js +130 -0
  446. package/src/components/Spinner/FlashingChar.js +52 -0
  447. package/src/components/Spinner/GlimmerMessage.js +329 -0
  448. package/src/components/Spinner/ShimmerChar.js +23 -0
  449. package/src/components/Spinner/SpinnerAnimationRow.js +170 -0
  450. package/src/components/Spinner/SpinnerGlyph.js +70 -0
  451. package/src/components/Spinner/TeammateSpinnerLine.js +171 -0
  452. package/src/components/Spinner/TeammateSpinnerTree.js +269 -0
  453. package/src/components/Spinner/index.js +9 -0
  454. package/src/components/Spinner/teammateSelectHint.js +1 -0
  455. package/src/components/Spinner/useShimmerAnimation.js +22 -0
  456. package/src/components/Spinner/useStalledAnimation.js +63 -0
  457. package/src/components/Spinner/utils.js +78 -0
  458. package/src/components/Spinner.js +474 -0
  459. package/src/components/Stats.js +1000 -0
  460. package/src/components/StatusLine.js +286 -0
  461. package/src/components/StatusNotices.js +50 -0
  462. package/src/components/StructuredDiff/Fallback.js +336 -0
  463. package/src/components/StructuredDiff/colorDiff.js +37 -0
  464. package/src/components/StructuredDiff.js +153 -0
  465. package/src/components/StructuredDiffList.js +9 -0
  466. package/src/components/TagTabs.js +101 -0
  467. package/src/components/TaskListV2.js +333 -0
  468. package/src/components/TeammateViewHeader.js +88 -0
  469. package/src/components/TeleportError.js +191 -0
  470. package/src/components/TeleportProgress.js +131 -0
  471. package/src/components/TeleportRepoMismatchDialog.js +98 -0
  472. package/src/components/TeleportResumeWrapper.js +158 -0
  473. package/src/components/TeleportStash.js +82 -0
  474. package/src/components/TextInput.js +108 -0
  475. package/src/components/ThaddeusHint/PluginHintMenu.js +37 -0
  476. package/src/components/ThemePicker.js +331 -0
  477. package/src/components/ThinkingToggle.js +154 -0
  478. package/src/components/TokenWarning.js +171 -0
  479. package/src/components/ToolUseLoader.js +35 -0
  480. package/src/components/TrustDialog/TrustDialog.js +301 -0
  481. package/src/components/TrustDialog/utils.js +199 -0
  482. package/src/components/UndercoverAutoCallout.js +5 -0
  483. package/src/components/ValidationErrorsList.js +147 -0
  484. package/src/components/VimTextInput.js +136 -0
  485. package/src/components/VirtualMessageList.js +893 -0
  486. package/src/components/WorkflowMultiselectDialog.js +118 -0
  487. package/src/components/WorktreeExitDialog.js +220 -0
  488. package/src/components/agents/AgentDetail.js +227 -0
  489. package/src/components/agents/AgentEditor.js +147 -0
  490. package/src/components/agents/AgentNavigationFooter.js +22 -0
  491. package/src/components/agents/AgentsList.js +436 -0
  492. package/src/components/agents/AgentsMenu.js +849 -0
  493. package/src/components/agents/ColorPicker.js +110 -0
  494. package/src/components/agents/ModelSelector.js +63 -0
  495. package/src/components/agents/SnapshotUpdateDialog.js +14 -0
  496. package/src/components/agents/ToolSelector.js +557 -0
  497. package/src/components/agents/agentFileUtils.js +179 -0
  498. package/src/components/agents/generateAgent.js +161 -0
  499. package/src/components/agents/new-agent-creation/CreateAgentWizard.js +89 -0
  500. package/src/components/agents/new-agent-creation/wizard-steps/ColorStep.js +81 -0
  501. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStep.js +387 -0
  502. package/src/components/agents/new-agent-creation/wizard-steps/ConfirmStepWrapper.js +63 -0
  503. package/src/components/agents/new-agent-creation/wizard-steps/DescriptionStep.js +126 -0
  504. package/src/components/agents/new-agent-creation/wizard-steps/GenerateStep.js +118 -0
  505. package/src/components/agents/new-agent-creation/wizard-steps/LocationStep.js +80 -0
  506. package/src/components/agents/new-agent-creation/wizard-steps/MemoryStep.js +108 -0
  507. package/src/components/agents/new-agent-creation/wizard-steps/MethodStep.js +80 -0
  508. package/src/components/agents/new-agent-creation/wizard-steps/ModelStep.js +49 -0
  509. package/src/components/agents/new-agent-creation/wizard-steps/PromptStep.js +131 -0
  510. package/src/components/agents/new-agent-creation/wizard-steps/ToolsStep.js +52 -0
  511. package/src/components/agents/new-agent-creation/wizard-steps/TypeStep.js +100 -0
  512. package/src/components/agents/types.js +4 -0
  513. package/src/components/agents/utils.js +14 -0
  514. package/src/components/agents/validateAgent.js +79 -0
  515. package/src/components/design-system/Byline.js +72 -0
  516. package/src/components/design-system/Dialog.js +117 -0
  517. package/src/components/design-system/Divider.js +110 -0
  518. package/src/components/design-system/FuzzyPicker.js +191 -0
  519. package/src/components/design-system/KeyboardShortcutHint.js +68 -0
  520. package/src/components/design-system/ListItem.js +184 -0
  521. package/src/components/design-system/LoadingState.js +69 -0
  522. package/src/components/design-system/Pane.js +69 -0
  523. package/src/components/design-system/ProgressBar.js +63 -0
  524. package/src/components/design-system/Ratchet.js +71 -0
  525. package/src/components/design-system/StatusIcon.js +70 -0
  526. package/src/components/design-system/Tabs.js +269 -0
  527. package/src/components/design-system/ThemeProvider.js +137 -0
  528. package/src/components/design-system/ThemedBox.js +126 -0
  529. package/src/components/design-system/ThemedText.js +60 -0
  530. package/src/components/design-system/color.js +22 -0
  531. package/src/components/diff/DiffDetailView.js +285 -0
  532. package/src/components/diff/DiffDialog.js +387 -0
  533. package/src/components/diff/DiffFileList.js +292 -0
  534. package/src/components/grove/Grove.js +483 -0
  535. package/src/components/hooks/HooksConfigMenu.js +583 -0
  536. package/src/components/hooks/PromptDialog.js +82 -0
  537. package/src/components/hooks/SelectEventMode.js +118 -0
  538. package/src/components/hooks/SelectHookMode.js +101 -0
  539. package/src/components/hooks/SelectMatcherMode.js +131 -0
  540. package/src/components/hooks/ViewHookMode.js +204 -0
  541. package/src/components/mcp/CapabilitiesSection.js +56 -0
  542. package/src/components/mcp/ElicitationDialog.js +945 -0
  543. package/src/components/mcp/MCPAgentServerMenu.js +95 -0
  544. package/src/components/mcp/MCPListPanel.js +505 -0
  545. package/src/components/mcp/MCPReconnect.js +168 -0
  546. package/src/components/mcp/MCPRemoteServerMenu.js +460 -0
  547. package/src/components/mcp/MCPSettings.js +414 -0
  548. package/src/components/mcp/MCPStdioServerMenu.js +95 -0
  549. package/src/components/mcp/MCPToolDetailView.js +219 -0
  550. package/src/components/mcp/MCPToolListView.js +137 -0
  551. package/src/components/mcp/McpParsingWarnings.js +212 -0
  552. package/src/components/mcp/index.js +8 -0
  553. package/src/components/mcp/utils/reconnectHelpers.js +35 -0
  554. package/src/components/memory/MemoryFileSelector.js +454 -0
  555. package/src/components/memory/MemoryUpdateNotification.js +43 -0
  556. package/src/components/messageActions.js +418 -0
  557. package/src/components/messages/AdvisorMessage.js +152 -0
  558. package/src/components/messages/AssistantRedactedThinkingMessage.js +28 -0
  559. package/src/components/messages/AssistantTextMessage.js +287 -0
  560. package/src/components/messages/AssistantThinkingMessage.js +70 -0
  561. package/src/components/messages/AssistantToolUseMessage.js +324 -0
  562. package/src/components/messages/AttachmentMessage.js +418 -0
  563. package/src/components/messages/CollapsedReadSearchContent.js +363 -0
  564. package/src/components/messages/CompactBoundaryMessage.js +19 -0
  565. package/src/components/messages/GroupedToolUseContent.js +37 -0
  566. package/src/components/messages/HighlightedThinkingText.js +165 -0
  567. package/src/components/messages/HookProgressMessage.js +111 -0
  568. package/src/components/messages/PlanApprovalMessage.js +213 -0
  569. package/src/components/messages/RateLimitMessage.js +149 -0
  570. package/src/components/messages/ShutdownMessage.js +124 -0
  571. package/src/components/messages/SnipBoundaryMessage.js +7 -0
  572. package/src/components/messages/SystemAPIErrorMessage.js +136 -0
  573. package/src/components/messages/SystemTextMessage.js +842 -0
  574. package/src/components/messages/TaskAssignmentMessage.js +72 -0
  575. package/src/components/messages/UserAgentNotificationMessage.js +78 -0
  576. package/src/components/messages/UserBashInputMessage.js +52 -0
  577. package/src/components/messages/UserBashOutputMessage.js +55 -0
  578. package/src/components/messages/UserChannelMessage.js +130 -0
  579. package/src/components/messages/UserCommandMessage.js +107 -0
  580. package/src/components/messages/UserCrossSessionMessage.js +11 -0
  581. package/src/components/messages/UserForkBoilerplateMessage.js +11 -0
  582. package/src/components/messages/UserGitHubWebhookMessage.js +12 -0
  583. package/src/components/messages/UserImageMessage.js +54 -0
  584. package/src/components/messages/UserLocalCommandOutputMessage.js +170 -0
  585. package/src/components/messages/UserMemoryInputMessage.js +73 -0
  586. package/src/components/messages/UserPlanMessage.js +38 -0
  587. package/src/components/messages/UserPromptMessage.js +63 -0
  588. package/src/components/messages/UserResourceUpdateMessage.js +102 -0
  589. package/src/components/messages/UserTeammateMessage.js +156 -0
  590. package/src/components/messages/UserTextMessage.js +270 -0
  591. package/src/components/messages/UserToolResultMessage/RejectedPlanMessage.js +28 -0
  592. package/src/components/messages/UserToolResultMessage/RejectedToolUseMessage.js +17 -0
  593. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.js +17 -0
  594. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.js +92 -0
  595. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.js +74 -0
  596. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.js +84 -0
  597. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.js +58 -0
  598. package/src/components/messages/UserToolResultMessage/utils.js +43 -0
  599. package/src/components/messages/nullRenderingAttachments.js +58 -0
  600. package/src/components/messages/teamMemCollapsed.js +142 -0
  601. package/src/components/messages/teamMemSaved.js +16 -0
  602. package/src/components/permissions/AskUserQuestionPermissionRequest/AskUserQuestionPermissionRequest.js +659 -0
  603. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewBox.js +219 -0
  604. package/src/components/permissions/AskUserQuestionPermissionRequest/PreviewQuestionView.js +227 -0
  605. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionNavigationBar.js +175 -0
  606. package/src/components/permissions/AskUserQuestionPermissionRequest/QuestionView.js +444 -0
  607. package/src/components/permissions/AskUserQuestionPermissionRequest/SubmitQuestionsView.js +137 -0
  608. package/src/components/permissions/AskUserQuestionPermissionRequest/use-multiple-choice-state.js +100 -0
  609. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.js +404 -0
  610. package/src/components/permissions/BashPermissionRequest/bashToolUseOptions.js +110 -0
  611. package/src/components/permissions/ComputerUseApproval/ComputerUseApproval.js +449 -0
  612. package/src/components/permissions/EnterPlanModePermissionRequest/EnterPlanModePermissionRequest.js +126 -0
  613. package/src/components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js +653 -0
  614. package/src/components/permissions/FallbackPermissionRequest.js +349 -0
  615. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.js +185 -0
  616. package/src/components/permissions/FilePermissionDialog/FilePermissionDialog.js +108 -0
  617. package/src/components/permissions/FilePermissionDialog/ideDiffConfig.js +13 -0
  618. package/src/components/permissions/FilePermissionDialog/permissionOptions.js +137 -0
  619. package/src/components/permissions/FilePermissionDialog/useFilePermissionDialog.js +131 -0
  620. package/src/components/permissions/FilePermissionDialog/usePermissionHandler.js +86 -0
  621. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.js +164 -0
  622. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.js +79 -0
  623. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +113 -0
  624. package/src/components/permissions/MonitorPermissionRequest/MonitorPermissionRequest.js +7 -0
  625. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditPermissionRequest.js +164 -0
  626. package/src/components/permissions/NotebookEditPermissionRequest/NotebookEditToolDiff.js +218 -0
  627. package/src/components/permissions/PermissionDecisionDebugInfo.js +467 -0
  628. package/src/components/permissions/PermissionDialog.js +55 -0
  629. package/src/components/permissions/PermissionExplanation.js +269 -0
  630. package/src/components/permissions/PermissionPrompt.js +316 -0
  631. package/src/components/permissions/PermissionRequest.js +159 -0
  632. package/src/components/permissions/PermissionRequestTitle.js +58 -0
  633. package/src/components/permissions/PermissionRuleExplanation.js +110 -0
  634. package/src/components/permissions/PowerShellPermissionRequest/PowerShellPermissionRequest.js +178 -0
  635. package/src/components/permissions/PowerShellPermissionRequest/powershellToolUseOptions.js +73 -0
  636. package/src/components/permissions/ReviewArtifactPermissionRequest/ReviewArtifactPermissionRequest.js +7 -0
  637. package/src/components/permissions/SandboxPermissionRequest.js +162 -0
  638. package/src/components/permissions/SedEditPermissionRequest/SedEditPermissionRequest.js +228 -0
  639. package/src/components/permissions/SkillPermissionRequest/SkillPermissionRequest.js +385 -0
  640. package/src/components/permissions/WebFetchPermissionRequest/WebFetchPermissionRequest.js +259 -0
  641. package/src/components/permissions/WorkerBadge.js +44 -0
  642. package/src/components/permissions/WorkerPendingPermission.js +107 -0
  643. package/src/components/permissions/hooks.js +163 -0
  644. package/src/components/permissions/rules/AddPermissionRules.js +171 -0
  645. package/src/components/permissions/rules/AddWorkspaceDirectory.js +335 -0
  646. package/src/components/permissions/rules/PermissionRuleDescription.js +78 -0
  647. package/src/components/permissions/rules/PermissionRuleInput.js +136 -0
  648. package/src/components/permissions/rules/PermissionRuleList.js +1190 -0
  649. package/src/components/permissions/rules/RecentDenialsTab.js +205 -0
  650. package/src/components/permissions/rules/RemoveWorkspaceDirectory.js +103 -0
  651. package/src/components/permissions/rules/WorkspaceTab.js +133 -0
  652. package/src/components/permissions/shellPermissionHelpers.js +112 -0
  653. package/src/components/permissions/useShellPermissionFeedback.js +108 -0
  654. package/src/components/permissions/utils.js +14 -0
  655. package/src/components/sandbox/SandboxConfigTab.js +48 -0
  656. package/src/components/sandbox/SandboxDependenciesTab.js +123 -0
  657. package/src/components/sandbox/SandboxDoctorSection.js +47 -0
  658. package/src/components/sandbox/SandboxOverridesTab.js +193 -0
  659. package/src/components/sandbox/SandboxSettings.js +297 -0
  660. package/src/components/shell/ExpandShellOutputContext.js +33 -0
  661. package/src/components/shell/OutputLine.js +110 -0
  662. package/src/components/shell/ShellProgressMessage.js +144 -0
  663. package/src/components/shell/ShellTimeDisplay.js +72 -0
  664. package/src/components/skills/SkillsMenu.js +239 -0
  665. package/src/components/tasks/AsyncAgentDetailDialog.js +235 -0
  666. package/src/components/tasks/BackgroundTask.js +364 -0
  667. package/src/components/tasks/BackgroundTaskStatus.js +419 -0
  668. package/src/components/tasks/BackgroundTasksDialog.js +494 -0
  669. package/src/components/tasks/DreamDetailDialog.js +251 -0
  670. package/src/components/tasks/InProcessTeammateDetailDialog.js +275 -0
  671. package/src/components/tasks/MonitorMcpDetailDialog.js +7 -0
  672. package/src/components/tasks/RemoteSessionDetailDialog.js +868 -0
  673. package/src/components/tasks/RemoteSessionProgress.js +249 -0
  674. package/src/components/tasks/ShellDetailDialog.js +403 -0
  675. package/src/components/tasks/ShellProgress.js +77 -0
  676. package/src/components/tasks/WorkflowDetailDialog.js +7 -0
  677. package/src/components/tasks/renderToolActivity.js +29 -0
  678. package/src/components/tasks/taskStatusUtils.js +94 -0
  679. package/src/components/teams/TeamStatus.js +77 -0
  680. package/src/components/teams/TeamsDialog.js +673 -0
  681. package/src/components/ui/OrderedList.js +66 -0
  682. package/src/components/ui/OrderedListItem.js +41 -0
  683. package/src/components/ui/TreeSelect.js +300 -0
  684. package/src/components/wizard/WizardDialogLayout.js +48 -0
  685. package/src/components/wizard/WizardNavigationFooter.js +11 -0
  686. package/src/components/wizard/WizardProvider.js +217 -0
  687. package/src/components/wizard/index.js +4 -0
  688. package/src/components/wizard/useWizard.js +9 -0
  689. package/src/constants/apiLimits.js +81 -0
  690. package/src/constants/betas.js +45 -0
  691. package/src/constants/common.js +29 -0
  692. package/src/constants/cyberRiskInstruction.js +23 -0
  693. package/src/constants/errorIds.js +14 -0
  694. package/src/constants/figures.js +38 -0
  695. package/src/constants/files.js +150 -0
  696. package/src/constants/github-app.js +139 -0
  697. package/src/constants/identity.js +112 -0
  698. package/src/constants/keys.js +10 -0
  699. package/src/constants/messages.js +1 -0
  700. package/src/constants/oauth.js +175 -0
  701. package/src/constants/outputStyles.js +162 -0
  702. package/src/constants/product.js +54 -0
  703. package/src/constants/prompts.js +994 -0
  704. package/src/constants/spinnerVerbs.js +98 -0
  705. package/src/constants/system.js +77 -0
  706. package/src/constants/systemPromptSections.js +39 -0
  707. package/src/constants/toolLimits.js +50 -0
  708. package/src/constants/tools.js +103 -0
  709. package/src/constants/turnCompletionVerbs.js +12 -0
  710. package/src/constants/xml.js +73 -0
  711. package/src/context/QueuedMessageContext.js +51 -0
  712. package/src/context/fpsMetrics.js +22 -0
  713. package/src/context/mailbox.js +35 -0
  714. package/src/context/modalContext.js +34 -0
  715. package/src/context/notifications.js +199 -0
  716. package/src/context/overlayContext.js +149 -0
  717. package/src/context/promptOverlayContext.js +118 -0
  718. package/src/context/stats.js +207 -0
  719. package/src/context/voice.js +74 -0
  720. package/src/context.js +146 -0
  721. package/src/coordinator/coordinatorMode.js +345 -0
  722. package/src/coordinator/workerAgent.js +24 -0
  723. package/src/cost-tracker.js +208 -0
  724. package/src/costHook.js +17 -0
  725. package/src/daemon/main.js +19 -0
  726. package/src/dialogLaunchers.js +77 -0
  727. package/src/entrypoints/agentSdkTypes.js +202 -0
  728. package/src/entrypoints/cli.js +226 -0
  729. package/src/entrypoints/init.js +265 -0
  730. package/src/entrypoints/mcp.js +141 -0
  731. package/src/entrypoints/sandboxTypes.js +112 -0
  732. package/src/entrypoints/sdk/controlSchemas.js +452 -0
  733. package/src/entrypoints/sdk/controlTypes.js +1 -0
  734. package/src/entrypoints/sdk/coreSchemas.js +1331 -0
  735. package/src/entrypoints/sdk/coreTypes.generated.js +3 -0
  736. package/src/entrypoints/sdk/coreTypes.js +49 -0
  737. package/src/entrypoints/sdk/runtimeTypes.js +1 -0
  738. package/src/entrypoints/sdk/sdkUtilityTypes.js +1 -0
  739. package/src/entrypoints/sdk/settingsTypes.generated.js +1 -0
  740. package/src/entrypoints/sdk/toolTypes.js +1 -0
  741. package/src/environment-runner/main.js +8 -0
  742. package/src/history.js +386 -0
  743. package/src/hooks/fileSuggestions.js +635 -0
  744. package/src/hooks/notifs/useAntOrgWarningNotification.js +5 -0
  745. package/src/hooks/notifs/useAutoModeUnavailableNotification.js +47 -0
  746. package/src/hooks/notifs/useCanSwitchToExistingSubscription.js +58 -0
  747. package/src/hooks/notifs/useDeprecationWarningNotification.js +43 -0
  748. package/src/hooks/notifs/useFastModeNotification.js +164 -0
  749. package/src/hooks/notifs/useIDEStatusIndicator.js +174 -0
  750. package/src/hooks/notifs/useInstallMessages.js +27 -0
  751. package/src/hooks/notifs/useLspInitializationNotification.js +144 -0
  752. package/src/hooks/notifs/useMcpConnectivityStatus.js +81 -0
  753. package/src/hooks/notifs/useModelMigrationNotifications.js +53 -0
  754. package/src/hooks/notifs/useNpmDeprecationNotification.js +25 -0
  755. package/src/hooks/notifs/usePluginAutoupdateNotification.js +83 -0
  756. package/src/hooks/notifs/usePluginInstallationStatus.js +128 -0
  757. package/src/hooks/notifs/useRateLimitWarningNotification.js +119 -0
  758. package/src/hooks/notifs/useSettingsErrors.js +64 -0
  759. package/src/hooks/notifs/useStartupNotification.js +33 -0
  760. package/src/hooks/notifs/useTeammateShutdownNotification.js +64 -0
  761. package/src/hooks/renderPlaceholder.js +26 -0
  762. package/src/hooks/toolPermission/PermissionContext.js +211 -0
  763. package/src/hooks/toolPermission/handlers/coordinatorHandler.js +44 -0
  764. package/src/hooks/toolPermission/handlers/interactiveHandler.js +397 -0
  765. package/src/hooks/toolPermission/handlers/swarmWorkerHandler.js +108 -0
  766. package/src/hooks/toolPermission/permissionLogging.js +145 -0
  767. package/src/hooks/unifiedSuggestions.js +130 -0
  768. package/src/hooks/useAfterFirstRender.js +12 -0
  769. package/src/hooks/useApiKeyVerification.js +63 -0
  770. package/src/hooks/useArrowKeyHistory.js +203 -0
  771. package/src/hooks/useAssistantHistory.js +193 -0
  772. package/src/hooks/useAwaySummary.js +105 -0
  773. package/src/hooks/useBackgroundTaskNavigation.js +204 -0
  774. package/src/hooks/useBlink.js +28 -0
  775. package/src/hooks/useCanUseTool.js +193 -0
  776. package/src/hooks/useCancelRequest.js +195 -0
  777. package/src/hooks/useChromeExtensionNotification.js +50 -0
  778. package/src/hooks/useClipboardImageHint.js +59 -0
  779. package/src/hooks/useCommandKeybindings.js +87 -0
  780. package/src/hooks/useCommandQueue.js +10 -0
  781. package/src/hooks/useCopyOnSelect.js +88 -0
  782. package/src/hooks/useDeferredHookMessages.js +43 -0
  783. package/src/hooks/useDiffData.js +69 -0
  784. package/src/hooks/useDiffInIDE.js +252 -0
  785. package/src/hooks/useDirectConnect.js +150 -0
  786. package/src/hooks/useDoublePress.js +44 -0
  787. package/src/hooks/useDynamicConfig.js +17 -0
  788. package/src/hooks/useElapsedTime.js +25 -0
  789. package/src/hooks/useExitOnCtrlCD.js +57 -0
  790. package/src/hooks/useExitOnCtrlCDWithKeybindings.js +17 -0
  791. package/src/hooks/useFileHistorySnapshotInit.js +14 -0
  792. package/src/hooks/useGlobalKeybindings.js +213 -0
  793. package/src/hooks/useHistorySearch.js +241 -0
  794. package/src/hooks/useIDEIntegration.js +56 -0
  795. package/src/hooks/useIdeAtMentioned.js +51 -0
  796. package/src/hooks/useIdeConnectionStatus.js +21 -0
  797. package/src/hooks/useIdeLogging.js +29 -0
  798. package/src/hooks/useIdeSelection.js +106 -0
  799. package/src/hooks/useInboxPoller.js +709 -0
  800. package/src/hooks/useInputBuffer.js +73 -0
  801. package/src/hooks/useIssueFlagBanner.js +115 -0
  802. package/src/hooks/useLogMessages.js +98 -0
  803. package/src/hooks/useLspPluginRecommendation.js +176 -0
  804. package/src/hooks/useMailboxBridge.js +15 -0
  805. package/src/hooks/useMainLoopModel.js +25 -0
  806. package/src/hooks/useManagePlugins.js +261 -0
  807. package/src/hooks/useMemoryUsage.js +28 -0
  808. package/src/hooks/useMergedClients.js +11 -0
  809. package/src/hooks/useMergedCommands.js +10 -0
  810. package/src/hooks/useMergedTools.js +32 -0
  811. package/src/hooks/useMinDisplayTime.js +26 -0
  812. package/src/hooks/useNotifyAfterTimeout.js +51 -0
  813. package/src/hooks/useOfficialMarketplaceNotification.js +47 -0
  814. package/src/hooks/usePasteHandler.js +195 -0
  815. package/src/hooks/usePluginRecommendationBase.js +101 -0
  816. package/src/hooks/usePrStatus.js +91 -0
  817. package/src/hooks/usePromptSuggestion.js +128 -0
  818. package/src/hooks/usePromptsFromClaudeInChrome.js +66 -0
  819. package/src/hooks/useQueueProcessor.js +46 -0
  820. package/src/hooks/useRemoteSession.js +431 -0
  821. package/src/hooks/useReplBridge.js +715 -0
  822. package/src/hooks/useSSHSession.js +167 -0
  823. package/src/hooks/useScheduledTasks.js +104 -0
  824. package/src/hooks/useSearchInput.js +302 -0
  825. package/src/hooks/useSessionBackgrounding.js +132 -0
  826. package/src/hooks/useSettings.js +10 -0
  827. package/src/hooks/useSettingsChange.js +13 -0
  828. package/src/hooks/useSkillImprovementSurvey.js +69 -0
  829. package/src/hooks/useSkillsChange.js +51 -0
  830. package/src/hooks/useSwarmInitialization.js +67 -0
  831. package/src/hooks/useSwarmPermissionPoller.js +215 -0
  832. package/src/hooks/useTaskListWatcher.js +157 -0
  833. package/src/hooks/useTasksV2.js +220 -0
  834. package/src/hooks/useTeammateViewAutoExit.js +55 -0
  835. package/src/hooks/useTeleportResume.js +81 -0
  836. package/src/hooks/useTerminalSize.js +9 -0
  837. package/src/hooks/useTextInput.js +397 -0
  838. package/src/hooks/useThaddeusHintRecommendation.js +117 -0
  839. package/src/hooks/useTimeout.js +10 -0
  840. package/src/hooks/useTurnDiffs.js +160 -0
  841. package/src/hooks/useTypeahead.js +1250 -0
  842. package/src/hooks/useUpdateNotification.js +21 -0
  843. package/src/hooks/useVimInput.js +232 -0
  844. package/src/hooks/useVirtualScroll.js +627 -0
  845. package/src/hooks/useVoice.js +952 -0
  846. package/src/hooks/useVoiceEnabled.js +21 -0
  847. package/src/hooks/useVoiceIntegration.js +629 -0
  848. package/src/infrastructure/audit.js +210 -0
  849. package/src/infrastructure/guardrails.js +513 -0
  850. package/src/infrastructure/index.js +11 -0
  851. package/src/ink/Ansi.js +269 -0
  852. package/src/ink/bidi.js +117 -0
  853. package/src/ink/clearTerminal.js +58 -0
  854. package/src/ink/colorize.js +198 -0
  855. package/src/ink/components/AlternateScreen.js +74 -0
  856. package/src/ink/components/App.js +562 -0
  857. package/src/ink/components/AppContext.js +11 -0
  858. package/src/ink/components/Box.js +155 -0
  859. package/src/ink/components/Button.js +166 -0
  860. package/src/ink/components/ClockContext.js +108 -0
  861. package/src/ink/components/CursorDeclarationContext.js +3 -0
  862. package/src/ink/components/ErrorOverview.js +50 -0
  863. package/src/ink/components/Link.js +34 -0
  864. package/src/ink/components/Newline.js +30 -0
  865. package/src/ink/components/NoSelect.js +57 -0
  866. package/src/ink/components/RawAnsi.js +46 -0
  867. package/src/ink/components/ScrollBox.js +171 -0
  868. package/src/ink/components/Spacer.js +20 -0
  869. package/src/ink/components/StdinContext.js +16 -0
  870. package/src/ink/components/TerminalFocusContext.js +45 -0
  871. package/src/ink/components/TerminalSizeContext.js +3 -0
  872. package/src/ink/components/Text.js +195 -0
  873. package/src/ink/constants.js +2 -0
  874. package/src/ink/dom.js +298 -0
  875. package/src/ink/events/click-event.js +36 -0
  876. package/src/ink/events/dispatcher.js +172 -0
  877. package/src/ink/events/emitter.js +31 -0
  878. package/src/ink/events/event-handlers.js +30 -0
  879. package/src/ink/events/event.js +9 -0
  880. package/src/ink/events/focus-event.js +16 -0
  881. package/src/ink/events/input-event.js +161 -0
  882. package/src/ink/events/keyboard-event.js +46 -0
  883. package/src/ink/events/terminal-event.js +78 -0
  884. package/src/ink/events/terminal-focus-event.js +15 -0
  885. package/src/ink/focus.js +158 -0
  886. package/src/ink/frame.js +30 -0
  887. package/src/ink/get-max-width.js +23 -0
  888. package/src/ink/hit-test.js +113 -0
  889. package/src/ink/hooks/use-animation-frame.js +48 -0
  890. package/src/ink/hooks/use-app.js +7 -0
  891. package/src/ink/hooks/use-declared-cursor.js +60 -0
  892. package/src/ink/hooks/use-input.js +70 -0
  893. package/src/ink/hooks/use-interval.js +54 -0
  894. package/src/ink/hooks/use-search-highlight.js +32 -0
  895. package/src/ink/hooks/use-selection.js +60 -0
  896. package/src/ink/hooks/use-stdin.js +7 -0
  897. package/src/ink/hooks/use-tab-status.js +57 -0
  898. package/src/ink/hooks/use-terminal-focus.js +15 -0
  899. package/src/ink/hooks/use-terminal-title.js +29 -0
  900. package/src/ink/hooks/use-terminal-viewport.js +77 -0
  901. package/src/ink/ink.js +1645 -0
  902. package/src/ink/instances.js +7 -0
  903. package/src/ink/layout/engine.js +4 -0
  904. package/src/ink/layout/geometry.js +61 -0
  905. package/src/ink/layout/node.js +62 -0
  906. package/src/ink/layout/yoga.js +237 -0
  907. package/src/ink/line-width-cache.js +19 -0
  908. package/src/ink/log-update.js +583 -0
  909. package/src/ink/measure-element.js +8 -0
  910. package/src/ink/measure-text.js +35 -0
  911. package/src/ink/node-cache.js +30 -0
  912. package/src/ink/optimizer.js +81 -0
  913. package/src/ink/output.js +556 -0
  914. package/src/ink/parse-keypress.js +695 -0
  915. package/src/ink/reconciler.js +384 -0
  916. package/src/ink/render-border.js +134 -0
  917. package/src/ink/render-node-to-output.js +1216 -0
  918. package/src/ink/render-to-screen.js +171 -0
  919. package/src/ink/renderer.js +129 -0
  920. package/src/ink/root.js +80 -0
  921. package/src/ink/screen.js +1132 -0
  922. package/src/ink/searchHighlight.js +78 -0
  923. package/src/ink/selection.js +792 -0
  924. package/src/ink/squash-text-nodes.js +56 -0
  925. package/src/ink/stringWidth.js +200 -0
  926. package/src/ink/styles.js +299 -0
  927. package/src/ink/supports-hyperlinks.js +40 -0
  928. package/src/ink/tabstops.js +39 -0
  929. package/src/ink/terminal-focus-state.js +35 -0
  930. package/src/ink/terminal-querier.js +173 -0
  931. package/src/ink/terminal.js +208 -0
  932. package/src/ink/termio/ansi.js +70 -0
  933. package/src/ink/termio/csi.js +260 -0
  934. package/src/ink/termio/dec.js +53 -0
  935. package/src/ink/termio/esc.js +55 -0
  936. package/src/ink/termio/osc.js +432 -0
  937. package/src/ink/termio/parser.js +356 -0
  938. package/src/ink/termio/sgr.js +292 -0
  939. package/src/ink/termio/tokenize.js +264 -0
  940. package/src/ink/termio/types.js +55 -0
  941. package/src/ink/termio.js +24 -0
  942. package/src/ink/useTerminalNotification.js +57 -0
  943. package/src/ink/warn.js +10 -0
  944. package/src/ink/widest-line.js +14 -0
  945. package/src/ink/wrap-text.js +54 -0
  946. package/src/ink/wrapAnsi.js +6 -0
  947. package/src/ink.js +50 -0
  948. package/src/integrations/credentialStore.js +176 -0
  949. package/src/integrations/index.js +5 -0
  950. package/src/integrations/integrationManager.js +180 -0
  951. package/src/integrations/providers/BaseProvider.js +180 -0
  952. package/src/integrations/providers/GitHubProvider.js +217 -0
  953. package/src/integrations/providers/GmailProvider.js +204 -0
  954. package/src/integrations/providers/GoogleCalendarProvider.js +113 -0
  955. package/src/integrations/providers/HubSpotProvider.js +159 -0
  956. package/src/integrations/providers/JiraProvider.js +216 -0
  957. package/src/integrations/providers/NotionProvider.js +221 -0
  958. package/src/integrations/providers/QuickBooksProvider.js +176 -0
  959. package/src/integrations/providers/SlackProvider.js +174 -0
  960. package/src/integrations/providers/StripeProvider.js +206 -0
  961. package/src/integrations/providers/TwilioProvider.js +239 -0
  962. package/src/integrations/providers/_template.js +112 -0
  963. package/src/integrations/types.js +7 -0
  964. package/src/interactiveHelpers.js +308 -0
  965. package/src/jobs/classifier.js +6 -0
  966. package/src/keybindings/KeybindingContext.js +184 -0
  967. package/src/keybindings/KeybindingProviderSetup.js +259 -0
  968. package/src/keybindings/defaultBindings.js +333 -0
  969. package/src/keybindings/loadUserBindings.js +393 -0
  970. package/src/keybindings/match.js +111 -0
  971. package/src/keybindings/parser.js +184 -0
  972. package/src/keybindings/reservedShortcuts.js +109 -0
  973. package/src/keybindings/resolver.js +182 -0
  974. package/src/keybindings/schema.js +205 -0
  975. package/src/keybindings/shortcutFormat.js +48 -0
  976. package/src/keybindings/template.js +40 -0
  977. package/src/keybindings/useKeybinding.js +161 -0
  978. package/src/keybindings/useShortcutDisplay.js +43 -0
  979. package/src/keybindings/validate.js +395 -0
  980. package/src/main.js +4128 -0
  981. package/src/memdir/findRelevantMemories.js +99 -0
  982. package/src/memdir/memdir.js +406 -0
  983. package/src/memdir/memoryAge.js +52 -0
  984. package/src/memdir/memoryScan.js +65 -0
  985. package/src/memdir/memoryShapeTelemetry.js +8 -0
  986. package/src/memdir/memoryTypes.js +260 -0
  987. package/src/memdir/paths.js +235 -0
  988. package/src/memdir/teamMemPaths.js +261 -0
  989. package/src/memdir/teamMemPrompts.js +82 -0
  990. package/src/migrations/migrateAutoUpdatesToSettings.js +47 -0
  991. package/src/migrations/migrateBypassPermissionsAcceptedToSettings.js +32 -0
  992. package/src/migrations/migrateEnableAllProjectMcpServersToSettings.js +83 -0
  993. package/src/migrations/migrateFennecToOpus.js +39 -0
  994. package/src/migrations/migrateLegacyOpusToCurrent.js +44 -0
  995. package/src/migrations/migrateOpusToOpus1m.js +31 -0
  996. package/src/migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.js +23 -0
  997. package/src/migrations/migrateSonnet1mToSonnet45.js +38 -0
  998. package/src/migrations/migrateSonnet45ToSonnet46.js +48 -0
  999. package/src/migrations/resetAutoModeOptInForDefaultOffer.js +47 -0
  1000. package/src/migrations/resetProToOpusDefault.js +46 -0
  1001. package/src/moreright/useMoreRight.js +13 -0
  1002. package/src/native-ts/color-diff/index.js +819 -0
  1003. package/src/native-ts/file-index/index.js +328 -0
  1004. package/src/native-ts/yoga-layout/enums.js +101 -0
  1005. package/src/native-ts/yoga-layout/index.js +2113 -0
  1006. package/src/outputStyles/loadOutputStylesDir.js +71 -0
  1007. package/src/plugins/builtinPlugins.js +132 -0
  1008. package/src/plugins/bundled/index.js +22 -0
  1009. package/src/proactive/index.js +138 -0
  1010. package/src/proactive/useProactive.js +82 -0
  1011. package/src/projectOnboardingState.js +61 -0
  1012. package/src/query/config.js +17 -0
  1013. package/src/query/deps.js +12 -0
  1014. package/src/query/stopHooks.js +332 -0
  1015. package/src/query/tokenBudget.js +49 -0
  1016. package/src/query.js +1264 -0
  1017. package/src/remote/RemoteSessionManager.js +172 -0
  1018. package/src/remote/SessionsWebSocket.js +308 -0
  1019. package/src/remote/remotePermissionBridge.js +70 -0
  1020. package/src/remote/sdkMessageAdapter.js +227 -0
  1021. package/src/replLauncher.js +7 -0
  1022. package/src/schemas/hooks.js +174 -0
  1023. package/src/screens/Doctor.js +580 -0
  1024. package/src/screens/REPL.js +4500 -0
  1025. package/src/screens/ResumeConversation.js +339 -0
  1026. package/src/self-hosted-runner/main.js +8 -0
  1027. package/src/server/backends/dangerousBackend.js +8 -0
  1028. package/src/server/connectHeadless.js +6 -0
  1029. package/src/server/createDirectConnectSession.js +62 -0
  1030. package/src/server/directConnectManager.js +153 -0
  1031. package/src/server/lockfile.js +11 -0
  1032. package/src/server/parseConnectUrl.js +20 -0
  1033. package/src/server/server.js +12 -0
  1034. package/src/server/serverBanner.js +9 -0
  1035. package/src/server/serverLog.js +11 -0
  1036. package/src/server/sessionManager.js +19 -0
  1037. package/src/server/types.js +7 -0
  1038. package/src/services/AgentSummary/agentSummary.js +147 -0
  1039. package/src/services/MagicDocs/magicDocs.js +193 -0
  1040. package/src/services/MagicDocs/prompts.js +110 -0
  1041. package/src/services/PromptSuggestion/promptSuggestion.js +402 -0
  1042. package/src/services/PromptSuggestion/speculation.js +643 -0
  1043. package/src/services/SessionMemory/prompts.js +254 -0
  1044. package/src/services/SessionMemory/sessionMemory.js +358 -0
  1045. package/src/services/SessionMemory/sessionMemoryUtils.js +157 -0
  1046. package/src/services/analytics/config.js +27 -0
  1047. package/src/services/analytics/datadog.js +26 -0
  1048. package/src/services/analytics/firstPartyEventLogger.js +65 -0
  1049. package/src/services/analytics/firstPartyEventLoggingExporter.js +595 -0
  1050. package/src/services/analytics/growthbook.js +103 -0
  1051. package/src/services/analytics/index.js +91 -0
  1052. package/src/services/analytics/metadata.js +696 -0
  1053. package/src/services/analytics/sink.js +19 -0
  1054. package/src/services/analytics/sinkKillswitch.js +19 -0
  1055. package/src/services/api/adminRequests.js +57 -0
  1056. package/src/services/api/bootstrap.js +118 -0
  1057. package/src/services/api/claude.js +2466 -0
  1058. package/src/services/api/client.js +335 -0
  1059. package/src/services/api/dumpPrompts.js +174 -0
  1060. package/src/services/api/emptyUsage.js +20 -0
  1061. package/src/services/api/errorUtils.js +203 -0
  1062. package/src/services/api/errors.js +926 -0
  1063. package/src/services/api/filesApi.js +523 -0
  1064. package/src/services/api/firstTokenDate.js +49 -0
  1065. package/src/services/api/grove.js +44 -0
  1066. package/src/services/api/logging.js +484 -0
  1067. package/src/services/api/metricsOptOut.js +15 -0
  1068. package/src/services/api/overageCreditGrant.js +123 -0
  1069. package/src/services/api/promptCacheBreakDetection.js +510 -0
  1070. package/src/services/api/referral.js +219 -0
  1071. package/src/services/api/sessionIngress.js +358 -0
  1072. package/src/services/api/ultrareviewQuota.js +29 -0
  1073. package/src/services/api/usage.js +31 -0
  1074. package/src/services/api/withRetry.js +587 -0
  1075. package/src/services/api/xai/anthropic-shim.js +885 -0
  1076. package/src/services/api/xai/brightDataSearch.js +161 -0
  1077. package/src/services/api/xai/thaddeus-engine.js +605 -0
  1078. package/src/services/api/xai/xai-client.js +276 -0
  1079. package/src/services/autoDream/autoDream.js +244 -0
  1080. package/src/services/autoDream/config.js +17 -0
  1081. package/src/services/autoDream/consolidationLock.js +122 -0
  1082. package/src/services/autoDream/consolidationPrompt.js +55 -0
  1083. package/src/services/awaySummary.js +61 -0
  1084. package/src/services/claudeAiLimits.js +331 -0
  1085. package/src/services/claudeAiLimitsHook.js +15 -0
  1086. package/src/services/compact/apiMicrocompact.js +97 -0
  1087. package/src/services/compact/autoCompact.js +234 -0
  1088. package/src/services/compact/cachedMCConfig.js +5 -0
  1089. package/src/services/compact/compact.js +1256 -0
  1090. package/src/services/compact/compactWarningHook.js +12 -0
  1091. package/src/services/compact/compactWarningState.js +15 -0
  1092. package/src/services/compact/grouping.js +58 -0
  1093. package/src/services/compact/microCompact.js +414 -0
  1094. package/src/services/compact/postCompactCleanup.js +70 -0
  1095. package/src/services/compact/prompt.js +325 -0
  1096. package/src/services/compact/reactiveCompact.js +20 -0
  1097. package/src/services/compact/sessionMemoryCompact.js +467 -0
  1098. package/src/services/compact/snipCompact.js +23 -0
  1099. package/src/services/compact/snipProjection.js +11 -0
  1100. package/src/services/compact/timeBasedMCConfig.js +11 -0
  1101. package/src/services/contextCollapse/index.js +33 -0
  1102. package/src/services/contextCollapse/operations.js +5 -0
  1103. package/src/services/contextCollapse/persist.js +5 -0
  1104. package/src/services/diagnosticTracking.js +282 -0
  1105. package/src/services/elevenlabsTTS.js +245 -0
  1106. package/src/services/extractMemories/extractMemories.js +442 -0
  1107. package/src/services/extractMemories/prompts.js +129 -0
  1108. package/src/services/internalLogging.js +68 -0
  1109. package/src/services/lsp/LSPClient.js +306 -0
  1110. package/src/services/lsp/LSPDiagnosticRegistry.js +277 -0
  1111. package/src/services/lsp/LSPServerInstance.js +388 -0
  1112. package/src/services/lsp/LSPServerManager.js +305 -0
  1113. package/src/services/lsp/config.js +57 -0
  1114. package/src/services/lsp/manager.js +246 -0
  1115. package/src/services/lsp/passiveFeedback.js +226 -0
  1116. package/src/services/mcp/InProcessTransport.js +54 -0
  1117. package/src/services/mcp/MCPConnectionManager.js +50 -0
  1118. package/src/services/mcp/SdkControlTransport.js +115 -0
  1119. package/src/services/mcp/auth.js +1882 -0
  1120. package/src/services/mcp/channelAllowlist.js +57 -0
  1121. package/src/services/mcp/channelNotification.js +235 -0
  1122. package/src/services/mcp/channelPermissions.js +192 -0
  1123. package/src/services/mcp/claudeai.js +123 -0
  1124. package/src/services/mcp/client.js +2478 -0
  1125. package/src/services/mcp/config.js +1271 -0
  1126. package/src/services/mcp/elicitationHandler.js +192 -0
  1127. package/src/services/mcp/envExpansion.js +30 -0
  1128. package/src/services/mcp/headersHelper.js +93 -0
  1129. package/src/services/mcp/mcpStringUtils.js +85 -0
  1130. package/src/services/mcp/normalization.js +21 -0
  1131. package/src/services/mcp/oauthPort.js +69 -0
  1132. package/src/services/mcp/officialRegistry.js +20 -0
  1133. package/src/services/mcp/types.js +94 -0
  1134. package/src/services/mcp/useManageMCPConnections.js +818 -0
  1135. package/src/services/mcp/utils.js +433 -0
  1136. package/src/services/mcp/vscodeSdkMcp.js +69 -0
  1137. package/src/services/mcp/xaa.js +342 -0
  1138. package/src/services/mcp/xaaIdpLogin.js +377 -0
  1139. package/src/services/mcpServerApproval.js +30 -0
  1140. package/src/services/mockRateLimits.js +666 -0
  1141. package/src/services/notifier.js +114 -0
  1142. package/src/services/oauth/auth-code-listener.js +165 -0
  1143. package/src/services/oauth/client.js +397 -0
  1144. package/src/services/oauth/crypto.js +19 -0
  1145. package/src/services/oauth/getOauthProfile.js +48 -0
  1146. package/src/services/oauth/index.js +133 -0
  1147. package/src/services/plugins/PluginInstallationManager.js +139 -0
  1148. package/src/services/plugins/pluginCliCommands.js +230 -0
  1149. package/src/services/plugins/pluginOperations.js +826 -0
  1150. package/src/services/policyLimits/index.js +547 -0
  1151. package/src/services/policyLimits/types.js +9 -0
  1152. package/src/services/preventSleep.js +143 -0
  1153. package/src/services/rateLimitMessages.js +271 -0
  1154. package/src/services/rateLimitMocking.js +91 -0
  1155. package/src/services/remoteManagedSettings/index.js +534 -0
  1156. package/src/services/remoteManagedSettings/securityCheck.js +60 -0
  1157. package/src/services/remoteManagedSettings/syncCache.js +90 -0
  1158. package/src/services/remoteManagedSettings/syncCacheState.js +89 -0
  1159. package/src/services/remoteManagedSettings/types.js +12 -0
  1160. package/src/services/sessionTranscript/sessionTranscript.js +5 -0
  1161. package/src/services/settingsSync/index.js +478 -0
  1162. package/src/services/settingsSync/types.js +35 -0
  1163. package/src/services/skillSearch/featureCheck.js +8 -0
  1164. package/src/services/skillSearch/localSearch.js +5 -0
  1165. package/src/services/skillSearch/prefetch.js +8 -0
  1166. package/src/services/skillSearch/remoteSkillLoader.js +8 -0
  1167. package/src/services/skillSearch/remoteSkillState.js +11 -0
  1168. package/src/services/skillSearch/signals.js +3 -0
  1169. package/src/services/skillSearch/telemetry.js +8 -0
  1170. package/src/services/teamMemorySync/index.js +976 -0
  1171. package/src/services/teamMemorySync/secretScanner.js +275 -0
  1172. package/src/services/teamMemorySync/teamMemSecretGuard.js +33 -0
  1173. package/src/services/teamMemorySync/types.js +47 -0
  1174. package/src/services/teamMemorySync/watcher.js +326 -0
  1175. package/src/services/thaddeusAuth.js +485 -0
  1176. package/src/services/thaddeusAuthTypes.js +9 -0
  1177. package/src/services/thaddeusLoginFlow.js +236 -0
  1178. package/src/services/tips/tipHistory.js +17 -0
  1179. package/src/services/tips/tipRegistry.js +593 -0
  1180. package/src/services/tips/tipScheduler.js +40 -0
  1181. package/src/services/tokenEstimation.js +365 -0
  1182. package/src/services/toolUseSummary/toolUseSummaryGenerator.js +87 -0
  1183. package/src/services/tools/StreamingToolExecutor.js +413 -0
  1184. package/src/services/tools/toolExecution.js +1309 -0
  1185. package/src/services/tools/toolHooks.js +454 -0
  1186. package/src/services/tools/toolOrchestration.js +110 -0
  1187. package/src/services/vcr.js +291 -0
  1188. package/src/services/voice.js +392 -0
  1189. package/src/services/voiceKeyterms.js +94 -0
  1190. package/src/services/voiceStreamSTT.js +405 -0
  1191. package/src/setup.js +310 -0
  1192. package/src/skills/bundled/batch.js +114 -0
  1193. package/src/skills/bundled/claudeApi.js +145 -0
  1194. package/src/skills/bundled/claudeApiContent.js +71 -0
  1195. package/src/skills/bundled/claudeInChrome.js +27 -0
  1196. package/src/skills/bundled/debug.js +99 -0
  1197. package/src/skills/bundled/dream.js +49 -0
  1198. package/src/skills/bundled/emailSetup.js +196 -0
  1199. package/src/skills/bundled/hunter.js +28 -0
  1200. package/src/skills/bundled/index.js +80 -0
  1201. package/src/skills/bundled/keybindings.js +292 -0
  1202. package/src/skills/bundled/loop.js +81 -0
  1203. package/src/skills/bundled/loremIpsum.js +264 -0
  1204. package/src/skills/bundled/reactor.js +31 -0
  1205. package/src/skills/bundled/remember.js +73 -0
  1206. package/src/skills/bundled/runSkillGenerator.js +12 -0
  1207. package/src/skills/bundled/scheduleRemoteAgents.js +373 -0
  1208. package/src/skills/bundled/simplify.js +66 -0
  1209. package/src/skills/bundled/skillify.js +182 -0
  1210. package/src/skills/bundled/stuck.js +69 -0
  1211. package/src/skills/bundled/updateConfig.js +463 -0
  1212. package/src/skills/bundled/verify.js +23 -0
  1213. package/src/skills/bundled/verifyContent.js +10 -0
  1214. package/src/skills/bundledSkills.js +159 -0
  1215. package/src/skills/loadSkillsDir.js +736 -0
  1216. package/src/skills/mcpSkillBuilders.js +10 -0
  1217. package/src/skills/mcpSkills.js +5 -0
  1218. package/src/state/AppState.js +182 -0
  1219. package/src/state/AppStateStore.js +117 -0
  1220. package/src/state/onChangeAppState.js +132 -0
  1221. package/src/state/selectors.js +51 -0
  1222. package/src/state/store.js +21 -0
  1223. package/src/state/teammateViewHelpers.js +124 -0
  1224. package/src/stubs/ant-chrome-mcp/index.js +4 -0
  1225. package/src/stubs/ant-computer-use-input/index.js +2 -0
  1226. package/src/stubs/ant-computer-use-mcp/index.js +7 -0
  1227. package/src/stubs/ant-computer-use-mcp/sentinelApps.js +2 -0
  1228. package/src/stubs/ant-computer-use-mcp/types.js +3 -0
  1229. package/src/stubs/ant-computer-use-swift/index.js +1 -0
  1230. package/src/stubs/anthropic-sandbox/index.js +34 -0
  1231. package/src/tasks/DreamTask/DreamTask.js +99 -0
  1232. package/src/tasks/InProcessTeammateTask/InProcessTeammateTask.js +116 -0
  1233. package/src/tasks/InProcessTeammateTask/types.js +35 -0
  1234. package/src/tasks/LocalAgentTask/LocalAgentTask.js +507 -0
  1235. package/src/tasks/LocalMainSessionTask.js +338 -0
  1236. package/src/tasks/LocalShellTask/LocalShellTask.js +475 -0
  1237. package/src/tasks/LocalShellTask/guards.js +9 -0
  1238. package/src/tasks/LocalShellTask/killShellTasks.js +59 -0
  1239. package/src/tasks/LocalWorkflowTask/LocalWorkflowTask.js +7 -0
  1240. package/src/tasks/MonitorMcpTask/MonitorMcpTask.js +20 -0
  1241. package/src/tasks/RemoteAgentTask/RemoteAgentTask.js +742 -0
  1242. package/src/tasks/pillLabel.js +69 -0
  1243. package/src/tasks/stopTask.js +67 -0
  1244. package/src/tasks/types.js +18 -0
  1245. package/src/tasks.js +37 -0
  1246. package/src/tools/AIEmployeesTool/AIEmployeesTool.js +674 -0
  1247. package/src/tools/AIEmployeesTool/constants.js +1 -0
  1248. package/src/tools/AIEmployeesTool/prompt.js +56 -0
  1249. package/src/tools/AgentTool/AgentTool.js +1221 -0
  1250. package/src/tools/AgentTool/UI.js +593 -0
  1251. package/src/tools/AgentTool/agentColorManager.js +43 -0
  1252. package/src/tools/AgentTool/agentDisplay.js +72 -0
  1253. package/src/tools/AgentTool/agentMemory.js +125 -0
  1254. package/src/tools/AgentTool/agentMemorySnapshot.js +136 -0
  1255. package/src/tools/AgentTool/agentToolUtils.js +456 -0
  1256. package/src/tools/AgentTool/built-in/exploreAgent.js +76 -0
  1257. package/src/tools/AgentTool/built-in/generalPurposeAgent.js +28 -0
  1258. package/src/tools/AgentTool/built-in/planAgent.js +87 -0
  1259. package/src/tools/AgentTool/built-in/statuslineSetup.js +140 -0
  1260. package/src/tools/AgentTool/built-in/thaddeusGuideAgent.js +174 -0
  1261. package/src/tools/AgentTool/built-in/verificationAgent.js +146 -0
  1262. package/src/tools/AgentTool/builtInAgents.js +56 -0
  1263. package/src/tools/AgentTool/constants.js +11 -0
  1264. package/src/tools/AgentTool/forkSubagent.js +177 -0
  1265. package/src/tools/AgentTool/loadAgentsDir.js +497 -0
  1266. package/src/tools/AgentTool/prompt.js +260 -0
  1267. package/src/tools/AgentTool/resumeAgent.js +182 -0
  1268. package/src/tools/AgentTool/runAgent.js +627 -0
  1269. package/src/tools/AppointmentsTool/AppointmentsTool.js +628 -0
  1270. package/src/tools/AppointmentsTool/constants.js +1 -0
  1271. package/src/tools/AppointmentsTool/prompt.js +15 -0
  1272. package/src/tools/AskUserQuestionTool/AskUserQuestionTool.js +238 -0
  1273. package/src/tools/AskUserQuestionTool/prompt.js +38 -0
  1274. package/src/tools/BashTool/BashTool.js +1009 -0
  1275. package/src/tools/BashTool/BashToolResultMessage.js +169 -0
  1276. package/src/tools/BashTool/UI.js +134 -0
  1277. package/src/tools/BashTool/bashCommandHelpers.js +184 -0
  1278. package/src/tools/BashTool/bashPermissions.js +2023 -0
  1279. package/src/tools/BashTool/bashSecurity.js +2267 -0
  1280. package/src/tools/BashTool/commandSemantics.js +105 -0
  1281. package/src/tools/BashTool/commentLabel.js +14 -0
  1282. package/src/tools/BashTool/destructiveCommandWarning.js +88 -0
  1283. package/src/tools/BashTool/modeValidation.js +86 -0
  1284. package/src/tools/BashTool/pathValidation.js +1079 -0
  1285. package/src/tools/BashTool/prompt.js +333 -0
  1286. package/src/tools/BashTool/readOnlyValidation.js +1794 -0
  1287. package/src/tools/BashTool/sedEditParser.js +282 -0
  1288. package/src/tools/BashTool/sedValidation.js +580 -0
  1289. package/src/tools/BashTool/shouldUseSandbox.js +125 -0
  1290. package/src/tools/BashTool/toolName.js +2 -0
  1291. package/src/tools/BashTool/utils.js +180 -0
  1292. package/src/tools/BriefTool/BriefTool.js +173 -0
  1293. package/src/tools/BriefTool/UI.js +67 -0
  1294. package/src/tools/BriefTool/attachments.js +86 -0
  1295. package/src/tools/BriefTool/prompt.js +19 -0
  1296. package/src/tools/BriefTool/upload.js +136 -0
  1297. package/src/tools/CalendarTool/CalendarTool.js +498 -0
  1298. package/src/tools/CalendarTool/constants.js +1 -0
  1299. package/src/tools/CalendarTool/prompt.js +11 -0
  1300. package/src/tools/ConfigTool/ConfigTool.js +398 -0
  1301. package/src/tools/ConfigTool/UI.js +25 -0
  1302. package/src/tools/ConfigTool/constants.js +1 -0
  1303. package/src/tools/ConfigTool/prompt.js +82 -0
  1304. package/src/tools/ConfigTool/supportedSettings.js +180 -0
  1305. package/src/tools/ContactsTool/ContactsTool.js +648 -0
  1306. package/src/tools/ContactsTool/constants.js +1 -0
  1307. package/src/tools/ContactsTool/prompt.js +15 -0
  1308. package/src/tools/CtxInspectTool/CtxInspectTool.js +44 -0
  1309. package/src/tools/DiscoverSkillsTool/prompt.js +4 -0
  1310. package/src/tools/EmailReadTool/index.js +410 -0
  1311. package/src/tools/EmailSendTool/index.js +178 -0
  1312. package/src/tools/EnterPlanModeTool/EnterPlanModeTool.js +98 -0
  1313. package/src/tools/EnterPlanModeTool/UI.js +14 -0
  1314. package/src/tools/EnterPlanModeTool/constants.js +1 -0
  1315. package/src/tools/EnterPlanModeTool/prompt.js +164 -0
  1316. package/src/tools/EnterWorktreeTool/EnterWorktreeTool.js +104 -0
  1317. package/src/tools/EnterWorktreeTool/UI.js +9 -0
  1318. package/src/tools/EnterWorktreeTool/constants.js +1 -0
  1319. package/src/tools/EnterWorktreeTool/prompt.js +30 -0
  1320. package/src/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js +383 -0
  1321. package/src/tools/ExitPlanModeTool/UI.js +32 -0
  1322. package/src/tools/ExitPlanModeTool/constants.js +2 -0
  1323. package/src/tools/ExitPlanModeTool/prompt.js +27 -0
  1324. package/src/tools/ExitWorktreeTool/ExitWorktreeTool.js +257 -0
  1325. package/src/tools/ExitWorktreeTool/UI.js +10 -0
  1326. package/src/tools/ExitWorktreeTool/constants.js +1 -0
  1327. package/src/tools/ExitWorktreeTool/prompt.js +32 -0
  1328. package/src/tools/FileEditTool/FileEditTool.js +480 -0
  1329. package/src/tools/FileEditTool/UI.js +202 -0
  1330. package/src/tools/FileEditTool/constants.js +7 -0
  1331. package/src/tools/FileEditTool/prompt.js +24 -0
  1332. package/src/tools/FileEditTool/types.js +50 -0
  1333. package/src/tools/FileEditTool/utils.js +579 -0
  1334. package/src/tools/FileReadTool/FileReadTool.js +889 -0
  1335. package/src/tools/FileReadTool/UI.js +126 -0
  1336. package/src/tools/FileReadTool/imageProcessor.js +46 -0
  1337. package/src/tools/FileReadTool/limits.js +70 -0
  1338. package/src/tools/FileReadTool/prompt.js +31 -0
  1339. package/src/tools/FileWriteTool/FileWriteTool.js +341 -0
  1340. package/src/tools/FileWriteTool/UI.js +339 -0
  1341. package/src/tools/FileWriteTool/prompt.js +15 -0
  1342. package/src/tools/GlobTool/GlobTool.js +161 -0
  1343. package/src/tools/GlobTool/UI.js +40 -0
  1344. package/src/tools/GlobTool/prompt.js +6 -0
  1345. package/src/tools/GrepTool/GrepTool.js +439 -0
  1346. package/src/tools/GrepTool/UI.js +155 -0
  1347. package/src/tools/GrepTool/prompt.js +16 -0
  1348. package/src/tools/IntegrationsTool/IntegrationsTool.js +217 -0
  1349. package/src/tools/IntegrationsTool/constants.js +1 -0
  1350. package/src/tools/IntegrationsTool/prompt.js +41 -0
  1351. package/src/tools/InteractionsTool/InteractionsTool.js +525 -0
  1352. package/src/tools/InteractionsTool/constants.js +1 -0
  1353. package/src/tools/InteractionsTool/prompt.js +14 -0
  1354. package/src/tools/InvoicesTool/InvoicesTool.js +581 -0
  1355. package/src/tools/InvoicesTool/constants.js +1 -0
  1356. package/src/tools/InvoicesTool/prompt.js +15 -0
  1357. package/src/tools/LSPTool/LSPTool.js +660 -0
  1358. package/src/tools/LSPTool/UI.js +205 -0
  1359. package/src/tools/LSPTool/formatters.js +445 -0
  1360. package/src/tools/LSPTool/prompt.js +20 -0
  1361. package/src/tools/LSPTool/schemas.js +197 -0
  1362. package/src/tools/LSPTool/symbolContext.js +75 -0
  1363. package/src/tools/LeadScorerTool/LeadScorerTool.js +509 -0
  1364. package/src/tools/LeadScorerTool/constants.js +1 -0
  1365. package/src/tools/LeadScorerTool/prompt.js +11 -0
  1366. package/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +100 -0
  1367. package/src/tools/ListMcpResourcesTool/UI.js +17 -0
  1368. package/src/tools/ListMcpResourcesTool/prompt.js +18 -0
  1369. package/src/tools/ListPeersTool/ListPeersTool.js +45 -0
  1370. package/src/tools/MCPTool/MCPTool.js +60 -0
  1371. package/src/tools/MCPTool/UI.js +343 -0
  1372. package/src/tools/MCPTool/classifyForCollapse.js +597 -0
  1373. package/src/tools/MCPTool/prompt.js +3 -0
  1374. package/src/tools/McpAuthTool/McpAuthTool.js +162 -0
  1375. package/src/tools/MonitorTool/MonitorTool.js +55 -0
  1376. package/src/tools/NotebookEditTool/NotebookEditTool.js +421 -0
  1377. package/src/tools/NotebookEditTool/UI.js +41 -0
  1378. package/src/tools/NotebookEditTool/constants.js +2 -0
  1379. package/src/tools/NotebookEditTool/prompt.js +2 -0
  1380. package/src/tools/OverflowTestTool/OverflowTestTool.js +51 -0
  1381. package/src/tools/PhoneBridgeTool/PhoneBridgeTool.js +301 -0
  1382. package/src/tools/PhoneBridgeTool/constants.js +1 -0
  1383. package/src/tools/PhoneBridgeTool/prompt.js +26 -0
  1384. package/src/tools/PowerShellTool/PowerShellTool.js +900 -0
  1385. package/src/tools/PowerShellTool/UI.js +58 -0
  1386. package/src/tools/PowerShellTool/clmTypes.js +207 -0
  1387. package/src/tools/PowerShellTool/commandSemantics.js +115 -0
  1388. package/src/tools/PowerShellTool/commonParameters.js +27 -0
  1389. package/src/tools/PowerShellTool/destructiveCommandWarning.js +92 -0
  1390. package/src/tools/PowerShellTool/gitSafety.js +185 -0
  1391. package/src/tools/PowerShellTool/modeValidation.js +357 -0
  1392. package/src/tools/PowerShellTool/pathValidation.js +1712 -0
  1393. package/src/tools/PowerShellTool/powershellPermissions.js +1351 -0
  1394. package/src/tools/PowerShellTool/powershellSecurity.js +942 -0
  1395. package/src/tools/PowerShellTool/prompt.js +132 -0
  1396. package/src/tools/PowerShellTool/readOnlyValidation.js +1633 -0
  1397. package/src/tools/PowerShellTool/toolName.js +2 -0
  1398. package/src/tools/PushNotificationTool/PushNotificationTool.js +35 -0
  1399. package/src/tools/REPLTool/REPLTool.js +44 -0
  1400. package/src/tools/REPLTool/constants.js +43 -0
  1401. package/src/tools/REPLTool/primitiveTools.js +36 -0
  1402. package/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +112 -0
  1403. package/src/tools/ReadMcpResourceTool/UI.js +24 -0
  1404. package/src/tools/ReadMcpResourceTool/prompt.js +15 -0
  1405. package/src/tools/RemoteTriggerTool/RemoteTriggerTool.js +142 -0
  1406. package/src/tools/RemoteTriggerTool/UI.js +12 -0
  1407. package/src/tools/RemoteTriggerTool/prompt.js +12 -0
  1408. package/src/tools/ReviewArtifactTool/ReviewArtifactTool.js +51 -0
  1409. package/src/tools/ScheduleCronTool/CronCreateTool.js +120 -0
  1410. package/src/tools/ScheduleCronTool/CronDeleteTool.js +74 -0
  1411. package/src/tools/ScheduleCronTool/CronListTool.js +77 -0
  1412. package/src/tools/ScheduleCronTool/UI.js +29 -0
  1413. package/src/tools/ScheduleCronTool/prompt.js +115 -0
  1414. package/src/tools/SendMessageTool/SendMessageTool.js +673 -0
  1415. package/src/tools/SendMessageTool/UI.js +24 -0
  1416. package/src/tools/SendMessageTool/constants.js +1 -0
  1417. package/src/tools/SendMessageTool/prompt.js +47 -0
  1418. package/src/tools/SendUserFileTool/SendUserFileTool.js +35 -0
  1419. package/src/tools/SendUserFileTool/prompt.js +5 -0
  1420. package/src/tools/SkillTool/SkillTool.js +825 -0
  1421. package/src/tools/SkillTool/UI.js +61 -0
  1422. package/src/tools/SkillTool/constants.js +1 -0
  1423. package/src/tools/SkillTool/prompt.js +184 -0
  1424. package/src/tools/SleepTool/SleepTool.js +42 -0
  1425. package/src/tools/SleepTool/prompt.js +14 -0
  1426. package/src/tools/SnipTool/SnipTool.js +47 -0
  1427. package/src/tools/SnipTool/prompt.js +5 -0
  1428. package/src/tools/SubscribePRTool/SubscribePRTool.js +49 -0
  1429. package/src/tools/SuggestBackgroundPRTool/SuggestBackgroundPRTool.js +44 -0
  1430. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.js +138 -0
  1431. package/src/tools/SyntheticOutputTool/SyntheticOutputTool.ts +1 -1
  1432. package/src/tools/TaskCreateTool/TaskCreateTool.js +104 -0
  1433. package/src/tools/TaskCreateTool/constants.js +1 -0
  1434. package/src/tools/TaskCreateTool/prompt.js +52 -0
  1435. package/src/tools/TaskGetTool/TaskGetTool.js +106 -0
  1436. package/src/tools/TaskGetTool/constants.js +1 -0
  1437. package/src/tools/TaskGetTool/prompt.js +23 -0
  1438. package/src/tools/TaskListTool/TaskListTool.js +89 -0
  1439. package/src/tools/TaskListTool/constants.js +1 -0
  1440. package/src/tools/TaskListTool/prompt.js +44 -0
  1441. package/src/tools/TaskOutputTool/TaskOutputTool.js +536 -0
  1442. package/src/tools/TaskOutputTool/constants.js +1 -0
  1443. package/src/tools/TaskStopTool/TaskStopTool.js +110 -0
  1444. package/src/tools/TaskStopTool/UI.js +31 -0
  1445. package/src/tools/TaskStopTool/prompt.js +7 -0
  1446. package/src/tools/TaskUpdateTool/TaskUpdateTool.js +301 -0
  1447. package/src/tools/TaskUpdateTool/constants.js +1 -0
  1448. package/src/tools/TaskUpdateTool/prompt.js +76 -0
  1449. package/src/tools/TeamCreateTool/TeamCreateTool.js +177 -0
  1450. package/src/tools/TeamCreateTool/UI.js +4 -0
  1451. package/src/tools/TeamCreateTool/constants.js +1 -0
  1452. package/src/tools/TeamCreateTool/prompt.js +113 -0
  1453. package/src/tools/TeamDeleteTool/TeamDeleteTool.js +102 -0
  1454. package/src/tools/TeamDeleteTool/UI.js +13 -0
  1455. package/src/tools/TeamDeleteTool/constants.js +1 -0
  1456. package/src/tools/TeamDeleteTool/prompt.js +16 -0
  1457. package/src/tools/TerminalCaptureTool/TerminalCaptureTool.js +47 -0
  1458. package/src/tools/TerminalCaptureTool/prompt.js +11 -0
  1459. package/src/tools/TodoWriteTool/TodoWriteTool.js +99 -0
  1460. package/src/tools/TodoWriteTool/constants.js +1 -0
  1461. package/src/tools/TodoWriteTool/prompt.js +181 -0
  1462. package/src/tools/ToolSearchTool/ToolSearchTool.js +357 -0
  1463. package/src/tools/ToolSearchTool/constants.js +1 -0
  1464. package/src/tools/ToolSearchTool/prompt.js +97 -0
  1465. package/src/tools/TungstenTool/TungstenLiveMonitor.js +7 -0
  1466. package/src/tools/TungstenTool/TungstenTool.js +3 -0
  1467. package/src/tools/VerifyPlanExecutionTool/VerifyPlanExecutionTool.js +45 -0
  1468. package/src/tools/VerifyPlanExecutionTool/constants.js +2 -0
  1469. package/src/tools/WebBrowserTool/WebBrowserPanel.js +5 -0
  1470. package/src/tools/WebBrowserTool/WebBrowserTool.js +58 -0
  1471. package/src/tools/WebFetchTool/UI.js +31 -0
  1472. package/src/tools/WebFetchTool/WebFetchTool.js +246 -0
  1473. package/src/tools/WebFetchTool/preapproved.js +154 -0
  1474. package/src/tools/WebFetchTool/prompt.js +39 -0
  1475. package/src/tools/WebFetchTool/utils.js +368 -0
  1476. package/src/tools/WebSearchTool/UI.js +67 -0
  1477. package/src/tools/WebSearchTool/WebSearchTool.js +396 -0
  1478. package/src/tools/WebSearchTool/prompt.js +32 -0
  1479. package/src/tools/WorkflowTool/WorkflowPermissionRequest.js +7 -0
  1480. package/src/tools/WorkflowTool/WorkflowTool.js +51 -0
  1481. package/src/tools/WorkflowTool/bundled/index.js +5 -0
  1482. package/src/tools/WorkflowTool/constants.js +1 -0
  1483. package/src/tools/WorkflowTool/createWorkflowCommand.js +5 -0
  1484. package/src/tools/shared/gitOperationTracking.js +220 -0
  1485. package/src/tools/shared/spawnMultiAgent.js +805 -0
  1486. package/src/tools/testing/TestingPermissionTool.js +72 -0
  1487. package/src/tools/utils.js +24 -0
  1488. package/src/tools.js +365 -0
  1489. package/src/types/command.js +8 -0
  1490. package/src/types/connectorText.js +3 -0
  1491. package/src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.js +673 -0
  1492. package/src/types/generated/events_mono/common/v1/auth.js +49 -0
  1493. package/src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.js +147 -0
  1494. package/src/types/generated/google/protobuf/timestamp.js +38 -0
  1495. package/src/types/hooks.js +153 -0
  1496. package/src/types/ids.js +27 -0
  1497. package/src/types/logs.js +11 -0
  1498. package/src/types/permissions.js +25 -0
  1499. package/src/types/plugin.js +72 -0
  1500. package/src/types/textInputTypes.js +20 -0
  1501. package/src/upstreamproxy/relay.js +346 -0
  1502. package/src/upstreamproxy/upstreamproxy.js +234 -0
  1503. package/src/utils/CircularBuffer.js +75 -0
  1504. package/src/utils/Cursor.js +1229 -0
  1505. package/src/utils/QueryGuard.js +115 -0
  1506. package/src/utils/Shell.js +374 -0
  1507. package/src/utils/ShellCommand.js +336 -0
  1508. package/src/utils/abortController.js +74 -0
  1509. package/src/utils/activityManager.js +127 -0
  1510. package/src/utils/advisor.js +77 -0
  1511. package/src/utils/agentContext.js +91 -0
  1512. package/src/utils/agentId.js +83 -0
  1513. package/src/utils/agentSwarmsEnabled.js +37 -0
  1514. package/src/utils/agenticSessionSearch.js +255 -0
  1515. package/src/utils/analyzeContext.js +846 -0
  1516. package/src/utils/ansiToPng.js +259 -0
  1517. package/src/utils/ansiToSvg.js +207 -0
  1518. package/src/utils/api.js +555 -0
  1519. package/src/utils/apiPreconnect.js +62 -0
  1520. package/src/utils/appleTerminalBackup.js +95 -0
  1521. package/src/utils/argumentSubstitution.js +114 -0
  1522. package/src/utils/array.js +12 -0
  1523. package/src/utils/asciicast.js +200 -0
  1524. package/src/utils/attachments.js +2518 -0
  1525. package/src/utils/attribution.js +308 -0
  1526. package/src/utils/auth.js +1598 -0
  1527. package/src/utils/authFileDescriptor.js +152 -0
  1528. package/src/utils/authPortable.js +14 -0
  1529. package/src/utils/autoModeDenials.js +15 -0
  1530. package/src/utils/autoRunIssue.js +113 -0
  1531. package/src/utils/autoUpdater.js +457 -0
  1532. package/src/utils/aws.js +44 -0
  1533. package/src/utils/awsAuthStatusManager.js +66 -0
  1534. package/src/utils/background/remote/preconditions.js +175 -0
  1535. package/src/utils/background/remote/remoteSession.js +53 -0
  1536. package/src/utils/backgroundHousekeeping.js +64 -0
  1537. package/src/utils/bash/ParsedCommand.js +241 -0
  1538. package/src/utils/bash/ShellSnapshot.js +489 -0
  1539. package/src/utils/bash/ast.js +2590 -0
  1540. package/src/utils/bash/bashParser.js +4355 -0
  1541. package/src/utils/bash/bashPipeCommand.js +249 -0
  1542. package/src/utils/bash/commands.js +1131 -0
  1543. package/src/utils/bash/heredoc.js +647 -0
  1544. package/src/utils/bash/parser.js +195 -0
  1545. package/src/utils/bash/prefix.js +154 -0
  1546. package/src/utils/bash/registry.js +23 -0
  1547. package/src/utils/bash/shellCompletion.js +196 -0
  1548. package/src/utils/bash/shellPrefix.js +25 -0
  1549. package/src/utils/bash/shellQuote.js +253 -0
  1550. package/src/utils/bash/shellQuoting.js +106 -0
  1551. package/src/utils/bash/specs/alias.js +11 -0
  1552. package/src/utils/bash/specs/index.js +16 -0
  1553. package/src/utils/bash/specs/nohup.js +10 -0
  1554. package/src/utils/bash/specs/pyright.js +88 -0
  1555. package/src/utils/bash/specs/sleep.js +10 -0
  1556. package/src/utils/bash/specs/srun.js +28 -0
  1557. package/src/utils/bash/specs/time.js +10 -0
  1558. package/src/utils/bash/specs/timeout.js +17 -0
  1559. package/src/utils/bash/treeSitterAnalysis.js +407 -0
  1560. package/src/utils/betas.js +331 -0
  1561. package/src/utils/billing.js +54 -0
  1562. package/src/utils/binaryCheck.js +40 -0
  1563. package/src/utils/browser.js +58 -0
  1564. package/src/utils/bufferedWriter.js +77 -0
  1565. package/src/utils/bundledMode.js +19 -0
  1566. package/src/utils/businessDb.js +390 -0
  1567. package/src/utils/caCerts.js +91 -0
  1568. package/src/utils/caCertsConfig.js +77 -0
  1569. package/src/utils/cachePaths.js +28 -0
  1570. package/src/utils/classifierApprovals.js +66 -0
  1571. package/src/utils/classifierApprovalsHook.js +10 -0
  1572. package/src/utils/claudeDesktop.js +108 -0
  1573. package/src/utils/claudeInChrome/chromeNativeHost.js +416 -0
  1574. package/src/utils/claudeInChrome/common.js +466 -0
  1575. package/src/utils/claudeInChrome/mcpServer.js +237 -0
  1576. package/src/utils/claudeInChrome/prompt.js +79 -0
  1577. package/src/utils/claudeInChrome/setup.js +304 -0
  1578. package/src/utils/claudeInChrome/setupPortable.js +172 -0
  1579. package/src/utils/claudeInChrome/toolRendering.js +235 -0
  1580. package/src/utils/claudemd.js +1052 -0
  1581. package/src/utils/cleanup.js +514 -0
  1582. package/src/utils/cleanupRegistry.js +22 -0
  1583. package/src/utils/cliArgs.js +53 -0
  1584. package/src/utils/cliHighlight.js +45 -0
  1585. package/src/utils/codeIndexing.js +149 -0
  1586. package/src/utils/collapseBackgroundBashNotifications.js +70 -0
  1587. package/src/utils/collapseHookSummaries.js +48 -0
  1588. package/src/utils/collapseReadSearch.js +869 -0
  1589. package/src/utils/collapseTeammateShutdowns.js +44 -0
  1590. package/src/utils/combinedAbortSignal.js +40 -0
  1591. package/src/utils/commandLifecycle.js +7 -0
  1592. package/src/utils/commitAttribution.js +718 -0
  1593. package/src/utils/completionCache.js +138 -0
  1594. package/src/utils/computerUse/appNames.js +170 -0
  1595. package/src/utils/computerUse/cleanup.js +65 -0
  1596. package/src/utils/computerUse/common.js +56 -0
  1597. package/src/utils/computerUse/computerUseLock.js +183 -0
  1598. package/src/utils/computerUse/drainRunLoop.js +71 -0
  1599. package/src/utils/computerUse/escHotkey.js +53 -0
  1600. package/src/utils/computerUse/executor.js +480 -0
  1601. package/src/utils/computerUse/gates.js +55 -0
  1602. package/src/utils/computerUse/hostAdapter.js +62 -0
  1603. package/src/utils/computerUse/inputLoader.js +25 -0
  1604. package/src/utils/computerUse/mcpServer.js +84 -0
  1605. package/src/utils/computerUse/setup.js +42 -0
  1606. package/src/utils/computerUse/swiftLoader.js +18 -0
  1607. package/src/utils/computerUse/toolRendering.js +101 -0
  1608. package/src/utils/computerUse/wrapper.js +317 -0
  1609. package/src/utils/concurrentSessions.js +179 -0
  1610. package/src/utils/config.js +1078 -0
  1611. package/src/utils/configConstants.js +18 -0
  1612. package/src/utils/contentArray.js +45 -0
  1613. package/src/utils/context.js +185 -0
  1614. package/src/utils/contextAnalysis.js +171 -0
  1615. package/src/utils/contextSuggestions.js +158 -0
  1616. package/src/utils/controlMessageCompat.js +31 -0
  1617. package/src/utils/conversationRecovery.js +434 -0
  1618. package/src/utils/cron.js +260 -0
  1619. package/src/utils/cronJitterConfig.js +62 -0
  1620. package/src/utils/cronScheduler.js +388 -0
  1621. package/src/utils/cronTasks.js +328 -0
  1622. package/src/utils/cronTasksLock.js +159 -0
  1623. package/src/utils/crossProjectResume.js +46 -0
  1624. package/src/utils/crypto.js +13 -0
  1625. package/src/utils/cwd.js +29 -0
  1626. package/src/utils/debug.js +220 -0
  1627. package/src/utils/debugFilter.js +125 -0
  1628. package/src/utils/deepLink/banner.js +103 -0
  1629. package/src/utils/deepLink/parseDeepLink.js +138 -0
  1630. package/src/utils/deepLink/protocolHandler.js +119 -0
  1631. package/src/utils/deepLink/registerProtocol.js +291 -0
  1632. package/src/utils/deepLink/terminalLauncher.js +455 -0
  1633. package/src/utils/deepLink/terminalPreference.js +51 -0
  1634. package/src/utils/desktopDeepLink.js +208 -0
  1635. package/src/utils/detectRepository.js +157 -0
  1636. package/src/utils/diagLogs.js +74 -0
  1637. package/src/utils/diff.js +108 -0
  1638. package/src/utils/directMemberMessage.js +34 -0
  1639. package/src/utils/displayTags.js +46 -0
  1640. package/src/utils/doctorContextWarnings.js +179 -0
  1641. package/src/utils/doctorDiagnostic.js +494 -0
  1642. package/src/utils/dxt/helpers.js +64 -0
  1643. package/src/utils/dxt/zip.js +167 -0
  1644. package/src/utils/earlyInput.js +166 -0
  1645. package/src/utils/editor.js +163 -0
  1646. package/src/utils/effort.js +271 -0
  1647. package/src/utils/embeddedTools.js +26 -0
  1648. package/src/utils/employeeChat.js +271 -0
  1649. package/src/utils/employeeDb.js +326 -0
  1650. package/src/utils/env.js +358 -0
  1651. package/src/utils/envDynamic.js +130 -0
  1652. package/src/utils/envUtils.js +161 -0
  1653. package/src/utils/envValidation.js +26 -0
  1654. package/src/utils/errorLogSink.js +196 -0
  1655. package/src/utils/errors.js +207 -0
  1656. package/src/utils/exampleCommands.js +165 -0
  1657. package/src/utils/execFileNoThrow.js +93 -0
  1658. package/src/utils/execFileNoThrowPortable.js +49 -0
  1659. package/src/utils/execSyncWrapper.js +6 -0
  1660. package/src/utils/exportRenderer.js +71 -0
  1661. package/src/utils/extraUsage.js +19 -0
  1662. package/src/utils/fastMode.js +393 -0
  1663. package/src/utils/file.js +467 -0
  1664. package/src/utils/fileHistory.js +851 -0
  1665. package/src/utils/fileOperationAnalytics.js +45 -0
  1666. package/src/utils/filePersistence/filePersistence.js +212 -0
  1667. package/src/utils/filePersistence/outputsScanner.js +104 -0
  1668. package/src/utils/filePersistence/types.js +4 -0
  1669. package/src/utils/fileRead.js +81 -0
  1670. package/src/utils/fileReadCache.js +78 -0
  1671. package/src/utils/fileStateCache.js +99 -0
  1672. package/src/utils/findExecutable.js +13 -0
  1673. package/src/utils/fingerprint.js +58 -0
  1674. package/src/utils/forkedAgent.js +410 -0
  1675. package/src/utils/format.js +238 -0
  1676. package/src/utils/formatBriefTimestamp.js +72 -0
  1677. package/src/utils/fpsTracker.js +34 -0
  1678. package/src/utils/frontmatterParser.js +260 -0
  1679. package/src/utils/fsOperations.js +555 -0
  1680. package/src/utils/fullscreen.js +194 -0
  1681. package/src/utils/generatedFiles.js +122 -0
  1682. package/src/utils/generators.js +67 -0
  1683. package/src/utils/genericProcessUtils.js +155 -0
  1684. package/src/utils/getWorktreePaths.js +56 -0
  1685. package/src/utils/getWorktreePathsPortable.js +23 -0
  1686. package/src/utils/ghPrStatus.js +71 -0
  1687. package/src/utils/git/gitConfigParser.js +226 -0
  1688. package/src/utils/git/gitFilesystem.js +606 -0
  1689. package/src/utils/git/gitignore.js +84 -0
  1690. package/src/utils/git.js +725 -0
  1691. package/src/utils/gitDiff.js +395 -0
  1692. package/src/utils/gitSettings.js +18 -0
  1693. package/src/utils/github/ghAuthStatus.js +23 -0
  1694. package/src/utils/githubRepoPathMapping.js +135 -0
  1695. package/src/utils/glob.js +90 -0
  1696. package/src/utils/gracefulShutdown.js +447 -0
  1697. package/src/utils/groupToolUses.js +126 -0
  1698. package/src/utils/handlePromptSubmit.js +398 -0
  1699. package/src/utils/hash.js +44 -0
  1700. package/src/utils/headlessProfiler.js +147 -0
  1701. package/src/utils/heapDumpService.js +201 -0
  1702. package/src/utils/heatmap.js +151 -0
  1703. package/src/utils/highlightMatch.js +29 -0
  1704. package/src/utils/hooks/AsyncHookRegistry.js +187 -0
  1705. package/src/utils/hooks/apiQueryHookHelper.js +77 -0
  1706. package/src/utils/hooks/execAgentHook.js +257 -0
  1707. package/src/utils/hooks/execHttpHook.js +184 -0
  1708. package/src/utils/hooks/execPromptHook.js +171 -0
  1709. package/src/utils/hooks/fileChangedWatcher.js +161 -0
  1710. package/src/utils/hooks/hookEvents.js +111 -0
  1711. package/src/utils/hooks/hookHelpers.js +60 -0
  1712. package/src/utils/hooks/hooksConfigManager.js +323 -0
  1713. package/src/utils/hooks/hooksConfigSnapshot.js +114 -0
  1714. package/src/utils/hooks/hooksSettings.js +204 -0
  1715. package/src/utils/hooks/postSamplingHooks.js +39 -0
  1716. package/src/utils/hooks/registerFrontmatterHooks.js +47 -0
  1717. package/src/utils/hooks/registerSkillHooks.js +40 -0
  1718. package/src/utils/hooks/sessionHooks.js +252 -0
  1719. package/src/utils/hooks/skillImprovement.js +211 -0
  1720. package/src/utils/hooks/ssrfGuard.js +258 -0
  1721. package/src/utils/hooks.js +3668 -0
  1722. package/src/utils/horizontalScroll.js +108 -0
  1723. package/src/utils/http.js +120 -0
  1724. package/src/utils/hyperlink.js +28 -0
  1725. package/src/utils/iTermBackup.js +48 -0
  1726. package/src/utils/ide.js +1195 -0
  1727. package/src/utils/idePathConversion.js +66 -0
  1728. package/src/utils/idleTimeout.js +44 -0
  1729. package/src/utils/imagePaste.js +343 -0
  1730. package/src/utils/imageResizer.js +664 -0
  1731. package/src/utils/imageStore.js +150 -0
  1732. package/src/utils/imageValidation.js +92 -0
  1733. package/src/utils/immediateCommand.js +12 -0
  1734. package/src/utils/inProcessTeammateHelpers.js +71 -0
  1735. package/src/utils/ink.js +20 -0
  1736. package/src/utils/intl.js +83 -0
  1737. package/src/utils/jetbrains.js +152 -0
  1738. package/src/utils/json.js +231 -0
  1739. package/src/utils/jsonRead.js +14 -0
  1740. package/src/utils/keyboardShortcuts.js +11 -0
  1741. package/src/utils/lazySchema.js +8 -0
  1742. package/src/utils/listSessionsImpl.js +332 -0
  1743. package/src/utils/localInstaller.js +130 -0
  1744. package/src/utils/lockfile.js +30 -0
  1745. package/src/utils/log.js +280 -0
  1746. package/src/utils/logoV2Utils.js +256 -0
  1747. package/src/utils/mailbox.js +50 -0
  1748. package/src/utils/managedEnv.js +160 -0
  1749. package/src/utils/managedEnvConstants.js +185 -0
  1750. package/src/utils/markdown.js +315 -0
  1751. package/src/utils/markdownConfigLoader.js +480 -0
  1752. package/src/utils/mcp/dateTimeParser.js +102 -0
  1753. package/src/utils/mcp/elicitationValidation.js +259 -0
  1754. package/src/utils/mcpInstructionsDelta.js +97 -0
  1755. package/src/utils/mcpOutputStorage.js +159 -0
  1756. package/src/utils/mcpValidation.js +165 -0
  1757. package/src/utils/mcpWebSocketTransport.js +180 -0
  1758. package/src/utils/memoize.js +205 -0
  1759. package/src/utils/memory/types.js +9 -0
  1760. package/src/utils/memory/versions.js +7 -0
  1761. package/src/utils/memoryFileDetection.js +245 -0
  1762. package/src/utils/messagePredicates.js +6 -0
  1763. package/src/utils/messageQueueManager.js +430 -0
  1764. package/src/utils/messages/mappers.js +240 -0
  1765. package/src/utils/messages/systemInit.js +72 -0
  1766. package/src/utils/messages.js +4286 -0
  1767. package/src/utils/model/agent.js +128 -0
  1768. package/src/utils/model/aliases.js +21 -0
  1769. package/src/utils/model/antModels.js +25 -0
  1770. package/src/utils/model/bedrock.js +220 -0
  1771. package/src/utils/model/check1mAccess.js +64 -0
  1772. package/src/utils/model/configs.js +86 -0
  1773. package/src/utils/model/contextWindowUpgradeCheck.js +41 -0
  1774. package/src/utils/model/deprecation.js +72 -0
  1775. package/src/utils/model/model.js +533 -0
  1776. package/src/utils/model/modelAllowlist.js +148 -0
  1777. package/src/utils/model/modelCapabilities.js +105 -0
  1778. package/src/utils/model/modelOptions.js +450 -0
  1779. package/src/utils/model/modelStrings.js +144 -0
  1780. package/src/utils/model/modelSupportOverrides.js +40 -0
  1781. package/src/utils/model/providers.js +35 -0
  1782. package/src/utils/model/validateModel.js +131 -0
  1783. package/src/utils/modelCost.js +160 -0
  1784. package/src/utils/modifiers.js +39 -0
  1785. package/src/utils/mtls.js +132 -0
  1786. package/src/utils/nativeInstaller/download.js +370 -0
  1787. package/src/utils/nativeInstaller/index.js +8 -0
  1788. package/src/utils/nativeInstaller/installer.js +1395 -0
  1789. package/src/utils/nativeInstaller/packageManagers.js +258 -0
  1790. package/src/utils/nativeInstaller/pidLock.js +347 -0
  1791. package/src/utils/notebook.js +176 -0
  1792. package/src/utils/objectGroupBy.js +15 -0
  1793. package/src/utils/pasteStore.js +93 -0
  1794. package/src/utils/path.js +140 -0
  1795. package/src/utils/pdf.js +236 -0
  1796. package/src/utils/pdfUtils.js +61 -0
  1797. package/src/utils/peerAddress.js +20 -0
  1798. package/src/utils/permissions/PermissionMode.js +95 -0
  1799. package/src/utils/permissions/PermissionPromptToolResultSchema.js +85 -0
  1800. package/src/utils/permissions/PermissionResult.js +11 -0
  1801. package/src/utils/permissions/PermissionRule.js +19 -0
  1802. package/src/utils/permissions/PermissionUpdate.js +268 -0
  1803. package/src/utils/permissions/PermissionUpdateSchema.js +61 -0
  1804. package/src/utils/permissions/autoModeState.js +31 -0
  1805. package/src/utils/permissions/bashClassifier.js +30 -0
  1806. package/src/utils/permissions/bypassPermissionsKillswitch.js +115 -0
  1807. package/src/utils/permissions/classifierDecision.js +86 -0
  1808. package/src/utils/permissions/classifierShared.js +28 -0
  1809. package/src/utils/permissions/dangerousPatterns.js +78 -0
  1810. package/src/utils/permissions/denialTracking.js +34 -0
  1811. package/src/utils/permissions/filesystem.js +1411 -0
  1812. package/src/utils/permissions/getNextPermissionMode.js +74 -0
  1813. package/src/utils/permissions/pathValidation.js +351 -0
  1814. package/src/utils/permissions/permissionExplainer.js +188 -0
  1815. package/src/utils/permissions/permissionRuleParser.js +175 -0
  1816. package/src/utils/permissions/permissionSetup.js +1162 -0
  1817. package/src/utils/permissions/permissions.js +1063 -0
  1818. package/src/utils/permissions/permissionsLoader.js +217 -0
  1819. package/src/utils/permissions/shadowedRuleDetection.js +149 -0
  1820. package/src/utils/permissions/shellRuleMatching.js +174 -0
  1821. package/src/utils/permissions/yoloClassifier.js +1193 -0
  1822. package/src/utils/planModeV2.js +75 -0
  1823. package/src/utils/plans.js +334 -0
  1824. package/src/utils/platform.js +122 -0
  1825. package/src/utils/plugins/addDirPluginSettings.js +53 -0
  1826. package/src/utils/plugins/cacheUtils.js +174 -0
  1827. package/src/utils/plugins/dependencyResolver.js +244 -0
  1828. package/src/utils/plugins/fetchTelemetry.js +108 -0
  1829. package/src/utils/plugins/gitAvailability.js +65 -0
  1830. package/src/utils/plugins/headlessPluginInstall.js +136 -0
  1831. package/src/utils/plugins/hintRecommendation.js +136 -0
  1832. package/src/utils/plugins/installCounts.js +221 -0
  1833. package/src/utils/plugins/installedPluginsManager.js +1003 -0
  1834. package/src/utils/plugins/loadPluginAgents.js +219 -0
  1835. package/src/utils/plugins/loadPluginCommands.js +595 -0
  1836. package/src/utils/plugins/loadPluginHooks.js +239 -0
  1837. package/src/utils/plugins/loadPluginOutputStyles.js +112 -0
  1838. package/src/utils/plugins/lspPluginIntegration.js +293 -0
  1839. package/src/utils/plugins/lspRecommendation.js +278 -0
  1840. package/src/utils/plugins/managedPlugins.js +26 -0
  1841. package/src/utils/plugins/marketplaceHelpers.js +470 -0
  1842. package/src/utils/plugins/marketplaceManager.js +1939 -0
  1843. package/src/utils/plugins/mcpPluginIntegration.js +465 -0
  1844. package/src/utils/plugins/mcpbHandler.js +708 -0
  1845. package/src/utils/plugins/officialMarketplace.js +19 -0
  1846. package/src/utils/plugins/officialMarketplaceGcs.js +202 -0
  1847. package/src/utils/plugins/officialMarketplaceStartupCheck.js +344 -0
  1848. package/src/utils/plugins/orphanedPluginFilter.js +96 -0
  1849. package/src/utils/plugins/parseMarketplaceInput.js +143 -0
  1850. package/src/utils/plugins/performStartupChecks.js +66 -0
  1851. package/src/utils/plugins/pluginAutoupdate.js +210 -0
  1852. package/src/utils/plugins/pluginBlocklist.js +93 -0
  1853. package/src/utils/plugins/pluginDirectories.js +170 -0
  1854. package/src/utils/plugins/pluginFlagging.js +173 -0
  1855. package/src/utils/plugins/pluginIdentifier.js +78 -0
  1856. package/src/utils/plugins/pluginInstallationHelpers.js +400 -0
  1857. package/src/utils/plugins/pluginLoader.js +2426 -0
  1858. package/src/utils/plugins/pluginOptionsStorage.js +311 -0
  1859. package/src/utils/plugins/pluginPolicy.js +18 -0
  1860. package/src/utils/plugins/pluginStartupCheck.js +261 -0
  1861. package/src/utils/plugins/pluginVersioning.js +128 -0
  1862. package/src/utils/plugins/reconciler.js +181 -0
  1863. package/src/utils/plugins/refresh.js +162 -0
  1864. package/src/utils/plugins/schemas.js +1283 -0
  1865. package/src/utils/plugins/validatePlugin.js +765 -0
  1866. package/src/utils/plugins/walkPluginMarkdown.js +49 -0
  1867. package/src/utils/plugins/zipCache.js +346 -0
  1868. package/src/utils/plugins/zipCacheAdapters.js +133 -0
  1869. package/src/utils/powershell/dangerousCmdlets.js +174 -0
  1870. package/src/utils/powershell/parser.js +1357 -0
  1871. package/src/utils/powershell/staticPrefix.js +277 -0
  1872. package/src/utils/preflightChecks.js +147 -0
  1873. package/src/utils/privacyLevel.js +49 -0
  1874. package/src/utils/process.js +56 -0
  1875. package/src/utils/processUserInput/processBashCommand.js +118 -0
  1876. package/src/utils/processUserInput/processSlashCommand.js +845 -0
  1877. package/src/utils/processUserInput/processTextPrompt.js +68 -0
  1878. package/src/utils/processUserInput/processUserInput.js +344 -0
  1879. package/src/utils/profilerBase.js +32 -0
  1880. package/src/utils/promptCategory.js +39 -0
  1881. package/src/utils/promptEditor.js +151 -0
  1882. package/src/utils/promptShellExecution.js +117 -0
  1883. package/src/utils/protectedNamespace.js +4 -0
  1884. package/src/utils/proxy.js +345 -0
  1885. package/src/utils/queryContext.js +110 -0
  1886. package/src/utils/queryHelpers.js +436 -0
  1887. package/src/utils/queryProfiler.js +242 -0
  1888. package/src/utils/queueProcessor.js +70 -0
  1889. package/src/utils/readEditContext.js +176 -0
  1890. package/src/utils/readFileInRange.js +278 -0
  1891. package/src/utils/releaseNotes.js +307 -0
  1892. package/src/utils/renderOptions.js +67 -0
  1893. package/src/utils/ripgrep.js +521 -0
  1894. package/src/utils/sandbox/sandbox-adapter.js +750 -0
  1895. package/src/utils/sandbox/sandbox-ui-utils.js +11 -0
  1896. package/src/utils/sanitization.js +72 -0
  1897. package/src/utils/screenshotClipboard.js +89 -0
  1898. package/src/utils/sdkEventQueue.js +49 -0
  1899. package/src/utils/secureStorage/fallbackStorage.js +59 -0
  1900. package/src/utils/secureStorage/index.js +13 -0
  1901. package/src/utils/secureStorage/keychainPrefetch.js +91 -0
  1902. package/src/utils/secureStorage/macOsKeychainHelpers.js +91 -0
  1903. package/src/utils/secureStorage/macOsKeychainStorage.js +192 -0
  1904. package/src/utils/secureStorage/plainTextStorage.js +81 -0
  1905. package/src/utils/semanticBoolean.js +23 -0
  1906. package/src/utils/semanticNumber.js +34 -0
  1907. package/src/utils/semver.js +51 -0
  1908. package/src/utils/sequential.js +43 -0
  1909. package/src/utils/sessionActivity.js +120 -0
  1910. package/src/utils/sessionEnvVars.js +18 -0
  1911. package/src/utils/sessionEnvironment.js +131 -0
  1912. package/src/utils/sessionFileAccessHooks.js +205 -0
  1913. package/src/utils/sessionIngressAuth.js +113 -0
  1914. package/src/utils/sessionRestore.js +357 -0
  1915. package/src/utils/sessionStart.js +165 -0
  1916. package/src/utils/sessionState.js +76 -0
  1917. package/src/utils/sessionStorage.js +4162 -0
  1918. package/src/utils/sessionStoragePortable.js +665 -0
  1919. package/src/utils/sessionTitle.js +120 -0
  1920. package/src/utils/sessionUrl.js +50 -0
  1921. package/src/utils/set.js +50 -0
  1922. package/src/utils/settings/allErrors.js +29 -0
  1923. package/src/utils/settings/applySettingsChange.js +65 -0
  1924. package/src/utils/settings/changeDetector.js +409 -0
  1925. package/src/utils/settings/constants.js +166 -0
  1926. package/src/utils/settings/internalWrites.js +33 -0
  1927. package/src/utils/settings/managedPath.js +29 -0
  1928. package/src/utils/settings/mdm/constants.js +62 -0
  1929. package/src/utils/settings/mdm/rawRead.js +97 -0
  1930. package/src/utils/settings/mdm/settings.js +254 -0
  1931. package/src/utils/settings/permissionValidation.js +224 -0
  1932. package/src/utils/settings/pluginOnlyPolicy.js +53 -0
  1933. package/src/utils/settings/schemaOutput.js +7 -0
  1934. package/src/utils/settings/settings.js +791 -0
  1935. package/src/utils/settings/settingsCache.js +47 -0
  1936. package/src/utils/settings/toolValidationConfig.js +76 -0
  1937. package/src/utils/settings/types.js +846 -0
  1938. package/src/utils/settings/validateEditTool.js +34 -0
  1939. package/src/utils/settings/validation.js +192 -0
  1940. package/src/utils/settings/validationTips.js +111 -0
  1941. package/src/utils/shell/bashProvider.js +202 -0
  1942. package/src/utils/shell/outputLimits.js +7 -0
  1943. package/src/utils/shell/powershellDetection.js +96 -0
  1944. package/src/utils/shell/powershellProvider.js +104 -0
  1945. package/src/utils/shell/prefix.js +246 -0
  1946. package/src/utils/shell/readOnlyCommandValidation.js +1776 -0
  1947. package/src/utils/shell/resolveDefaultShell.js +13 -0
  1948. package/src/utils/shell/shellProvider.js +2 -0
  1949. package/src/utils/shell/shellToolUtils.js +21 -0
  1950. package/src/utils/shell/specPrefix.js +198 -0
  1951. package/src/utils/shellConfig.js +136 -0
  1952. package/src/utils/sideQuery.js +134 -0
  1953. package/src/utils/sideQuestion.js +121 -0
  1954. package/src/utils/signal.js +34 -0
  1955. package/src/utils/sinks.js +15 -0
  1956. package/src/utils/skills/skillChangeDetector.js +264 -0
  1957. package/src/utils/slashCommandParsing.js +46 -0
  1958. package/src/utils/sleep.js +72 -0
  1959. package/src/utils/sliceAnsi.js +74 -0
  1960. package/src/utils/slowOperations.js +216 -0
  1961. package/src/utils/standaloneAgent.js +20 -0
  1962. package/src/utils/startupProfiler.js +149 -0
  1963. package/src/utils/staticRender.js +104 -0
  1964. package/src/utils/stats.js +802 -0
  1965. package/src/utils/statsCache.js +330 -0
  1966. package/src/utils/status.js +359 -0
  1967. package/src/utils/statusNoticeDefinitions.js +123 -0
  1968. package/src/utils/statusNoticeHelpers.js +15 -0
  1969. package/src/utils/stream.js +73 -0
  1970. package/src/utils/streamJsonStdoutGuard.js +107 -0
  1971. package/src/utils/streamlinedTransform.js +162 -0
  1972. package/src/utils/stringUtils.js +202 -0
  1973. package/src/utils/subprocessEnv.js +87 -0
  1974. package/src/utils/suggestions/commandSuggestions.js +458 -0
  1975. package/src/utils/suggestions/directoryCompletion.js +191 -0
  1976. package/src/utils/suggestions/shellHistoryCompletion.js +95 -0
  1977. package/src/utils/suggestions/skillUsageTracking.js +50 -0
  1978. package/src/utils/suggestions/slackChannelSuggestions.js +169 -0
  1979. package/src/utils/swarm/It2SetupPrompt.js +386 -0
  1980. package/src/utils/swarm/backends/ITermBackend.js +276 -0
  1981. package/src/utils/swarm/backends/InProcessBackend.js +237 -0
  1982. package/src/utils/swarm/backends/PaneBackendExecutor.js +250 -0
  1983. package/src/utils/swarm/backends/TmuxBackend.js +574 -0
  1984. package/src/utils/swarm/backends/detection.js +112 -0
  1985. package/src/utils/swarm/backends/it2Setup.js +185 -0
  1986. package/src/utils/swarm/backends/registry.js +369 -0
  1987. package/src/utils/swarm/backends/teammateModeSnapshot.js +68 -0
  1988. package/src/utils/swarm/backends/types.js +9 -0
  1989. package/src/utils/swarm/constants.js +29 -0
  1990. package/src/utils/swarm/inProcessRunner.js +1021 -0
  1991. package/src/utils/swarm/leaderPermissionBridge.js +31 -0
  1992. package/src/utils/swarm/permissionSync.js +667 -0
  1993. package/src/utils/swarm/reconnection.js +82 -0
  1994. package/src/utils/swarm/spawnInProcess.js +218 -0
  1995. package/src/utils/swarm/spawnUtils.js +123 -0
  1996. package/src/utils/swarm/teamHelpers.js +484 -0
  1997. package/src/utils/swarm/teammateInit.js +87 -0
  1998. package/src/utils/swarm/teammateLayoutManager.js +82 -0
  1999. package/src/utils/swarm/teammateModel.js +9 -0
  2000. package/src/utils/swarm/teammatePromptAddendum.js +17 -0
  2001. package/src/utils/systemDirectories.js +51 -0
  2002. package/src/utils/systemPrompt.js +88 -0
  2003. package/src/utils/systemPromptType.js +9 -0
  2004. package/src/utils/systemTheme.js +108 -0
  2005. package/src/utils/taggedId.js +49 -0
  2006. package/src/utils/task/TaskOutput.js +320 -0
  2007. package/src/utils/task/diskOutput.js +387 -0
  2008. package/src/utils/task/framework.js +236 -0
  2009. package/src/utils/task/outputFormatting.js +24 -0
  2010. package/src/utils/task/sdkProgress.js +24 -0
  2011. package/src/utils/taskSummary.js +3 -0
  2012. package/src/utils/tasks.js +672 -0
  2013. package/src/utils/teamDiscovery.js +48 -0
  2014. package/src/utils/teamMemoryOps.js +67 -0
  2015. package/src/utils/teammate.js +237 -0
  2016. package/src/utils/teammateContext.js +56 -0
  2017. package/src/utils/teammateMailbox.js +793 -0
  2018. package/src/utils/telemetry/betaSessionTracing.js +25 -0
  2019. package/src/utils/telemetry/bigqueryExporter.js +17 -0
  2020. package/src/utils/telemetry/events.js +7 -0
  2021. package/src/utils/telemetry/instrumentation.js +16 -0
  2022. package/src/utils/telemetry/logger.js +25 -0
  2023. package/src/utils/telemetry/perfettoTracing.js +882 -0
  2024. package/src/utils/telemetry/pluginTelemetry.js +76 -0
  2025. package/src/utils/telemetry/sessionTracing.js +62 -0
  2026. package/src/utils/telemetry/skillLoadedEvent.js +4 -0
  2027. package/src/utils/telemetryAttributes.js +56 -0
  2028. package/src/utils/teleport/api.js +299 -0
  2029. package/src/utils/teleport/environmentSelection.js +55 -0
  2030. package/src/utils/teleport/environments.js +84 -0
  2031. package/src/utils/teleport/gitBundle.js +192 -0
  2032. package/src/utils/teleport.js +1047 -0
  2033. package/src/utils/tempfile.js +26 -0
  2034. package/src/utils/terminal.js +105 -0
  2035. package/src/utils/terminalPanel.js +155 -0
  2036. package/src/utils/textHighlighting.js +113 -0
  2037. package/src/utils/thaddeusHints.js +142 -0
  2038. package/src/utils/theme.js +525 -0
  2039. package/src/utils/thinking.js +130 -0
  2040. package/src/utils/timeouts.js +35 -0
  2041. package/src/utils/tmuxSocket.js +373 -0
  2042. package/src/utils/todo/types.js +9 -0
  2043. package/src/utils/tokenBudget.js +62 -0
  2044. package/src/utils/tokens.js +223 -0
  2045. package/src/utils/toolErrors.js +101 -0
  2046. package/src/utils/toolPool.js +61 -0
  2047. package/src/utils/toolResultStorage.js +768 -0
  2048. package/src/utils/toolSchemaCache.js +7 -0
  2049. package/src/utils/toolSearch.js +551 -0
  2050. package/src/utils/transcriptSearch.js +200 -0
  2051. package/src/utils/treeify.js +111 -0
  2052. package/src/utils/truncate.js +164 -0
  2053. package/src/utils/udsClient.js +5 -0
  2054. package/src/utils/udsMessaging.js +23 -0
  2055. package/src/utils/ultraplan/ccrSession.js +264 -0
  2056. package/src/utils/ultraplan/keyword.js +122 -0
  2057. package/src/utils/unaryLogging.js +16 -0
  2058. package/src/utils/undercover.js +89 -0
  2059. package/src/utils/user.js +137 -0
  2060. package/src/utils/userAgent.js +9 -0
  2061. package/src/utils/userPromptKeywords.js +21 -0
  2062. package/src/utils/uuid.js +22 -0
  2063. package/src/utils/warningHandler.js +97 -0
  2064. package/src/utils/which.js +75 -0
  2065. package/src/utils/windowsPaths.js +146 -0
  2066. package/src/utils/withResolvers.js +13 -0
  2067. package/src/utils/words.js +793 -0
  2068. package/src/utils/workforceIntent.js +192 -0
  2069. package/src/utils/workloadContext.js +42 -0
  2070. package/src/utils/worktree.js +1142 -0
  2071. package/src/utils/worktreeModeEnabled.js +11 -0
  2072. package/src/utils/xdg.js +52 -0
  2073. package/src/utils/xml.js +15 -0
  2074. package/src/utils/yaml.js +14 -0
  2075. package/src/utils/zodToJsonSchema.js +19 -0
  2076. package/src/vim/motions.js +73 -0
  2077. package/src/vim/operators.js +401 -0
  2078. package/src/vim/textObjects.js +153 -0
  2079. package/src/vim/transitions.js +340 -0
  2080. package/src/vim/types.js +93 -0
  2081. package/src/voice/voiceModeEnabled.js +20 -0
  2082. package/thaddeus-terminal.ts +401 -3
@@ -0,0 +1,2554 @@
1
+ import { execFileSync } from 'child_process';
2
+ import { diffLines } from 'diff';
3
+ import { constants as fsConstants } from 'fs';
4
+ import { copyFile, mkdir, mkdtemp, readdir, readFile, rm, unlink, writeFile, } from 'fs/promises';
5
+ import { tmpdir } from 'os';
6
+ import { extname, join } from 'path';
7
+ import { queryWithModel } from '../services/api/claude.js';
8
+ import { AGENT_TOOL_NAME, LEGACY_AGENT_TOOL_NAME, } from '../tools/AgentTool/constants.js';
9
+ import { getClaudeConfigHomeDir } from '../utils/envUtils.js';
10
+ import { toError } from '../utils/errors.js';
11
+ import { execFileNoThrow } from '../utils/execFileNoThrow.js';
12
+ import { logError } from '../utils/log.js';
13
+ import { extractTextContent } from '../utils/messages.js';
14
+ import { getDefaultOpusModel } from '../utils/model/model.js';
15
+ import { getProjectsDir, getSessionFilesWithMtime, getSessionIdFromLog, loadAllLogsFromSessionFile, } from '../utils/sessionStorage.js';
16
+ import { jsonParse, jsonStringify } from '../utils/slowOperations.js';
17
+ import { countCharInString } from '../utils/stringUtils.js';
18
+ import { asSystemPrompt } from '../utils/systemPromptType.js';
19
+ import { escapeXmlAttr as escapeHtml } from '../utils/xml.js';
20
+ // Model for facet extraction and summarization (Opus - best quality)
21
+ function getAnalysisModel() {
22
+ return getDefaultOpusModel();
23
+ }
24
+ // Model for narrative insights (Opus - best quality)
25
+ function getInsightsModel() {
26
+ return getDefaultOpusModel();
27
+ }
28
+ /* eslint-disable custom-rules/no-process-env-top-level */
29
+ const getRunningRemoteHosts = process.env.USER_TYPE === 'ant'
30
+ ? async () => {
31
+ const { stdout, code } = await execFileNoThrow('coder', ['list', '-o', 'json'], { timeout: 30000 });
32
+ if (code !== 0)
33
+ return [];
34
+ try {
35
+ const workspaces = jsonParse(stdout);
36
+ return workspaces
37
+ .filter(w => w.latest_build?.status === 'running')
38
+ .map(w => w.name);
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ }
44
+ : async () => [];
45
+ const getRemoteHostSessionCount = process.env.USER_TYPE === 'ant'
46
+ ? async (homespace) => {
47
+ const { stdout, code } = await execFileNoThrow('ssh', [
48
+ `${homespace}.coder`,
49
+ 'find /root/.claude/projects -name "*.jsonl" 2>/dev/null | wc -l',
50
+ ], { timeout: 30000 });
51
+ if (code !== 0)
52
+ return 0;
53
+ return parseInt(stdout.trim(), 10) || 0;
54
+ }
55
+ : async () => 0;
56
+ const collectFromRemoteHost = process.env.USER_TYPE === 'ant'
57
+ ? async (homespace, destDir) => {
58
+ const result = { copied: 0, skipped: 0 };
59
+ // Create temp directory
60
+ const tempDir = await mkdtemp(join(tmpdir(), 'claude-hs-'));
61
+ try {
62
+ // SCP the projects folder
63
+ const scpResult = await execFileNoThrow('scp', ['-rq', `${homespace}.coder:/root/.claude/projects/`, tempDir], { timeout: 300000 });
64
+ if (scpResult.code !== 0) {
65
+ // SCP failed
66
+ return result;
67
+ }
68
+ const projectsDir = join(tempDir, 'projects');
69
+ let projectDirents;
70
+ try {
71
+ projectDirents = await readdir(projectsDir, { withFileTypes: true });
72
+ }
73
+ catch {
74
+ return result;
75
+ }
76
+ // Merge into destination (parallel per project directory)
77
+ await Promise.all(projectDirents.map(async (dirent) => {
78
+ const projectName = dirent.name;
79
+ const projectPath = join(projectsDir, projectName);
80
+ // Skip if not a directory
81
+ if (!dirent.isDirectory())
82
+ return;
83
+ const destProjectName = `${projectName}__${homespace}`;
84
+ const destProjectPath = join(destDir, destProjectName);
85
+ try {
86
+ await mkdir(destProjectPath, { recursive: true });
87
+ }
88
+ catch {
89
+ // Directory may already exist
90
+ }
91
+ // Copy session files (skip existing)
92
+ let files;
93
+ try {
94
+ files = await readdir(projectPath, { withFileTypes: true });
95
+ }
96
+ catch {
97
+ return;
98
+ }
99
+ await Promise.all(files.map(async (fileDirent) => {
100
+ const fileName = fileDirent.name;
101
+ if (!fileName.endsWith('.jsonl'))
102
+ return;
103
+ const srcFile = join(projectPath, fileName);
104
+ const destFile = join(destProjectPath, fileName);
105
+ try {
106
+ await copyFile(srcFile, destFile, fsConstants.COPYFILE_EXCL);
107
+ result.copied++;
108
+ }
109
+ catch {
110
+ // EEXIST from COPYFILE_EXCL means dest already exists
111
+ result.skipped++;
112
+ }
113
+ }));
114
+ }));
115
+ }
116
+ finally {
117
+ try {
118
+ await rm(tempDir, { recursive: true, force: true });
119
+ }
120
+ catch {
121
+ // Ignore cleanup errors
122
+ }
123
+ }
124
+ return result;
125
+ }
126
+ : async () => ({ copied: 0, skipped: 0 });
127
+ const collectAllRemoteHostData = process.env.USER_TYPE === 'ant'
128
+ ? async (destDir) => {
129
+ const rHosts = await getRunningRemoteHosts();
130
+ const result = [];
131
+ let totalCopied = 0;
132
+ let totalSkipped = 0;
133
+ // Collect from all hosts in parallel (SCP per host can take seconds)
134
+ const hostResults = await Promise.all(rHosts.map(async (hs) => {
135
+ const sessionCount = await getRemoteHostSessionCount(hs);
136
+ if (sessionCount > 0) {
137
+ const { copied, skipped } = await collectFromRemoteHost(hs, destDir);
138
+ return { name: hs, sessionCount, copied, skipped };
139
+ }
140
+ return { name: hs, sessionCount, copied: 0, skipped: 0 };
141
+ }));
142
+ for (const hr of hostResults) {
143
+ result.push({ name: hr.name, sessionCount: hr.sessionCount });
144
+ totalCopied += hr.copied;
145
+ totalSkipped += hr.skipped;
146
+ }
147
+ return { hosts: result, totalCopied, totalSkipped };
148
+ }
149
+ : async () => ({ hosts: [], totalCopied: 0, totalSkipped: 0 });
150
+ // ============================================================================
151
+ // Constants
152
+ // ============================================================================
153
+ const EXTENSION_TO_LANGUAGE = {
154
+ '.ts': 'TypeScript',
155
+ '.tsx': 'TypeScript',
156
+ '.js': 'JavaScript',
157
+ '.jsx': 'JavaScript',
158
+ '.py': 'Python',
159
+ '.rb': 'Ruby',
160
+ '.go': 'Go',
161
+ '.rs': 'Rust',
162
+ '.java': 'Java',
163
+ '.md': 'Markdown',
164
+ '.json': 'JSON',
165
+ '.yaml': 'YAML',
166
+ '.yml': 'YAML',
167
+ '.sh': 'Shell',
168
+ '.css': 'CSS',
169
+ '.html': 'HTML',
170
+ };
171
+ // Label map for cleaning up category names (matching Python reference)
172
+ const LABEL_MAP = {
173
+ // Goal categories
174
+ debug_investigate: 'Debug/Investigate',
175
+ implement_feature: 'Implement Feature',
176
+ fix_bug: 'Fix Bug',
177
+ write_script_tool: 'Write Script/Tool',
178
+ refactor_code: 'Refactor Code',
179
+ configure_system: 'Configure System',
180
+ create_pr_commit: 'Create PR/Commit',
181
+ analyze_data: 'Analyze Data',
182
+ understand_codebase: 'Understand Codebase',
183
+ write_tests: 'Write Tests',
184
+ write_docs: 'Write Docs',
185
+ deploy_infra: 'Deploy/Infra',
186
+ warmup_minimal: 'Cache Warmup',
187
+ // Success factors
188
+ fast_accurate_search: 'Fast/Accurate Search',
189
+ correct_code_edits: 'Correct Code Edits',
190
+ good_explanations: 'Good Explanations',
191
+ proactive_help: 'Proactive Help',
192
+ multi_file_changes: 'Multi-file Changes',
193
+ handled_complexity: 'Multi-file Changes',
194
+ good_debugging: 'Good Debugging',
195
+ // Friction types
196
+ misunderstood_request: 'Misunderstood Request',
197
+ wrong_approach: 'Wrong Approach',
198
+ buggy_code: 'Buggy Code',
199
+ user_rejected_action: 'User Rejected Action',
200
+ claude_got_blocked: 'Thaddeus Got Blocked',
201
+ user_stopped_early: 'User Stopped Early',
202
+ wrong_file_or_location: 'Wrong File/Location',
203
+ excessive_changes: 'Excessive Changes',
204
+ slow_or_verbose: 'Slow/Verbose',
205
+ tool_failed: 'Tool Failed',
206
+ user_unclear: 'User Unclear',
207
+ external_issue: 'External Issue',
208
+ // Satisfaction labels
209
+ frustrated: 'Frustrated',
210
+ dissatisfied: 'Dissatisfied',
211
+ likely_satisfied: 'Likely Satisfied',
212
+ satisfied: 'Satisfied',
213
+ happy: 'Happy',
214
+ unsure: 'Unsure',
215
+ neutral: 'Neutral',
216
+ delighted: 'Delighted',
217
+ // Session types
218
+ single_task: 'Single Task',
219
+ multi_task: 'Multi Task',
220
+ iterative_refinement: 'Iterative Refinement',
221
+ exploration: 'Exploration',
222
+ quick_question: 'Quick Question',
223
+ // Outcomes
224
+ fully_achieved: 'Fully Achieved',
225
+ mostly_achieved: 'Mostly Achieved',
226
+ partially_achieved: 'Partially Achieved',
227
+ not_achieved: 'Not Achieved',
228
+ unclear_from_transcript: 'Unclear',
229
+ // Helpfulness
230
+ unhelpful: 'Unhelpful',
231
+ slightly_helpful: 'Slightly Helpful',
232
+ moderately_helpful: 'Moderately Helpful',
233
+ very_helpful: 'Very Helpful',
234
+ essential: 'Essential',
235
+ };
236
+ // Lazy getters: getClaudeConfigHomeDir() is memoized and reads process.env.
237
+ // Calling it at module scope would populate the memoize cache before
238
+ // entrypoints can set CLAUDE_CONFIG_DIR, breaking all 150+ other callers.
239
+ function getDataDir() {
240
+ return join(getClaudeConfigHomeDir(), 'usage-data');
241
+ }
242
+ function getFacetsDir() {
243
+ return join(getDataDir(), 'facets');
244
+ }
245
+ function getSessionMetaDir() {
246
+ return join(getDataDir(), 'session-meta');
247
+ }
248
+ const FACET_EXTRACTION_PROMPT = `Analyze this Thaddeus session and extract structured facets.
249
+
250
+ CRITICAL GUIDELINES:
251
+
252
+ 1. **goal_categories**: Count ONLY what the USER explicitly asked for.
253
+ - DO NOT count Thaddeus's autonomous codebase exploration
254
+ - DO NOT count work Thaddeus decided to do on its own
255
+ - ONLY count when user says "can you...", "please...", "I need...", "let's..."
256
+
257
+ 2. **user_satisfaction_counts**: Base ONLY on explicit user signals.
258
+ - "Yay!", "great!", "perfect!" → happy
259
+ - "thanks", "looks good", "that works" → satisfied
260
+ - "ok, now let's..." (continuing without complaint) → likely_satisfied
261
+ - "that's not right", "try again" → dissatisfied
262
+ - "this is broken", "I give up" → frustrated
263
+
264
+ 3. **friction_counts**: Be specific about what went wrong.
265
+ - misunderstood_request: Thaddeus interpreted incorrectly
266
+ - wrong_approach: Right goal, wrong solution method
267
+ - buggy_code: Code didn't work correctly
268
+ - user_rejected_action: User said no/stop to a tool call
269
+ - excessive_changes: Over-engineered or changed too much
270
+
271
+ 4. If very short or just warmup, use warmup_minimal for goal_category
272
+
273
+ SESSION:
274
+ `;
275
+ // ============================================================================
276
+ // Helper Functions
277
+ // ============================================================================
278
+ function getLanguageFromPath(filePath) {
279
+ const ext = extname(filePath).toLowerCase();
280
+ return EXTENSION_TO_LANGUAGE[ext] || null;
281
+ }
282
+ function extractToolStats(log) {
283
+ const toolCounts = {};
284
+ const languages = {};
285
+ let gitCommits = 0;
286
+ let gitPushes = 0;
287
+ let inputTokens = 0;
288
+ let outputTokens = 0;
289
+ // New stats
290
+ let userInterruptions = 0;
291
+ const userResponseTimes = [];
292
+ let toolErrors = 0;
293
+ const toolErrorCategories = {};
294
+ let usesTaskAgent = false;
295
+ // Additional stats
296
+ let linesAdded = 0;
297
+ let linesRemoved = 0;
298
+ const filesModified = new Set();
299
+ const messageHours = [];
300
+ const userMessageTimestamps = []; // For multi-clauding detection
301
+ let usesMcp = false;
302
+ let usesWebSearch = false;
303
+ let usesWebFetch = false;
304
+ let lastAssistantTimestamp = null;
305
+ for (const msg of log.messages) {
306
+ // Get message timestamp for response time calculation
307
+ const msgTimestamp = msg.timestamp;
308
+ if (msg.type === 'assistant' && msg.message) {
309
+ // Track timestamp for response time calculation
310
+ if (msgTimestamp) {
311
+ lastAssistantTimestamp = msgTimestamp;
312
+ }
313
+ const usage = msg.message.usage;
314
+ if (usage) {
315
+ inputTokens += usage.input_tokens || 0;
316
+ outputTokens += usage.output_tokens || 0;
317
+ }
318
+ const content = msg.message.content;
319
+ if (Array.isArray(content)) {
320
+ for (const block of content) {
321
+ if (block.type === 'tool_use' && 'name' in block) {
322
+ const toolName = block.name;
323
+ toolCounts[toolName] = (toolCounts[toolName] || 0) + 1;
324
+ // Check for special tool usage
325
+ if (toolName === AGENT_TOOL_NAME ||
326
+ toolName === LEGACY_AGENT_TOOL_NAME)
327
+ usesTaskAgent = true;
328
+ if (toolName.startsWith('mcp__'))
329
+ usesMcp = true;
330
+ if (toolName === 'WebSearch')
331
+ usesWebSearch = true;
332
+ if (toolName === 'WebFetch')
333
+ usesWebFetch = true;
334
+ const input = block.input;
335
+ if (input) {
336
+ const filePath = input.file_path || '';
337
+ if (filePath) {
338
+ const lang = getLanguageFromPath(filePath);
339
+ if (lang) {
340
+ languages[lang] = (languages[lang] || 0) + 1;
341
+ }
342
+ // Track files modified by Edit/Write tools
343
+ if (toolName === 'Edit' || toolName === 'Write') {
344
+ filesModified.add(filePath);
345
+ }
346
+ }
347
+ if (toolName === 'Edit') {
348
+ const oldString = input.old_string || '';
349
+ const newString = input.new_string || '';
350
+ for (const change of diffLines(oldString, newString)) {
351
+ if (change.added)
352
+ linesAdded += change.count || 0;
353
+ if (change.removed)
354
+ linesRemoved += change.count || 0;
355
+ }
356
+ }
357
+ // Track lines from Write tool (all added)
358
+ if (toolName === 'Write') {
359
+ const writeContent = input.content || '';
360
+ if (writeContent) {
361
+ linesAdded += countCharInString(writeContent, '\n') + 1;
362
+ }
363
+ }
364
+ const command = input.command || '';
365
+ if (command.includes('git commit'))
366
+ gitCommits++;
367
+ if (command.includes('git push'))
368
+ gitPushes++;
369
+ }
370
+ }
371
+ }
372
+ }
373
+ }
374
+ // Check user messages
375
+ if (msg.type === 'user' && msg.message) {
376
+ const content = msg.message.content;
377
+ // Check if this is an actual human message (has text) vs just tool_result
378
+ // matching Python reference logic
379
+ let isHumanMessage = false;
380
+ if (typeof content === 'string' && content.trim()) {
381
+ isHumanMessage = true;
382
+ }
383
+ else if (Array.isArray(content)) {
384
+ for (const block of content) {
385
+ if (block.type === 'text' && 'text' in block) {
386
+ isHumanMessage = true;
387
+ break;
388
+ }
389
+ }
390
+ }
391
+ // Only track message hours and response times for actual human messages
392
+ if (isHumanMessage) {
393
+ // Track message hour for time-of-day analysis and timestamp for multi-clauding
394
+ if (msgTimestamp) {
395
+ try {
396
+ const msgDate = new Date(msgTimestamp);
397
+ const hour = msgDate.getHours(); // Local hour 0-23
398
+ messageHours.push(hour);
399
+ // Collect timestamp for multi-clauding detection (matching Python)
400
+ userMessageTimestamps.push(msgTimestamp);
401
+ }
402
+ catch {
403
+ // Skip invalid timestamps
404
+ }
405
+ }
406
+ // Calculate response time (time from last assistant message to this user message)
407
+ // Only count gaps > 2 seconds (real user think time, not tool results)
408
+ if (lastAssistantTimestamp && msgTimestamp) {
409
+ const assistantTime = new Date(lastAssistantTimestamp).getTime();
410
+ const userTime = new Date(msgTimestamp).getTime();
411
+ const responseTimeSec = (userTime - assistantTime) / 1000;
412
+ // Only count reasonable response times (2s-1 hour) matching Python
413
+ if (responseTimeSec > 2 && responseTimeSec < 3600) {
414
+ userResponseTimes.push(responseTimeSec);
415
+ }
416
+ }
417
+ }
418
+ // Process tool results (for error tracking)
419
+ if (Array.isArray(content)) {
420
+ for (const block of content) {
421
+ if (block.type === 'tool_result' && 'content' in block) {
422
+ const isError = block.is_error;
423
+ // Count and categorize tool errors (matching Python reference logic)
424
+ if (isError) {
425
+ toolErrors++;
426
+ const resultContent = block.content;
427
+ let category = 'Other';
428
+ if (typeof resultContent === 'string') {
429
+ const lowerContent = resultContent.toLowerCase();
430
+ if (lowerContent.includes('exit code')) {
431
+ category = 'Command Failed';
432
+ }
433
+ else if (lowerContent.includes('rejected') ||
434
+ lowerContent.includes("doesn't want")) {
435
+ category = 'User Rejected';
436
+ }
437
+ else if (lowerContent.includes('string to replace not found') ||
438
+ lowerContent.includes('no changes')) {
439
+ category = 'Edit Failed';
440
+ }
441
+ else if (lowerContent.includes('modified since read')) {
442
+ category = 'File Changed';
443
+ }
444
+ else if (lowerContent.includes('exceeds maximum') ||
445
+ lowerContent.includes('too large')) {
446
+ category = 'File Too Large';
447
+ }
448
+ else if (lowerContent.includes('file not found') ||
449
+ lowerContent.includes('does not exist')) {
450
+ category = 'File Not Found';
451
+ }
452
+ }
453
+ toolErrorCategories[category] =
454
+ (toolErrorCategories[category] || 0) + 1;
455
+ }
456
+ }
457
+ }
458
+ }
459
+ // Check for interruptions (matching Python reference)
460
+ if (typeof content === 'string') {
461
+ if (content.includes('[Request interrupted by user')) {
462
+ userInterruptions++;
463
+ }
464
+ }
465
+ else if (Array.isArray(content)) {
466
+ for (const block of content) {
467
+ if (block.type === 'text' &&
468
+ 'text' in block &&
469
+ block.text.includes('[Request interrupted by user')) {
470
+ userInterruptions++;
471
+ break;
472
+ }
473
+ }
474
+ }
475
+ }
476
+ }
477
+ return {
478
+ toolCounts,
479
+ languages,
480
+ gitCommits,
481
+ gitPushes,
482
+ inputTokens,
483
+ outputTokens,
484
+ // New stats
485
+ userInterruptions,
486
+ userResponseTimes,
487
+ toolErrors,
488
+ toolErrorCategories,
489
+ usesTaskAgent,
490
+ usesMcp,
491
+ usesWebSearch,
492
+ usesWebFetch,
493
+ // Additional stats
494
+ linesAdded,
495
+ linesRemoved,
496
+ filesModified,
497
+ messageHours,
498
+ userMessageTimestamps,
499
+ };
500
+ }
501
+ function hasValidDates(log) {
502
+ return (!Number.isNaN(log.created.getTime()) &&
503
+ !Number.isNaN(log.modified.getTime()));
504
+ }
505
+ function logToSessionMeta(log) {
506
+ const stats = extractToolStats(log);
507
+ const sessionId = getSessionIdFromLog(log) || 'unknown';
508
+ const startTime = log.created.toISOString();
509
+ const durationMinutes = Math.round((log.modified.getTime() - log.created.getTime()) / 1000 / 60);
510
+ let userMessageCount = 0;
511
+ let assistantMessageCount = 0;
512
+ for (const msg of log.messages) {
513
+ if (msg.type === 'assistant')
514
+ assistantMessageCount++;
515
+ // Only count user messages that have actual text content (human messages)
516
+ // not just tool_result messages (matching Python reference)
517
+ if (msg.type === 'user' && msg.message) {
518
+ const content = msg.message.content;
519
+ let isHumanMessage = false;
520
+ if (typeof content === 'string' && content.trim()) {
521
+ isHumanMessage = true;
522
+ }
523
+ else if (Array.isArray(content)) {
524
+ for (const block of content) {
525
+ if (block.type === 'text' && 'text' in block) {
526
+ isHumanMessage = true;
527
+ break;
528
+ }
529
+ }
530
+ }
531
+ if (isHumanMessage) {
532
+ userMessageCount++;
533
+ }
534
+ }
535
+ }
536
+ return {
537
+ session_id: sessionId,
538
+ project_path: log.projectPath || '',
539
+ start_time: startTime,
540
+ duration_minutes: durationMinutes,
541
+ user_message_count: userMessageCount,
542
+ assistant_message_count: assistantMessageCount,
543
+ tool_counts: stats.toolCounts,
544
+ languages: stats.languages,
545
+ git_commits: stats.gitCommits,
546
+ git_pushes: stats.gitPushes,
547
+ input_tokens: stats.inputTokens,
548
+ output_tokens: stats.outputTokens,
549
+ first_prompt: log.firstPrompt || '',
550
+ summary: log.summary,
551
+ // New stats
552
+ user_interruptions: stats.userInterruptions,
553
+ user_response_times: stats.userResponseTimes,
554
+ tool_errors: stats.toolErrors,
555
+ tool_error_categories: stats.toolErrorCategories,
556
+ uses_task_agent: stats.usesTaskAgent,
557
+ uses_mcp: stats.usesMcp,
558
+ uses_web_search: stats.usesWebSearch,
559
+ uses_web_fetch: stats.usesWebFetch,
560
+ // Additional stats
561
+ lines_added: stats.linesAdded,
562
+ lines_removed: stats.linesRemoved,
563
+ files_modified: stats.filesModified.size,
564
+ message_hours: stats.messageHours,
565
+ user_message_timestamps: stats.userMessageTimestamps,
566
+ };
567
+ }
568
+ /**
569
+ * Deduplicate conversation branches within the same session.
570
+ *
571
+ * When a session file has multiple leaf messages (from retries or branching),
572
+ * loadAllLogsFromSessionFile produces one LogOption per leaf. Each branch
573
+ * shares the same root message, so its duration overlaps with sibling
574
+ * branches. This keeps only the branch with the most user messages
575
+ * (tie-break by longest duration) per session_id.
576
+ */
577
+ export function deduplicateSessionBranches(entries) {
578
+ const bestBySession = new Map();
579
+ for (const entry of entries) {
580
+ const id = entry.meta.session_id;
581
+ const existing = bestBySession.get(id);
582
+ if (!existing ||
583
+ entry.meta.user_message_count > existing.meta.user_message_count ||
584
+ (entry.meta.user_message_count === existing.meta.user_message_count &&
585
+ entry.meta.duration_minutes > existing.meta.duration_minutes)) {
586
+ bestBySession.set(id, entry);
587
+ }
588
+ }
589
+ return [...bestBySession.values()];
590
+ }
591
+ function formatTranscriptForFacets(log) {
592
+ const lines = [];
593
+ const meta = logToSessionMeta(log);
594
+ lines.push(`Session: ${meta.session_id.slice(0, 8)}`);
595
+ lines.push(`Date: ${meta.start_time}`);
596
+ lines.push(`Project: ${meta.project_path}`);
597
+ lines.push(`Duration: ${meta.duration_minutes} min`);
598
+ lines.push('');
599
+ for (const msg of log.messages) {
600
+ if (msg.type === 'user' && msg.message) {
601
+ const content = msg.message.content;
602
+ if (typeof content === 'string') {
603
+ lines.push(`[User]: ${content.slice(0, 500)}`);
604
+ }
605
+ else if (Array.isArray(content)) {
606
+ for (const block of content) {
607
+ if (block.type === 'text' && 'text' in block) {
608
+ lines.push(`[User]: ${block.text.slice(0, 500)}`);
609
+ }
610
+ }
611
+ }
612
+ }
613
+ else if (msg.type === 'assistant' && msg.message) {
614
+ const content = msg.message.content;
615
+ if (Array.isArray(content)) {
616
+ for (const block of content) {
617
+ if (block.type === 'text' && 'text' in block) {
618
+ lines.push(`[Assistant]: ${block.text.slice(0, 300)}`);
619
+ }
620
+ else if (block.type === 'tool_use' && 'name' in block) {
621
+ lines.push(`[Tool: ${block.name}]`);
622
+ }
623
+ }
624
+ }
625
+ }
626
+ }
627
+ return lines.join('\n');
628
+ }
629
+ const SUMMARIZE_CHUNK_PROMPT = `Summarize this portion of a Thaddeus session transcript. Focus on:
630
+ 1. What the user asked for
631
+ 2. What Thaddeus did (tools used, files modified)
632
+ 3. Any friction or issues
633
+ 4. The outcome
634
+
635
+ Keep it concise - 3-5 sentences. Preserve specific details like file names, error messages, and user feedback.
636
+
637
+ TRANSCRIPT CHUNK:
638
+ `;
639
+ async function summarizeTranscriptChunk(chunk) {
640
+ try {
641
+ const result = await queryWithModel({
642
+ systemPrompt: asSystemPrompt([]),
643
+ userPrompt: SUMMARIZE_CHUNK_PROMPT + chunk,
644
+ signal: new AbortController().signal,
645
+ options: {
646
+ model: getAnalysisModel(),
647
+ querySource: 'insights',
648
+ agents: [],
649
+ isNonInteractiveSession: true,
650
+ hasAppendSystemPrompt: false,
651
+ mcpTools: [],
652
+ maxOutputTokensOverride: 500,
653
+ },
654
+ });
655
+ const text = extractTextContent(result.message.content);
656
+ return text || chunk.slice(0, 2000);
657
+ }
658
+ catch {
659
+ // On error, just return truncated chunk
660
+ return chunk.slice(0, 2000);
661
+ }
662
+ }
663
+ async function formatTranscriptWithSummarization(log) {
664
+ const fullTranscript = formatTranscriptForFacets(log);
665
+ // If under 30k chars, use as-is
666
+ if (fullTranscript.length <= 30000) {
667
+ return fullTranscript;
668
+ }
669
+ // For long transcripts, split into chunks and summarize in parallel
670
+ const CHUNK_SIZE = 25000;
671
+ const chunks = [];
672
+ for (let i = 0; i < fullTranscript.length; i += CHUNK_SIZE) {
673
+ chunks.push(fullTranscript.slice(i, i + CHUNK_SIZE));
674
+ }
675
+ // Summarize all chunks in parallel
676
+ const summaries = await Promise.all(chunks.map(summarizeTranscriptChunk));
677
+ // Combine summaries with session header
678
+ const meta = logToSessionMeta(log);
679
+ const header = [
680
+ `Session: ${meta.session_id.slice(0, 8)}`,
681
+ `Date: ${meta.start_time}`,
682
+ `Project: ${meta.project_path}`,
683
+ `Duration: ${meta.duration_minutes} min`,
684
+ `[Long session - ${chunks.length} parts summarized]`,
685
+ '',
686
+ ].join('\n');
687
+ return header + summaries.join('\n\n---\n\n');
688
+ }
689
+ async function loadCachedFacets(sessionId) {
690
+ const facetPath = join(getFacetsDir(), `${sessionId}.json`);
691
+ try {
692
+ const content = await readFile(facetPath, { encoding: 'utf-8' });
693
+ const parsed = jsonParse(content);
694
+ if (!isValidSessionFacets(parsed)) {
695
+ // Delete corrupted cache file so it gets re-extracted next run
696
+ try {
697
+ await unlink(facetPath);
698
+ }
699
+ catch {
700
+ // Ignore deletion errors
701
+ }
702
+ return null;
703
+ }
704
+ return parsed;
705
+ }
706
+ catch {
707
+ return null;
708
+ }
709
+ }
710
+ async function saveFacets(facets) {
711
+ try {
712
+ await mkdir(getFacetsDir(), { recursive: true });
713
+ }
714
+ catch {
715
+ // Directory may already exist
716
+ }
717
+ const facetPath = join(getFacetsDir(), `${facets.session_id}.json`);
718
+ await writeFile(facetPath, jsonStringify(facets, null, 2), {
719
+ encoding: 'utf-8',
720
+ mode: 0o600,
721
+ });
722
+ }
723
+ async function loadCachedSessionMeta(sessionId) {
724
+ const metaPath = join(getSessionMetaDir(), `${sessionId}.json`);
725
+ try {
726
+ const content = await readFile(metaPath, { encoding: 'utf-8' });
727
+ return jsonParse(content);
728
+ }
729
+ catch {
730
+ return null;
731
+ }
732
+ }
733
+ async function saveSessionMeta(meta) {
734
+ try {
735
+ await mkdir(getSessionMetaDir(), { recursive: true });
736
+ }
737
+ catch {
738
+ // Directory may already exist
739
+ }
740
+ const metaPath = join(getSessionMetaDir(), `${meta.session_id}.json`);
741
+ await writeFile(metaPath, jsonStringify(meta, null, 2), {
742
+ encoding: 'utf-8',
743
+ mode: 0o600,
744
+ });
745
+ }
746
+ async function extractFacetsFromAPI(log, sessionId) {
747
+ try {
748
+ // Use summarization for long transcripts
749
+ const transcript = await formatTranscriptWithSummarization(log);
750
+ // Build prompt asking for JSON directly (no tool use)
751
+ const jsonPrompt = `${FACET_EXTRACTION_PROMPT}${transcript}
752
+
753
+ RESPOND WITH ONLY A VALID JSON OBJECT matching this schema:
754
+ {
755
+ "underlying_goal": "What the user fundamentally wanted to achieve",
756
+ "goal_categories": {"category_name": count, ...},
757
+ "outcome": "fully_achieved|mostly_achieved|partially_achieved|not_achieved|unclear_from_transcript",
758
+ "user_satisfaction_counts": {"level": count, ...},
759
+ "claude_helpfulness": "unhelpful|slightly_helpful|moderately_helpful|very_helpful|essential",
760
+ "session_type": "single_task|multi_task|iterative_refinement|exploration|quick_question",
761
+ "friction_counts": {"friction_type": count, ...},
762
+ "friction_detail": "One sentence describing friction or empty",
763
+ "primary_success": "none|fast_accurate_search|correct_code_edits|good_explanations|proactive_help|multi_file_changes|good_debugging",
764
+ "brief_summary": "One sentence: what user wanted and whether they got it"
765
+ }`;
766
+ const result = await queryWithModel({
767
+ systemPrompt: asSystemPrompt([]),
768
+ userPrompt: jsonPrompt,
769
+ signal: new AbortController().signal,
770
+ options: {
771
+ model: getAnalysisModel(),
772
+ querySource: 'insights',
773
+ agents: [],
774
+ isNonInteractiveSession: true,
775
+ hasAppendSystemPrompt: false,
776
+ mcpTools: [],
777
+ maxOutputTokensOverride: 4096,
778
+ },
779
+ });
780
+ const text = extractTextContent(result.message.content);
781
+ // Parse JSON from response
782
+ const jsonMatch = text.match(/\{[\s\S]*\}/);
783
+ if (!jsonMatch)
784
+ return null;
785
+ const parsed = jsonParse(jsonMatch[0]);
786
+ if (!isValidSessionFacets(parsed))
787
+ return null;
788
+ const facets = { ...parsed, session_id: sessionId };
789
+ return facets;
790
+ }
791
+ catch (err) {
792
+ logError(new Error(`Facet extraction failed: ${toError(err).message}`));
793
+ return null;
794
+ }
795
+ }
796
+ /**
797
+ * Detects multi-session usage (using multiple Thaddeus sessions concurrently).
798
+ * Uses a sliding window to find the pattern: session1 -> session2 -> session1
799
+ * within a 30-minute window.
800
+ */
801
+ export function detectMultiClauding(sessions) {
802
+ const OVERLAP_WINDOW_MS = 30 * 60000;
803
+ const allSessionMessages = [];
804
+ for (const session of sessions) {
805
+ for (const timestamp of session.user_message_timestamps) {
806
+ try {
807
+ const ts = new Date(timestamp).getTime();
808
+ allSessionMessages.push({ ts, sessionId: session.session_id });
809
+ }
810
+ catch {
811
+ // Skip invalid timestamps
812
+ }
813
+ }
814
+ }
815
+ allSessionMessages.sort((a, b) => a.ts - b.ts);
816
+ const multiClaudeSessionPairs = new Set();
817
+ const messagesDuringMulticlaude = new Set();
818
+ // Sliding window: sessionLastIndex tracks the most recent index for each session
819
+ let windowStart = 0;
820
+ const sessionLastIndex = new Map();
821
+ for (let i = 0; i < allSessionMessages.length; i++) {
822
+ const msg = allSessionMessages[i];
823
+ // Shrink window from the left
824
+ while (windowStart < i &&
825
+ msg.ts - allSessionMessages[windowStart].ts > OVERLAP_WINDOW_MS) {
826
+ const expiring = allSessionMessages[windowStart];
827
+ if (sessionLastIndex.get(expiring.sessionId) === windowStart) {
828
+ sessionLastIndex.delete(expiring.sessionId);
829
+ }
830
+ windowStart++;
831
+ }
832
+ // Check if this session appeared earlier in the window (pattern: s1 -> s2 -> s1)
833
+ const prevIndex = sessionLastIndex.get(msg.sessionId);
834
+ if (prevIndex !== undefined) {
835
+ for (let j = prevIndex + 1; j < i; j++) {
836
+ const between = allSessionMessages[j];
837
+ if (between.sessionId !== msg.sessionId) {
838
+ const pair = [msg.sessionId, between.sessionId].sort().join(':');
839
+ multiClaudeSessionPairs.add(pair);
840
+ messagesDuringMulticlaude.add(`${allSessionMessages[prevIndex].ts}:${msg.sessionId}`);
841
+ messagesDuringMulticlaude.add(`${between.ts}:${between.sessionId}`);
842
+ messagesDuringMulticlaude.add(`${msg.ts}:${msg.sessionId}`);
843
+ break;
844
+ }
845
+ }
846
+ }
847
+ sessionLastIndex.set(msg.sessionId, i);
848
+ }
849
+ const sessionsWithOverlaps = new Set();
850
+ for (const pair of multiClaudeSessionPairs) {
851
+ const [s1, s2] = pair.split(':');
852
+ if (s1)
853
+ sessionsWithOverlaps.add(s1);
854
+ if (s2)
855
+ sessionsWithOverlaps.add(s2);
856
+ }
857
+ return {
858
+ overlap_events: multiClaudeSessionPairs.size,
859
+ sessions_involved: sessionsWithOverlaps.size,
860
+ user_messages_during: messagesDuringMulticlaude.size,
861
+ };
862
+ }
863
+ function aggregateData(sessions, facets) {
864
+ const result = {
865
+ total_sessions: sessions.length,
866
+ sessions_with_facets: facets.size,
867
+ date_range: { start: '', end: '' },
868
+ total_messages: 0,
869
+ total_duration_hours: 0,
870
+ total_input_tokens: 0,
871
+ total_output_tokens: 0,
872
+ tool_counts: {},
873
+ languages: {},
874
+ git_commits: 0,
875
+ git_pushes: 0,
876
+ projects: {},
877
+ goal_categories: {},
878
+ outcomes: {},
879
+ satisfaction: {},
880
+ helpfulness: {},
881
+ session_types: {},
882
+ friction: {},
883
+ success: {},
884
+ session_summaries: [],
885
+ // New stats
886
+ total_interruptions: 0,
887
+ total_tool_errors: 0,
888
+ tool_error_categories: {},
889
+ user_response_times: [],
890
+ median_response_time: 0,
891
+ avg_response_time: 0,
892
+ sessions_using_task_agent: 0,
893
+ sessions_using_mcp: 0,
894
+ sessions_using_web_search: 0,
895
+ sessions_using_web_fetch: 0,
896
+ // Additional stats
897
+ total_lines_added: 0,
898
+ total_lines_removed: 0,
899
+ total_files_modified: 0,
900
+ days_active: 0,
901
+ messages_per_day: 0,
902
+ message_hours: [],
903
+ // Multi-clauding stats (matching Python reference)
904
+ multi_clauding: {
905
+ overlap_events: 0,
906
+ sessions_involved: 0,
907
+ user_messages_during: 0,
908
+ },
909
+ };
910
+ const dates = [];
911
+ const allResponseTimes = [];
912
+ const allMessageHours = [];
913
+ for (const session of sessions) {
914
+ dates.push(session.start_time);
915
+ result.total_messages += session.user_message_count;
916
+ result.total_duration_hours += session.duration_minutes / 60;
917
+ result.total_input_tokens += session.input_tokens;
918
+ result.total_output_tokens += session.output_tokens;
919
+ result.git_commits += session.git_commits;
920
+ result.git_pushes += session.git_pushes;
921
+ // New stats aggregation
922
+ result.total_interruptions += session.user_interruptions;
923
+ result.total_tool_errors += session.tool_errors;
924
+ for (const [cat, count] of Object.entries(session.tool_error_categories)) {
925
+ result.tool_error_categories[cat] =
926
+ (result.tool_error_categories[cat] || 0) + count;
927
+ }
928
+ allResponseTimes.push(...session.user_response_times);
929
+ if (session.uses_task_agent)
930
+ result.sessions_using_task_agent++;
931
+ if (session.uses_mcp)
932
+ result.sessions_using_mcp++;
933
+ if (session.uses_web_search)
934
+ result.sessions_using_web_search++;
935
+ if (session.uses_web_fetch)
936
+ result.sessions_using_web_fetch++;
937
+ // Additional stats aggregation
938
+ result.total_lines_added += session.lines_added;
939
+ result.total_lines_removed += session.lines_removed;
940
+ result.total_files_modified += session.files_modified;
941
+ allMessageHours.push(...session.message_hours);
942
+ for (const [tool, count] of Object.entries(session.tool_counts)) {
943
+ result.tool_counts[tool] = (result.tool_counts[tool] || 0) + count;
944
+ }
945
+ for (const [lang, count] of Object.entries(session.languages)) {
946
+ result.languages[lang] = (result.languages[lang] || 0) + count;
947
+ }
948
+ if (session.project_path) {
949
+ result.projects[session.project_path] =
950
+ (result.projects[session.project_path] || 0) + 1;
951
+ }
952
+ const sessionFacets = facets.get(session.session_id);
953
+ if (sessionFacets) {
954
+ // Goal categories
955
+ for (const [cat, count] of safeEntries(sessionFacets.goal_categories)) {
956
+ if (count > 0) {
957
+ result.goal_categories[cat] =
958
+ (result.goal_categories[cat] || 0) + count;
959
+ }
960
+ }
961
+ // Outcomes
962
+ result.outcomes[sessionFacets.outcome] =
963
+ (result.outcomes[sessionFacets.outcome] || 0) + 1;
964
+ // Satisfaction counts
965
+ for (const [level, count] of safeEntries(sessionFacets.user_satisfaction_counts)) {
966
+ if (count > 0) {
967
+ result.satisfaction[level] = (result.satisfaction[level] || 0) + count;
968
+ }
969
+ }
970
+ // Helpfulness
971
+ result.helpfulness[sessionFacets.claude_helpfulness] =
972
+ (result.helpfulness[sessionFacets.claude_helpfulness] || 0) + 1;
973
+ // Session types
974
+ result.session_types[sessionFacets.session_type] =
975
+ (result.session_types[sessionFacets.session_type] || 0) + 1;
976
+ // Friction counts
977
+ for (const [type, count] of safeEntries(sessionFacets.friction_counts)) {
978
+ if (count > 0) {
979
+ result.friction[type] = (result.friction[type] || 0) + count;
980
+ }
981
+ }
982
+ // Success factors
983
+ if (sessionFacets.primary_success !== 'none') {
984
+ result.success[sessionFacets.primary_success] =
985
+ (result.success[sessionFacets.primary_success] || 0) + 1;
986
+ }
987
+ }
988
+ if (result.session_summaries.length < 50) {
989
+ result.session_summaries.push({
990
+ id: session.session_id.slice(0, 8),
991
+ date: session.start_time.split('T')[0] || '',
992
+ summary: session.summary || session.first_prompt.slice(0, 100),
993
+ goal: sessionFacets?.underlying_goal,
994
+ });
995
+ }
996
+ }
997
+ dates.sort();
998
+ result.date_range.start = dates[0]?.split('T')[0] || '';
999
+ result.date_range.end = dates[dates.length - 1]?.split('T')[0] || '';
1000
+ // Calculate response time stats
1001
+ result.user_response_times = allResponseTimes;
1002
+ if (allResponseTimes.length > 0) {
1003
+ const sorted = [...allResponseTimes].sort((a, b) => a - b);
1004
+ result.median_response_time = sorted[Math.floor(sorted.length / 2)] || 0;
1005
+ result.avg_response_time =
1006
+ allResponseTimes.reduce((a, b) => a + b, 0) / allResponseTimes.length;
1007
+ }
1008
+ // Calculate days active and messages per day
1009
+ const uniqueDays = new Set(dates.map(d => d.split('T')[0]));
1010
+ result.days_active = uniqueDays.size;
1011
+ result.messages_per_day =
1012
+ result.days_active > 0
1013
+ ? Math.round((result.total_messages / result.days_active) * 10) / 10
1014
+ : 0;
1015
+ // Store message hours for time-of-day chart
1016
+ result.message_hours = allMessageHours;
1017
+ result.multi_clauding = detectMultiClauding(sessions);
1018
+ return result;
1019
+ }
1020
+ // Sections that run in parallel first
1021
+ const INSIGHT_SECTIONS = [
1022
+ {
1023
+ name: 'project_areas',
1024
+ prompt: `Analyze this Thaddeus usage data and identify project areas.
1025
+
1026
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1027
+ {
1028
+ "areas": [
1029
+ {"name": "Area name", "session_count": N, "description": "2-3 sentences about what was worked on and how Thaddeus was used."}
1030
+ ]
1031
+ }
1032
+
1033
+ Include 4-5 areas. Skip internal CC operations.`,
1034
+ maxTokens: 8192,
1035
+ },
1036
+ {
1037
+ name: 'interaction_style',
1038
+ prompt: `Analyze this Thaddeus usage data and describe the user's interaction style.
1039
+
1040
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1041
+ {
1042
+ "narrative": "2-3 paragraphs analyzing HOW the user interacts with Thaddeus. Use second person 'you'. Describe patterns: iterate quickly vs detailed upfront specs? Interrupt often or let Thaddeus run? Include specific examples. Use **bold** for key insights.",
1043
+ "key_pattern": "One sentence summary of most distinctive interaction style"
1044
+ }`,
1045
+ maxTokens: 8192,
1046
+ },
1047
+ {
1048
+ name: 'what_works',
1049
+ prompt: `Analyze this Thaddeus usage data and identify what's working well for this user. Use second person ("you").
1050
+
1051
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1052
+ {
1053
+ "intro": "1 sentence of context",
1054
+ "impressive_workflows": [
1055
+ {"title": "Short title (3-6 words)", "description": "2-3 sentences describing the impressive workflow or approach. Use 'you' not 'the user'."}
1056
+ ]
1057
+ }
1058
+
1059
+ Include 3 impressive workflows.`,
1060
+ maxTokens: 8192,
1061
+ },
1062
+ {
1063
+ name: 'friction_analysis',
1064
+ prompt: `Analyze this Thaddeus usage data and identify friction points for this user. Use second person ("you").
1065
+
1066
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1067
+ {
1068
+ "intro": "1 sentence summarizing friction patterns",
1069
+ "categories": [
1070
+ {"category": "Concrete category name", "description": "1-2 sentences explaining this category and what could be done differently. Use 'you' not 'the user'.", "examples": ["Specific example with consequence", "Another example"]}
1071
+ ]
1072
+ }
1073
+
1074
+ Include 3 friction categories with 2 examples each.`,
1075
+ maxTokens: 8192,
1076
+ },
1077
+ {
1078
+ name: 'suggestions',
1079
+ prompt: `Analyze this Thaddeus usage data and suggest improvements.
1080
+
1081
+ ## CC FEATURES REFERENCE (pick from these for features_to_try):
1082
+ 1. **MCP Servers**: Connect Thaddeus to external tools, databases, and APIs via Model Context Protocol.
1083
+ - How to use: Run \`claude mcp add <server-name> -- <command>\`
1084
+ - Good for: database queries, Slack integration, GitHub issue lookup, connecting to internal APIs
1085
+
1086
+ 2. **Custom Skills**: Reusable prompts you define as markdown files that run with a single /command.
1087
+ - How to use: Create \`.claude/skills/commit/SKILL.md\` with instructions. Then type \`/commit\` to run it.
1088
+ - Good for: repetitive workflows - /commit, /review, /test, /deploy, /pr, or complex multi-step workflows
1089
+
1090
+ 3. **Hooks**: Shell commands that auto-run at specific lifecycle events.
1091
+ - How to use: Add to \`.claude/settings.json\` under "hooks" key.
1092
+ - Good for: auto-formatting code, running type checks, enforcing conventions
1093
+
1094
+ 4. **Headless Mode**: Run Thaddeus non-interactively from scripts and CI/CD.
1095
+ - How to use: \`claude -p "fix lint errors" --allowedTools "Edit,Read,Bash"\`
1096
+ - Good for: CI/CD integration, batch code fixes, automated reviews
1097
+
1098
+ 5. **Task Agents**: Thaddeus spawns focused sub-agents for complex exploration or parallel work.
1099
+ - How to use: Thaddeus auto-invokes when helpful, or ask "use an agent to explore X"
1100
+ - Good for: codebase exploration, understanding complex systems
1101
+
1102
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1103
+ {
1104
+ "claude_md_additions": [
1105
+ {"addition": "A specific line or block to add to THADDEUS.md based on workflow patterns. E.g., 'Always run tests after modifying auth-related files'", "why": "1 sentence explaining why this would help based on actual sessions", "prompt_scaffold": "Instructions for where to add this in THADDEUS.md. E.g., 'Add under ## Testing section'"}
1106
+ ],
1107
+ "features_to_try": [
1108
+ {"feature": "Feature name from CC FEATURES REFERENCE above", "one_liner": "What it does", "why_for_you": "Why this would help YOU based on your sessions", "example_code": "Actual command or config to copy"}
1109
+ ],
1110
+ "usage_patterns": [
1111
+ {"title": "Short title", "suggestion": "1-2 sentence summary", "detail": "3-4 sentences explaining how this applies to YOUR work", "copyable_prompt": "A specific prompt to copy and try"}
1112
+ ]
1113
+ }
1114
+
1115
+ IMPORTANT for claude_md_additions: PRIORITIZE instructions that appear MULTIPLE TIMES in the user data. If user told Thaddeus the same thing in 2+ sessions (e.g., 'always run tests', 'use TypeScript'), that's a PRIME candidate - they shouldn't have to repeat themselves.
1116
+
1117
+ IMPORTANT for features_to_try: Pick 2-3 from the CC FEATURES REFERENCE above. Include 2-3 items for each category.`,
1118
+ maxTokens: 8192,
1119
+ },
1120
+ {
1121
+ name: 'on_the_horizon',
1122
+ prompt: `Analyze this Thaddeus usage data and identify future opportunities.
1123
+
1124
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1125
+ {
1126
+ "intro": "1 sentence about evolving AI-assisted development",
1127
+ "opportunities": [
1128
+ {"title": "Short title (4-8 words)", "whats_possible": "2-3 ambitious sentences about autonomous workflows", "how_to_try": "1-2 sentences mentioning relevant tooling", "copyable_prompt": "Detailed prompt to try"}
1129
+ ]
1130
+ }
1131
+
1132
+ Include 3 opportunities. Think BIG - autonomous workflows, parallel agents, iterating against tests.`,
1133
+ maxTokens: 8192,
1134
+ },
1135
+ ...(process.env.USER_TYPE === 'ant'
1136
+ ? [
1137
+ {
1138
+ name: 'cc_team_improvements',
1139
+ prompt: `Analyze this Thaddeus usage data and suggest product improvements for the CC team.
1140
+
1141
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1142
+ {
1143
+ "improvements": [
1144
+ {"title": "Product/tooling improvement", "detail": "3-4 sentences describing the improvement", "evidence": "3-4 sentences with specific session examples"}
1145
+ ]
1146
+ }
1147
+
1148
+ Include 2-3 improvements based on friction patterns observed.`,
1149
+ maxTokens: 8192,
1150
+ },
1151
+ {
1152
+ name: 'model_behavior_improvements',
1153
+ prompt: `Analyze this Thaddeus usage data and suggest model behavior improvements.
1154
+
1155
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1156
+ {
1157
+ "improvements": [
1158
+ {"title": "Model behavior change", "detail": "3-4 sentences describing what the model should do differently", "evidence": "3-4 sentences with specific examples"}
1159
+ ]
1160
+ }
1161
+
1162
+ Include 2-3 improvements based on friction patterns observed.`,
1163
+ maxTokens: 8192,
1164
+ },
1165
+ ]
1166
+ : []),
1167
+ {
1168
+ name: 'fun_ending',
1169
+ prompt: `Analyze this Thaddeus usage data and find a memorable moment.
1170
+
1171
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1172
+ {
1173
+ "headline": "A memorable QUALITATIVE moment from the transcripts - not a statistic. Something human, funny, or surprising.",
1174
+ "detail": "Brief context about when/where this happened"
1175
+ }
1176
+
1177
+ Find something genuinely interesting or amusing from the session summaries.`,
1178
+ maxTokens: 8192,
1179
+ },
1180
+ ];
1181
+ async function generateSectionInsight(section, dataContext) {
1182
+ try {
1183
+ const result = await queryWithModel({
1184
+ systemPrompt: asSystemPrompt([]),
1185
+ userPrompt: section.prompt + '\n\nDATA:\n' + dataContext,
1186
+ signal: new AbortController().signal,
1187
+ options: {
1188
+ model: getInsightsModel(),
1189
+ querySource: 'insights',
1190
+ agents: [],
1191
+ isNonInteractiveSession: true,
1192
+ hasAppendSystemPrompt: false,
1193
+ mcpTools: [],
1194
+ maxOutputTokensOverride: section.maxTokens,
1195
+ },
1196
+ });
1197
+ const text = extractTextContent(result.message.content);
1198
+ if (text) {
1199
+ // Parse JSON from response
1200
+ const jsonMatch = text.match(/\{[\s\S]*\}/);
1201
+ if (jsonMatch) {
1202
+ try {
1203
+ return { name: section.name, result: jsonParse(jsonMatch[0]) };
1204
+ }
1205
+ catch {
1206
+ return { name: section.name, result: null };
1207
+ }
1208
+ }
1209
+ }
1210
+ return { name: section.name, result: null };
1211
+ }
1212
+ catch (err) {
1213
+ logError(new Error(`${section.name} failed: ${toError(err).message}`));
1214
+ return { name: section.name, result: null };
1215
+ }
1216
+ }
1217
+ async function generateParallelInsights(data, facets) {
1218
+ // Build data context string
1219
+ const facetSummaries = Array.from(facets.values())
1220
+ .slice(0, 50)
1221
+ .map(f => `- ${f.brief_summary} (${f.outcome}, ${f.claude_helpfulness})`)
1222
+ .join('\n');
1223
+ const frictionDetails = Array.from(facets.values())
1224
+ .filter(f => f.friction_detail)
1225
+ .slice(0, 20)
1226
+ .map(f => `- ${f.friction_detail}`)
1227
+ .join('\n');
1228
+ const userInstructions = Array.from(facets.values())
1229
+ .flatMap(f => f.user_instructions_to_claude || [])
1230
+ .slice(0, 15)
1231
+ .map(i => `- ${i}`)
1232
+ .join('\n');
1233
+ const dataContext = jsonStringify({
1234
+ sessions: data.total_sessions,
1235
+ analyzed: data.sessions_with_facets,
1236
+ date_range: data.date_range,
1237
+ messages: data.total_messages,
1238
+ hours: Math.round(data.total_duration_hours),
1239
+ commits: data.git_commits,
1240
+ top_tools: Object.entries(data.tool_counts)
1241
+ .sort((a, b) => b[1] - a[1])
1242
+ .slice(0, 8),
1243
+ top_goals: Object.entries(data.goal_categories)
1244
+ .sort((a, b) => b[1] - a[1])
1245
+ .slice(0, 8),
1246
+ outcomes: data.outcomes,
1247
+ satisfaction: data.satisfaction,
1248
+ friction: data.friction,
1249
+ success: data.success,
1250
+ languages: data.languages,
1251
+ }, null, 2);
1252
+ const fullContext = dataContext +
1253
+ '\n\nSESSION SUMMARIES:\n' +
1254
+ facetSummaries +
1255
+ '\n\nFRICTION DETAILS:\n' +
1256
+ frictionDetails +
1257
+ '\n\nUSER INSTRUCTIONS TO CLAUDE:\n' +
1258
+ (userInstructions || 'None captured');
1259
+ // Run sections in parallel first (excluding at_a_glance)
1260
+ const results = await Promise.all(INSIGHT_SECTIONS.map(section => generateSectionInsight(section, fullContext)));
1261
+ // Combine results
1262
+ const insights = {};
1263
+ for (const { name, result } of results) {
1264
+ if (result) {
1265
+ ;
1266
+ insights[name] = result;
1267
+ }
1268
+ }
1269
+ // Build rich context from generated sections for At a Glance
1270
+ const projectAreasText = insights.project_areas?.areas
1271
+ ?.map(a => `- ${a.name}: ${a.description}`)
1272
+ .join('\n') || '';
1273
+ const bigWinsText = insights.what_works?.impressive_workflows
1274
+ ?.map(w => `- ${w.title}: ${w.description}`)
1275
+ .join('\n') || '';
1276
+ const frictionText = insights.friction_analysis?.categories
1277
+ ?.map(c => `- ${c.category}: ${c.description}`)
1278
+ .join('\n') || '';
1279
+ const featuresText = insights.suggestions?.features_to_try
1280
+ ?.map(f => `- ${f.feature}: ${f.one_liner}`)
1281
+ .join('\n') || '';
1282
+ const patternsText = insights.suggestions?.usage_patterns
1283
+ ?.map(p => `- ${p.title}: ${p.suggestion}`)
1284
+ .join('\n') || '';
1285
+ const horizonText = insights.on_the_horizon?.opportunities
1286
+ ?.map(o => `- ${o.title}: ${o.whats_possible}`)
1287
+ .join('\n') || '';
1288
+ // Now generate "At a Glance" with access to other sections' outputs
1289
+ const atAGlancePrompt = `You're writing an "At a Glance" summary for a Thaddeus usage insights report for Thaddeus users. The goal is to help them understand their usage and improve how they can use Thaddeus better, especially as models improve.
1290
+
1291
+ Use this 4-part structure:
1292
+
1293
+ 1. **What's working** - What is the user's unique style of interacting with Thaddeus and what are some impactful things they've done? You can include one or two details, but keep it high level since things might not be fresh in the user's memory. Don't be fluffy or overly complimentary. Also, don't focus on the tool calls they use.
1294
+
1295
+ 2. **What's hindering you** - Split into (a) Thaddeus's fault (misunderstandings, wrong approaches, bugs) and (b) user-side friction (not providing enough context, environment issues -- ideally more general than just one project). Be honest but constructive.
1296
+
1297
+ 3. **Quick wins to try** - Specific Thaddeus features they could try from the examples below, or a workflow technique if you think it's really compelling. (Avoid stuff like "Ask Thaddeus to confirm before taking actions" or "Type out more context up front" which are less compelling.)
1298
+
1299
+ 4. **Ambitious workflows for better models** - As we move to much more capable models over the next 3-6 months, what should they prepare for? What workflows that seem impossible now will become possible? Draw from the appropriate section below.
1300
+
1301
+ Keep each section to 2-3 not-too-long sentences. Don't overwhelm the user. Don't mention specific numerical stats or underlined_categories from the session data below. Use a coaching tone.
1302
+
1303
+ RESPOND WITH ONLY A VALID JSON OBJECT:
1304
+ {
1305
+ "whats_working": "(refer to instructions above)",
1306
+ "whats_hindering": "(refer to instructions above)",
1307
+ "quick_wins": "(refer to instructions above)",
1308
+ "ambitious_workflows": "(refer to instructions above)"
1309
+ }
1310
+
1311
+ SESSION DATA:
1312
+ ${fullContext}
1313
+
1314
+ ## Project Areas (what user works on)
1315
+ ${projectAreasText}
1316
+
1317
+ ## Big Wins (impressive accomplishments)
1318
+ ${bigWinsText}
1319
+
1320
+ ## Friction Categories (where things go wrong)
1321
+ ${frictionText}
1322
+
1323
+ ## Features to Try
1324
+ ${featuresText}
1325
+
1326
+ ## Usage Patterns to Adopt
1327
+ ${patternsText}
1328
+
1329
+ ## On the Horizon (ambitious workflows for better models)
1330
+ ${horizonText}`;
1331
+ const atAGlanceSection = {
1332
+ name: 'at_a_glance',
1333
+ prompt: atAGlancePrompt,
1334
+ maxTokens: 8192,
1335
+ };
1336
+ const atAGlanceResult = await generateSectionInsight(atAGlanceSection, '');
1337
+ if (atAGlanceResult.result) {
1338
+ insights.at_a_glance = atAGlanceResult.result;
1339
+ }
1340
+ return insights;
1341
+ }
1342
+ // Escape HTML but render **bold** as <strong>
1343
+ function escapeHtmlWithBold(text) {
1344
+ const escaped = escapeHtml(text);
1345
+ return escaped.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
1346
+ }
1347
+ // Fixed orderings for specific charts (matching Python reference)
1348
+ const SATISFACTION_ORDER = [
1349
+ 'frustrated',
1350
+ 'dissatisfied',
1351
+ 'likely_satisfied',
1352
+ 'satisfied',
1353
+ 'happy',
1354
+ 'unsure',
1355
+ ];
1356
+ const OUTCOME_ORDER = [
1357
+ 'not_achieved',
1358
+ 'partially_achieved',
1359
+ 'mostly_achieved',
1360
+ 'fully_achieved',
1361
+ 'unclear_from_transcript',
1362
+ ];
1363
+ function generateBarChart(data, color, maxItems = 6, fixedOrder) {
1364
+ let entries;
1365
+ if (fixedOrder) {
1366
+ // Use fixed order, only including items that exist in data
1367
+ entries = fixedOrder
1368
+ .filter(key => key in data && (data[key] ?? 0) > 0)
1369
+ .map(key => [key, data[key] ?? 0]);
1370
+ }
1371
+ else {
1372
+ // Sort by count descending
1373
+ entries = Object.entries(data)
1374
+ .sort((a, b) => b[1] - a[1])
1375
+ .slice(0, maxItems);
1376
+ }
1377
+ if (entries.length === 0)
1378
+ return '<p class="empty">No data</p>';
1379
+ const maxVal = Math.max(...entries.map(e => e[1]));
1380
+ return entries
1381
+ .map(([label, count]) => {
1382
+ const pct = (count / maxVal) * 100;
1383
+ // Use LABEL_MAP if available, otherwise clean up underscores and title case
1384
+ const cleanLabel = LABEL_MAP[label] ||
1385
+ label.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
1386
+ return `<div class="bar-row">
1387
+ <div class="bar-label">${escapeHtml(cleanLabel)}</div>
1388
+ <div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:${color}"></div></div>
1389
+ <div class="bar-value">${count}</div>
1390
+ </div>`;
1391
+ })
1392
+ .join('\n');
1393
+ }
1394
+ function generateResponseTimeHistogram(times) {
1395
+ if (times.length === 0)
1396
+ return '<p class="empty">No response time data</p>';
1397
+ // Create buckets (matching Python reference)
1398
+ const buckets = {
1399
+ '2-10s': 0,
1400
+ '10-30s': 0,
1401
+ '30s-1m': 0,
1402
+ '1-2m': 0,
1403
+ '2-5m': 0,
1404
+ '5-15m': 0,
1405
+ '>15m': 0,
1406
+ };
1407
+ for (const t of times) {
1408
+ if (t < 10)
1409
+ buckets['2-10s'] = (buckets['2-10s'] ?? 0) + 1;
1410
+ else if (t < 30)
1411
+ buckets['10-30s'] = (buckets['10-30s'] ?? 0) + 1;
1412
+ else if (t < 60)
1413
+ buckets['30s-1m'] = (buckets['30s-1m'] ?? 0) + 1;
1414
+ else if (t < 120)
1415
+ buckets['1-2m'] = (buckets['1-2m'] ?? 0) + 1;
1416
+ else if (t < 300)
1417
+ buckets['2-5m'] = (buckets['2-5m'] ?? 0) + 1;
1418
+ else if (t < 900)
1419
+ buckets['5-15m'] = (buckets['5-15m'] ?? 0) + 1;
1420
+ else
1421
+ buckets['>15m'] = (buckets['>15m'] ?? 0) + 1;
1422
+ }
1423
+ const maxVal = Math.max(...Object.values(buckets));
1424
+ if (maxVal === 0)
1425
+ return '<p class="empty">No response time data</p>';
1426
+ return Object.entries(buckets)
1427
+ .map(([label, count]) => {
1428
+ const pct = (count / maxVal) * 100;
1429
+ return `<div class="bar-row">
1430
+ <div class="bar-label">${label}</div>
1431
+ <div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:#6366f1"></div></div>
1432
+ <div class="bar-value">${count}</div>
1433
+ </div>`;
1434
+ })
1435
+ .join('\n');
1436
+ }
1437
+ function generateTimeOfDayChart(messageHours) {
1438
+ if (messageHours.length === 0)
1439
+ return '<p class="empty">No time data</p>';
1440
+ // Group into time periods
1441
+ const periods = [
1442
+ { label: 'Morning (6-12)', range: [6, 7, 8, 9, 10, 11] },
1443
+ { label: 'Afternoon (12-18)', range: [12, 13, 14, 15, 16, 17] },
1444
+ { label: 'Evening (18-24)', range: [18, 19, 20, 21, 22, 23] },
1445
+ { label: 'Night (0-6)', range: [0, 1, 2, 3, 4, 5] },
1446
+ ];
1447
+ const hourCounts = {};
1448
+ for (const h of messageHours) {
1449
+ hourCounts[h] = (hourCounts[h] || 0) + 1;
1450
+ }
1451
+ const periodCounts = periods.map(p => ({
1452
+ label: p.label,
1453
+ count: p.range.reduce((sum, h) => sum + (hourCounts[h] || 0), 0),
1454
+ }));
1455
+ const maxVal = Math.max(...periodCounts.map(p => p.count)) || 1;
1456
+ const barsHtml = periodCounts
1457
+ .map(p => `
1458
+ <div class="bar-row">
1459
+ <div class="bar-label">${p.label}</div>
1460
+ <div class="bar-track"><div class="bar-fill" style="width:${(p.count / maxVal) * 100}%;background:#8b5cf6"></div></div>
1461
+ <div class="bar-value">${p.count}</div>
1462
+ </div>`)
1463
+ .join('\n');
1464
+ return `<div id="hour-histogram">${barsHtml}</div>`;
1465
+ }
1466
+ function getHourCountsJson(messageHours) {
1467
+ const hourCounts = {};
1468
+ for (const h of messageHours) {
1469
+ hourCounts[h] = (hourCounts[h] || 0) + 1;
1470
+ }
1471
+ return jsonStringify(hourCounts);
1472
+ }
1473
+ function generateHtmlReport(data, insights) {
1474
+ const markdownToHtml = (md) => {
1475
+ if (!md)
1476
+ return '';
1477
+ return md
1478
+ .split('\n\n')
1479
+ .map(p => {
1480
+ let html = escapeHtml(p);
1481
+ html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
1482
+ html = html.replace(/^- /gm, '• ');
1483
+ html = html.replace(/\n/g, '<br>');
1484
+ return `<p>${html}</p>`;
1485
+ })
1486
+ .join('\n');
1487
+ };
1488
+ // Build At a Glance section (new 4-part format with links to sections)
1489
+ const atAGlance = insights.at_a_glance;
1490
+ const atAGlanceHtml = atAGlance
1491
+ ? `
1492
+ <div class="at-a-glance">
1493
+ <div class="glance-title">At a Glance</div>
1494
+ <div class="glance-sections">
1495
+ ${atAGlance.whats_working ? `<div class="glance-section"><strong>What's working:</strong> ${escapeHtmlWithBold(atAGlance.whats_working)} <a href="#section-wins" class="see-more">Impressive Things You Did →</a></div>` : ''}
1496
+ ${atAGlance.whats_hindering ? `<div class="glance-section"><strong>What's hindering you:</strong> ${escapeHtmlWithBold(atAGlance.whats_hindering)} <a href="#section-friction" class="see-more">Where Things Go Wrong →</a></div>` : ''}
1497
+ ${atAGlance.quick_wins ? `<div class="glance-section"><strong>Quick wins to try:</strong> ${escapeHtmlWithBold(atAGlance.quick_wins)} <a href="#section-features" class="see-more">Features to Try →</a></div>` : ''}
1498
+ ${atAGlance.ambitious_workflows ? `<div class="glance-section"><strong>Ambitious workflows:</strong> ${escapeHtmlWithBold(atAGlance.ambitious_workflows)} <a href="#section-horizon" class="see-more">On the Horizon →</a></div>` : ''}
1499
+ </div>
1500
+ </div>
1501
+ `
1502
+ : '';
1503
+ // Build project areas section
1504
+ const projectAreas = insights.project_areas?.areas || [];
1505
+ const projectAreasHtml = projectAreas.length > 0
1506
+ ? `
1507
+ <h2 id="section-work">What You Work On</h2>
1508
+ <div class="project-areas">
1509
+ ${projectAreas
1510
+ .map(area => `
1511
+ <div class="project-area">
1512
+ <div class="area-header">
1513
+ <span class="area-name">${escapeHtml(area.name)}</span>
1514
+ <span class="area-count">~${area.session_count} sessions</span>
1515
+ </div>
1516
+ <div class="area-desc">${escapeHtml(area.description)}</div>
1517
+ </div>
1518
+ `)
1519
+ .join('')}
1520
+ </div>
1521
+ `
1522
+ : '';
1523
+ // Build interaction style section
1524
+ const interactionStyle = insights.interaction_style;
1525
+ const interactionHtml = interactionStyle?.narrative
1526
+ ? `
1527
+ <h2 id="section-usage">How You Use Thaddeus</h2>
1528
+ <div class="narrative">
1529
+ ${markdownToHtml(interactionStyle.narrative)}
1530
+ ${interactionStyle.key_pattern ? `<div class="key-insight"><strong>Key pattern:</strong> ${escapeHtml(interactionStyle.key_pattern)}</div>` : ''}
1531
+ </div>
1532
+ `
1533
+ : '';
1534
+ // Build what works section
1535
+ const whatWorks = insights.what_works;
1536
+ const whatWorksHtml = whatWorks?.impressive_workflows && whatWorks.impressive_workflows.length > 0
1537
+ ? `
1538
+ <h2 id="section-wins">Impressive Things You Did</h2>
1539
+ ${whatWorks.intro ? `<p class="section-intro">${escapeHtml(whatWorks.intro)}</p>` : ''}
1540
+ <div class="big-wins">
1541
+ ${whatWorks.impressive_workflows
1542
+ .map(wf => `
1543
+ <div class="big-win">
1544
+ <div class="big-win-title">${escapeHtml(wf.title || '')}</div>
1545
+ <div class="big-win-desc">${escapeHtml(wf.description || '')}</div>
1546
+ </div>
1547
+ `)
1548
+ .join('')}
1549
+ </div>
1550
+ `
1551
+ : '';
1552
+ // Build friction section
1553
+ const frictionAnalysis = insights.friction_analysis;
1554
+ const frictionHtml = frictionAnalysis?.categories && frictionAnalysis.categories.length > 0
1555
+ ? `
1556
+ <h2 id="section-friction">Where Things Go Wrong</h2>
1557
+ ${frictionAnalysis.intro ? `<p class="section-intro">${escapeHtml(frictionAnalysis.intro)}</p>` : ''}
1558
+ <div class="friction-categories">
1559
+ ${frictionAnalysis.categories
1560
+ .map(cat => `
1561
+ <div class="friction-category">
1562
+ <div class="friction-title">${escapeHtml(cat.category || '')}</div>
1563
+ <div class="friction-desc">${escapeHtml(cat.description || '')}</div>
1564
+ ${cat.examples ? `<ul class="friction-examples">${cat.examples.map(ex => `<li>${escapeHtml(ex)}</li>`).join('')}</ul>` : ''}
1565
+ </div>
1566
+ `)
1567
+ .join('')}
1568
+ </div>
1569
+ `
1570
+ : '';
1571
+ // Build suggestions section
1572
+ const suggestions = insights.suggestions;
1573
+ const suggestionsHtml = suggestions
1574
+ ? `
1575
+ ${suggestions.claude_md_additions &&
1576
+ suggestions.claude_md_additions.length > 0
1577
+ ? `
1578
+ <h2 id="section-features">Existing CC Features to Try</h2>
1579
+ <div class="claude-md-section">
1580
+ <h3>Suggested THADDEUS.md Additions</h3>
1581
+ <p style="font-size: 12px; color: #64748b; margin-bottom: 12px;">Just copy this into Thaddeus to add it to your THADDEUS.md.</p>
1582
+ <div class="claude-md-actions">
1583
+ <button class="copy-all-btn" onclick="copyAllCheckedClaudeMd()">Copy All Checked</button>
1584
+ </div>
1585
+ ${suggestions.claude_md_additions
1586
+ .map((add, i) => `
1587
+ <div class="claude-md-item">
1588
+ <input type="checkbox" id="cmd-${i}" class="cmd-checkbox" checked data-text="${escapeHtml(add.prompt_scaffold || add.where || 'Add to THADDEUS.md')}\\n\\n${escapeHtml(add.addition)}">
1589
+ <label for="cmd-${i}">
1590
+ <code class="cmd-code">${escapeHtml(add.addition)}</code>
1591
+ <button class="copy-btn" onclick="copyCmdItem(${i})">Copy</button>
1592
+ </label>
1593
+ <div class="cmd-why">${escapeHtml(add.why)}</div>
1594
+ </div>
1595
+ `)
1596
+ .join('')}
1597
+ </div>
1598
+ `
1599
+ : ''}
1600
+ ${suggestions.features_to_try && suggestions.features_to_try.length > 0
1601
+ ? `
1602
+ <p style="font-size: 13px; color: #64748b; margin-bottom: 12px;">Just copy this into Thaddeus and it'll set it up for you.</p>
1603
+ <div class="features-section">
1604
+ ${suggestions.features_to_try
1605
+ .map(feat => `
1606
+ <div class="feature-card">
1607
+ <div class="feature-title">${escapeHtml(feat.feature || '')}</div>
1608
+ <div class="feature-oneliner">${escapeHtml(feat.one_liner || '')}</div>
1609
+ <div class="feature-why"><strong>Why for you:</strong> ${escapeHtml(feat.why_for_you || '')}</div>
1610
+ ${feat.example_code
1611
+ ? `
1612
+ <div class="feature-examples">
1613
+ <div class="feature-example">
1614
+ <div class="example-code-row">
1615
+ <code class="example-code">${escapeHtml(feat.example_code)}</code>
1616
+ <button class="copy-btn" onclick="copyText(this)">Copy</button>
1617
+ </div>
1618
+ </div>
1619
+ </div>
1620
+ `
1621
+ : ''}
1622
+ </div>
1623
+ `)
1624
+ .join('')}
1625
+ </div>
1626
+ `
1627
+ : ''}
1628
+ ${suggestions.usage_patterns && suggestions.usage_patterns.length > 0
1629
+ ? `
1630
+ <h2 id="section-patterns">New Ways to Use Thaddeus</h2>
1631
+ <p style="font-size: 13px; color: #64748b; margin-bottom: 12px;">Just copy this into Thaddeus and it'll walk you through it.</p>
1632
+ <div class="patterns-section">
1633
+ ${suggestions.usage_patterns
1634
+ .map(pat => `
1635
+ <div class="pattern-card">
1636
+ <div class="pattern-title">${escapeHtml(pat.title || '')}</div>
1637
+ <div class="pattern-summary">${escapeHtml(pat.suggestion || '')}</div>
1638
+ ${pat.detail ? `<div class="pattern-detail">${escapeHtml(pat.detail)}</div>` : ''}
1639
+ ${pat.copyable_prompt
1640
+ ? `
1641
+ <div class="copyable-prompt-section">
1642
+ <div class="prompt-label">Paste into Thaddeus:</div>
1643
+ <div class="copyable-prompt-row">
1644
+ <code class="copyable-prompt">${escapeHtml(pat.copyable_prompt)}</code>
1645
+ <button class="copy-btn" onclick="copyText(this)">Copy</button>
1646
+ </div>
1647
+ </div>
1648
+ `
1649
+ : ''}
1650
+ </div>
1651
+ `)
1652
+ .join('')}
1653
+ </div>
1654
+ `
1655
+ : ''}
1656
+ `
1657
+ : '';
1658
+ // Build On the Horizon section
1659
+ const horizonData = insights.on_the_horizon;
1660
+ const horizonHtml = horizonData?.opportunities && horizonData.opportunities.length > 0
1661
+ ? `
1662
+ <h2 id="section-horizon">On the Horizon</h2>
1663
+ ${horizonData.intro ? `<p class="section-intro">${escapeHtml(horizonData.intro)}</p>` : ''}
1664
+ <div class="horizon-section">
1665
+ ${horizonData.opportunities
1666
+ .map(opp => `
1667
+ <div class="horizon-card">
1668
+ <div class="horizon-title">${escapeHtml(opp.title || '')}</div>
1669
+ <div class="horizon-possible">${escapeHtml(opp.whats_possible || '')}</div>
1670
+ ${opp.how_to_try ? `<div class="horizon-tip"><strong>Getting started:</strong> ${escapeHtml(opp.how_to_try)}</div>` : ''}
1671
+ ${opp.copyable_prompt ? `<div class="pattern-prompt"><div class="prompt-label">Paste into Thaddeus:</div><code>${escapeHtml(opp.copyable_prompt)}</code><button class="copy-btn" onclick="copyText(this)">Copy</button></div>` : ''}
1672
+ </div>
1673
+ `)
1674
+ .join('')}
1675
+ </div>
1676
+ `
1677
+ : '';
1678
+ // Build Team Feedback section (collapsible, ant-only)
1679
+ const ccImprovements = process.env.USER_TYPE === 'ant'
1680
+ ? insights.cc_team_improvements?.improvements || []
1681
+ : [];
1682
+ const modelImprovements = process.env.USER_TYPE === 'ant'
1683
+ ? insights.model_behavior_improvements?.improvements || []
1684
+ : [];
1685
+ const teamFeedbackHtml = ccImprovements.length > 0 || modelImprovements.length > 0
1686
+ ? `
1687
+ <h2 id="section-feedback" class="feedback-header">Closing the Loop: Feedback for Other Teams</h2>
1688
+ <p class="feedback-intro">Suggestions for the CC product and model teams based on your usage patterns. Click to expand.</p>
1689
+ ${ccImprovements.length > 0
1690
+ ? `
1691
+ <div class="collapsible-section">
1692
+ <div class="collapsible-header" onclick="toggleCollapsible(this)">
1693
+ <span class="collapsible-arrow">▶</span>
1694
+ <h3>Product Improvements for CC Team</h3>
1695
+ </div>
1696
+ <div class="collapsible-content">
1697
+ <div class="suggestions-section">
1698
+ ${ccImprovements
1699
+ .map(imp => `
1700
+ <div class="feedback-card team-card">
1701
+ <div class="feedback-title">${escapeHtml(imp.title || '')}</div>
1702
+ <div class="feedback-detail">${escapeHtml(imp.detail || '')}</div>
1703
+ ${imp.evidence ? `<div class="feedback-evidence"><em>Evidence:</em> ${escapeHtml(imp.evidence)}</div>` : ''}
1704
+ </div>
1705
+ `)
1706
+ .join('')}
1707
+ </div>
1708
+ </div>
1709
+ </div>
1710
+ `
1711
+ : ''}
1712
+ ${modelImprovements.length > 0
1713
+ ? `
1714
+ <div class="collapsible-section">
1715
+ <div class="collapsible-header" onclick="toggleCollapsible(this)">
1716
+ <span class="collapsible-arrow">▶</span>
1717
+ <h3>Model Behavior Improvements</h3>
1718
+ </div>
1719
+ <div class="collapsible-content">
1720
+ <div class="suggestions-section">
1721
+ ${modelImprovements
1722
+ .map(imp => `
1723
+ <div class="feedback-card model-card">
1724
+ <div class="feedback-title">${escapeHtml(imp.title || '')}</div>
1725
+ <div class="feedback-detail">${escapeHtml(imp.detail || '')}</div>
1726
+ ${imp.evidence ? `<div class="feedback-evidence"><em>Evidence:</em> ${escapeHtml(imp.evidence)}</div>` : ''}
1727
+ </div>
1728
+ `)
1729
+ .join('')}
1730
+ </div>
1731
+ </div>
1732
+ </div>
1733
+ `
1734
+ : ''}
1735
+ `
1736
+ : '';
1737
+ // Build Fun Ending section
1738
+ const funEnding = insights.fun_ending;
1739
+ const funEndingHtml = funEnding?.headline
1740
+ ? `
1741
+ <div class="fun-ending">
1742
+ <div class="fun-headline">"${escapeHtml(funEnding.headline)}"</div>
1743
+ ${funEnding.detail ? `<div class="fun-detail">${escapeHtml(funEnding.detail)}</div>` : ''}
1744
+ </div>
1745
+ `
1746
+ : '';
1747
+ const css = `
1748
+ * { box-sizing: border-box; margin: 0; padding: 0; }
1749
+ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; background: #f8fafc; color: #334155; line-height: 1.65; padding: 48px 24px; }
1750
+ .container { max-width: 800px; margin: 0 auto; }
1751
+ h1 { font-size: 32px; font-weight: 700; color: #0f172a; margin-bottom: 8px; }
1752
+ h2 { font-size: 20px; font-weight: 600; color: #0f172a; margin-top: 48px; margin-bottom: 16px; }
1753
+ .subtitle { color: #64748b; font-size: 15px; margin-bottom: 32px; }
1754
+ .nav-toc { display: flex; flex-wrap: wrap; gap: 8px; margin: 24px 0 32px 0; padding: 16px; background: white; border-radius: 8px; border: 1px solid #e2e8f0; }
1755
+ .nav-toc a { font-size: 12px; color: #64748b; text-decoration: none; padding: 6px 12px; border-radius: 6px; background: #f1f5f9; transition: all 0.15s; }
1756
+ .nav-toc a:hover { background: #e2e8f0; color: #334155; }
1757
+ .stats-row { display: flex; gap: 24px; margin-bottom: 40px; padding: 20px 0; border-top: 1px solid #e2e8f0; border-bottom: 1px solid #e2e8f0; flex-wrap: wrap; }
1758
+ .stat { text-align: center; }
1759
+ .stat-value { font-size: 24px; font-weight: 700; color: #0f172a; }
1760
+ .stat-label { font-size: 11px; color: #64748b; text-transform: uppercase; }
1761
+ .at-a-glance { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #f59e0b; border-radius: 12px; padding: 20px 24px; margin-bottom: 32px; }
1762
+ .glance-title { font-size: 16px; font-weight: 700; color: #92400e; margin-bottom: 16px; }
1763
+ .glance-sections { display: flex; flex-direction: column; gap: 12px; }
1764
+ .glance-section { font-size: 14px; color: #78350f; line-height: 1.6; }
1765
+ .glance-section strong { color: #92400e; }
1766
+ .see-more { color: #b45309; text-decoration: none; font-size: 13px; white-space: nowrap; }
1767
+ .see-more:hover { text-decoration: underline; }
1768
+ .project-areas { display: flex; flex-direction: column; gap: 12px; margin-bottom: 32px; }
1769
+ .project-area { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; }
1770
+ .area-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
1771
+ .area-name { font-weight: 600; font-size: 15px; color: #0f172a; }
1772
+ .area-count { font-size: 12px; color: #64748b; background: #f1f5f9; padding: 2px 8px; border-radius: 4px; }
1773
+ .area-desc { font-size: 14px; color: #475569; line-height: 1.5; }
1774
+ .narrative { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 24px; }
1775
+ .narrative p { margin-bottom: 12px; font-size: 14px; color: #475569; line-height: 1.7; }
1776
+ .key-insight { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 8px; padding: 12px 16px; margin-top: 12px; font-size: 14px; color: #166534; }
1777
+ .section-intro { font-size: 14px; color: #64748b; margin-bottom: 16px; }
1778
+ .big-wins { display: flex; flex-direction: column; gap: 12px; margin-bottom: 24px; }
1779
+ .big-win { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 8px; padding: 16px; }
1780
+ .big-win-title { font-weight: 600; font-size: 15px; color: #166534; margin-bottom: 8px; }
1781
+ .big-win-desc { font-size: 14px; color: #15803d; line-height: 1.5; }
1782
+ .friction-categories { display: flex; flex-direction: column; gap: 16px; margin-bottom: 24px; }
1783
+ .friction-category { background: #fef2f2; border: 1px solid #fca5a5; border-radius: 8px; padding: 16px; }
1784
+ .friction-title { font-weight: 600; font-size: 15px; color: #991b1b; margin-bottom: 6px; }
1785
+ .friction-desc { font-size: 13px; color: #7f1d1d; margin-bottom: 10px; }
1786
+ .friction-examples { margin: 0 0 0 20px; font-size: 13px; color: #334155; }
1787
+ .friction-examples li { margin-bottom: 4px; }
1788
+ .claude-md-section { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px; padding: 16px; margin-bottom: 20px; }
1789
+ .claude-md-section h3 { font-size: 14px; font-weight: 600; color: #1e40af; margin: 0 0 12px 0; }
1790
+ .claude-md-actions { margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #dbeafe; }
1791
+ .copy-all-btn { background: #2563eb; color: white; border: none; border-radius: 4px; padding: 6px 12px; font-size: 12px; cursor: pointer; font-weight: 500; transition: all 0.2s; }
1792
+ .copy-all-btn:hover { background: #1d4ed8; }
1793
+ .copy-all-btn.copied { background: #16a34a; }
1794
+ .claude-md-item { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 8px; padding: 10px 0; border-bottom: 1px solid #dbeafe; }
1795
+ .claude-md-item:last-child { border-bottom: none; }
1796
+ .cmd-checkbox { margin-top: 2px; }
1797
+ .cmd-code { background: white; padding: 8px 12px; border-radius: 4px; font-size: 12px; color: #1e40af; border: 1px solid #bfdbfe; font-family: monospace; display: block; white-space: pre-wrap; word-break: break-word; flex: 1; }
1798
+ .cmd-why { font-size: 12px; color: #64748b; width: 100%; padding-left: 24px; margin-top: 4px; }
1799
+ .features-section, .patterns-section { display: flex; flex-direction: column; gap: 12px; margin: 16px 0; }
1800
+ .feature-card { background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; padding: 16px; }
1801
+ .pattern-card { background: #f0f9ff; border: 1px solid #7dd3fc; border-radius: 8px; padding: 16px; }
1802
+ .feature-title, .pattern-title { font-weight: 600; font-size: 15px; color: #0f172a; margin-bottom: 6px; }
1803
+ .feature-oneliner { font-size: 14px; color: #475569; margin-bottom: 8px; }
1804
+ .pattern-summary { font-size: 14px; color: #475569; margin-bottom: 8px; }
1805
+ .feature-why, .pattern-detail { font-size: 13px; color: #334155; line-height: 1.5; }
1806
+ .feature-examples { margin-top: 12px; }
1807
+ .feature-example { padding: 8px 0; border-top: 1px solid #d1fae5; }
1808
+ .feature-example:first-child { border-top: none; }
1809
+ .example-desc { font-size: 13px; color: #334155; margin-bottom: 6px; }
1810
+ .example-code-row { display: flex; align-items: flex-start; gap: 8px; }
1811
+ .example-code { flex: 1; background: #f1f5f9; padding: 8px 12px; border-radius: 4px; font-family: monospace; font-size: 12px; color: #334155; overflow-x: auto; white-space: pre-wrap; }
1812
+ .copyable-prompt-section { margin-top: 12px; padding-top: 12px; border-top: 1px solid #e2e8f0; }
1813
+ .copyable-prompt-row { display: flex; align-items: flex-start; gap: 8px; }
1814
+ .copyable-prompt { flex: 1; background: #f8fafc; padding: 10px 12px; border-radius: 4px; font-family: monospace; font-size: 12px; color: #334155; border: 1px solid #e2e8f0; white-space: pre-wrap; line-height: 1.5; }
1815
+ .feature-code { background: #f8fafc; padding: 12px; border-radius: 6px; margin-top: 12px; border: 1px solid #e2e8f0; display: flex; align-items: flex-start; gap: 8px; }
1816
+ .feature-code code { flex: 1; font-family: monospace; font-size: 12px; color: #334155; white-space: pre-wrap; }
1817
+ .pattern-prompt { background: #f8fafc; padding: 12px; border-radius: 6px; margin-top: 12px; border: 1px solid #e2e8f0; }
1818
+ .pattern-prompt code { font-family: monospace; font-size: 12px; color: #334155; display: block; white-space: pre-wrap; margin-bottom: 8px; }
1819
+ .prompt-label { font-size: 11px; font-weight: 600; text-transform: uppercase; color: #64748b; margin-bottom: 6px; }
1820
+ .copy-btn { background: #e2e8f0; border: none; border-radius: 4px; padding: 4px 8px; font-size: 11px; cursor: pointer; color: #475569; flex-shrink: 0; }
1821
+ .copy-btn:hover { background: #cbd5e1; }
1822
+ .charts-row { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin: 24px 0; }
1823
+ .chart-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; }
1824
+ .chart-title { font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; margin-bottom: 12px; }
1825
+ .bar-row { display: flex; align-items: center; margin-bottom: 6px; }
1826
+ .bar-label { width: 100px; font-size: 11px; color: #475569; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1827
+ .bar-track { flex: 1; height: 6px; background: #f1f5f9; border-radius: 3px; margin: 0 8px; }
1828
+ .bar-fill { height: 100%; border-radius: 3px; }
1829
+ .bar-value { width: 28px; font-size: 11px; font-weight: 500; color: #64748b; text-align: right; }
1830
+ .empty { color: #94a3b8; font-size: 13px; }
1831
+ .horizon-section { display: flex; flex-direction: column; gap: 16px; }
1832
+ .horizon-card { background: linear-gradient(135deg, #faf5ff 0%, #f5f3ff 100%); border: 1px solid #c4b5fd; border-radius: 8px; padding: 16px; }
1833
+ .horizon-title { font-weight: 600; font-size: 15px; color: #5b21b6; margin-bottom: 8px; }
1834
+ .horizon-possible { font-size: 14px; color: #334155; margin-bottom: 10px; line-height: 1.5; }
1835
+ .horizon-tip { font-size: 13px; color: #6b21a8; background: rgba(255,255,255,0.6); padding: 8px 12px; border-radius: 4px; }
1836
+ .feedback-header { margin-top: 48px; color: #64748b; font-size: 16px; }
1837
+ .feedback-intro { font-size: 13px; color: #94a3b8; margin-bottom: 16px; }
1838
+ .feedback-section { margin-top: 16px; }
1839
+ .feedback-section h3 { font-size: 14px; font-weight: 600; color: #475569; margin-bottom: 12px; }
1840
+ .feedback-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; margin-bottom: 12px; }
1841
+ .feedback-card.team-card { background: #eff6ff; border-color: #bfdbfe; }
1842
+ .feedback-card.model-card { background: #faf5ff; border-color: #e9d5ff; }
1843
+ .feedback-title { font-weight: 600; font-size: 14px; color: #0f172a; margin-bottom: 6px; }
1844
+ .feedback-detail { font-size: 13px; color: #475569; line-height: 1.5; }
1845
+ .feedback-evidence { font-size: 12px; color: #64748b; margin-top: 8px; }
1846
+ .fun-ending { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #fbbf24; border-radius: 12px; padding: 24px; margin-top: 40px; text-align: center; }
1847
+ .fun-headline { font-size: 18px; font-weight: 600; color: #78350f; margin-bottom: 8px; }
1848
+ .fun-detail { font-size: 14px; color: #92400e; }
1849
+ .collapsible-section { margin-top: 16px; }
1850
+ .collapsible-header { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 12px 0; border-bottom: 1px solid #e2e8f0; }
1851
+ .collapsible-header h3 { margin: 0; font-size: 14px; font-weight: 600; color: #475569; }
1852
+ .collapsible-arrow { font-size: 12px; color: #94a3b8; transition: transform 0.2s; }
1853
+ .collapsible-content { display: none; padding-top: 16px; }
1854
+ .collapsible-content.open { display: block; }
1855
+ .collapsible-header.open .collapsible-arrow { transform: rotate(90deg); }
1856
+ @media (max-width: 640px) { .charts-row { grid-template-columns: 1fr; } .stats-row { justify-content: center; } }
1857
+ `;
1858
+ const hourCountsJson = getHourCountsJson(data.message_hours);
1859
+ const js = `
1860
+ function toggleCollapsible(header) {
1861
+ header.classList.toggle('open');
1862
+ const content = header.nextElementSibling;
1863
+ content.classList.toggle('open');
1864
+ }
1865
+ function copyText(btn) {
1866
+ const code = btn.previousElementSibling;
1867
+ navigator.clipboard.writeText(code.textContent).then(() => {
1868
+ btn.textContent = 'Copied!';
1869
+ setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
1870
+ });
1871
+ }
1872
+ function copyCmdItem(idx) {
1873
+ const checkbox = document.getElementById('cmd-' + idx);
1874
+ if (checkbox) {
1875
+ const text = checkbox.dataset.text;
1876
+ navigator.clipboard.writeText(text).then(() => {
1877
+ const btn = checkbox.nextElementSibling.querySelector('.copy-btn');
1878
+ if (btn) { btn.textContent = 'Copied!'; setTimeout(() => { btn.textContent = 'Copy'; }, 2000); }
1879
+ });
1880
+ }
1881
+ }
1882
+ function copyAllCheckedClaudeMd() {
1883
+ const checkboxes = document.querySelectorAll('.cmd-checkbox:checked');
1884
+ const texts = [];
1885
+ checkboxes.forEach(cb => {
1886
+ if (cb.dataset.text) { texts.push(cb.dataset.text); }
1887
+ });
1888
+ const combined = texts.join('\\n');
1889
+ const btn = document.querySelector('.copy-all-btn');
1890
+ if (btn) {
1891
+ navigator.clipboard.writeText(combined).then(() => {
1892
+ btn.textContent = 'Copied ' + texts.length + ' items!';
1893
+ btn.classList.add('copied');
1894
+ setTimeout(() => { btn.textContent = 'Copy All Checked'; btn.classList.remove('copied'); }, 2000);
1895
+ });
1896
+ }
1897
+ }
1898
+ // Timezone selector for time of day chart (data is from our own analytics, not user input)
1899
+ const rawHourCounts = ${hourCountsJson};
1900
+ function updateHourHistogram(offsetFromPT) {
1901
+ const periods = [
1902
+ { label: "Morning (6-12)", range: [6,7,8,9,10,11] },
1903
+ { label: "Afternoon (12-18)", range: [12,13,14,15,16,17] },
1904
+ { label: "Evening (18-24)", range: [18,19,20,21,22,23] },
1905
+ { label: "Night (0-6)", range: [0,1,2,3,4,5] }
1906
+ ];
1907
+ const adjustedCounts = {};
1908
+ for (const [hour, count] of Object.entries(rawHourCounts)) {
1909
+ const newHour = (parseInt(hour) + offsetFromPT + 24) % 24;
1910
+ adjustedCounts[newHour] = (adjustedCounts[newHour] || 0) + count;
1911
+ }
1912
+ const periodCounts = periods.map(p => ({
1913
+ label: p.label,
1914
+ count: p.range.reduce((sum, h) => sum + (adjustedCounts[h] || 0), 0)
1915
+ }));
1916
+ const maxCount = Math.max(...periodCounts.map(p => p.count)) || 1;
1917
+ const container = document.getElementById('hour-histogram');
1918
+ container.textContent = '';
1919
+ periodCounts.forEach(p => {
1920
+ const row = document.createElement('div');
1921
+ row.className = 'bar-row';
1922
+ const label = document.createElement('div');
1923
+ label.className = 'bar-label';
1924
+ label.textContent = p.label;
1925
+ const track = document.createElement('div');
1926
+ track.className = 'bar-track';
1927
+ const fill = document.createElement('div');
1928
+ fill.className = 'bar-fill';
1929
+ fill.style.width = (p.count / maxCount) * 100 + '%';
1930
+ fill.style.background = '#8b5cf6';
1931
+ track.appendChild(fill);
1932
+ const value = document.createElement('div');
1933
+ value.className = 'bar-value';
1934
+ value.textContent = p.count;
1935
+ row.appendChild(label);
1936
+ row.appendChild(track);
1937
+ row.appendChild(value);
1938
+ container.appendChild(row);
1939
+ });
1940
+ }
1941
+ document.getElementById('timezone-select').addEventListener('change', function() {
1942
+ const customInput = document.getElementById('custom-offset');
1943
+ if (this.value === 'custom') {
1944
+ customInput.style.display = 'inline-block';
1945
+ customInput.focus();
1946
+ } else {
1947
+ customInput.style.display = 'none';
1948
+ updateHourHistogram(parseInt(this.value));
1949
+ }
1950
+ });
1951
+ document.getElementById('custom-offset').addEventListener('change', function() {
1952
+ const offset = parseInt(this.value) + 8;
1953
+ updateHourHistogram(offset);
1954
+ });
1955
+ `;
1956
+ return `<!DOCTYPE html>
1957
+ <html>
1958
+ <head>
1959
+ <meta charset="utf-8">
1960
+ <title>Thaddeus Insights</title>
1961
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
1962
+ <style>${css}</style>
1963
+ </head>
1964
+ <body>
1965
+ <div class="container">
1966
+ <h1>Thaddeus Insights</h1>
1967
+ <p class="subtitle">${data.total_messages.toLocaleString()} messages across ${data.total_sessions} sessions${data.total_sessions_scanned && data.total_sessions_scanned > data.total_sessions ? ` (${data.total_sessions_scanned.toLocaleString()} total)` : ''} | ${data.date_range.start} to ${data.date_range.end}</p>
1968
+
1969
+ ${atAGlanceHtml}
1970
+
1971
+ <nav class="nav-toc">
1972
+ <a href="#section-work">What You Work On</a>
1973
+ <a href="#section-usage">How You Use CC</a>
1974
+ <a href="#section-wins">Impressive Things</a>
1975
+ <a href="#section-friction">Where Things Go Wrong</a>
1976
+ <a href="#section-features">Features to Try</a>
1977
+ <a href="#section-patterns">New Usage Patterns</a>
1978
+ <a href="#section-horizon">On the Horizon</a>
1979
+ <a href="#section-feedback">Team Feedback</a>
1980
+ </nav>
1981
+
1982
+ <div class="stats-row">
1983
+ <div class="stat"><div class="stat-value">${data.total_messages.toLocaleString()}</div><div class="stat-label">Messages</div></div>
1984
+ <div class="stat"><div class="stat-value">+${data.total_lines_added.toLocaleString()}/-${data.total_lines_removed.toLocaleString()}</div><div class="stat-label">Lines</div></div>
1985
+ <div class="stat"><div class="stat-value">${data.total_files_modified}</div><div class="stat-label">Files</div></div>
1986
+ <div class="stat"><div class="stat-value">${data.days_active}</div><div class="stat-label">Days</div></div>
1987
+ <div class="stat"><div class="stat-value">${data.messages_per_day}</div><div class="stat-label">Msgs/Day</div></div>
1988
+ </div>
1989
+
1990
+ ${projectAreasHtml}
1991
+
1992
+ <div class="charts-row">
1993
+ <div class="chart-card">
1994
+ <div class="chart-title">What You Wanted</div>
1995
+ ${generateBarChart(data.goal_categories, '#2563eb')}
1996
+ </div>
1997
+ <div class="chart-card">
1998
+ <div class="chart-title">Top Tools Used</div>
1999
+ ${generateBarChart(data.tool_counts, '#0891b2')}
2000
+ </div>
2001
+ </div>
2002
+
2003
+ <div class="charts-row">
2004
+ <div class="chart-card">
2005
+ <div class="chart-title">Languages</div>
2006
+ ${generateBarChart(data.languages, '#10b981')}
2007
+ </div>
2008
+ <div class="chart-card">
2009
+ <div class="chart-title">Session Types</div>
2010
+ ${generateBarChart(data.session_types || {}, '#8b5cf6')}
2011
+ </div>
2012
+ </div>
2013
+
2014
+ ${interactionHtml}
2015
+
2016
+ <!-- Response Time Distribution -->
2017
+ <div class="chart-card" style="margin: 24px 0;">
2018
+ <div class="chart-title">User Response Time Distribution</div>
2019
+ ${generateResponseTimeHistogram(data.user_response_times)}
2020
+ <div style="font-size: 12px; color: #64748b; margin-top: 8px;">
2021
+ Median: ${data.median_response_time.toFixed(1)}s &bull; Average: ${data.avg_response_time.toFixed(1)}s
2022
+ </div>
2023
+ </div>
2024
+
2025
+ <!-- Multi-clauding Section (matching Python reference) -->
2026
+ <div class="chart-card" style="margin: 24px 0;">
2027
+ <div class="chart-title">Multi-Clauding (Parallel Sessions)</div>
2028
+ ${data.multi_clauding.overlap_events === 0
2029
+ ? `
2030
+ <p style="font-size: 14px; color: #64748b; padding: 8px 0;">
2031
+ No parallel session usage detected. You typically work with one Thaddeus session at a time.
2032
+ </p>
2033
+ `
2034
+ : `
2035
+ <div style="display: flex; gap: 24px; margin: 12px 0;">
2036
+ <div style="text-align: center;">
2037
+ <div style="font-size: 24px; font-weight: 700; color: #7c3aed;">${data.multi_clauding.overlap_events}</div>
2038
+ <div style="font-size: 11px; color: #64748b; text-transform: uppercase;">Overlap Events</div>
2039
+ </div>
2040
+ <div style="text-align: center;">
2041
+ <div style="font-size: 24px; font-weight: 700; color: #7c3aed;">${data.multi_clauding.sessions_involved}</div>
2042
+ <div style="font-size: 11px; color: #64748b; text-transform: uppercase;">Sessions Involved</div>
2043
+ </div>
2044
+ <div style="text-align: center;">
2045
+ <div style="font-size: 24px; font-weight: 700; color: #7c3aed;">${data.total_messages > 0 ? Math.round((100 * data.multi_clauding.user_messages_during) / data.total_messages) : 0}%</div>
2046
+ <div style="font-size: 11px; color: #64748b; text-transform: uppercase;">Of Messages</div>
2047
+ </div>
2048
+ </div>
2049
+ <p style="font-size: 13px; color: #475569; margin-top: 12px;">
2050
+ You run multiple Thaddeus sessions simultaneously. Multi-clauding is detected when sessions
2051
+ overlap in time, suggesting parallel workflows.
2052
+ </p>
2053
+ `}
2054
+ </div>
2055
+
2056
+ <!-- Time of Day & Tool Errors -->
2057
+ <div class="charts-row">
2058
+ <div class="chart-card">
2059
+ <div class="chart-title" style="display: flex; align-items: center; gap: 12px;">
2060
+ User Messages by Time of Day
2061
+ <select id="timezone-select" style="font-size: 12px; padding: 4px 8px; border-radius: 4px; border: 1px solid #e2e8f0;">
2062
+ <option value="0">PT (UTC-8)</option>
2063
+ <option value="3">ET (UTC-5)</option>
2064
+ <option value="8">London (UTC)</option>
2065
+ <option value="9">CET (UTC+1)</option>
2066
+ <option value="17">Tokyo (UTC+9)</option>
2067
+ <option value="custom">Custom offset...</option>
2068
+ </select>
2069
+ <input type="number" id="custom-offset" placeholder="UTC offset" style="display: none; width: 80px; font-size: 12px; padding: 4px; border-radius: 4px; border: 1px solid #e2e8f0;">
2070
+ </div>
2071
+ ${generateTimeOfDayChart(data.message_hours)}
2072
+ </div>
2073
+ <div class="chart-card">
2074
+ <div class="chart-title">Tool Errors Encountered</div>
2075
+ ${Object.keys(data.tool_error_categories).length > 0 ? generateBarChart(data.tool_error_categories, '#dc2626') : '<p class="empty">No tool errors</p>'}
2076
+ </div>
2077
+ </div>
2078
+
2079
+ ${whatWorksHtml}
2080
+
2081
+ <div class="charts-row">
2082
+ <div class="chart-card">
2083
+ <div class="chart-title">What Helped Most (Thaddeus's Capabilities)</div>
2084
+ ${generateBarChart(data.success, '#16a34a')}
2085
+ </div>
2086
+ <div class="chart-card">
2087
+ <div class="chart-title">Outcomes</div>
2088
+ ${generateBarChart(data.outcomes, '#8b5cf6', 6, OUTCOME_ORDER)}
2089
+ </div>
2090
+ </div>
2091
+
2092
+ ${frictionHtml}
2093
+
2094
+ <div class="charts-row">
2095
+ <div class="chart-card">
2096
+ <div class="chart-title">Primary Friction Types</div>
2097
+ ${generateBarChart(data.friction, '#dc2626')}
2098
+ </div>
2099
+ <div class="chart-card">
2100
+ <div class="chart-title">Inferred Satisfaction (model-estimated)</div>
2101
+ ${generateBarChart(data.satisfaction, '#eab308', 6, SATISFACTION_ORDER)}
2102
+ </div>
2103
+ </div>
2104
+
2105
+ ${suggestionsHtml}
2106
+
2107
+ ${horizonHtml}
2108
+
2109
+ ${funEndingHtml}
2110
+
2111
+ ${teamFeedbackHtml}
2112
+ </div>
2113
+ <script>${js}</script>
2114
+ </body>
2115
+ </html>`;
2116
+ }
2117
+ /**
2118
+ * Build export data from already-computed values.
2119
+ * Used by background upload to S3.
2120
+ */
2121
+ export function buildExportData(data, insights, facets, remoteStats) {
2122
+ const version = typeof MACRO !== 'undefined' ? MACRO.VERSION : 'unknown';
2123
+ const remote_hosts_collected = remoteStats?.hosts
2124
+ .filter(h => h.sessionCount > 0)
2125
+ .map(h => h.name);
2126
+ const facets_summary = {
2127
+ total: facets.size,
2128
+ goal_categories: {},
2129
+ outcomes: {},
2130
+ satisfaction: {},
2131
+ friction: {},
2132
+ };
2133
+ for (const f of facets.values()) {
2134
+ for (const [cat, count] of safeEntries(f.goal_categories)) {
2135
+ if (count > 0) {
2136
+ facets_summary.goal_categories[cat] =
2137
+ (facets_summary.goal_categories[cat] || 0) + count;
2138
+ }
2139
+ }
2140
+ facets_summary.outcomes[f.outcome] =
2141
+ (facets_summary.outcomes[f.outcome] || 0) + 1;
2142
+ for (const [level, count] of safeEntries(f.user_satisfaction_counts)) {
2143
+ if (count > 0) {
2144
+ facets_summary.satisfaction[level] =
2145
+ (facets_summary.satisfaction[level] || 0) + count;
2146
+ }
2147
+ }
2148
+ for (const [type, count] of safeEntries(f.friction_counts)) {
2149
+ if (count > 0) {
2150
+ facets_summary.friction[type] =
2151
+ (facets_summary.friction[type] || 0) + count;
2152
+ }
2153
+ }
2154
+ }
2155
+ return {
2156
+ metadata: {
2157
+ username: process.env.SAFEUSER || process.env.USER || 'unknown',
2158
+ generated_at: new Date().toISOString(),
2159
+ claude_code_version: version,
2160
+ date_range: data.date_range,
2161
+ session_count: data.total_sessions,
2162
+ ...(remote_hosts_collected &&
2163
+ remote_hosts_collected.length > 0 && {
2164
+ remote_hosts_collected,
2165
+ }),
2166
+ },
2167
+ aggregated_data: data,
2168
+ insights,
2169
+ facets_summary,
2170
+ };
2171
+ }
2172
+ /**
2173
+ * Scans all project directories using filesystem metadata only (no JSONL parsing).
2174
+ * Returns a list of session file info sorted by mtime descending.
2175
+ * Yields to the event loop between project directories to keep the UI responsive.
2176
+ */
2177
+ async function scanAllSessions() {
2178
+ const projectsDir = getProjectsDir();
2179
+ let dirents;
2180
+ try {
2181
+ dirents = await readdir(projectsDir, { withFileTypes: true });
2182
+ }
2183
+ catch {
2184
+ return [];
2185
+ }
2186
+ const projectDirs = dirents
2187
+ .filter(dirent => dirent.isDirectory())
2188
+ .map(dirent => join(projectsDir, dirent.name));
2189
+ const allSessions = [];
2190
+ for (let i = 0; i < projectDirs.length; i++) {
2191
+ const sessionFiles = await getSessionFilesWithMtime(projectDirs[i]);
2192
+ for (const [sessionId, fileInfo] of sessionFiles) {
2193
+ allSessions.push({
2194
+ sessionId,
2195
+ path: fileInfo.path,
2196
+ mtime: fileInfo.mtime,
2197
+ size: fileInfo.size,
2198
+ });
2199
+ }
2200
+ // Yield to event loop every 10 project directories
2201
+ if (i % 10 === 9) {
2202
+ await new Promise(resolve => setImmediate(resolve));
2203
+ }
2204
+ }
2205
+ // Sort by mtime descending (most recent first)
2206
+ allSessions.sort((a, b) => b.mtime - a.mtime);
2207
+ return allSessions;
2208
+ }
2209
+ // ============================================================================
2210
+ // Main Function
2211
+ // ============================================================================
2212
+ export async function generateUsageReport(options) {
2213
+ let remoteStats;
2214
+ // Optionally collect data from remote hosts first (ant-only)
2215
+ if (process.env.USER_TYPE === 'ant' && options?.collectRemote) {
2216
+ const destDir = join(getClaudeConfigHomeDir(), 'projects');
2217
+ const { hosts, totalCopied } = await collectAllRemoteHostData(destDir);
2218
+ remoteStats = { hosts, totalCopied };
2219
+ }
2220
+ // Phase 1: Lite scan — filesystem metadata only (no JSONL parsing)
2221
+ const allScannedSessions = await scanAllSessions();
2222
+ const totalSessionsScanned = allScannedSessions.length;
2223
+ // Phase 2: Load SessionMeta — use cache where available, parse only uncached
2224
+ // Read cached metas in parallel batches to avoid blocking the event loop
2225
+ const META_BATCH_SIZE = 50;
2226
+ const MAX_SESSIONS_TO_LOAD = 200;
2227
+ let allMetas = [];
2228
+ const uncachedSessions = [];
2229
+ for (let i = 0; i < allScannedSessions.length; i += META_BATCH_SIZE) {
2230
+ const batch = allScannedSessions.slice(i, i + META_BATCH_SIZE);
2231
+ const results = await Promise.all(batch.map(async (sessionInfo) => ({
2232
+ sessionInfo,
2233
+ cached: await loadCachedSessionMeta(sessionInfo.sessionId),
2234
+ })));
2235
+ for (const { sessionInfo, cached } of results) {
2236
+ if (cached) {
2237
+ allMetas.push(cached);
2238
+ }
2239
+ else if (uncachedSessions.length < MAX_SESSIONS_TO_LOAD) {
2240
+ uncachedSessions.push(sessionInfo);
2241
+ }
2242
+ }
2243
+ }
2244
+ // Load full message data only for uncached sessions and compute SessionMeta
2245
+ const logsForFacets = new Map();
2246
+ // Filter out /insights meta-sessions (facet extraction API calls get logged as sessions)
2247
+ const isMetaSession = (log) => {
2248
+ for (const msg of log.messages.slice(0, 5)) {
2249
+ if (msg.type === 'user' && msg.message) {
2250
+ const content = msg.message.content;
2251
+ if (typeof content === 'string') {
2252
+ if (content.includes('RESPOND WITH ONLY A VALID JSON OBJECT') ||
2253
+ content.includes('record_facets')) {
2254
+ return true;
2255
+ }
2256
+ }
2257
+ }
2258
+ }
2259
+ return false;
2260
+ };
2261
+ // Load uncached sessions in batches to yield to event loop between batches
2262
+ const LOAD_BATCH_SIZE = 10;
2263
+ for (let i = 0; i < uncachedSessions.length; i += LOAD_BATCH_SIZE) {
2264
+ const batch = uncachedSessions.slice(i, i + LOAD_BATCH_SIZE);
2265
+ const batchResults = await Promise.all(batch.map(async (sessionInfo) => {
2266
+ try {
2267
+ return await loadAllLogsFromSessionFile(sessionInfo.path);
2268
+ }
2269
+ catch {
2270
+ return [];
2271
+ }
2272
+ }));
2273
+ // Collect metas synchronously, then save them in parallel (independent writes)
2274
+ const metasToSave = [];
2275
+ for (const logs of batchResults) {
2276
+ for (const log of logs) {
2277
+ if (isMetaSession(log) || !hasValidDates(log))
2278
+ continue;
2279
+ const meta = logToSessionMeta(log);
2280
+ allMetas.push(meta);
2281
+ metasToSave.push(meta);
2282
+ // Keep the log around for potential facet extraction
2283
+ logsForFacets.set(meta.session_id, log);
2284
+ }
2285
+ }
2286
+ await Promise.all(metasToSave.map(meta => saveSessionMeta(meta)));
2287
+ }
2288
+ // Deduplicate session branches (keep the one with most user messages per session_id)
2289
+ // This prevents inflated totals when a session has multiple conversation branches
2290
+ const bestBySession = new Map();
2291
+ for (const meta of allMetas) {
2292
+ const existing = bestBySession.get(meta.session_id);
2293
+ if (!existing ||
2294
+ meta.user_message_count > existing.user_message_count ||
2295
+ (meta.user_message_count === existing.user_message_count &&
2296
+ meta.duration_minutes > existing.duration_minutes)) {
2297
+ bestBySession.set(meta.session_id, meta);
2298
+ }
2299
+ }
2300
+ // Replace allMetas with deduplicated list and remove unused logs from logsForFacets
2301
+ const keptSessionIds = new Set(bestBySession.keys());
2302
+ allMetas = [...bestBySession.values()];
2303
+ for (const sessionId of logsForFacets.keys()) {
2304
+ if (!keptSessionIds.has(sessionId)) {
2305
+ logsForFacets.delete(sessionId);
2306
+ }
2307
+ }
2308
+ // Sort all metas by start_time descending (most recent first)
2309
+ allMetas.sort((a, b) => b.start_time.localeCompare(a.start_time));
2310
+ // Pre-filter obviously minimal sessions to save API calls
2311
+ // (matching Python's substantive filtering concept)
2312
+ const isSubstantiveSession = (meta) => {
2313
+ // Skip sessions with very few user messages
2314
+ if (meta.user_message_count < 2)
2315
+ return false;
2316
+ // Skip very short sessions (< 1 minute)
2317
+ if (meta.duration_minutes < 1)
2318
+ return false;
2319
+ return true;
2320
+ };
2321
+ const substantiveMetas = allMetas.filter(isSubstantiveSession);
2322
+ // Phase 3: Facet extraction — only for sessions without cached facets
2323
+ const facets = new Map();
2324
+ const toExtract = [];
2325
+ const MAX_FACET_EXTRACTIONS = 50;
2326
+ // Load cached facets for all substantive sessions in parallel
2327
+ const cachedFacetResults = await Promise.all(substantiveMetas.map(async (meta) => ({
2328
+ sessionId: meta.session_id,
2329
+ cached: await loadCachedFacets(meta.session_id),
2330
+ })));
2331
+ for (const { sessionId, cached } of cachedFacetResults) {
2332
+ if (cached) {
2333
+ facets.set(sessionId, cached);
2334
+ }
2335
+ else {
2336
+ const log = logsForFacets.get(sessionId);
2337
+ if (log && toExtract.length < MAX_FACET_EXTRACTIONS) {
2338
+ toExtract.push({ log, sessionId });
2339
+ }
2340
+ }
2341
+ }
2342
+ // Extract facets for sessions that need them (50 concurrent)
2343
+ const CONCURRENCY = 50;
2344
+ for (let i = 0; i < toExtract.length; i += CONCURRENCY) {
2345
+ const batch = toExtract.slice(i, i + CONCURRENCY);
2346
+ const results = await Promise.all(batch.map(async ({ log, sessionId }) => {
2347
+ const newFacets = await extractFacetsFromAPI(log, sessionId);
2348
+ return { sessionId, newFacets };
2349
+ }));
2350
+ // Collect facets synchronously, save in parallel (independent writes)
2351
+ const facetsToSave = [];
2352
+ for (const { sessionId, newFacets } of results) {
2353
+ if (newFacets) {
2354
+ facets.set(sessionId, newFacets);
2355
+ facetsToSave.push(newFacets);
2356
+ }
2357
+ }
2358
+ await Promise.all(facetsToSave.map(f => saveFacets(f)));
2359
+ }
2360
+ // Filter out warmup/minimal sessions (matching Python's is_minimal)
2361
+ // A session is minimal if warmup_minimal is the ONLY goal category
2362
+ const isMinimalSession = (sessionId) => {
2363
+ const sessionFacets = facets.get(sessionId);
2364
+ if (!sessionFacets)
2365
+ return false;
2366
+ const cats = sessionFacets.goal_categories;
2367
+ const catKeys = safeKeys(cats).filter(k => (cats[k] ?? 0) > 0);
2368
+ return catKeys.length === 1 && catKeys[0] === 'warmup_minimal';
2369
+ };
2370
+ const substantiveSessions = substantiveMetas.filter(s => !isMinimalSession(s.session_id));
2371
+ const substantiveFacets = new Map();
2372
+ for (const [sessionId, f] of facets) {
2373
+ if (!isMinimalSession(sessionId)) {
2374
+ substantiveFacets.set(sessionId, f);
2375
+ }
2376
+ }
2377
+ const aggregated = aggregateData(substantiveSessions, substantiveFacets);
2378
+ aggregated.total_sessions_scanned = totalSessionsScanned;
2379
+ // Generate parallel insights from Thaddeus (6 sections)
2380
+ const insights = await generateParallelInsights(aggregated, facets);
2381
+ // Generate HTML report
2382
+ const htmlReport = generateHtmlReport(aggregated, insights);
2383
+ // Save reports
2384
+ try {
2385
+ await mkdir(getDataDir(), { recursive: true });
2386
+ }
2387
+ catch {
2388
+ // Directory may already exist
2389
+ }
2390
+ const htmlPath = join(getDataDir(), 'report.html');
2391
+ await writeFile(htmlPath, htmlReport, {
2392
+ encoding: 'utf-8',
2393
+ mode: 0o600,
2394
+ });
2395
+ return {
2396
+ insights,
2397
+ htmlPath,
2398
+ data: aggregated,
2399
+ remoteStats,
2400
+ facets: substantiveFacets,
2401
+ };
2402
+ }
2403
+ function safeEntries(obj) {
2404
+ return obj ? Object.entries(obj) : [];
2405
+ }
2406
+ function safeKeys(obj) {
2407
+ return obj ? Object.keys(obj) : [];
2408
+ }
2409
+ // ============================================================================
2410
+ // Command Definition
2411
+ // ============================================================================
2412
+ const usageReport = {
2413
+ type: 'prompt',
2414
+ name: 'insights',
2415
+ description: 'Generate a report analyzing your Thaddeus sessions',
2416
+ contentLength: 0, // Dynamic content
2417
+ progressMessage: 'analyzing your sessions',
2418
+ source: 'builtin',
2419
+ async getPromptForCommand(args) {
2420
+ let collectRemote = false;
2421
+ let remoteHosts = [];
2422
+ let hasRemoteHosts = false;
2423
+ if (process.env.USER_TYPE === 'ant') {
2424
+ // Parse --homespaces flag
2425
+ collectRemote = args?.includes('--homespaces') ?? false;
2426
+ // Check for available remote hosts
2427
+ remoteHosts = await getRunningRemoteHosts();
2428
+ hasRemoteHosts = remoteHosts.length > 0;
2429
+ // Show collection message if collecting
2430
+ if (collectRemote && hasRemoteHosts) {
2431
+ // biome-ignore lint/suspicious/noConsole: intentional
2432
+ console.error(`Collecting sessions from ${remoteHosts.length} homespace(s): ${remoteHosts.join(', ')}...`);
2433
+ }
2434
+ }
2435
+ const { insights, htmlPath, data, remoteStats } = await generateUsageReport({ collectRemote });
2436
+ let reportUrl = `file://${htmlPath}`;
2437
+ let uploadHint = '';
2438
+ if (process.env.USER_TYPE === 'ant') {
2439
+ // Try to upload to S3
2440
+ const timestamp = new Date()
2441
+ .toISOString()
2442
+ .replace(/[-:]/g, '')
2443
+ .replace('T', '_')
2444
+ .slice(0, 15);
2445
+ const username = process.env.SAFEUSER || process.env.USER || 'unknown';
2446
+ const filename = `${username}_insights_${timestamp}.html`;
2447
+ const s3Path = `s3://anthropic-serve/atamkin/cc-user-reports/${filename}`;
2448
+ const s3Url = `https://s3-frontend.infra.ant.dev/anthropic-serve/atamkin/cc-user-reports/${filename}`;
2449
+ reportUrl = s3Url;
2450
+ try {
2451
+ execFileSync('ff', ['cp', htmlPath, s3Path], {
2452
+ timeout: 60000,
2453
+ stdio: 'pipe', // Suppress output
2454
+ });
2455
+ }
2456
+ catch {
2457
+ // Upload failed - fall back to local file and show upload command
2458
+ reportUrl = `file://${htmlPath}`;
2459
+ uploadHint = `\nAutomatic upload failed. Are you on the boron namespace? Try \`use-bo\` and ensure you've run \`sso\`.
2460
+ To share, run: ff cp ${htmlPath} ${s3Path}
2461
+ Then access at: ${s3Url}`;
2462
+ }
2463
+ }
2464
+ // Build header with stats
2465
+ const sessionLabel = data.total_sessions_scanned &&
2466
+ data.total_sessions_scanned > data.total_sessions
2467
+ ? `${data.total_sessions_scanned.toLocaleString()} sessions total · ${data.total_sessions} analyzed`
2468
+ : `${data.total_sessions} sessions`;
2469
+ const stats = [
2470
+ sessionLabel,
2471
+ `${data.total_messages.toLocaleString()} messages`,
2472
+ `${Math.round(data.total_duration_hours)}h`,
2473
+ `${data.git_commits} commits`,
2474
+ ].join(' · ');
2475
+ // Build remote host info (ant-only)
2476
+ let remoteInfo = '';
2477
+ if (process.env.USER_TYPE === 'ant') {
2478
+ if (remoteStats && remoteStats.totalCopied > 0) {
2479
+ const hsNames = remoteStats.hosts
2480
+ .filter(h => h.sessionCount > 0)
2481
+ .map(h => h.name)
2482
+ .join(', ');
2483
+ remoteInfo = `\n_Collected ${remoteStats.totalCopied} new sessions from: ${hsNames}_\n`;
2484
+ }
2485
+ else if (!collectRemote && hasRemoteHosts) {
2486
+ // Suggest using --homespaces if they have remote hosts but didn't use the flag
2487
+ remoteInfo = `\n_Tip: Run \`/insights --homespaces\` to include sessions from your ${remoteHosts.length} running homespace(s)_\n`;
2488
+ }
2489
+ }
2490
+ // Build markdown summary from insights
2491
+ const atAGlance = insights.at_a_glance;
2492
+ const summaryText = atAGlance
2493
+ ? `## At a Glance
2494
+
2495
+ ${atAGlance.whats_working ? `**What's working:** ${atAGlance.whats_working} See _Impressive Things You Did_.` : ''}
2496
+
2497
+ ${atAGlance.whats_hindering ? `**What's hindering you:** ${atAGlance.whats_hindering} See _Where Things Go Wrong_.` : ''}
2498
+
2499
+ ${atAGlance.quick_wins ? `**Quick wins to try:** ${atAGlance.quick_wins} See _Features to Try_.` : ''}
2500
+
2501
+ ${atAGlance.ambitious_workflows ? `**Ambitious workflows:** ${atAGlance.ambitious_workflows} See _On the Horizon_.` : ''}`
2502
+ : '_No insights generated_';
2503
+ const header = `# Thaddeus Insights
2504
+
2505
+ ${stats}
2506
+ ${data.date_range.start} to ${data.date_range.end}
2507
+ ${remoteInfo}
2508
+ `;
2509
+ const userSummary = `${header}${summaryText}
2510
+
2511
+ Your full shareable insights report is ready: ${reportUrl}${uploadHint}`;
2512
+ // Return prompt for Thaddeus to respond to
2513
+ return [
2514
+ {
2515
+ type: 'text',
2516
+ text: `The user just ran /insights to generate a usage report analyzing their Thaddeus sessions.
2517
+
2518
+ Here is the full insights data:
2519
+ ${jsonStringify(insights, null, 2)}
2520
+
2521
+ Report URL: ${reportUrl}
2522
+ HTML file: ${htmlPath}
2523
+ Facets directory: ${getFacetsDir()}
2524
+
2525
+ Here is what the user sees:
2526
+ ${userSummary}
2527
+
2528
+ Now output the following message exactly:
2529
+
2530
+ <message>
2531
+ Your shareable insights report is ready:
2532
+ ${reportUrl}${uploadHint}
2533
+
2534
+ Want to dig into any section or try one of the suggestions?
2535
+ </message>`,
2536
+ },
2537
+ ];
2538
+ },
2539
+ };
2540
+ function isValidSessionFacets(obj) {
2541
+ if (!obj || typeof obj !== 'object')
2542
+ return false;
2543
+ const o = obj;
2544
+ return (typeof o.underlying_goal === 'string' &&
2545
+ typeof o.outcome === 'string' &&
2546
+ typeof o.brief_summary === 'string' &&
2547
+ o.goal_categories !== null &&
2548
+ typeof o.goal_categories === 'object' &&
2549
+ o.user_satisfaction_counts !== null &&
2550
+ typeof o.user_satisfaction_counts === 'object' &&
2551
+ o.friction_counts !== null &&
2552
+ typeof o.friction_counts === 'object');
2553
+ }
2554
+ export default usageReport;