@oh-my-pi/pi-coding-agent 0.1.0

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 (337) hide show
  1. package/CHANGELOG.md +1629 -0
  2. package/README.md +1041 -0
  3. package/docs/compaction.md +403 -0
  4. package/docs/config-usage.md +113 -0
  5. package/docs/custom-tools.md +541 -0
  6. package/docs/extension-loading.md +1004 -0
  7. package/docs/hooks.md +867 -0
  8. package/docs/rpc.md +1040 -0
  9. package/docs/sdk.md +994 -0
  10. package/docs/session-tree-plan.md +441 -0
  11. package/docs/session.md +240 -0
  12. package/docs/skills.md +290 -0
  13. package/docs/theme.md +670 -0
  14. package/docs/tree.md +197 -0
  15. package/docs/tui.md +341 -0
  16. package/examples/README.md +21 -0
  17. package/examples/custom-tools/README.md +124 -0
  18. package/examples/custom-tools/hello/index.ts +20 -0
  19. package/examples/custom-tools/question/index.ts +84 -0
  20. package/examples/custom-tools/subagent/README.md +172 -0
  21. package/examples/custom-tools/subagent/agents/planner.md +37 -0
  22. package/examples/custom-tools/subagent/agents/scout.md +50 -0
  23. package/examples/custom-tools/subagent/agents/worker.md +24 -0
  24. package/examples/custom-tools/subagent/agents.ts +156 -0
  25. package/examples/custom-tools/subagent/commands/implement-and-review.md +10 -0
  26. package/examples/custom-tools/subagent/commands/implement.md +10 -0
  27. package/examples/custom-tools/subagent/commands/scout-and-plan.md +9 -0
  28. package/examples/custom-tools/subagent/index.ts +1002 -0
  29. package/examples/custom-tools/todo/index.ts +212 -0
  30. package/examples/hooks/README.md +56 -0
  31. package/examples/hooks/auto-commit-on-exit.ts +49 -0
  32. package/examples/hooks/confirm-destructive.ts +59 -0
  33. package/examples/hooks/custom-compaction.ts +116 -0
  34. package/examples/hooks/dirty-repo-guard.ts +52 -0
  35. package/examples/hooks/file-trigger.ts +41 -0
  36. package/examples/hooks/git-checkpoint.ts +53 -0
  37. package/examples/hooks/handoff.ts +150 -0
  38. package/examples/hooks/permission-gate.ts +34 -0
  39. package/examples/hooks/protected-paths.ts +30 -0
  40. package/examples/hooks/qna.ts +119 -0
  41. package/examples/hooks/snake.ts +343 -0
  42. package/examples/hooks/status-line.ts +40 -0
  43. package/examples/sdk/01-minimal.ts +22 -0
  44. package/examples/sdk/02-custom-model.ts +49 -0
  45. package/examples/sdk/03-custom-prompt.ts +44 -0
  46. package/examples/sdk/04-skills.ts +44 -0
  47. package/examples/sdk/05-tools.ts +90 -0
  48. package/examples/sdk/06-hooks.ts +61 -0
  49. package/examples/sdk/07-context-files.ts +36 -0
  50. package/examples/sdk/08-slash-commands.ts +42 -0
  51. package/examples/sdk/09-api-keys-and-oauth.ts +55 -0
  52. package/examples/sdk/10-settings.ts +38 -0
  53. package/examples/sdk/11-sessions.ts +48 -0
  54. package/examples/sdk/12-full-control.ts +95 -0
  55. package/examples/sdk/README.md +154 -0
  56. package/package.json +89 -0
  57. package/src/bun-imports.d.ts +16 -0
  58. package/src/capability/context-file.ts +40 -0
  59. package/src/capability/extension.ts +48 -0
  60. package/src/capability/hook.ts +40 -0
  61. package/src/capability/index.ts +616 -0
  62. package/src/capability/instruction.ts +37 -0
  63. package/src/capability/mcp.ts +52 -0
  64. package/src/capability/prompt.ts +35 -0
  65. package/src/capability/rule.ts +56 -0
  66. package/src/capability/settings.ts +35 -0
  67. package/src/capability/skill.ts +49 -0
  68. package/src/capability/slash-command.ts +40 -0
  69. package/src/capability/system-prompt.ts +35 -0
  70. package/src/capability/tool.ts +38 -0
  71. package/src/capability/types.ts +166 -0
  72. package/src/cli/args.ts +259 -0
  73. package/src/cli/file-processor.ts +121 -0
  74. package/src/cli/list-models.ts +104 -0
  75. package/src/cli/plugin-cli.ts +661 -0
  76. package/src/cli/session-picker.ts +41 -0
  77. package/src/cli/update-cli.ts +274 -0
  78. package/src/cli.ts +10 -0
  79. package/src/config.ts +391 -0
  80. package/src/core/agent-session.ts +2178 -0
  81. package/src/core/auth-storage.ts +258 -0
  82. package/src/core/bash-executor.ts +197 -0
  83. package/src/core/compaction/branch-summarization.ts +315 -0
  84. package/src/core/compaction/compaction.ts +664 -0
  85. package/src/core/compaction/index.ts +7 -0
  86. package/src/core/compaction/utils.ts +153 -0
  87. package/src/core/custom-commands/bundled/review/index.ts +156 -0
  88. package/src/core/custom-commands/index.ts +15 -0
  89. package/src/core/custom-commands/loader.ts +226 -0
  90. package/src/core/custom-commands/types.ts +112 -0
  91. package/src/core/custom-tools/index.ts +22 -0
  92. package/src/core/custom-tools/loader.ts +248 -0
  93. package/src/core/custom-tools/types.ts +185 -0
  94. package/src/core/custom-tools/wrapper.ts +29 -0
  95. package/src/core/exec.ts +139 -0
  96. package/src/core/export-html/index.ts +159 -0
  97. package/src/core/export-html/template.css +774 -0
  98. package/src/core/export-html/template.generated.ts +2 -0
  99. package/src/core/export-html/template.html +45 -0
  100. package/src/core/export-html/template.js +1185 -0
  101. package/src/core/export-html/template.macro.ts +24 -0
  102. package/src/core/file-mentions.ts +54 -0
  103. package/src/core/hooks/index.ts +16 -0
  104. package/src/core/hooks/loader.ts +288 -0
  105. package/src/core/hooks/runner.ts +434 -0
  106. package/src/core/hooks/tool-wrapper.ts +98 -0
  107. package/src/core/hooks/types.ts +770 -0
  108. package/src/core/index.ts +53 -0
  109. package/src/core/logger.ts +112 -0
  110. package/src/core/mcp/client.ts +185 -0
  111. package/src/core/mcp/config.ts +248 -0
  112. package/src/core/mcp/index.ts +45 -0
  113. package/src/core/mcp/loader.ts +99 -0
  114. package/src/core/mcp/manager.ts +235 -0
  115. package/src/core/mcp/tool-bridge.ts +156 -0
  116. package/src/core/mcp/transports/http.ts +316 -0
  117. package/src/core/mcp/transports/index.ts +6 -0
  118. package/src/core/mcp/transports/stdio.ts +252 -0
  119. package/src/core/mcp/types.ts +228 -0
  120. package/src/core/messages.ts +211 -0
  121. package/src/core/model-registry.ts +334 -0
  122. package/src/core/model-resolver.ts +494 -0
  123. package/src/core/plugins/doctor.ts +67 -0
  124. package/src/core/plugins/index.ts +38 -0
  125. package/src/core/plugins/installer.ts +189 -0
  126. package/src/core/plugins/loader.ts +339 -0
  127. package/src/core/plugins/manager.ts +672 -0
  128. package/src/core/plugins/parser.ts +105 -0
  129. package/src/core/plugins/paths.ts +37 -0
  130. package/src/core/plugins/types.ts +190 -0
  131. package/src/core/sdk.ts +900 -0
  132. package/src/core/session-manager.ts +1837 -0
  133. package/src/core/settings-manager.ts +860 -0
  134. package/src/core/skills.ts +352 -0
  135. package/src/core/slash-commands.ts +132 -0
  136. package/src/core/system-prompt.ts +442 -0
  137. package/src/core/timings.ts +25 -0
  138. package/src/core/title-generator.ts +110 -0
  139. package/src/core/tools/ask.ts +193 -0
  140. package/src/core/tools/bash-interceptor.ts +120 -0
  141. package/src/core/tools/bash.ts +91 -0
  142. package/src/core/tools/context.ts +32 -0
  143. package/src/core/tools/edit-diff.ts +487 -0
  144. package/src/core/tools/edit.ts +140 -0
  145. package/src/core/tools/exa/company.ts +59 -0
  146. package/src/core/tools/exa/index.ts +63 -0
  147. package/src/core/tools/exa/linkedin.ts +59 -0
  148. package/src/core/tools/exa/mcp-client.ts +368 -0
  149. package/src/core/tools/exa/render.ts +200 -0
  150. package/src/core/tools/exa/researcher.ts +90 -0
  151. package/src/core/tools/exa/search.ts +338 -0
  152. package/src/core/tools/exa/types.ts +167 -0
  153. package/src/core/tools/exa/websets.ts +248 -0
  154. package/src/core/tools/find.ts +244 -0
  155. package/src/core/tools/grep.ts +584 -0
  156. package/src/core/tools/index.ts +283 -0
  157. package/src/core/tools/ls.ts +142 -0
  158. package/src/core/tools/lsp/client.ts +767 -0
  159. package/src/core/tools/lsp/clients/biome-client.ts +207 -0
  160. package/src/core/tools/lsp/clients/index.ts +49 -0
  161. package/src/core/tools/lsp/clients/lsp-linter-client.ts +98 -0
  162. package/src/core/tools/lsp/config.ts +845 -0
  163. package/src/core/tools/lsp/edits.ts +110 -0
  164. package/src/core/tools/lsp/index.ts +1364 -0
  165. package/src/core/tools/lsp/render.ts +560 -0
  166. package/src/core/tools/lsp/rust-analyzer.ts +145 -0
  167. package/src/core/tools/lsp/types.ts +495 -0
  168. package/src/core/tools/lsp/utils.ts +526 -0
  169. package/src/core/tools/notebook.ts +182 -0
  170. package/src/core/tools/output.ts +198 -0
  171. package/src/core/tools/path-utils.ts +61 -0
  172. package/src/core/tools/read.ts +507 -0
  173. package/src/core/tools/renderers.ts +820 -0
  174. package/src/core/tools/review.ts +275 -0
  175. package/src/core/tools/rulebook.ts +124 -0
  176. package/src/core/tools/task/agents.ts +158 -0
  177. package/src/core/tools/task/artifacts.ts +114 -0
  178. package/src/core/tools/task/commands.ts +157 -0
  179. package/src/core/tools/task/discovery.ts +217 -0
  180. package/src/core/tools/task/executor.ts +531 -0
  181. package/src/core/tools/task/index.ts +548 -0
  182. package/src/core/tools/task/model-resolver.ts +176 -0
  183. package/src/core/tools/task/parallel.ts +38 -0
  184. package/src/core/tools/task/render.ts +502 -0
  185. package/src/core/tools/task/subprocess-tool-registry.ts +89 -0
  186. package/src/core/tools/task/types.ts +142 -0
  187. package/src/core/tools/truncate.ts +265 -0
  188. package/src/core/tools/web-fetch.ts +2511 -0
  189. package/src/core/tools/web-search/auth.ts +199 -0
  190. package/src/core/tools/web-search/index.ts +583 -0
  191. package/src/core/tools/web-search/providers/anthropic.ts +198 -0
  192. package/src/core/tools/web-search/providers/exa.ts +196 -0
  193. package/src/core/tools/web-search/providers/perplexity.ts +195 -0
  194. package/src/core/tools/web-search/render.ts +372 -0
  195. package/src/core/tools/web-search/types.ts +180 -0
  196. package/src/core/tools/write.ts +63 -0
  197. package/src/core/ttsr.ts +211 -0
  198. package/src/core/utils.ts +187 -0
  199. package/src/discovery/agents-md.ts +75 -0
  200. package/src/discovery/builtin.ts +647 -0
  201. package/src/discovery/claude.ts +623 -0
  202. package/src/discovery/cline.ts +104 -0
  203. package/src/discovery/codex.ts +571 -0
  204. package/src/discovery/cursor.ts +266 -0
  205. package/src/discovery/gemini.ts +368 -0
  206. package/src/discovery/github.ts +120 -0
  207. package/src/discovery/helpers.test.ts +127 -0
  208. package/src/discovery/helpers.ts +249 -0
  209. package/src/discovery/index.ts +84 -0
  210. package/src/discovery/mcp-json.ts +127 -0
  211. package/src/discovery/vscode.ts +99 -0
  212. package/src/discovery/windsurf.ts +219 -0
  213. package/src/index.ts +192 -0
  214. package/src/main.ts +507 -0
  215. package/src/migrations.ts +156 -0
  216. package/src/modes/cleanup.ts +23 -0
  217. package/src/modes/index.ts +48 -0
  218. package/src/modes/interactive/components/armin.ts +382 -0
  219. package/src/modes/interactive/components/assistant-message.ts +86 -0
  220. package/src/modes/interactive/components/bash-execution.ts +199 -0
  221. package/src/modes/interactive/components/bordered-loader.ts +41 -0
  222. package/src/modes/interactive/components/branch-summary-message.ts +42 -0
  223. package/src/modes/interactive/components/compaction-summary-message.ts +45 -0
  224. package/src/modes/interactive/components/custom-editor.ts +122 -0
  225. package/src/modes/interactive/components/diff.ts +147 -0
  226. package/src/modes/interactive/components/dynamic-border.ts +25 -0
  227. package/src/modes/interactive/components/extensions/extension-dashboard.ts +296 -0
  228. package/src/modes/interactive/components/extensions/extension-list.ts +479 -0
  229. package/src/modes/interactive/components/extensions/index.ts +9 -0
  230. package/src/modes/interactive/components/extensions/inspector-panel.ts +313 -0
  231. package/src/modes/interactive/components/extensions/state-manager.ts +558 -0
  232. package/src/modes/interactive/components/extensions/types.ts +191 -0
  233. package/src/modes/interactive/components/hook-editor.ts +117 -0
  234. package/src/modes/interactive/components/hook-input.ts +64 -0
  235. package/src/modes/interactive/components/hook-message.ts +96 -0
  236. package/src/modes/interactive/components/hook-selector.ts +91 -0
  237. package/src/modes/interactive/components/model-selector.ts +560 -0
  238. package/src/modes/interactive/components/oauth-selector.ts +136 -0
  239. package/src/modes/interactive/components/plugin-settings.ts +481 -0
  240. package/src/modes/interactive/components/queue-mode-selector.ts +56 -0
  241. package/src/modes/interactive/components/session-selector.ts +220 -0
  242. package/src/modes/interactive/components/settings-defs.ts +597 -0
  243. package/src/modes/interactive/components/settings-selector.ts +545 -0
  244. package/src/modes/interactive/components/show-images-selector.ts +45 -0
  245. package/src/modes/interactive/components/status-line/index.ts +4 -0
  246. package/src/modes/interactive/components/status-line/presets.ts +94 -0
  247. package/src/modes/interactive/components/status-line/segments.ts +350 -0
  248. package/src/modes/interactive/components/status-line/separators.ts +55 -0
  249. package/src/modes/interactive/components/status-line/types.ts +81 -0
  250. package/src/modes/interactive/components/status-line-segment-editor.ts +357 -0
  251. package/src/modes/interactive/components/status-line.ts +384 -0
  252. package/src/modes/interactive/components/theme-selector.ts +62 -0
  253. package/src/modes/interactive/components/thinking-selector.ts +64 -0
  254. package/src/modes/interactive/components/tool-execution.ts +946 -0
  255. package/src/modes/interactive/components/tree-selector.ts +877 -0
  256. package/src/modes/interactive/components/ttsr-notification.ts +82 -0
  257. package/src/modes/interactive/components/user-message-selector.ts +159 -0
  258. package/src/modes/interactive/components/user-message.ts +18 -0
  259. package/src/modes/interactive/components/visual-truncate.ts +50 -0
  260. package/src/modes/interactive/components/welcome.ts +228 -0
  261. package/src/modes/interactive/interactive-mode.ts +2669 -0
  262. package/src/modes/interactive/theme/dark.json +102 -0
  263. package/src/modes/interactive/theme/defaults/dark-arctic.json +111 -0
  264. package/src/modes/interactive/theme/defaults/dark-catppuccin.json +106 -0
  265. package/src/modes/interactive/theme/defaults/dark-cyberpunk.json +109 -0
  266. package/src/modes/interactive/theme/defaults/dark-dracula.json +105 -0
  267. package/src/modes/interactive/theme/defaults/dark-forest.json +103 -0
  268. package/src/modes/interactive/theme/defaults/dark-github.json +112 -0
  269. package/src/modes/interactive/theme/defaults/dark-gruvbox.json +119 -0
  270. package/src/modes/interactive/theme/defaults/dark-monochrome.json +101 -0
  271. package/src/modes/interactive/theme/defaults/dark-monokai.json +105 -0
  272. package/src/modes/interactive/theme/defaults/dark-nord.json +104 -0
  273. package/src/modes/interactive/theme/defaults/dark-ocean.json +108 -0
  274. package/src/modes/interactive/theme/defaults/dark-one.json +107 -0
  275. package/src/modes/interactive/theme/defaults/dark-retro.json +99 -0
  276. package/src/modes/interactive/theme/defaults/dark-rose-pine.json +95 -0
  277. package/src/modes/interactive/theme/defaults/dark-solarized.json +96 -0
  278. package/src/modes/interactive/theme/defaults/dark-sunset.json +106 -0
  279. package/src/modes/interactive/theme/defaults/dark-synthwave.json +102 -0
  280. package/src/modes/interactive/theme/defaults/dark-tokyo-night.json +108 -0
  281. package/src/modes/interactive/theme/defaults/index.ts +67 -0
  282. package/src/modes/interactive/theme/defaults/light-arctic.json +106 -0
  283. package/src/modes/interactive/theme/defaults/light-catppuccin.json +105 -0
  284. package/src/modes/interactive/theme/defaults/light-cyberpunk.json +103 -0
  285. package/src/modes/interactive/theme/defaults/light-forest.json +107 -0
  286. package/src/modes/interactive/theme/defaults/light-github.json +114 -0
  287. package/src/modes/interactive/theme/defaults/light-gruvbox.json +115 -0
  288. package/src/modes/interactive/theme/defaults/light-monochrome.json +100 -0
  289. package/src/modes/interactive/theme/defaults/light-ocean.json +106 -0
  290. package/src/modes/interactive/theme/defaults/light-one.json +105 -0
  291. package/src/modes/interactive/theme/defaults/light-retro.json +105 -0
  292. package/src/modes/interactive/theme/defaults/light-solarized.json +101 -0
  293. package/src/modes/interactive/theme/defaults/light-sunset.json +106 -0
  294. package/src/modes/interactive/theme/defaults/light-synthwave.json +105 -0
  295. package/src/modes/interactive/theme/defaults/light-tokyo-night.json +118 -0
  296. package/src/modes/interactive/theme/light.json +99 -0
  297. package/src/modes/interactive/theme/theme-schema.json +424 -0
  298. package/src/modes/interactive/theme/theme.ts +2211 -0
  299. package/src/modes/print-mode.ts +163 -0
  300. package/src/modes/rpc/rpc-client.ts +527 -0
  301. package/src/modes/rpc/rpc-mode.ts +494 -0
  302. package/src/modes/rpc/rpc-types.ts +203 -0
  303. package/src/prompts/architect-plan.md +10 -0
  304. package/src/prompts/branch-summary-preamble.md +3 -0
  305. package/src/prompts/branch-summary.md +28 -0
  306. package/src/prompts/browser.md +71 -0
  307. package/src/prompts/compaction-summary.md +34 -0
  308. package/src/prompts/compaction-turn-prefix.md +16 -0
  309. package/src/prompts/compaction-update-summary.md +41 -0
  310. package/src/prompts/explore.md +82 -0
  311. package/src/prompts/implement-with-critic.md +11 -0
  312. package/src/prompts/implement.md +11 -0
  313. package/src/prompts/init.md +30 -0
  314. package/src/prompts/plan.md +54 -0
  315. package/src/prompts/reviewer.md +81 -0
  316. package/src/prompts/summarization-system.md +3 -0
  317. package/src/prompts/system-prompt.md +27 -0
  318. package/src/prompts/task.md +56 -0
  319. package/src/prompts/title-system.md +8 -0
  320. package/src/prompts/tools/ask.md +24 -0
  321. package/src/prompts/tools/bash.md +23 -0
  322. package/src/prompts/tools/edit.md +9 -0
  323. package/src/prompts/tools/find.md +6 -0
  324. package/src/prompts/tools/grep.md +12 -0
  325. package/src/prompts/tools/lsp.md +14 -0
  326. package/src/prompts/tools/output.md +23 -0
  327. package/src/prompts/tools/read.md +25 -0
  328. package/src/prompts/tools/web-fetch.md +8 -0
  329. package/src/prompts/tools/web-search.md +10 -0
  330. package/src/prompts/tools/write.md +10 -0
  331. package/src/utils/changelog.ts +99 -0
  332. package/src/utils/clipboard.ts +265 -0
  333. package/src/utils/fuzzy.ts +108 -0
  334. package/src/utils/mime.ts +30 -0
  335. package/src/utils/shell-snapshot.ts +218 -0
  336. package/src/utils/shell.ts +364 -0
  337. package/src/utils/tools-manager.ts +265 -0
@@ -0,0 +1,2178 @@
1
+ /**
2
+ * AgentSession - Core abstraction for agent lifecycle and session management.
3
+ *
4
+ * This class is shared between all run modes (interactive, print, rpc).
5
+ * It encapsulates:
6
+ * - Agent state access
7
+ * - Event subscription with automatic session persistence
8
+ * - Model and thinking level management
9
+ * - Compaction (manual and auto)
10
+ * - Bash execution
11
+ * - Session switching and branching
12
+ *
13
+ * Modes use this class and add their own I/O layer on top.
14
+ */
15
+
16
+ import type { Agent, AgentEvent, AgentMessage, AgentState, ThinkingLevel } from "@oh-my-pi/pi-agent-core";
17
+ import type { AssistantMessage, ImageContent, Message, Model, TextContent, Usage } from "@oh-my-pi/pi-ai";
18
+ import { isContextOverflow, modelsAreEqual, supportsXhigh } from "@oh-my-pi/pi-ai";
19
+ import type { Rule } from "../capability/rule";
20
+ import { getAuthPath } from "../config";
21
+ import { type BashResult, executeBash as executeBashCommand } from "./bash-executor";
22
+ import {
23
+ type CompactionResult,
24
+ calculateContextTokens,
25
+ collectEntriesForBranchSummary,
26
+ compact,
27
+ generateBranchSummary,
28
+ prepareCompaction,
29
+ shouldCompact,
30
+ } from "./compaction/index";
31
+ import type { LoadedCustomCommand } from "./custom-commands/index";
32
+ import type { CustomToolContext, CustomToolSessionEvent, LoadedCustomTool } from "./custom-tools/index";
33
+ import { exportSessionToHtml } from "./export-html/index";
34
+ import { extractFileMentions, generateFileMentionMessages } from "./file-mentions";
35
+ import type {
36
+ HookRunner,
37
+ SessionBeforeBranchResult,
38
+ SessionBeforeCompactResult,
39
+ SessionBeforeSwitchResult,
40
+ SessionBeforeTreeResult,
41
+ TreePreparation,
42
+ TurnEndEvent,
43
+ TurnStartEvent,
44
+ } from "./hooks/index";
45
+ import { logger } from "./logger";
46
+ import type { BashExecutionMessage, HookMessage } from "./messages";
47
+ import type { ModelRegistry } from "./model-registry";
48
+ import type { BranchSummaryEntry, CompactionEntry, NewSessionOptions, SessionManager } from "./session-manager";
49
+ import type { SettingsManager, SkillsSettings } from "./settings-manager";
50
+ import { expandSlashCommand, type FileSlashCommand, parseCommandArgs } from "./slash-commands";
51
+ import type { TtsrManager } from "./ttsr";
52
+
53
+ /** Session-specific events that extend the core AgentEvent */
54
+ export type AgentSessionEvent =
55
+ | AgentEvent
56
+ | { type: "auto_compaction_start"; reason: "threshold" | "overflow" }
57
+ | { type: "auto_compaction_end"; result: CompactionResult | undefined; aborted: boolean; willRetry: boolean }
58
+ | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
59
+ | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string }
60
+ | { type: "ttsr_triggered"; rules: Rule[] };
61
+
62
+ /** Listener function for agent session events */
63
+ export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
64
+
65
+ // ============================================================================
66
+ // Types
67
+ // ============================================================================
68
+
69
+ export interface AgentSessionConfig {
70
+ agent: Agent;
71
+ sessionManager: SessionManager;
72
+ settingsManager: SettingsManager;
73
+ /** Models to cycle through with Ctrl+P (from --models flag) */
74
+ scopedModels?: Array<{ model: Model<any>; thinkingLevel: ThinkingLevel }>;
75
+ /** File-based slash commands for expansion */
76
+ fileCommands?: FileSlashCommand[];
77
+ /** Hook runner (created in main.ts with wrapped tools) */
78
+ hookRunner?: HookRunner;
79
+ /** Custom tools for session lifecycle events */
80
+ customTools?: LoadedCustomTool[];
81
+ /** Custom commands (TypeScript slash commands) */
82
+ customCommands?: LoadedCustomCommand[];
83
+ skillsSettings?: Required<SkillsSettings>;
84
+ /** Model registry for API key resolution and model discovery */
85
+ modelRegistry: ModelRegistry;
86
+ /** TTSR manager for time-traveling stream rules */
87
+ ttsrManager?: TtsrManager;
88
+ }
89
+
90
+ /** Options for AgentSession.prompt() */
91
+ export interface PromptOptions {
92
+ /** Whether to expand file-based slash commands (default: true) */
93
+ expandSlashCommands?: boolean;
94
+ /** Image attachments */
95
+ images?: ImageContent[];
96
+ }
97
+
98
+ /** Result from cycleModel() */
99
+ export interface ModelCycleResult {
100
+ model: Model<any>;
101
+ thinkingLevel: ThinkingLevel;
102
+ /** Whether cycling through scoped models (--models flag) or all available */
103
+ isScoped: boolean;
104
+ }
105
+
106
+ /** Session statistics for /session command */
107
+ export interface SessionStats {
108
+ sessionFile: string | undefined;
109
+ sessionId: string;
110
+ userMessages: number;
111
+ assistantMessages: number;
112
+ toolCalls: number;
113
+ toolResults: number;
114
+ totalMessages: number;
115
+ tokens: {
116
+ input: number;
117
+ output: number;
118
+ cacheRead: number;
119
+ cacheWrite: number;
120
+ total: number;
121
+ };
122
+ cost: number;
123
+ }
124
+
125
+ /** Internal marker for hook messages queued through the agent loop */
126
+ // ============================================================================
127
+ // Constants
128
+ // ============================================================================
129
+
130
+ /** Standard thinking levels */
131
+ const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high"];
132
+
133
+ /** Thinking levels including xhigh (for supported models) */
134
+ const THINKING_LEVELS_WITH_XHIGH: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
135
+
136
+ // ============================================================================
137
+ // AgentSession Class
138
+ // ============================================================================
139
+
140
+ export class AgentSession {
141
+ readonly agent: Agent;
142
+ readonly sessionManager: SessionManager;
143
+ readonly settingsManager: SettingsManager;
144
+
145
+ private _scopedModels: Array<{ model: Model<any>; thinkingLevel: ThinkingLevel }>;
146
+ private _fileCommands: FileSlashCommand[];
147
+
148
+ // Event subscription state
149
+ private _unsubscribeAgent?: () => void;
150
+ private _eventListeners: AgentSessionEventListener[] = [];
151
+
152
+ // Message queue state
153
+ private _queuedMessages: string[] = [];
154
+
155
+ // Compaction state
156
+ private _compactionAbortController: AbortController | undefined = undefined;
157
+ private _autoCompactionAbortController: AbortController | undefined = undefined;
158
+
159
+ // Branch summarization state
160
+ private _branchSummaryAbortController: AbortController | undefined = undefined;
161
+
162
+ // Retry state
163
+ private _retryAbortController: AbortController | undefined = undefined;
164
+ private _retryAttempt = 0;
165
+ private _retryPromise: Promise<void> | undefined = undefined;
166
+ private _retryResolve: (() => void) | undefined = undefined;
167
+
168
+ // Bash execution state
169
+ private _bashAbortController: AbortController | undefined = undefined;
170
+ private _pendingBashMessages: BashExecutionMessage[] = [];
171
+
172
+ // Hook system
173
+ private _hookRunner: HookRunner | undefined = undefined;
174
+ private _turnIndex = 0;
175
+
176
+ // Custom tools for session lifecycle
177
+ private _customTools: LoadedCustomTool[] = [];
178
+
179
+ // Custom commands (TypeScript slash commands)
180
+ private _customCommands: LoadedCustomCommand[] = [];
181
+
182
+ private _skillsSettings: Required<SkillsSettings> | undefined;
183
+
184
+ // Model registry for API key resolution
185
+ private _modelRegistry: ModelRegistry;
186
+
187
+ // TTSR manager for time-traveling stream rules
188
+ private _ttsrManager: TtsrManager | undefined = undefined;
189
+ private _pendingTtsrInjections: Rule[] = [];
190
+ private _ttsrAbortPending = false;
191
+
192
+ constructor(config: AgentSessionConfig) {
193
+ this.agent = config.agent;
194
+ this.sessionManager = config.sessionManager;
195
+ this.settingsManager = config.settingsManager;
196
+ this._scopedModels = config.scopedModels ?? [];
197
+ this._fileCommands = config.fileCommands ?? [];
198
+ this._hookRunner = config.hookRunner;
199
+ this._customTools = config.customTools ?? [];
200
+ this._customCommands = config.customCommands ?? [];
201
+ this._skillsSettings = config.skillsSettings;
202
+ this._modelRegistry = config.modelRegistry;
203
+ this._ttsrManager = config.ttsrManager;
204
+
205
+ // Always subscribe to agent events for internal handling
206
+ // (session persistence, hooks, auto-compaction, retry logic)
207
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
208
+ }
209
+
210
+ /** Model registry for API key resolution and model discovery */
211
+ get modelRegistry(): ModelRegistry {
212
+ return this._modelRegistry;
213
+ }
214
+
215
+ /** TTSR manager for time-traveling stream rules */
216
+ get ttsrManager(): TtsrManager | undefined {
217
+ return this._ttsrManager;
218
+ }
219
+
220
+ /** Whether a TTSR abort is pending (stream was aborted to inject rules) */
221
+ get isTtsrAbortPending(): boolean {
222
+ return this._ttsrAbortPending;
223
+ }
224
+
225
+ // =========================================================================
226
+ // Event Subscription
227
+ // =========================================================================
228
+
229
+ /** Emit an event to all listeners */
230
+ private _emit(event: AgentSessionEvent): void {
231
+ // Copy array before iteration to avoid mutation during iteration
232
+ const listeners = [...this._eventListeners];
233
+ for (const l of listeners) {
234
+ l(event);
235
+ }
236
+ }
237
+
238
+ // Track last assistant message for auto-compaction check
239
+ private _lastAssistantMessage: AssistantMessage | undefined = undefined;
240
+
241
+ /** Internal handler for agent events - shared by subscribe and reconnect */
242
+ private _handleAgentEvent = async (event: AgentEvent): Promise<void> => {
243
+ // When a user message starts, check if it's from the queue and remove it BEFORE emitting
244
+ // This ensures the UI sees the updated queue state
245
+ if (event.type === "message_start" && event.message.role === "user" && this._queuedMessages.length > 0) {
246
+ // Extract text content from the message
247
+ const messageText = this._getUserMessageText(event.message);
248
+ if (messageText && this._queuedMessages.includes(messageText)) {
249
+ // Remove the first occurrence of this message from the queue
250
+ const index = this._queuedMessages.indexOf(messageText);
251
+ if (index !== -1) {
252
+ this._queuedMessages.splice(index, 1);
253
+ }
254
+ }
255
+ }
256
+
257
+ // Emit to hooks first
258
+ await this._emitHookEvent(event);
259
+
260
+ // Notify all listeners
261
+ this._emit(event);
262
+
263
+ // TTSR: Reset buffer on turn start
264
+ if (event.type === "turn_start" && this._ttsrManager) {
265
+ this._ttsrManager.resetBuffer();
266
+ }
267
+
268
+ // TTSR: Increment message count on turn end (for repeat-after-gap tracking)
269
+ if (event.type === "turn_end" && this._ttsrManager) {
270
+ this._ttsrManager.incrementMessageCount();
271
+ }
272
+
273
+ // TTSR: Check for pattern matches on text deltas and tool call argument deltas
274
+ if (event.type === "message_update" && this._ttsrManager?.hasRules()) {
275
+ const assistantEvent = event.assistantMessageEvent;
276
+ // Monitor both assistant prose (text_delta) and tool call arguments (toolcall_delta)
277
+ if (assistantEvent.type === "text_delta" || assistantEvent.type === "toolcall_delta") {
278
+ this._ttsrManager.appendToBuffer(assistantEvent.delta);
279
+ const matches = this._ttsrManager.check(this._ttsrManager.getBuffer());
280
+ if (matches.length > 0) {
281
+ // Mark rules as injected so they don't trigger again
282
+ this._ttsrManager.markInjected(matches);
283
+ // Store for injection on retry
284
+ this._pendingTtsrInjections.push(...matches);
285
+ // Emit TTSR event before aborting (so UI can handle it)
286
+ this._ttsrAbortPending = true;
287
+ this._emit({ type: "ttsr_triggered", rules: matches });
288
+ // Abort the stream
289
+ this.agent.abort();
290
+ // Schedule retry after a short delay
291
+ setTimeout(async () => {
292
+ this._ttsrAbortPending = false;
293
+
294
+ // Handle context mode: discard partial output if configured
295
+ const ttsrSettings = this._ttsrManager?.getSettings();
296
+ if (ttsrSettings?.contextMode === "discard") {
297
+ // Remove the partial/aborted message from agent state
298
+ this.agent.popMessage();
299
+ }
300
+
301
+ // Inject TTSR rules as system reminder before retry
302
+ const injectionContent = this._getTtsrInjectionContent();
303
+ if (injectionContent) {
304
+ this.agent.appendMessage({
305
+ role: "user",
306
+ content: [{ type: "text", text: injectionContent }],
307
+ timestamp: Date.now(),
308
+ });
309
+ }
310
+ this.agent.continue().catch(() => {});
311
+ }, 50);
312
+ return;
313
+ }
314
+ }
315
+ }
316
+
317
+ // Handle session persistence
318
+ if (event.type === "message_end") {
319
+ // Check if this is a hook message
320
+ if (event.message.role === "hookMessage") {
321
+ // Persist as CustomMessageEntry
322
+ this.sessionManager.appendCustomMessageEntry(
323
+ event.message.customType,
324
+ event.message.content,
325
+ event.message.display,
326
+ event.message.details,
327
+ );
328
+ } else if (
329
+ event.message.role === "user" ||
330
+ event.message.role === "assistant" ||
331
+ event.message.role === "toolResult"
332
+ ) {
333
+ // Regular LLM message - persist as SessionMessageEntry
334
+ this.sessionManager.appendMessage(event.message);
335
+ }
336
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
337
+
338
+ // Track assistant message for auto-compaction (checked on agent_end)
339
+ if (event.message.role === "assistant") {
340
+ this._lastAssistantMessage = event.message;
341
+ }
342
+ }
343
+
344
+ // Check auto-retry and auto-compaction after agent completes
345
+ if (event.type === "agent_end" && this._lastAssistantMessage) {
346
+ const msg = this._lastAssistantMessage;
347
+ this._lastAssistantMessage = undefined;
348
+
349
+ // Check for retryable errors first (overloaded, rate limit, server errors)
350
+ if (this._isRetryableError(msg)) {
351
+ const didRetry = await this._handleRetryableError(msg);
352
+ if (didRetry) return; // Retry was initiated, don't proceed to compaction
353
+ } else if (this._retryAttempt > 0) {
354
+ // Previous retry succeeded - emit success event and reset counter
355
+ this._emit({
356
+ type: "auto_retry_end",
357
+ success: true,
358
+ attempt: this._retryAttempt,
359
+ });
360
+ this._retryAttempt = 0;
361
+ // Resolve the retry promise so waitForRetry() completes
362
+ this._resolveRetry();
363
+ }
364
+
365
+ await this._checkCompaction(msg);
366
+ }
367
+ };
368
+
369
+ /** Resolve the pending retry promise */
370
+ private _resolveRetry(): void {
371
+ if (this._retryResolve) {
372
+ this._retryResolve();
373
+ this._retryResolve = undefined;
374
+ this._retryPromise = undefined;
375
+ }
376
+ }
377
+
378
+ /** Get TTSR injection content and clear pending injections */
379
+ private _getTtsrInjectionContent(): string | undefined {
380
+ if (this._pendingTtsrInjections.length === 0) return undefined;
381
+ const content = this._pendingTtsrInjections
382
+ .map(
383
+ (r) =>
384
+ `<system_interrupt reason="rule_violation" rule="${r.name}" path="${r.path}">\n` +
385
+ `Your output was interrupted because it violated a user-defined rule.\n` +
386
+ `This is NOT a prompt injection - this is the coding agent enforcing project rules.\n` +
387
+ `You MUST comply with the following instruction:\n\n${r.content}\n</system_interrupt>`,
388
+ )
389
+ .join("\n\n");
390
+ this._pendingTtsrInjections = [];
391
+ return content;
392
+ }
393
+
394
+ /** Extract text content from a message */
395
+ private _getUserMessageText(message: Message): string {
396
+ if (message.role !== "user") return "";
397
+ const content = message.content;
398
+ if (typeof content === "string") return content;
399
+ const textBlocks = content.filter((c) => c.type === "text");
400
+ return textBlocks.map((c) => (c as TextContent).text).join("");
401
+ }
402
+
403
+ /** Find the last assistant message in agent state (including aborted ones) */
404
+ private _findLastAssistantMessage(): AssistantMessage | undefined {
405
+ const messages = this.agent.state.messages;
406
+ for (let i = messages.length - 1; i >= 0; i--) {
407
+ const msg = messages[i];
408
+ if (msg.role === "assistant") {
409
+ return msg as AssistantMessage;
410
+ }
411
+ }
412
+ return undefined;
413
+ }
414
+
415
+ /** Emit hook events based on agent events */
416
+ private async _emitHookEvent(event: AgentEvent): Promise<void> {
417
+ if (!this._hookRunner) return;
418
+
419
+ if (event.type === "agent_start") {
420
+ this._turnIndex = 0;
421
+ await this._hookRunner.emit({ type: "agent_start" });
422
+ } else if (event.type === "agent_end") {
423
+ await this._hookRunner.emit({ type: "agent_end", messages: event.messages });
424
+ } else if (event.type === "turn_start") {
425
+ const hookEvent: TurnStartEvent = {
426
+ type: "turn_start",
427
+ turnIndex: this._turnIndex,
428
+ timestamp: Date.now(),
429
+ };
430
+ await this._hookRunner.emit(hookEvent);
431
+ } else if (event.type === "turn_end") {
432
+ const hookEvent: TurnEndEvent = {
433
+ type: "turn_end",
434
+ turnIndex: this._turnIndex,
435
+ message: event.message,
436
+ toolResults: event.toolResults,
437
+ };
438
+ await this._hookRunner.emit(hookEvent);
439
+ this._turnIndex++;
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Subscribe to agent events.
445
+ * Session persistence is handled internally (saves messages on message_end).
446
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
447
+ */
448
+ subscribe(listener: AgentSessionEventListener): () => void {
449
+ this._eventListeners.push(listener);
450
+
451
+ // Return unsubscribe function for this specific listener
452
+ return () => {
453
+ const index = this._eventListeners.indexOf(listener);
454
+ if (index !== -1) {
455
+ this._eventListeners.splice(index, 1);
456
+ }
457
+ };
458
+ }
459
+
460
+ /**
461
+ * Temporarily disconnect from agent events.
462
+ * User listeners are preserved and will receive events again after resubscribe().
463
+ * Used internally during operations that need to pause event processing.
464
+ */
465
+ private _disconnectFromAgent(): void {
466
+ if (this._unsubscribeAgent) {
467
+ this._unsubscribeAgent();
468
+ this._unsubscribeAgent = undefined;
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Reconnect to agent events after _disconnectFromAgent().
474
+ * Preserves all existing listeners.
475
+ */
476
+ private _reconnectToAgent(): void {
477
+ if (this._unsubscribeAgent) return; // Already connected
478
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
479
+ }
480
+
481
+ /**
482
+ * Remove all listeners, flush pending writes, and disconnect from agent.
483
+ * Call this when completely done with the session.
484
+ */
485
+ async dispose(): Promise<void> {
486
+ await this.sessionManager.flush();
487
+ this._disconnectFromAgent();
488
+ this._eventListeners = [];
489
+ }
490
+
491
+ // =========================================================================
492
+ // Read-only State Access
493
+ // =========================================================================
494
+
495
+ /** Full agent state */
496
+ get state(): AgentState {
497
+ return this.agent.state;
498
+ }
499
+
500
+ /** Current model (may be undefined if not yet selected) */
501
+ get model(): Model<any> | undefined {
502
+ return this.agent.state.model;
503
+ }
504
+
505
+ /** Current thinking level */
506
+ get thinkingLevel(): ThinkingLevel {
507
+ return this.agent.state.thinkingLevel;
508
+ }
509
+
510
+ /** Whether agent is currently streaming a response */
511
+ get isStreaming(): boolean {
512
+ return this.agent.state.isStreaming;
513
+ }
514
+
515
+ /** Whether auto-compaction is currently running */
516
+ get isCompacting(): boolean {
517
+ return this._autoCompactionAbortController !== undefined || this._compactionAbortController !== undefined;
518
+ }
519
+
520
+ /** All messages including custom types like BashExecutionMessage */
521
+ get messages(): AgentMessage[] {
522
+ return this.agent.state.messages;
523
+ }
524
+
525
+ /** Current queue mode */
526
+ get queueMode(): "all" | "one-at-a-time" {
527
+ return this.agent.getQueueMode();
528
+ }
529
+
530
+ /** Current interrupt mode */
531
+ get interruptMode(): "immediate" | "wait" {
532
+ return this.agent.getInterruptMode();
533
+ }
534
+
535
+ /** Current session file path, or undefined if sessions are disabled */
536
+ get sessionFile(): string | undefined {
537
+ return this.sessionManager.getSessionFile();
538
+ }
539
+
540
+ /** Current session ID */
541
+ get sessionId(): string {
542
+ return this.sessionManager.getSessionId();
543
+ }
544
+
545
+ /** Scoped models for cycling (from --models flag) */
546
+ get scopedModels(): ReadonlyArray<{ model: Model<any>; thinkingLevel: ThinkingLevel }> {
547
+ return this._scopedModels;
548
+ }
549
+
550
+ /** File-based slash commands */
551
+ get fileCommands(): ReadonlyArray<FileSlashCommand> {
552
+ return this._fileCommands;
553
+ }
554
+
555
+ /** Custom commands (TypeScript slash commands) */
556
+ get customCommands(): ReadonlyArray<LoadedCustomCommand> {
557
+ return this._customCommands;
558
+ }
559
+
560
+ // =========================================================================
561
+ // Prompting
562
+ // =========================================================================
563
+
564
+ /**
565
+ * Send a prompt to the agent.
566
+ * - Validates model and API key before sending
567
+ * - Handles hook commands (registered via pi.registerCommand)
568
+ * - Expands file-based slash commands by default
569
+ * @throws Error if no model selected or no API key available
570
+ */
571
+ async prompt(text: string, options?: PromptOptions): Promise<void> {
572
+ // Flush any pending bash messages before the new prompt
573
+ this._flushPendingBashMessages();
574
+
575
+ const expandCommands = options?.expandSlashCommands ?? true;
576
+
577
+ // Handle hook commands first (if enabled and text is a slash command)
578
+ if (expandCommands && text.startsWith("/")) {
579
+ const handled = await this._tryExecuteHookCommand(text);
580
+ if (handled) {
581
+ // Hook command executed, no prompt to send
582
+ return;
583
+ }
584
+
585
+ // Try custom commands (TypeScript slash commands)
586
+ const customResult = await this._tryExecuteCustomCommand(text);
587
+ if (customResult !== null) {
588
+ if (customResult === "") {
589
+ // Command handled, nothing to send
590
+ return;
591
+ }
592
+ // Command returned a prompt - use it instead of the original text
593
+ text = customResult;
594
+ }
595
+ }
596
+
597
+ // Validate model
598
+ if (!this.model) {
599
+ throw new Error(
600
+ "No model selected.\n\n" +
601
+ `Use /login, set an API key environment variable, or create ${getAuthPath()}\n\n` +
602
+ "Then use /model to select a model.",
603
+ );
604
+ }
605
+
606
+ // Validate API key
607
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
608
+ if (!apiKey) {
609
+ throw new Error(
610
+ `No API key found for ${this.model.provider}.\n\n` +
611
+ `Use /login, set an API key environment variable, or create ${getAuthPath()}`,
612
+ );
613
+ }
614
+
615
+ // Check if we need to compact before sending (catches aborted responses)
616
+ const lastAssistant = this._findLastAssistantMessage();
617
+ if (lastAssistant) {
618
+ await this._checkCompaction(lastAssistant, false);
619
+ }
620
+
621
+ // Expand file-based slash commands if requested
622
+ const expandedText = expandCommands ? expandSlashCommand(text, [...this._fileCommands]) : text;
623
+
624
+ // Build messages array (hook message if any, then user message)
625
+ const messages: AgentMessage[] = [];
626
+
627
+ // Add user message
628
+ const userContent: (TextContent | ImageContent)[] = [{ type: "text", text: expandedText }];
629
+ if (options?.images) {
630
+ userContent.push(...options.images);
631
+ }
632
+ messages.push({
633
+ role: "user",
634
+ content: userContent,
635
+ timestamp: Date.now(),
636
+ });
637
+
638
+ // Auto-read @filepath mentions
639
+ const fileMentions = extractFileMentions(expandedText);
640
+ if (fileMentions.length > 0) {
641
+ const fileMentionMessages = await generateFileMentionMessages(fileMentions, this.sessionManager.getCwd());
642
+ messages.push(...fileMentionMessages);
643
+ }
644
+
645
+ // Emit before_agent_start hook event
646
+ if (this._hookRunner) {
647
+ const result = await this._hookRunner.emitBeforeAgentStart(expandedText, options?.images);
648
+ if (result?.message) {
649
+ messages.push({
650
+ role: "hookMessage",
651
+ customType: result.message.customType,
652
+ content: result.message.content,
653
+ display: result.message.display,
654
+ details: result.message.details,
655
+ timestamp: Date.now(),
656
+ });
657
+ }
658
+ }
659
+
660
+ await this.agent.prompt(messages);
661
+ await this.waitForRetry();
662
+ }
663
+
664
+ /**
665
+ * Try to execute a hook command. Returns true if command was found and executed.
666
+ */
667
+ private async _tryExecuteHookCommand(text: string): Promise<boolean> {
668
+ if (!this._hookRunner) return false;
669
+
670
+ // Parse command name and args
671
+ const spaceIndex = text.indexOf(" ");
672
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
673
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
674
+
675
+ const command = this._hookRunner.getCommand(commandName);
676
+ if (!command) return false;
677
+
678
+ // Get command context from hook runner (includes session control methods)
679
+ const ctx = this._hookRunner.createCommandContext();
680
+
681
+ try {
682
+ await command.handler(args, ctx);
683
+ return true;
684
+ } catch (err) {
685
+ // Emit error via hook runner
686
+ this._hookRunner.emitError({
687
+ hookPath: `command:${commandName}`,
688
+ event: "command",
689
+ error: err instanceof Error ? err.message : String(err),
690
+ });
691
+ return true;
692
+ }
693
+ }
694
+
695
+ /**
696
+ * Try to execute a custom command. Returns the prompt string if found, null otherwise.
697
+ * If the command returns void, returns empty string to indicate it was handled.
698
+ */
699
+ private async _tryExecuteCustomCommand(text: string): Promise<string | null> {
700
+ if (this._customCommands.length === 0) return null;
701
+ if (!this._hookRunner) return null; // Need hook runner for command context
702
+
703
+ // Parse command name and args
704
+ const spaceIndex = text.indexOf(" ");
705
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
706
+ const argsString = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
707
+
708
+ // Find matching command
709
+ const loaded = this._customCommands.find((c) => c.command.name === commandName);
710
+ if (!loaded) return null;
711
+
712
+ // Get command context from hook runner (includes session control methods)
713
+ const ctx = this._hookRunner.createCommandContext();
714
+
715
+ try {
716
+ const args = parseCommandArgs(argsString);
717
+ const result = await loaded.command.execute(args, ctx);
718
+ // If result is a string, it's a prompt to send to LLM
719
+ // If void/undefined, command handled everything
720
+ return result ?? "";
721
+ } catch (err) {
722
+ // Emit error via hook runner
723
+ this._hookRunner.emitError({
724
+ hookPath: `custom-command:${commandName}`,
725
+ event: "command",
726
+ error: err instanceof Error ? err.message : String(err),
727
+ });
728
+ return ""; // Command was handled (with error)
729
+ }
730
+ }
731
+
732
+ /**
733
+ * Queue a message to be sent after the current response completes.
734
+ * Use when agent is currently streaming.
735
+ */
736
+ async queueMessage(text: string): Promise<void> {
737
+ this._queuedMessages.push(text);
738
+ await this.agent.queueMessage({
739
+ role: "user",
740
+ content: [{ type: "text", text }],
741
+ timestamp: Date.now(),
742
+ });
743
+ }
744
+
745
+ /**
746
+ * Send a hook message to the session. Creates a CustomMessageEntry.
747
+ *
748
+ * Handles three cases:
749
+ * - Streaming: queues message, processed when loop pulls from queue
750
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
751
+ * - Not streaming + no trigger: appends to state/session, no turn
752
+ *
753
+ * @param message Hook message with customType, content, display, details
754
+ * @param triggerTurn If true and not streaming, triggers a new LLM turn
755
+ */
756
+ async sendHookMessage<T = unknown>(
757
+ message: Pick<HookMessage<T>, "customType" | "content" | "display" | "details">,
758
+ triggerTurn?: boolean,
759
+ ): Promise<void> {
760
+ const appMessage = {
761
+ role: "hookMessage" as const,
762
+ customType: message.customType,
763
+ content: message.content,
764
+ display: message.display,
765
+ details: message.details,
766
+ timestamp: Date.now(),
767
+ } satisfies HookMessage<T>;
768
+ if (this.isStreaming) {
769
+ // Queue for processing by agent loop
770
+ await this.agent.queueMessage(appMessage);
771
+ } else if (triggerTurn) {
772
+ // Send as prompt - agent loop will emit message events
773
+ await this.agent.prompt(appMessage);
774
+ } else {
775
+ // Just append to agent state and session, no turn
776
+ this.agent.appendMessage(appMessage);
777
+ this.sessionManager.appendCustomMessageEntry(
778
+ message.customType,
779
+ message.content,
780
+ message.display,
781
+ message.details,
782
+ );
783
+ }
784
+ }
785
+
786
+ /**
787
+ * Clear queued messages and return them.
788
+ * Useful for restoring to editor when user aborts.
789
+ */
790
+ clearQueue(): string[] {
791
+ const queued = [...this._queuedMessages];
792
+ this._queuedMessages = [];
793
+ this.agent.clearMessageQueue();
794
+ return queued;
795
+ }
796
+
797
+ /** Number of messages currently queued */
798
+ get queuedMessageCount(): number {
799
+ return this._queuedMessages.length;
800
+ }
801
+
802
+ /** Get queued messages (read-only) */
803
+ getQueuedMessages(): readonly string[] {
804
+ return this._queuedMessages;
805
+ }
806
+
807
+ get skillsSettings(): Required<SkillsSettings> | undefined {
808
+ return this._skillsSettings;
809
+ }
810
+
811
+ /**
812
+ * Abort current operation and wait for agent to become idle.
813
+ */
814
+ async abort(): Promise<void> {
815
+ this.abortRetry();
816
+ this.agent.abort();
817
+ await this.agent.waitForIdle();
818
+ }
819
+
820
+ /**
821
+ * Start a new session, optionally with initial messages and parent tracking.
822
+ * Clears all messages and starts a new session.
823
+ * Listeners are preserved and will continue receiving events.
824
+ * @param options - Optional initial messages and parent session path
825
+ * @returns true if completed, false if cancelled by hook
826
+ */
827
+ async newSession(options?: NewSessionOptions): Promise<boolean> {
828
+ const previousSessionFile = this.sessionFile;
829
+
830
+ // Emit session_before_switch event with reason "new" (can be cancelled)
831
+ if (this._hookRunner?.hasHandlers("session_before_switch")) {
832
+ const result = (await this._hookRunner.emit({
833
+ type: "session_before_switch",
834
+ reason: "new",
835
+ })) as SessionBeforeSwitchResult | undefined;
836
+
837
+ if (result?.cancel) {
838
+ return false;
839
+ }
840
+ }
841
+
842
+ this._disconnectFromAgent();
843
+ await this.abort();
844
+ this.agent.reset();
845
+ await this.sessionManager.flush();
846
+ this.sessionManager.newSession(options);
847
+ this._queuedMessages = [];
848
+ this._reconnectToAgent();
849
+
850
+ // Emit session_switch event with reason "new" to hooks
851
+ if (this._hookRunner) {
852
+ await this._hookRunner.emit({
853
+ type: "session_switch",
854
+ reason: "new",
855
+ previousSessionFile,
856
+ });
857
+ }
858
+
859
+ // Emit session event to custom tools
860
+ await this.emitCustomToolSessionEvent("switch", previousSessionFile);
861
+ return true;
862
+ }
863
+
864
+ // =========================================================================
865
+ // Model Management
866
+ // =========================================================================
867
+
868
+ /**
869
+ * Set model directly.
870
+ * Validates API key, saves to session and settings.
871
+ * @throws Error if no API key available for the model
872
+ */
873
+ async setModel(model: Model<any>, role: string = "default"): Promise<void> {
874
+ const apiKey = await this._modelRegistry.getApiKey(model);
875
+ if (!apiKey) {
876
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
877
+ }
878
+
879
+ this.agent.setModel(model);
880
+ this.sessionManager.appendModelChange(`${model.provider}/${model.id}`, role);
881
+ this.settingsManager.setModelRole(role, `${model.provider}/${model.id}`);
882
+
883
+ // Re-clamp thinking level for new model's capabilities
884
+ this.setThinkingLevel(this.thinkingLevel);
885
+ }
886
+
887
+ /**
888
+ * Cycle to next/previous model.
889
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
890
+ * @param direction - "forward" (default) or "backward"
891
+ * @returns The new model info, or undefined if only one model available
892
+ */
893
+ async cycleModel(direction: "forward" | "backward" = "forward"): Promise<ModelCycleResult | undefined> {
894
+ if (this._scopedModels.length > 0) {
895
+ return this._cycleScopedModel(direction);
896
+ }
897
+ return this._cycleAvailableModel(direction);
898
+ }
899
+
900
+ private async _cycleScopedModel(direction: "forward" | "backward"): Promise<ModelCycleResult | undefined> {
901
+ if (this._scopedModels.length <= 1) return undefined;
902
+
903
+ const currentModel = this.model;
904
+ let currentIndex = this._scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
905
+
906
+ if (currentIndex === -1) currentIndex = 0;
907
+ const len = this._scopedModels.length;
908
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
909
+ const next = this._scopedModels[nextIndex];
910
+
911
+ // Validate API key
912
+ const apiKey = await this._modelRegistry.getApiKey(next.model);
913
+ if (!apiKey) {
914
+ throw new Error(`No API key for ${next.model.provider}/${next.model.id}`);
915
+ }
916
+
917
+ // Apply model
918
+ this.agent.setModel(next.model);
919
+ this.sessionManager.appendModelChange(`${next.model.provider}/${next.model.id}`);
920
+ this.settingsManager.setModelRole("default", `${next.model.provider}/${next.model.id}`);
921
+
922
+ // Apply thinking level (setThinkingLevel clamps to model capabilities)
923
+ this.setThinkingLevel(next.thinkingLevel);
924
+
925
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
926
+ }
927
+
928
+ private async _cycleAvailableModel(direction: "forward" | "backward"): Promise<ModelCycleResult | undefined> {
929
+ const availableModels = await this._modelRegistry.getAvailable();
930
+ if (availableModels.length <= 1) return undefined;
931
+
932
+ const currentModel = this.model;
933
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
934
+
935
+ if (currentIndex === -1) currentIndex = 0;
936
+ const len = availableModels.length;
937
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
938
+ const nextModel = availableModels[nextIndex];
939
+
940
+ const apiKey = await this._modelRegistry.getApiKey(nextModel);
941
+ if (!apiKey) {
942
+ throw new Error(`No API key for ${nextModel.provider}/${nextModel.id}`);
943
+ }
944
+
945
+ this.agent.setModel(nextModel);
946
+ this.sessionManager.appendModelChange(`${nextModel.provider}/${nextModel.id}`);
947
+ this.settingsManager.setModelRole("default", `${nextModel.provider}/${nextModel.id}`);
948
+
949
+ // Re-clamp thinking level for new model's capabilities
950
+ this.setThinkingLevel(this.thinkingLevel);
951
+
952
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
953
+ }
954
+
955
+ /**
956
+ * Get all available models with valid API keys.
957
+ */
958
+ async getAvailableModels(): Promise<Model<any>[]> {
959
+ return this._modelRegistry.getAvailable();
960
+ }
961
+
962
+ // =========================================================================
963
+ // Thinking Level Management
964
+ // =========================================================================
965
+
966
+ /**
967
+ * Set thinking level.
968
+ * Clamps to model capabilities: "off" if no reasoning, "high" if xhigh unsupported.
969
+ * Saves to session and settings.
970
+ */
971
+ setThinkingLevel(level: ThinkingLevel): void {
972
+ let effectiveLevel = level;
973
+ if (!this.supportsThinking()) {
974
+ effectiveLevel = "off";
975
+ } else if (level === "xhigh" && !this.supportsXhighThinking()) {
976
+ effectiveLevel = "high";
977
+ }
978
+ this.agent.setThinkingLevel(effectiveLevel);
979
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
980
+ this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
981
+ }
982
+
983
+ /**
984
+ * Cycle to next thinking level.
985
+ * @returns New level, or undefined if model doesn't support thinking
986
+ */
987
+ cycleThinkingLevel(): ThinkingLevel | undefined {
988
+ if (!this.supportsThinking()) return undefined;
989
+
990
+ const levels = this.getAvailableThinkingLevels();
991
+ const currentIndex = levels.indexOf(this.thinkingLevel);
992
+ const nextIndex = (currentIndex + 1) % levels.length;
993
+ const nextLevel = levels[nextIndex];
994
+
995
+ this.setThinkingLevel(nextLevel);
996
+ return nextLevel;
997
+ }
998
+
999
+ /**
1000
+ * Get available thinking levels for current model.
1001
+ */
1002
+ getAvailableThinkingLevels(): ThinkingLevel[] {
1003
+ return this.supportsXhighThinking() ? THINKING_LEVELS_WITH_XHIGH : THINKING_LEVELS;
1004
+ }
1005
+
1006
+ /**
1007
+ * Check if current model supports xhigh thinking level.
1008
+ */
1009
+ supportsXhighThinking(): boolean {
1010
+ return this.model ? supportsXhigh(this.model) : false;
1011
+ }
1012
+
1013
+ /**
1014
+ * Check if current model supports thinking/reasoning.
1015
+ */
1016
+ supportsThinking(): boolean {
1017
+ return !!this.model?.reasoning;
1018
+ }
1019
+
1020
+ // =========================================================================
1021
+ // Queue Mode Management
1022
+ // =========================================================================
1023
+
1024
+ /**
1025
+ * Set message queue mode.
1026
+ * Saves to settings.
1027
+ */
1028
+ setQueueMode(mode: "all" | "one-at-a-time"): void {
1029
+ this.agent.setQueueMode(mode);
1030
+ this.settingsManager.setQueueMode(mode);
1031
+ }
1032
+
1033
+ /**
1034
+ * Set interrupt mode.
1035
+ * Saves to settings.
1036
+ */
1037
+ setInterruptMode(mode: "immediate" | "wait"): void {
1038
+ this.agent.setInterruptMode(mode);
1039
+ this.settingsManager.setInterruptMode(mode);
1040
+ }
1041
+
1042
+ // =========================================================================
1043
+ // Compaction
1044
+ // =========================================================================
1045
+
1046
+ /**
1047
+ * Manually compact the session context.
1048
+ * Aborts current agent operation first.
1049
+ * @param customInstructions Optional instructions for the compaction summary
1050
+ */
1051
+ async compact(customInstructions?: string): Promise<CompactionResult> {
1052
+ this._disconnectFromAgent();
1053
+ await this.abort();
1054
+ this._compactionAbortController = new AbortController();
1055
+
1056
+ try {
1057
+ if (!this.model) {
1058
+ throw new Error("No model selected");
1059
+ }
1060
+
1061
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
1062
+ if (!apiKey) {
1063
+ throw new Error(`No API key for ${this.model.provider}`);
1064
+ }
1065
+
1066
+ const pathEntries = this.sessionManager.getBranch();
1067
+ const settings = this.settingsManager.getCompactionSettings();
1068
+
1069
+ const preparation = prepareCompaction(pathEntries, settings);
1070
+ if (!preparation) {
1071
+ // Check why we can't compact
1072
+ const lastEntry = pathEntries[pathEntries.length - 1];
1073
+ if (lastEntry?.type === "compaction") {
1074
+ throw new Error("Already compacted");
1075
+ }
1076
+ throw new Error("Nothing to compact (session too small)");
1077
+ }
1078
+
1079
+ let hookCompaction: CompactionResult | undefined;
1080
+ let fromHook = false;
1081
+
1082
+ if (this._hookRunner?.hasHandlers("session_before_compact")) {
1083
+ const result = (await this._hookRunner.emit({
1084
+ type: "session_before_compact",
1085
+ preparation,
1086
+ branchEntries: pathEntries,
1087
+ customInstructions,
1088
+ signal: this._compactionAbortController.signal,
1089
+ })) as SessionBeforeCompactResult | undefined;
1090
+
1091
+ if (result?.cancel) {
1092
+ throw new Error("Compaction cancelled");
1093
+ }
1094
+
1095
+ if (result?.compaction) {
1096
+ hookCompaction = result.compaction;
1097
+ fromHook = true;
1098
+ }
1099
+ }
1100
+
1101
+ let summary: string;
1102
+ let firstKeptEntryId: string;
1103
+ let tokensBefore: number;
1104
+ let details: unknown;
1105
+
1106
+ if (hookCompaction) {
1107
+ // Hook provided compaction content
1108
+ summary = hookCompaction.summary;
1109
+ firstKeptEntryId = hookCompaction.firstKeptEntryId;
1110
+ tokensBefore = hookCompaction.tokensBefore;
1111
+ details = hookCompaction.details;
1112
+ } else {
1113
+ // Generate compaction result
1114
+ const result = await compact(
1115
+ preparation,
1116
+ this.model,
1117
+ apiKey,
1118
+ customInstructions,
1119
+ this._compactionAbortController.signal,
1120
+ );
1121
+ summary = result.summary;
1122
+ firstKeptEntryId = result.firstKeptEntryId;
1123
+ tokensBefore = result.tokensBefore;
1124
+ details = result.details;
1125
+ }
1126
+
1127
+ if (this._compactionAbortController.signal.aborted) {
1128
+ throw new Error("Compaction cancelled");
1129
+ }
1130
+
1131
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook);
1132
+ const newEntries = this.sessionManager.getEntries();
1133
+ const sessionContext = this.sessionManager.buildSessionContext();
1134
+ this.agent.replaceMessages(sessionContext.messages);
1135
+
1136
+ // Get the saved compaction entry for the hook
1137
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
1138
+ | CompactionEntry
1139
+ | undefined;
1140
+
1141
+ if (this._hookRunner && savedCompactionEntry) {
1142
+ await this._hookRunner.emit({
1143
+ type: "session_compact",
1144
+ compactionEntry: savedCompactionEntry,
1145
+ fromHook,
1146
+ });
1147
+ }
1148
+
1149
+ return {
1150
+ summary,
1151
+ firstKeptEntryId,
1152
+ tokensBefore,
1153
+ details,
1154
+ };
1155
+ } finally {
1156
+ this._compactionAbortController = undefined;
1157
+ this._reconnectToAgent();
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * Cancel in-progress compaction (manual or auto).
1163
+ */
1164
+ abortCompaction(): void {
1165
+ this._compactionAbortController?.abort();
1166
+ this._autoCompactionAbortController?.abort();
1167
+ }
1168
+
1169
+ /**
1170
+ * Cancel in-progress branch summarization.
1171
+ */
1172
+ abortBranchSummary(): void {
1173
+ this._branchSummaryAbortController?.abort();
1174
+ }
1175
+
1176
+ /**
1177
+ * Check if compaction is needed and run it.
1178
+ * Called after agent_end and before prompt submission.
1179
+ *
1180
+ * Two cases:
1181
+ * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
1182
+ * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
1183
+ *
1184
+ * @param assistantMessage The assistant message to check
1185
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
1186
+ */
1187
+ private async _checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {
1188
+ const settings = this.settingsManager.getCompactionSettings();
1189
+ if (!settings.enabled) return;
1190
+
1191
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1192
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted") return;
1193
+
1194
+ const contextWindow = this.model?.contextWindow ?? 0;
1195
+
1196
+ // Case 1: Overflow - LLM returned context overflow error
1197
+ if (isContextOverflow(assistantMessage, contextWindow)) {
1198
+ // Remove the error message from agent state (it IS saved to session for history,
1199
+ // but we don't want it in context for the retry)
1200
+ const messages = this.agent.state.messages;
1201
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1202
+ this.agent.replaceMessages(messages.slice(0, -1));
1203
+ }
1204
+ await this._runAutoCompaction("overflow", true);
1205
+ return;
1206
+ }
1207
+
1208
+ // Case 2: Threshold - turn succeeded but context is getting large
1209
+ // Skip if this was an error (non-overflow errors don't have usage data)
1210
+ if (assistantMessage.stopReason === "error") return;
1211
+
1212
+ const contextTokens = calculateContextTokens(assistantMessage.usage);
1213
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
1214
+ await this._runAutoCompaction("threshold", false);
1215
+ }
1216
+ }
1217
+
1218
+ /**
1219
+ * Internal: Run auto-compaction with events.
1220
+ */
1221
+ private async _runAutoCompaction(reason: "overflow" | "threshold", willRetry: boolean): Promise<void> {
1222
+ const settings = this.settingsManager.getCompactionSettings();
1223
+
1224
+ this._emit({ type: "auto_compaction_start", reason });
1225
+ // Properly abort and null existing controller before replacing
1226
+ if (this._autoCompactionAbortController) {
1227
+ this._autoCompactionAbortController.abort();
1228
+ }
1229
+ this._autoCompactionAbortController = new AbortController();
1230
+
1231
+ try {
1232
+ if (!this.model) {
1233
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
1234
+ return;
1235
+ }
1236
+
1237
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
1238
+ if (!apiKey) {
1239
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
1240
+ return;
1241
+ }
1242
+
1243
+ const pathEntries = this.sessionManager.getBranch();
1244
+
1245
+ const preparation = prepareCompaction(pathEntries, settings);
1246
+ if (!preparation) {
1247
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
1248
+ return;
1249
+ }
1250
+
1251
+ let hookCompaction: CompactionResult | undefined;
1252
+ let fromHook = false;
1253
+
1254
+ if (this._hookRunner?.hasHandlers("session_before_compact")) {
1255
+ const hookResult = (await this._hookRunner.emit({
1256
+ type: "session_before_compact",
1257
+ preparation,
1258
+ branchEntries: pathEntries,
1259
+ customInstructions: undefined,
1260
+ signal: this._autoCompactionAbortController.signal,
1261
+ })) as SessionBeforeCompactResult | undefined;
1262
+
1263
+ if (hookResult?.cancel) {
1264
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: true, willRetry: false });
1265
+ return;
1266
+ }
1267
+
1268
+ if (hookResult?.compaction) {
1269
+ hookCompaction = hookResult.compaction;
1270
+ fromHook = true;
1271
+ }
1272
+ }
1273
+
1274
+ let summary: string;
1275
+ let firstKeptEntryId: string;
1276
+ let tokensBefore: number;
1277
+ let details: unknown;
1278
+
1279
+ if (hookCompaction) {
1280
+ // Hook provided compaction content
1281
+ summary = hookCompaction.summary;
1282
+ firstKeptEntryId = hookCompaction.firstKeptEntryId;
1283
+ tokensBefore = hookCompaction.tokensBefore;
1284
+ details = hookCompaction.details;
1285
+ } else {
1286
+ // Generate compaction result
1287
+ const compactResult = await compact(
1288
+ preparation,
1289
+ this.model,
1290
+ apiKey,
1291
+ undefined,
1292
+ this._autoCompactionAbortController.signal,
1293
+ );
1294
+ summary = compactResult.summary;
1295
+ firstKeptEntryId = compactResult.firstKeptEntryId;
1296
+ tokensBefore = compactResult.tokensBefore;
1297
+ details = compactResult.details;
1298
+ }
1299
+
1300
+ if (this._autoCompactionAbortController.signal.aborted) {
1301
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: true, willRetry: false });
1302
+ return;
1303
+ }
1304
+
1305
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook);
1306
+ const newEntries = this.sessionManager.getEntries();
1307
+ const sessionContext = this.sessionManager.buildSessionContext();
1308
+ this.agent.replaceMessages(sessionContext.messages);
1309
+
1310
+ // Get the saved compaction entry for the hook
1311
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
1312
+ | CompactionEntry
1313
+ | undefined;
1314
+
1315
+ if (this._hookRunner && savedCompactionEntry) {
1316
+ await this._hookRunner.emit({
1317
+ type: "session_compact",
1318
+ compactionEntry: savedCompactionEntry,
1319
+ fromHook,
1320
+ });
1321
+ }
1322
+
1323
+ const result: CompactionResult = {
1324
+ summary,
1325
+ firstKeptEntryId,
1326
+ tokensBefore,
1327
+ details,
1328
+ };
1329
+ this._emit({ type: "auto_compaction_end", result, aborted: false, willRetry });
1330
+
1331
+ if (willRetry) {
1332
+ const messages = this.agent.state.messages;
1333
+ const lastMsg = messages[messages.length - 1];
1334
+ if (lastMsg?.role === "assistant" && (lastMsg as AssistantMessage).stopReason === "error") {
1335
+ this.agent.replaceMessages(messages.slice(0, -1));
1336
+ }
1337
+
1338
+ setTimeout(() => {
1339
+ this.agent.continue().catch(() => {});
1340
+ }, 100);
1341
+ }
1342
+ } catch (error) {
1343
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
1344
+
1345
+ if (reason === "overflow") {
1346
+ throw new Error(
1347
+ `Context overflow: ${
1348
+ error instanceof Error ? error.message : "compaction failed"
1349
+ }. Your input may be too large for the context window.`,
1350
+ );
1351
+ }
1352
+ } finally {
1353
+ this._autoCompactionAbortController = undefined;
1354
+ }
1355
+ }
1356
+
1357
+ /**
1358
+ * Toggle auto-compaction setting.
1359
+ */
1360
+ setAutoCompactionEnabled(enabled: boolean): void {
1361
+ this.settingsManager.setCompactionEnabled(enabled);
1362
+ }
1363
+
1364
+ /** Whether auto-compaction is enabled */
1365
+ get autoCompactionEnabled(): boolean {
1366
+ return this.settingsManager.getCompactionEnabled();
1367
+ }
1368
+
1369
+ // =========================================================================
1370
+ // Auto-Retry
1371
+ // =========================================================================
1372
+
1373
+ /**
1374
+ * Check if an error is retryable (overloaded, rate limit, server errors).
1375
+ * Context overflow errors are NOT retryable (handled by compaction instead).
1376
+ */
1377
+ private _isRetryableError(message: AssistantMessage): boolean {
1378
+ if (message.stopReason !== "error" || !message.errorMessage) return false;
1379
+
1380
+ // Context overflow is handled by compaction, not retry
1381
+ const contextWindow = this.model?.contextWindow ?? 0;
1382
+ if (isContextOverflow(message, contextWindow)) return false;
1383
+
1384
+ const err = message.errorMessage;
1385
+ // Match: overloaded_error, rate limit, 429, 500, 502, 503, 504, service unavailable, connection error
1386
+ return /overloaded|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server error|internal error|connection.?error/i.test(
1387
+ err,
1388
+ );
1389
+ }
1390
+
1391
+ /**
1392
+ * Handle retryable errors with exponential backoff.
1393
+ * @returns true if retry was initiated, false if max retries exceeded or disabled
1394
+ */
1395
+ private async _handleRetryableError(message: AssistantMessage): Promise<boolean> {
1396
+ const settings = this.settingsManager.getRetrySettings();
1397
+ if (!settings.enabled) return false;
1398
+
1399
+ this._retryAttempt++;
1400
+
1401
+ // Create retry promise on first attempt so waitForRetry() can await it
1402
+ // Ensure only one promise exists (avoid orphaned promises from concurrent calls)
1403
+ if (!this._retryPromise) {
1404
+ this._retryPromise = new Promise((resolve) => {
1405
+ this._retryResolve = resolve;
1406
+ });
1407
+ }
1408
+
1409
+ if (this._retryAttempt > settings.maxRetries) {
1410
+ // Max retries exceeded, emit final failure and reset
1411
+ this._emit({
1412
+ type: "auto_retry_end",
1413
+ success: false,
1414
+ attempt: this._retryAttempt - 1,
1415
+ finalError: message.errorMessage,
1416
+ });
1417
+ this._retryAttempt = 0;
1418
+ this._resolveRetry(); // Resolve so waitForRetry() completes
1419
+ return false;
1420
+ }
1421
+
1422
+ const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
1423
+
1424
+ this._emit({
1425
+ type: "auto_retry_start",
1426
+ attempt: this._retryAttempt,
1427
+ maxAttempts: settings.maxRetries,
1428
+ delayMs,
1429
+ errorMessage: message.errorMessage || "Unknown error",
1430
+ });
1431
+
1432
+ // Remove error message from agent state (keep in session for history)
1433
+ const messages = this.agent.state.messages;
1434
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1435
+ this.agent.replaceMessages(messages.slice(0, -1));
1436
+ }
1437
+
1438
+ // Wait with exponential backoff (abortable)
1439
+ // Properly abort and null existing controller before replacing
1440
+ if (this._retryAbortController) {
1441
+ this._retryAbortController.abort();
1442
+ }
1443
+ this._retryAbortController = new AbortController();
1444
+ try {
1445
+ await this._sleep(delayMs, this._retryAbortController.signal);
1446
+ } catch {
1447
+ // Aborted during sleep - emit end event so UI can clean up
1448
+ const attempt = this._retryAttempt;
1449
+ this._retryAttempt = 0;
1450
+ this._retryAbortController = undefined;
1451
+ this._emit({
1452
+ type: "auto_retry_end",
1453
+ success: false,
1454
+ attempt,
1455
+ finalError: "Retry cancelled",
1456
+ });
1457
+ this._resolveRetry();
1458
+ return false;
1459
+ }
1460
+ this._retryAbortController = undefined;
1461
+
1462
+ // Retry via continue() - use setTimeout to break out of event handler chain
1463
+ setTimeout(() => {
1464
+ this.agent.continue().catch(() => {
1465
+ // Retry failed - will be caught by next agent_end
1466
+ });
1467
+ }, 0);
1468
+
1469
+ return true;
1470
+ }
1471
+
1472
+ /**
1473
+ * Sleep helper that respects abort signal.
1474
+ */
1475
+ private _sleep(ms: number, signal?: AbortSignal): Promise<void> {
1476
+ return new Promise((resolve, reject) => {
1477
+ if (signal?.aborted) {
1478
+ reject(new Error("Aborted"));
1479
+ return;
1480
+ }
1481
+
1482
+ const timeout = setTimeout(resolve, ms);
1483
+
1484
+ signal?.addEventListener("abort", () => {
1485
+ clearTimeout(timeout);
1486
+ reject(new Error("Aborted"));
1487
+ });
1488
+ });
1489
+ }
1490
+
1491
+ /**
1492
+ * Cancel in-progress retry.
1493
+ */
1494
+ abortRetry(): void {
1495
+ this._retryAbortController?.abort();
1496
+ this._retryAttempt = 0;
1497
+ this._resolveRetry();
1498
+ }
1499
+
1500
+ /**
1501
+ * Wait for any in-progress retry to complete.
1502
+ * Returns immediately if no retry is in progress.
1503
+ */
1504
+ private async waitForRetry(): Promise<void> {
1505
+ if (this._retryPromise) {
1506
+ await this._retryPromise;
1507
+ }
1508
+ }
1509
+
1510
+ /** Whether auto-retry is currently in progress */
1511
+ get isRetrying(): boolean {
1512
+ return this._retryPromise !== undefined;
1513
+ }
1514
+
1515
+ /** Whether auto-retry is enabled */
1516
+ get autoRetryEnabled(): boolean {
1517
+ return this.settingsManager.getRetryEnabled();
1518
+ }
1519
+
1520
+ /**
1521
+ * Toggle auto-retry setting.
1522
+ */
1523
+ setAutoRetryEnabled(enabled: boolean): void {
1524
+ this.settingsManager.setRetryEnabled(enabled);
1525
+ }
1526
+
1527
+ // =========================================================================
1528
+ // Bash Execution
1529
+ // =========================================================================
1530
+
1531
+ /**
1532
+ * Execute a bash command.
1533
+ * Adds result to agent context and session.
1534
+ * @param command The bash command to execute
1535
+ * @param onChunk Optional streaming callback for output
1536
+ */
1537
+ async executeBash(command: string, onChunk?: (chunk: string) => void): Promise<BashResult> {
1538
+ this._bashAbortController = new AbortController();
1539
+
1540
+ try {
1541
+ const result = await executeBashCommand(command, {
1542
+ onChunk,
1543
+ signal: this._bashAbortController.signal,
1544
+ });
1545
+
1546
+ // Create and save message
1547
+ const bashMessage: BashExecutionMessage = {
1548
+ role: "bashExecution",
1549
+ command,
1550
+ output: result.output,
1551
+ exitCode: result.exitCode,
1552
+ cancelled: result.cancelled,
1553
+ truncated: result.truncated,
1554
+ fullOutputPath: result.fullOutputPath,
1555
+ timestamp: Date.now(),
1556
+ };
1557
+
1558
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
1559
+ if (this.isStreaming) {
1560
+ // Queue for later - will be flushed on agent_end
1561
+ this._pendingBashMessages.push(bashMessage);
1562
+ } else {
1563
+ // Add to agent state immediately
1564
+ this.agent.appendMessage(bashMessage);
1565
+
1566
+ // Save to session
1567
+ this.sessionManager.appendMessage(bashMessage);
1568
+ }
1569
+
1570
+ return result;
1571
+ } finally {
1572
+ this._bashAbortController = undefined;
1573
+ }
1574
+ }
1575
+
1576
+ /**
1577
+ * Cancel running bash command.
1578
+ */
1579
+ abortBash(): void {
1580
+ this._bashAbortController?.abort();
1581
+ }
1582
+
1583
+ /** Whether a bash command is currently running */
1584
+ get isBashRunning(): boolean {
1585
+ return this._bashAbortController !== undefined;
1586
+ }
1587
+
1588
+ /** Whether there are pending bash messages waiting to be flushed */
1589
+ get hasPendingBashMessages(): boolean {
1590
+ return this._pendingBashMessages.length > 0;
1591
+ }
1592
+
1593
+ /**
1594
+ * Flush pending bash messages to agent state and session.
1595
+ * Called after agent turn completes to maintain proper message ordering.
1596
+ */
1597
+ private _flushPendingBashMessages(): void {
1598
+ if (this._pendingBashMessages.length === 0) return;
1599
+
1600
+ for (const bashMessage of this._pendingBashMessages) {
1601
+ // Add to agent state
1602
+ this.agent.appendMessage(bashMessage);
1603
+
1604
+ // Save to session
1605
+ this.sessionManager.appendMessage(bashMessage);
1606
+ }
1607
+
1608
+ this._pendingBashMessages = [];
1609
+ }
1610
+
1611
+ // =========================================================================
1612
+ // Session Management
1613
+ // =========================================================================
1614
+
1615
+ /**
1616
+ * Switch to a different session file.
1617
+ * Aborts current operation, loads messages, restores model/thinking.
1618
+ * Listeners are preserved and will continue receiving events.
1619
+ * @returns true if switch completed, false if cancelled by hook
1620
+ */
1621
+ async switchSession(sessionPath: string): Promise<boolean> {
1622
+ const previousSessionFile = this.sessionManager.getSessionFile();
1623
+
1624
+ // Emit session_before_switch event (can be cancelled)
1625
+ if (this._hookRunner?.hasHandlers("session_before_switch")) {
1626
+ const result = (await this._hookRunner.emit({
1627
+ type: "session_before_switch",
1628
+ reason: "resume",
1629
+ targetSessionFile: sessionPath,
1630
+ })) as SessionBeforeSwitchResult | undefined;
1631
+
1632
+ if (result?.cancel) {
1633
+ return false;
1634
+ }
1635
+ }
1636
+
1637
+ this._disconnectFromAgent();
1638
+ await this.abort();
1639
+ this._queuedMessages = [];
1640
+
1641
+ // Flush pending writes before switching
1642
+ await this.sessionManager.flush();
1643
+
1644
+ // Set new session
1645
+ await this.sessionManager.setSessionFile(sessionPath);
1646
+
1647
+ // Reload messages
1648
+ const sessionContext = this.sessionManager.buildSessionContext();
1649
+
1650
+ // Emit session_switch event to hooks
1651
+ if (this._hookRunner) {
1652
+ await this._hookRunner.emit({
1653
+ type: "session_switch",
1654
+ reason: "resume",
1655
+ previousSessionFile,
1656
+ });
1657
+ }
1658
+
1659
+ // Emit session event to custom tools
1660
+ await this.emitCustomToolSessionEvent("switch", previousSessionFile);
1661
+
1662
+ this.agent.replaceMessages(sessionContext.messages);
1663
+
1664
+ // Restore model if saved
1665
+ const defaultModelStr = sessionContext.models.default;
1666
+ if (defaultModelStr) {
1667
+ const slashIdx = defaultModelStr.indexOf("/");
1668
+ if (slashIdx > 0) {
1669
+ const provider = defaultModelStr.slice(0, slashIdx);
1670
+ const modelId = defaultModelStr.slice(slashIdx + 1);
1671
+ const availableModels = await this._modelRegistry.getAvailable();
1672
+ const match = availableModels.find((m) => m.provider === provider && m.id === modelId);
1673
+ if (match) {
1674
+ this.agent.setModel(match);
1675
+ }
1676
+ }
1677
+ }
1678
+
1679
+ // Restore thinking level if saved (setThinkingLevel clamps to model capabilities)
1680
+ if (sessionContext.thinkingLevel) {
1681
+ this.setThinkingLevel(sessionContext.thinkingLevel as ThinkingLevel);
1682
+ }
1683
+
1684
+ this._reconnectToAgent();
1685
+ return true;
1686
+ }
1687
+
1688
+ /**
1689
+ * Create a branch from a specific entry.
1690
+ * Emits before_branch/branch session events to hooks.
1691
+ *
1692
+ * @param entryId ID of the entry to branch from
1693
+ * @returns Object with:
1694
+ * - selectedText: The text of the selected user message (for editor pre-fill)
1695
+ * - cancelled: True if a hook cancelled the branch
1696
+ */
1697
+ async branch(entryId: string): Promise<{ selectedText: string; cancelled: boolean }> {
1698
+ const previousSessionFile = this.sessionFile;
1699
+ const selectedEntry = this.sessionManager.getEntry(entryId);
1700
+
1701
+ if (!selectedEntry || selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
1702
+ throw new Error("Invalid entry ID for branching");
1703
+ }
1704
+
1705
+ const selectedText = this._extractUserMessageText(selectedEntry.message.content);
1706
+
1707
+ let skipConversationRestore = false;
1708
+
1709
+ // Emit session_before_branch event (can be cancelled)
1710
+ if (this._hookRunner?.hasHandlers("session_before_branch")) {
1711
+ const result = (await this._hookRunner.emit({
1712
+ type: "session_before_branch",
1713
+ entryId,
1714
+ })) as SessionBeforeBranchResult | undefined;
1715
+
1716
+ if (result?.cancel) {
1717
+ return { selectedText, cancelled: true };
1718
+ }
1719
+ skipConversationRestore = result?.skipConversationRestore ?? false;
1720
+ }
1721
+
1722
+ // Flush pending writes before branching
1723
+ await this.sessionManager.flush();
1724
+
1725
+ if (!selectedEntry.parentId) {
1726
+ this.sessionManager.newSession();
1727
+ } else {
1728
+ this.sessionManager.createBranchedSession(selectedEntry.parentId);
1729
+ }
1730
+
1731
+ // Reload messages from entries (works for both file and in-memory mode)
1732
+ const sessionContext = this.sessionManager.buildSessionContext();
1733
+
1734
+ // Emit session_branch event to hooks (after branch completes)
1735
+ if (this._hookRunner) {
1736
+ await this._hookRunner.emit({
1737
+ type: "session_branch",
1738
+ previousSessionFile,
1739
+ });
1740
+ }
1741
+
1742
+ // Emit session event to custom tools (with reason "branch")
1743
+ await this.emitCustomToolSessionEvent("branch", previousSessionFile);
1744
+
1745
+ if (!skipConversationRestore) {
1746
+ this.agent.replaceMessages(sessionContext.messages);
1747
+ }
1748
+
1749
+ return { selectedText, cancelled: false };
1750
+ }
1751
+
1752
+ // =========================================================================
1753
+ // Tree Navigation
1754
+ // =========================================================================
1755
+
1756
+ /**
1757
+ * Navigate to a different node in the session tree.
1758
+ * Unlike branch() which creates a new session file, this stays in the same file.
1759
+ *
1760
+ * @param targetId The entry ID to navigate to
1761
+ * @param options.summarize Whether user wants to summarize abandoned branch
1762
+ * @param options.customInstructions Custom instructions for summarizer
1763
+ * @returns Result with editorText (if user message) and cancelled status
1764
+ */
1765
+ async navigateTree(
1766
+ targetId: string,
1767
+ options: { summarize?: boolean; customInstructions?: string } = {},
1768
+ ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
1769
+ const oldLeafId = this.sessionManager.getLeafId();
1770
+
1771
+ // No-op if already at target
1772
+ if (targetId === oldLeafId) {
1773
+ return { cancelled: false };
1774
+ }
1775
+
1776
+ // Model required for summarization
1777
+ if (options.summarize && !this.model) {
1778
+ throw new Error("No model available for summarization");
1779
+ }
1780
+
1781
+ const targetEntry = this.sessionManager.getEntry(targetId);
1782
+ if (!targetEntry) {
1783
+ throw new Error(`Entry ${targetId} not found`);
1784
+ }
1785
+
1786
+ // Collect entries to summarize (from old leaf to common ancestor)
1787
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(
1788
+ this.sessionManager,
1789
+ oldLeafId,
1790
+ targetId,
1791
+ );
1792
+
1793
+ // Prepare event data
1794
+ const preparation: TreePreparation = {
1795
+ targetId,
1796
+ oldLeafId,
1797
+ commonAncestorId,
1798
+ entriesToSummarize,
1799
+ userWantsSummary: options.summarize ?? false,
1800
+ };
1801
+
1802
+ // Set up abort controller for summarization
1803
+ this._branchSummaryAbortController = new AbortController();
1804
+ let hookSummary: { summary: string; details?: unknown } | undefined;
1805
+ let fromHook = false;
1806
+
1807
+ // Emit session_before_tree event
1808
+ if (this._hookRunner?.hasHandlers("session_before_tree")) {
1809
+ const result = (await this._hookRunner.emit({
1810
+ type: "session_before_tree",
1811
+ preparation,
1812
+ signal: this._branchSummaryAbortController.signal,
1813
+ })) as SessionBeforeTreeResult | undefined;
1814
+
1815
+ if (result?.cancel) {
1816
+ return { cancelled: true };
1817
+ }
1818
+
1819
+ if (result?.summary && options.summarize) {
1820
+ hookSummary = result.summary;
1821
+ fromHook = true;
1822
+ }
1823
+ }
1824
+
1825
+ // Run default summarizer if needed
1826
+ let summaryText: string | undefined;
1827
+ let summaryDetails: unknown;
1828
+ if (options.summarize && entriesToSummarize.length > 0 && !hookSummary) {
1829
+ const model = this.model!;
1830
+ const apiKey = await this._modelRegistry.getApiKey(model);
1831
+ if (!apiKey) {
1832
+ throw new Error(`No API key for ${model.provider}`);
1833
+ }
1834
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
1835
+ const result = await generateBranchSummary(entriesToSummarize, {
1836
+ model,
1837
+ apiKey,
1838
+ signal: this._branchSummaryAbortController.signal,
1839
+ customInstructions: options.customInstructions,
1840
+ reserveTokens: branchSummarySettings.reserveTokens,
1841
+ });
1842
+ this._branchSummaryAbortController = undefined;
1843
+ if (result.aborted) {
1844
+ return { cancelled: true, aborted: true };
1845
+ }
1846
+ if (result.error) {
1847
+ throw new Error(result.error);
1848
+ }
1849
+ summaryText = result.summary;
1850
+ summaryDetails = {
1851
+ readFiles: result.readFiles || [],
1852
+ modifiedFiles: result.modifiedFiles || [],
1853
+ };
1854
+ } else if (hookSummary) {
1855
+ summaryText = hookSummary.summary;
1856
+ summaryDetails = hookSummary.details;
1857
+ }
1858
+
1859
+ // Determine the new leaf position based on target type
1860
+ let newLeafId: string | null;
1861
+ let editorText: string | undefined;
1862
+
1863
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
1864
+ // User message: leaf = parent (null if root), text goes to editor
1865
+ newLeafId = targetEntry.parentId;
1866
+ editorText = this._extractUserMessageText(targetEntry.message.content);
1867
+ } else if (targetEntry.type === "custom_message") {
1868
+ // Custom message: leaf = parent (null if root), text goes to editor
1869
+ newLeafId = targetEntry.parentId;
1870
+ editorText =
1871
+ typeof targetEntry.content === "string"
1872
+ ? targetEntry.content
1873
+ : targetEntry.content
1874
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
1875
+ .map((c) => c.text)
1876
+ .join("");
1877
+ } else {
1878
+ // Non-user message: leaf = selected node
1879
+ newLeafId = targetId;
1880
+ }
1881
+
1882
+ // Switch leaf (with or without summary)
1883
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
1884
+ let summaryEntry: BranchSummaryEntry | undefined;
1885
+ if (summaryText) {
1886
+ // Create summary at target position (can be null for root)
1887
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromHook);
1888
+ summaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;
1889
+ } else if (newLeafId === null) {
1890
+ // No summary, navigating to root - reset leaf
1891
+ this.sessionManager.resetLeaf();
1892
+ } else {
1893
+ // No summary, navigating to non-root
1894
+ this.sessionManager.branch(newLeafId);
1895
+ }
1896
+
1897
+ // Update agent state
1898
+ const sessionContext = this.sessionManager.buildSessionContext();
1899
+ this.agent.replaceMessages(sessionContext.messages);
1900
+
1901
+ // Emit session_tree event
1902
+ if (this._hookRunner) {
1903
+ await this._hookRunner.emit({
1904
+ type: "session_tree",
1905
+ newLeafId: this.sessionManager.getLeafId(),
1906
+ oldLeafId,
1907
+ summaryEntry,
1908
+ fromHook: summaryText ? fromHook : undefined,
1909
+ });
1910
+ }
1911
+
1912
+ // Emit to custom tools
1913
+ await this.emitCustomToolSessionEvent("tree", this.sessionFile);
1914
+
1915
+ this._branchSummaryAbortController = undefined;
1916
+ return { editorText, cancelled: false, summaryEntry };
1917
+ }
1918
+
1919
+ /**
1920
+ * Get all user messages from session for branch selector.
1921
+ */
1922
+ getUserMessagesForBranching(): Array<{ entryId: string; text: string }> {
1923
+ const entries = this.sessionManager.getEntries();
1924
+ const result: Array<{ entryId: string; text: string }> = [];
1925
+
1926
+ for (const entry of entries) {
1927
+ if (entry.type !== "message") continue;
1928
+ if (entry.message.role !== "user") continue;
1929
+
1930
+ const text = this._extractUserMessageText(entry.message.content);
1931
+ if (text) {
1932
+ result.push({ entryId: entry.id, text });
1933
+ }
1934
+ }
1935
+
1936
+ return result;
1937
+ }
1938
+
1939
+ private _extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {
1940
+ if (typeof content === "string") return content;
1941
+ if (Array.isArray(content)) {
1942
+ return content
1943
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
1944
+ .map((c) => c.text)
1945
+ .join("");
1946
+ }
1947
+ return "";
1948
+ }
1949
+
1950
+ /**
1951
+ * Get session statistics.
1952
+ */
1953
+ getSessionStats(): SessionStats {
1954
+ const state = this.state;
1955
+ const userMessages = state.messages.filter((m) => m.role === "user").length;
1956
+ const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
1957
+ const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
1958
+
1959
+ let toolCalls = 0;
1960
+ let totalInput = 0;
1961
+ let totalOutput = 0;
1962
+ let totalCacheRead = 0;
1963
+ let totalCacheWrite = 0;
1964
+ let totalCost = 0;
1965
+
1966
+ const getTaskToolUsage = (details: unknown): Usage | undefined => {
1967
+ if (!details || typeof details !== "object") return undefined;
1968
+ const record = details as Record<string, unknown>;
1969
+ const usage = record.usage;
1970
+ if (!usage || typeof usage !== "object") return undefined;
1971
+ return usage as Usage;
1972
+ };
1973
+
1974
+ for (const message of state.messages) {
1975
+ if (message.role === "assistant") {
1976
+ const assistantMsg = message as AssistantMessage;
1977
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
1978
+ totalInput += assistantMsg.usage.input;
1979
+ totalOutput += assistantMsg.usage.output;
1980
+ totalCacheRead += assistantMsg.usage.cacheRead;
1981
+ totalCacheWrite += assistantMsg.usage.cacheWrite;
1982
+ totalCost += assistantMsg.usage.cost.total;
1983
+ }
1984
+
1985
+ if (message.role === "toolResult" && message.toolName === "task") {
1986
+ const usage = getTaskToolUsage(message.details);
1987
+ if (usage) {
1988
+ totalInput += usage.input;
1989
+ totalOutput += usage.output;
1990
+ totalCacheRead += usage.cacheRead;
1991
+ totalCacheWrite += usage.cacheWrite;
1992
+ totalCost += usage.cost.total;
1993
+ }
1994
+ }
1995
+ }
1996
+
1997
+ return {
1998
+ sessionFile: this.sessionFile,
1999
+ sessionId: this.sessionId,
2000
+ userMessages,
2001
+ assistantMessages,
2002
+ toolCalls,
2003
+ toolResults,
2004
+ totalMessages: state.messages.length,
2005
+ tokens: {
2006
+ input: totalInput,
2007
+ output: totalOutput,
2008
+ cacheRead: totalCacheRead,
2009
+ cacheWrite: totalCacheWrite,
2010
+ total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
2011
+ },
2012
+ cost: totalCost,
2013
+ };
2014
+ }
2015
+
2016
+ /**
2017
+ * Export session to HTML.
2018
+ * @param outputPath Optional output path (defaults to session directory)
2019
+ * @returns Path to exported file
2020
+ */
2021
+ async exportToHtml(outputPath?: string): Promise<string> {
2022
+ const themeName = this.settingsManager.getTheme();
2023
+ return exportSessionToHtml(this.sessionManager, this.state, { outputPath, themeName });
2024
+ }
2025
+
2026
+ // =========================================================================
2027
+ // Utilities
2028
+ // =========================================================================
2029
+
2030
+ /**
2031
+ * Get text content of last assistant message.
2032
+ * Useful for /copy command.
2033
+ * @returns Text content, or undefined if no assistant message exists
2034
+ */
2035
+ getLastAssistantText(): string | undefined {
2036
+ const lastAssistant = this.messages
2037
+ .slice()
2038
+ .reverse()
2039
+ .find((m) => {
2040
+ if (m.role !== "assistant") return false;
2041
+ const msg = m as AssistantMessage;
2042
+ // Skip aborted messages with no content
2043
+ if (msg.stopReason === "aborted" && msg.content.length === 0) return false;
2044
+ return true;
2045
+ });
2046
+
2047
+ if (!lastAssistant) return undefined;
2048
+
2049
+ let text = "";
2050
+ for (const content of (lastAssistant as AssistantMessage).content) {
2051
+ if (content.type === "text") {
2052
+ text += content.text;
2053
+ }
2054
+ }
2055
+
2056
+ return text.trim() || undefined;
2057
+ }
2058
+
2059
+ /**
2060
+ * Format the entire session as plain text for clipboard export.
2061
+ * Includes user messages, assistant text, thinking blocks, tool calls, and tool results.
2062
+ */
2063
+ formatSessionAsText(): string {
2064
+ const lines: string[] = [];
2065
+
2066
+ for (const msg of this.messages) {
2067
+ if (msg.role === "user") {
2068
+ lines.push("## User\n");
2069
+ if (typeof msg.content === "string") {
2070
+ lines.push(msg.content);
2071
+ } else {
2072
+ for (const c of msg.content) {
2073
+ if (c.type === "text") {
2074
+ lines.push(c.text);
2075
+ } else if (c.type === "image") {
2076
+ lines.push("[Image]");
2077
+ }
2078
+ }
2079
+ }
2080
+ lines.push("\n");
2081
+ } else if (msg.role === "assistant") {
2082
+ const assistantMsg = msg as AssistantMessage;
2083
+ lines.push("## Assistant\n");
2084
+
2085
+ for (const c of assistantMsg.content) {
2086
+ if (c.type === "text") {
2087
+ lines.push(c.text);
2088
+ } else if (c.type === "thinking") {
2089
+ lines.push("<thinking>");
2090
+ lines.push(c.thinking);
2091
+ lines.push("</thinking>\n");
2092
+ } else if (c.type === "toolCall") {
2093
+ lines.push(`### Tool: ${c.name}`);
2094
+ lines.push("```json");
2095
+ lines.push(JSON.stringify(c.arguments, null, 2));
2096
+ lines.push("```\n");
2097
+ }
2098
+ }
2099
+ lines.push("");
2100
+ } else if (msg.role === "toolResult") {
2101
+ lines.push(`### Tool Result: ${msg.toolName}`);
2102
+ if (msg.isError) {
2103
+ lines.push("(error)");
2104
+ }
2105
+ for (const c of msg.content) {
2106
+ if (c.type === "text") {
2107
+ lines.push("```");
2108
+ lines.push(c.text);
2109
+ lines.push("```");
2110
+ } else if (c.type === "image") {
2111
+ lines.push("[Image output]");
2112
+ }
2113
+ }
2114
+ lines.push("");
2115
+ }
2116
+ }
2117
+
2118
+ return lines.join("\n").trim();
2119
+ }
2120
+
2121
+ // =========================================================================
2122
+ // Hook System
2123
+ // =========================================================================
2124
+
2125
+ /**
2126
+ * Check if hooks have handlers for a specific event type.
2127
+ */
2128
+ hasHookHandlers(eventType: string): boolean {
2129
+ return this._hookRunner?.hasHandlers(eventType) ?? false;
2130
+ }
2131
+
2132
+ /**
2133
+ * Get the hook runner (for setting UI context and error handlers).
2134
+ */
2135
+ get hookRunner(): HookRunner | undefined {
2136
+ return this._hookRunner;
2137
+ }
2138
+
2139
+ /**
2140
+ * Get custom tools (for setting UI context in modes).
2141
+ */
2142
+ get customTools(): LoadedCustomTool[] {
2143
+ return this._customTools;
2144
+ }
2145
+
2146
+ /**
2147
+ * Emit session event to all custom tools.
2148
+ * Called on session switch, branch, tree navigation, and shutdown.
2149
+ */
2150
+ async emitCustomToolSessionEvent(
2151
+ reason: CustomToolSessionEvent["reason"],
2152
+ previousSessionFile?: string | undefined,
2153
+ ): Promise<void> {
2154
+ if (!this._customTools) return;
2155
+
2156
+ const event: CustomToolSessionEvent = { reason, previousSessionFile };
2157
+ const ctx: CustomToolContext = {
2158
+ sessionManager: this.sessionManager,
2159
+ modelRegistry: this._modelRegistry,
2160
+ model: this.agent.state.model,
2161
+ isIdle: () => !this.isStreaming,
2162
+ hasQueuedMessages: () => this.queuedMessageCount > 0,
2163
+ abort: () => {
2164
+ this.abort();
2165
+ },
2166
+ };
2167
+
2168
+ for (const { tool } of this._customTools) {
2169
+ if (tool.onSession) {
2170
+ try {
2171
+ await tool.onSession(event, ctx);
2172
+ } catch (err) {
2173
+ logger.warn("Tool onSession error", { error: String(err) });
2174
+ }
2175
+ }
2176
+ }
2177
+ }
2178
+ }