shortcutxl 0.2.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 (423) hide show
  1. package/README.md +59 -0
  2. package/agent-docs/README.md +397 -0
  3. package/agent-docs/docs/compaction.md +390 -0
  4. package/agent-docs/docs/custom-provider.md +580 -0
  5. package/agent-docs/docs/development.md +69 -0
  6. package/agent-docs/docs/extensions.md +1971 -0
  7. package/agent-docs/docs/json.md +79 -0
  8. package/agent-docs/docs/keybindings.md +174 -0
  9. package/agent-docs/docs/models.md +293 -0
  10. package/agent-docs/docs/packages.md +209 -0
  11. package/agent-docs/docs/prompt-templates.md +67 -0
  12. package/agent-docs/docs/providers.md +186 -0
  13. package/agent-docs/docs/rpc.md +1317 -0
  14. package/agent-docs/docs/sdk.md +962 -0
  15. package/agent-docs/docs/session.md +412 -0
  16. package/agent-docs/docs/settings.md +223 -0
  17. package/agent-docs/docs/shell-aliases.md +13 -0
  18. package/agent-docs/docs/skills.md +231 -0
  19. package/agent-docs/docs/terminal-setup.md +70 -0
  20. package/agent-docs/docs/termux.md +127 -0
  21. package/agent-docs/docs/themes.md +295 -0
  22. package/agent-docs/docs/tree.md +219 -0
  23. package/agent-docs/docs/tui.md +887 -0
  24. package/agent-docs/docs/windows.md +17 -0
  25. package/agent-docs/examples/README.md +25 -0
  26. package/agent-docs/examples/extensions/README.md +205 -0
  27. package/agent-docs/examples/extensions/antigravity-image-gen.ts +447 -0
  28. package/agent-docs/examples/extensions/auto-commit-on-exit.ts +49 -0
  29. package/agent-docs/examples/extensions/bash-spawn-hook.ts +30 -0
  30. package/agent-docs/examples/extensions/bookmark.ts +50 -0
  31. package/agent-docs/examples/extensions/built-in-tool-renderer.ts +256 -0
  32. package/agent-docs/examples/extensions/claude-rules.ts +86 -0
  33. package/agent-docs/examples/extensions/commands.ts +75 -0
  34. package/agent-docs/examples/extensions/confirm-destructive.ts +59 -0
  35. package/agent-docs/examples/extensions/custom-compaction.ts +126 -0
  36. package/agent-docs/examples/extensions/custom-footer.ts +63 -0
  37. package/agent-docs/examples/extensions/custom-header.ts +73 -0
  38. package/agent-docs/examples/extensions/custom-provider-anthropic/index.ts +660 -0
  39. package/agent-docs/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  40. package/agent-docs/examples/extensions/custom-provider-anthropic/package.json +19 -0
  41. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/index.ts +362 -0
  42. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  43. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/test.ts +88 -0
  44. package/agent-docs/examples/extensions/custom-provider-qwen-cli/index.ts +349 -0
  45. package/agent-docs/examples/extensions/custom-provider-qwen-cli/package.json +16 -0
  46. package/agent-docs/examples/extensions/dirty-repo-guard.ts +56 -0
  47. package/agent-docs/examples/extensions/doom-overlay/README.md +46 -0
  48. package/agent-docs/examples/extensions/doom-overlay/doom/build.sh +152 -0
  49. package/agent-docs/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  50. package/agent-docs/examples/extensions/doom-overlay/doom-component.ts +133 -0
  51. package/agent-docs/examples/extensions/doom-overlay/doom-engine.ts +186 -0
  52. package/agent-docs/examples/extensions/doom-overlay/doom-keys.ts +108 -0
  53. package/agent-docs/examples/extensions/doom-overlay/index.ts +74 -0
  54. package/agent-docs/examples/extensions/doom-overlay/wad-finder.ts +51 -0
  55. package/agent-docs/examples/extensions/dynamic-resources/SKILL.md +8 -0
  56. package/agent-docs/examples/extensions/dynamic-resources/dynamic.json +79 -0
  57. package/agent-docs/examples/extensions/dynamic-resources/dynamic.md +5 -0
  58. package/agent-docs/examples/extensions/dynamic-resources/index.ts +15 -0
  59. package/agent-docs/examples/extensions/dynamic-tools.ts +77 -0
  60. package/agent-docs/examples/extensions/event-bus.ts +43 -0
  61. package/agent-docs/examples/extensions/file-trigger.ts +41 -0
  62. package/agent-docs/examples/extensions/git-checkpoint.ts +53 -0
  63. package/agent-docs/examples/extensions/handoff.ts +155 -0
  64. package/agent-docs/examples/extensions/hello.ts +25 -0
  65. package/agent-docs/examples/extensions/inline-bash.ts +94 -0
  66. package/agent-docs/examples/extensions/input-transform.ts +43 -0
  67. package/agent-docs/examples/extensions/interactive-shell.ts +209 -0
  68. package/agent-docs/examples/extensions/mac-system-theme.ts +47 -0
  69. package/agent-docs/examples/extensions/message-renderer.ts +59 -0
  70. package/agent-docs/examples/extensions/minimal-mode.ts +430 -0
  71. package/agent-docs/examples/extensions/modal-editor.ts +90 -0
  72. package/agent-docs/examples/extensions/model-status.ts +31 -0
  73. package/agent-docs/examples/extensions/notify.ts +55 -0
  74. package/agent-docs/examples/extensions/overlay-qa-tests.ts +936 -0
  75. package/agent-docs/examples/extensions/overlay-test.ts +159 -0
  76. package/agent-docs/examples/extensions/permission-gate.ts +37 -0
  77. package/agent-docs/examples/extensions/pirate.ts +47 -0
  78. package/agent-docs/examples/extensions/plan-mode/README.md +65 -0
  79. package/agent-docs/examples/extensions/plan-mode/index.ts +363 -0
  80. package/agent-docs/examples/extensions/plan-mode/utils.ts +173 -0
  81. package/agent-docs/examples/extensions/preset.ts +418 -0
  82. package/agent-docs/examples/extensions/protected-paths.ts +30 -0
  83. package/agent-docs/examples/extensions/qna.ts +122 -0
  84. package/agent-docs/examples/extensions/question.ts +278 -0
  85. package/agent-docs/examples/extensions/questionnaire.ts +440 -0
  86. package/agent-docs/examples/extensions/rainbow-editor.ts +90 -0
  87. package/agent-docs/examples/extensions/reload-runtime.ts +37 -0
  88. package/agent-docs/examples/extensions/rpc-demo.ts +124 -0
  89. package/agent-docs/examples/extensions/sandbox/index.ts +324 -0
  90. package/agent-docs/examples/extensions/sandbox/package-lock.json +92 -0
  91. package/agent-docs/examples/extensions/sandbox/package.json +19 -0
  92. package/agent-docs/examples/extensions/send-user-message.ts +97 -0
  93. package/agent-docs/examples/extensions/session-name.ts +27 -0
  94. package/agent-docs/examples/extensions/shutdown-command.ts +69 -0
  95. package/agent-docs/examples/extensions/snake.ts +343 -0
  96. package/agent-docs/examples/extensions/space-invaders.ts +566 -0
  97. package/agent-docs/examples/extensions/ssh.ts +233 -0
  98. package/agent-docs/examples/extensions/status-line.ts +40 -0
  99. package/agent-docs/examples/extensions/subagent/README.md +172 -0
  100. package/agent-docs/examples/extensions/subagent/agents/planner.md +37 -0
  101. package/agent-docs/examples/extensions/subagent/agents/reviewer.md +35 -0
  102. package/agent-docs/examples/extensions/subagent/agents/scout.md +50 -0
  103. package/agent-docs/examples/extensions/subagent/agents/worker.md +24 -0
  104. package/agent-docs/examples/extensions/subagent/agents.ts +130 -0
  105. package/agent-docs/examples/extensions/subagent/index.ts +1068 -0
  106. package/agent-docs/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  107. package/agent-docs/examples/extensions/subagent/prompts/implement.md +10 -0
  108. package/agent-docs/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  109. package/agent-docs/examples/extensions/summarize.ts +206 -0
  110. package/agent-docs/examples/extensions/system-prompt-header.ts +17 -0
  111. package/agent-docs/examples/extensions/timed-confirm.ts +72 -0
  112. package/agent-docs/examples/extensions/titlebar-spinner.ts +58 -0
  113. package/agent-docs/examples/extensions/todo.ts +314 -0
  114. package/agent-docs/examples/extensions/tool-override.ts +146 -0
  115. package/agent-docs/examples/extensions/tools.ts +145 -0
  116. package/agent-docs/examples/extensions/trigger-compact.ts +40 -0
  117. package/agent-docs/examples/extensions/truncated-tool.ts +194 -0
  118. package/agent-docs/examples/extensions/widget-placement.ts +17 -0
  119. package/agent-docs/examples/extensions/with-deps/index.ts +37 -0
  120. package/agent-docs/examples/extensions/with-deps/package-lock.json +31 -0
  121. package/agent-docs/examples/extensions/with-deps/package.json +22 -0
  122. package/agent-docs/examples/rpc-extension-ui.ts +654 -0
  123. package/agent-docs/examples/sdk/01-minimal.ts +22 -0
  124. package/agent-docs/examples/sdk/02-custom-model.ts +48 -0
  125. package/agent-docs/examples/sdk/03-custom-prompt.ts +55 -0
  126. package/agent-docs/examples/sdk/04-skills.ts +53 -0
  127. package/agent-docs/examples/sdk/05-tools.ts +56 -0
  128. package/agent-docs/examples/sdk/06-extensions.ts +88 -0
  129. package/agent-docs/examples/sdk/07-context-files.ts +40 -0
  130. package/agent-docs/examples/sdk/08-prompt-templates.ts +47 -0
  131. package/agent-docs/examples/sdk/09-api-keys-and-oauth.ts +48 -0
  132. package/agent-docs/examples/sdk/10-settings.ts +54 -0
  133. package/agent-docs/examples/sdk/11-sessions.ts +48 -0
  134. package/agent-docs/examples/sdk/12-full-control.ts +82 -0
  135. package/agent-docs/examples/sdk/README.md +144 -0
  136. package/agent-docs/xll-skill.md +61 -0
  137. package/agent-docs/xll-spec.md +110 -0
  138. package/dist/cli/args.js +290 -0
  139. package/dist/cli/config-selector.js +31 -0
  140. package/dist/cli/file-processor.js +79 -0
  141. package/dist/cli/list-models.js +92 -0
  142. package/dist/cli/package-commands.js +210 -0
  143. package/dist/cli/report-settings-errors.js +11 -0
  144. package/dist/cli/session-picker.js +34 -0
  145. package/dist/cli.js +19 -0
  146. package/dist/config.js +288 -0
  147. package/dist/core/abort.js +15 -0
  148. package/dist/core/agent-loop.js +352 -0
  149. package/dist/core/agent-session.js +2019 -0
  150. package/dist/core/agent.js +410 -0
  151. package/dist/core/auth-storage.js +456 -0
  152. package/dist/core/bash-executor.js +222 -0
  153. package/dist/core/compaction/branch-summarization.js +242 -0
  154. package/dist/core/compaction/compaction.js +610 -0
  155. package/dist/core/compaction/index.js +7 -0
  156. package/dist/core/compaction/utils.js +139 -0
  157. package/dist/core/defaults.js +6 -0
  158. package/dist/core/diagnostics.js +2 -0
  159. package/dist/core/event-bus.js +25 -0
  160. package/dist/core/exec.js +71 -0
  161. package/dist/core/export-html/ansi-to-html.js +256 -0
  162. package/dist/core/export-html/index.js +238 -0
  163. package/dist/core/export-html/session-view-model.js +342 -0
  164. package/dist/core/export-html/template.css +1110 -0
  165. package/dist/core/export-html/template.html +76 -0
  166. package/dist/core/export-html/template.js +1990 -0
  167. package/dist/core/export-html/tool-renderer.js +63 -0
  168. package/dist/core/export-html/vendor/highlight.min.js +7725 -0
  169. package/dist/core/export-html/vendor/marked.min.js +1803 -0
  170. package/dist/core/extensions/index.js +9 -0
  171. package/dist/core/extensions/loader.js +422 -0
  172. package/dist/core/extensions/runner.js +651 -0
  173. package/dist/core/extensions/types.js +35 -0
  174. package/dist/core/extensions/wrapper.js +102 -0
  175. package/dist/core/footer-data-provider.js +162 -0
  176. package/dist/core/index.js +9 -0
  177. package/dist/core/keybindings.js +153 -0
  178. package/dist/core/messages.js +133 -0
  179. package/dist/core/model-registry.js +539 -0
  180. package/dist/core/model-resolver.js +370 -0
  181. package/dist/core/package-manager.js +1485 -0
  182. package/dist/core/prompt-templates.js +253 -0
  183. package/dist/core/resolve-config-value.js +59 -0
  184. package/dist/core/resource-loader.js +700 -0
  185. package/dist/core/sdk.js +197 -0
  186. package/dist/core/session-bash.js +99 -0
  187. package/dist/core/session-compaction.js +165 -0
  188. package/dist/core/session-manager.js +1153 -0
  189. package/dist/core/session-models.js +99 -0
  190. package/dist/core/session-retry.js +155 -0
  191. package/dist/core/settings-manager.js +572 -0
  192. package/dist/core/skills.js +382 -0
  193. package/dist/core/slash-commands.js +31 -0
  194. package/dist/core/system-prompt.js +161 -0
  195. package/dist/core/theme.js +770 -0
  196. package/dist/core/timings.js +26 -0
  197. package/dist/core/tools/bash.js +258 -0
  198. package/dist/core/tools/edit-diff.js +245 -0
  199. package/dist/core/tools/edit.js +148 -0
  200. package/dist/core/tools/find.js +208 -0
  201. package/dist/core/tools/grep.js +246 -0
  202. package/dist/core/tools/index.js +67 -0
  203. package/dist/core/tools/ls.js +123 -0
  204. package/dist/core/tools/path-utils.js +81 -0
  205. package/dist/core/tools/read.js +160 -0
  206. package/dist/core/tools/truncate.js +70 -0
  207. package/dist/core/tools/write.js +82 -0
  208. package/dist/custom/agents/action.js +13 -0
  209. package/dist/custom/agents/document-reader.js +70 -0
  210. package/dist/custom/agents/general.js +26 -0
  211. package/dist/custom/agents/index.js +49 -0
  212. package/dist/custom/agents/installation.js +13 -0
  213. package/dist/custom/agents/types.js +7 -0
  214. package/dist/custom/auth/refresh-timer.js +33 -0
  215. package/dist/custom/auth/shortcut-oauth.js +145 -0
  216. package/dist/custom/constants.js +21 -0
  217. package/dist/custom/context/workbook-summary.js +73 -0
  218. package/dist/custom/credits/shortcut-credits.js +29 -0
  219. package/dist/custom/cron/cron-daemon-entry.js +18 -0
  220. package/dist/custom/cron/daemon-ipc.js +131 -0
  221. package/dist/custom/cron/daemon.js +224 -0
  222. package/dist/custom/cron/jobs.js +226 -0
  223. package/dist/custom/cron/run-log.js +51 -0
  224. package/dist/custom/cron/schedule.js +72 -0
  225. package/dist/custom/cron/status-line.js +98 -0
  226. package/dist/custom/cron/store.js +87 -0
  227. package/dist/custom/cron/types.js +8 -0
  228. package/dist/custom/dev/index.js +59 -0
  229. package/dist/custom/dev/trace-export.js +58 -0
  230. package/dist/custom/ensure-excel.js +63 -0
  231. package/dist/custom/excel-config.js +36 -0
  232. package/dist/custom/preflight.js +422 -0
  233. package/dist/custom/prompts/action.js +100 -0
  234. package/dist/custom/prompts/api.js +66 -0
  235. package/dist/custom/prompts/installation.js +124 -0
  236. package/dist/custom/prompts/shared.js +138 -0
  237. package/dist/custom/providers/llm-usage.js +42 -0
  238. package/dist/custom/providers/message-converter.js +74 -0
  239. package/dist/custom/providers/provider-ids.js +9 -0
  240. package/dist/custom/providers/register-openai-codex-provider.js +27 -0
  241. package/dist/custom/providers/register-shortcut-provider.js +52 -0
  242. package/dist/custom/providers/shortcut-invoke.js +117 -0
  243. package/dist/custom/providers/shortcut-stream.js +252 -0
  244. package/dist/custom/providers/sse-protocol.js +38 -0
  245. package/dist/custom/sync-xll.js +130 -0
  246. package/dist/custom/tools/cron.js +413 -0
  247. package/dist/custom/tools/excel-exec.js +167 -0
  248. package/dist/custom/tools/excel-range.js +50 -0
  249. package/dist/custom/tools/llm-analysis.js +265 -0
  250. package/dist/custom/tools/render-helpers.js +38 -0
  251. package/dist/custom/tools/switch-mode.js +94 -0
  252. package/dist/custom/tools/task/agents.js +6 -0
  253. package/dist/custom/tools/task/index.js +8 -0
  254. package/dist/custom/tools/task/render.js +348 -0
  255. package/dist/custom/tools/task/subprocess.js +320 -0
  256. package/dist/custom/tools/task/task.js +205 -0
  257. package/dist/custom/tools/todo-list.js +195 -0
  258. package/dist/custom/tracing/session-upload.js +93 -0
  259. package/dist/index.js +45 -0
  260. package/dist/main.js +613 -0
  261. package/dist/migrations.js +265 -0
  262. package/dist/modes/index.js +8 -0
  263. package/dist/modes/interactive/components/armin.js +337 -0
  264. package/dist/modes/interactive/components/assistant-message.js +94 -0
  265. package/dist/modes/interactive/components/bash-execution.js +171 -0
  266. package/dist/modes/interactive/components/bordered-loader.js +51 -0
  267. package/dist/modes/interactive/components/branch-summary-message.js +45 -0
  268. package/dist/modes/interactive/components/compaction-summary-message.js +46 -0
  269. package/dist/modes/interactive/components/config-selector.js +488 -0
  270. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  271. package/dist/modes/interactive/components/custom-editor.js +93 -0
  272. package/dist/modes/interactive/components/custom-message.js +81 -0
  273. package/dist/modes/interactive/components/daxnuts.js +140 -0
  274. package/dist/modes/interactive/components/diff.js +133 -0
  275. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  276. package/dist/modes/interactive/components/extension-editor.js +105 -0
  277. package/dist/modes/interactive/components/extension-input.js +61 -0
  278. package/dist/modes/interactive/components/extension-selector.js +78 -0
  279. package/dist/modes/interactive/components/footer.js +309 -0
  280. package/dist/modes/interactive/components/index.js +33 -0
  281. package/dist/modes/interactive/components/keybinding-hints.js +61 -0
  282. package/dist/modes/interactive/components/layout.js +64 -0
  283. package/dist/modes/interactive/components/login-dialog.js +148 -0
  284. package/dist/modes/interactive/components/model-selector.js +237 -0
  285. package/dist/modes/interactive/components/oauth-selector.js +111 -0
  286. package/dist/modes/interactive/components/session-selector-search.js +157 -0
  287. package/dist/modes/interactive/components/session-selector.js +860 -0
  288. package/dist/modes/interactive/components/settings-selector.js +123 -0
  289. package/dist/modes/interactive/components/show-images-selector.js +35 -0
  290. package/dist/modes/interactive/components/skill-invocation-message.js +48 -0
  291. package/dist/modes/interactive/components/theme-selector.js +47 -0
  292. package/dist/modes/interactive/components/thinking-selector.js +47 -0
  293. package/dist/modes/interactive/components/tool-execution.js +789 -0
  294. package/dist/modes/interactive/components/tool-group.js +106 -0
  295. package/dist/modes/interactive/components/tree-selector.js +962 -0
  296. package/dist/modes/interactive/components/user-message-selector.js +115 -0
  297. package/dist/modes/interactive/components/user-message.js +48 -0
  298. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  299. package/dist/modes/interactive/file-attachments.js +135 -0
  300. package/dist/modes/interactive/interactive-mode.js +3775 -0
  301. package/dist/modes/interactive/theme/dark.json +85 -0
  302. package/dist/modes/interactive/theme/light.json +85 -0
  303. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  304. package/dist/modes/interactive/theme/theme.js +177 -0
  305. package/dist/modes/print-mode.js +101 -0
  306. package/dist/modes/rpc/rpc-client.js +387 -0
  307. package/dist/modes/rpc/rpc-mode.js +509 -0
  308. package/dist/modes/rpc/rpc-types.js +8 -0
  309. package/dist/subagent-entry.js +145 -0
  310. package/dist/tool-names.js +34 -0
  311. package/dist/tui/autocomplete.js +596 -0
  312. package/dist/tui/components/box.js +104 -0
  313. package/dist/tui/components/cancellable-loader.js +35 -0
  314. package/dist/tui/components/editor.js +1679 -0
  315. package/dist/tui/components/image.js +69 -0
  316. package/dist/tui/components/input.js +433 -0
  317. package/dist/tui/components/loader.js +49 -0
  318. package/dist/tui/components/markdown.js +629 -0
  319. package/dist/tui/components/select-list.js +152 -0
  320. package/dist/tui/components/settings-list.js +185 -0
  321. package/dist/tui/components/spacer.js +23 -0
  322. package/dist/tui/components/text.js +89 -0
  323. package/dist/tui/components/truncated-text.js +51 -0
  324. package/dist/tui/editor-component.js +2 -0
  325. package/dist/tui/fuzzy.js +107 -0
  326. package/dist/tui/get-east-asian-width/index.js +32 -0
  327. package/dist/tui/get-east-asian-width/lookup.js +404 -0
  328. package/dist/tui/index.js +32 -0
  329. package/dist/tui/keybindings.js +114 -0
  330. package/dist/tui/keys.js +959 -0
  331. package/dist/tui/kill-ring.js +44 -0
  332. package/dist/tui/stdin-buffer.js +317 -0
  333. package/dist/tui/terminal-image.js +288 -0
  334. package/dist/tui/terminal.js +249 -0
  335. package/dist/tui/tui/autocomplete.js +596 -0
  336. package/dist/tui/tui/components/box.js +106 -0
  337. package/dist/tui/tui/components/cancellable-loader.js +35 -0
  338. package/dist/tui/tui/components/editor.js +1679 -0
  339. package/dist/tui/tui/components/image.js +69 -0
  340. package/dist/tui/tui/components/input.js +433 -0
  341. package/dist/tui/tui/components/loader.js +49 -0
  342. package/dist/tui/tui/components/markdown.js +629 -0
  343. package/dist/tui/tui/components/select-list.js +152 -0
  344. package/dist/tui/tui/components/settings-list.js +185 -0
  345. package/dist/tui/tui/components/spacer.js +23 -0
  346. package/dist/tui/tui/components/text.js +91 -0
  347. package/dist/tui/tui/components/truncated-text.js +51 -0
  348. package/dist/tui/tui/editor-component.js +2 -0
  349. package/dist/tui/tui/fuzzy.js +107 -0
  350. package/dist/tui/tui/get-east-asian-width/index.js +32 -0
  351. package/dist/tui/tui/get-east-asian-width/lookup.js +404 -0
  352. package/dist/tui/tui/index.js +32 -0
  353. package/dist/tui/tui/keybindings.js +114 -0
  354. package/dist/tui/tui/keys.js +959 -0
  355. package/dist/tui/tui/kill-ring.js +44 -0
  356. package/dist/tui/tui/stdin-buffer.js +317 -0
  357. package/dist/tui/tui/terminal-image.js +288 -0
  358. package/dist/tui/tui/terminal.js +249 -0
  359. package/dist/tui/tui/tui.js +955 -0
  360. package/dist/tui/tui/undo-stack.js +25 -0
  361. package/dist/tui/tui/utils.js +800 -0
  362. package/dist/tui/tui.js +955 -0
  363. package/dist/tui/undo-stack.js +25 -0
  364. package/dist/tui/utils.js +800 -0
  365. package/dist/utils/changelog.js +87 -0
  366. package/dist/utils/clipboard-image.js +164 -0
  367. package/dist/utils/clipboard-native.js +14 -0
  368. package/dist/utils/clipboard.js +67 -0
  369. package/dist/utils/frontmatter.js +26 -0
  370. package/dist/utils/git.js +166 -0
  371. package/dist/utils/image-convert.js +35 -0
  372. package/dist/utils/image-resize.js +183 -0
  373. package/dist/utils/mime.js +26 -0
  374. package/dist/utils/photon.js +121 -0
  375. package/dist/utils/shell.js +217 -0
  376. package/dist/utils/sleep.js +17 -0
  377. package/dist/utils/tools-manager.js +259 -0
  378. package/package.json +78 -0
  379. package/skills/excel-com-api/SKILL.md +74 -0
  380. package/skills/excel-com-api/excel-type-library.py +27767 -0
  381. package/skills/excel-com-api/office-type-library.py +10867 -0
  382. package/skills/integrations/SKILL.md +138 -0
  383. package/skills/integrations/alphasense.md +457 -0
  384. package/skills/integrations/bloomberg.md +803 -0
  385. package/skills/integrations/calcbench.md +315 -0
  386. package/skills/integrations/capiq.md +848 -0
  387. package/skills/integrations/dynamics-365-finance.md +354 -0
  388. package/skills/integrations/earnings_transcripts.md +387 -0
  389. package/skills/integrations/factset.md +758 -0
  390. package/skills/integrations/ice-fixed-income.md +344 -0
  391. package/skills/integrations/moodys-analytics.md +313 -0
  392. package/skills/integrations/morningstar.md +433 -0
  393. package/skills/integrations/nasdaq-data-link.md +249 -0
  394. package/skills/integrations/pitchbook.md +413 -0
  395. package/skills/integrations/preqin.md +422 -0
  396. package/skills/integrations/quickbooks.md +289 -0
  397. package/skills/integrations/quickfs.md +314 -0
  398. package/skills/integrations/refinitiv.md +473 -0
  399. package/skills/integrations/sage-intacct.md +401 -0
  400. package/skills/integrations/visible-alpha.md +320 -0
  401. package/skills/integrations/xero.md +393 -0
  402. package/skills/integrations/ycharts.md +306 -0
  403. package/skills/pdf-creation/SKILL.md +93 -0
  404. package/skills/pdf-extraction/SKILL.md +32 -0
  405. package/skills/powerpoint-creation/SKILL.md +110 -0
  406. package/skills/sec-edgar/SKILL.md +127 -0
  407. package/skills/sec-edgar/sec_to_pdf.py +109 -0
  408. package/xll/ShortcutXL.xll +0 -0
  409. package/xll/modules/debug_render.py +272 -0
  410. package/xll/modules/gameboy.py +241 -0
  411. package/xll/modules/pong.py +188 -0
  412. package/xll/modules/shortcut_xl/__init__.py +18 -0
  413. package/xll/modules/shortcut_xl/_categorize.py +200 -0
  414. package/xll/modules/shortcut_xl/_com.py +108 -0
  415. package/xll/modules/shortcut_xl/_format.py +252 -0
  416. package/xll/modules/shortcut_xl/_log.py +12 -0
  417. package/xll/modules/shortcut_xl/_managed.py +116 -0
  418. package/xll/modules/shortcut_xl/_registry.py +44 -0
  419. package/xll/modules/shortcut_xl/_threading.py +161 -0
  420. package/xll/modules/shortcut_xl/_tracking.py +283 -0
  421. package/xll/modules/stocks.py +100 -0
  422. package/xll/python3.dll +0 -0
  423. package/xll/python312.dll +0 -0
@@ -0,0 +1,2019 @@
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
+ import { isContextOverflow, modelsAreEqual } from '@mariozechner/pi-ai';
16
+ import { readFileSync } from 'node:fs';
17
+ import { basename, dirname } from 'node:path';
18
+ // SHORTCUT PATCH: removed getDocsPath import — login errors no longer reference providers.md
19
+ import { stripFrontmatter } from '../utils/frontmatter.js';
20
+ import { calculateContextTokens, collectEntriesForBranchSummary, estimateContextTokens, generateBranchSummary } from './compaction/index.js';
21
+ import { DEFAULT_THINKING_LEVEL } from './defaults.js';
22
+ import { exportFromFile } from './export-html/index.js';
23
+ import { createToolHtmlRenderer } from './export-html/tool-renderer.js';
24
+ import { ExtensionRunner, wrapRegisteredTools, wrapToolsWithExtensions } from './extensions/index.js';
25
+ import { expandPromptTemplate } from './prompt-templates.js';
26
+ import { SessionBash } from './session-bash.js';
27
+ import { checkCompactionNeeded, SessionCompaction } from './session-compaction.js';
28
+ import { getLatestCompactionEntry } from './session-manager.js';
29
+ import { clampThinkingLevel, computeNextModel, cycleThinkingLevel as computeNextThinkingLevel, getAvailableThinkingLevels, supportsThinking, supportsXhighThinking } from './session-models.js';
30
+ import { isRetryableError, SessionRetry } from './session-retry.js';
31
+ import { ALL_BUILTIN_SLASH_COMMAND_NAMES } from './slash-commands.js';
32
+ import { buildSystemPrompt } from './system-prompt.js';
33
+ import { theme } from './theme.js';
34
+ import { createAllTools } from './tools/index.js';
35
+ // ============================================================================
36
+ // SHORTCUT PATCH: LoginRequiredError — thrown when no auth credentials are available.
37
+ // The interactive mode catches this to auto-trigger the Shortcut login flow.
38
+ // ============================================================================
39
+ export class LoginRequiredError extends Error {
40
+ constructor(message = 'You must log in to Shortcut first.') {
41
+ super(message);
42
+ this.name = 'LoginRequiredError';
43
+ }
44
+ }
45
+ // ============================================================================
46
+ // Skill Block Parsing
47
+ // ============================================================================
48
+ // Re-export parseSkillBlock from its new home in skills.ts
49
+ export { parseSkillBlock } from './skills.js';
50
+ // ============================================================================
51
+ // Constants
52
+ // ============================================================================
53
+ // ============================================================================
54
+ // AgentSession Class
55
+ // ============================================================================
56
+ export class AgentSession {
57
+ agent;
58
+ sessionManager;
59
+ settingsManager;
60
+ // Event subscription state
61
+ _unsubscribeAgent;
62
+ _eventListeners = [];
63
+ _agentEventQueue = Promise.resolve();
64
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
65
+ _steeringMessages = [];
66
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
67
+ _followUpMessages = [];
68
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
69
+ _pendingNextTurnMessages = [];
70
+ // Compaction state machine (extracted module)
71
+ _compaction = new SessionCompaction();
72
+ // Branch summarization state
73
+ _branchSummaryAbortController = undefined;
74
+ // Retry state machine (extracted module)
75
+ _retry = new SessionRetry();
76
+ // Bash execution (extracted module)
77
+ _bash = new SessionBash();
78
+ // Extension system
79
+ _extensionRunner = undefined;
80
+ _turnIndex = 0;
81
+ // Timing state for observability
82
+ _agentStartTime = 0;
83
+ _turnStartTime = 0;
84
+ _toolStartTimes = new Map();
85
+ _resourceLoader;
86
+ _customTools;
87
+ _baseToolRegistry = new Map();
88
+ _cwd;
89
+ _extensionRunnerRef;
90
+ _prePromptContext;
91
+ /** Details from the last prePromptContext call (e.g. { workbooks: string[] }). Read by TUI for annotations. */
92
+ lastPrePromptDetails;
93
+ _initialActiveToolNames;
94
+ _baseToolsOverride;
95
+ _extensionUIContext;
96
+ _extensionCommandContextActions;
97
+ _extensionShutdownHandler;
98
+ _extensionErrorListener;
99
+ _extensionErrorUnsubscriber;
100
+ // Model registry for API key resolution
101
+ _modelRegistry;
102
+ // Tool registry for extension getTools/setTools
103
+ _toolRegistry = new Map();
104
+ _toolPromptSnippets = new Map();
105
+ _toolPromptGuidelines = new Map();
106
+ // Base system prompt (without extension appends) - used to apply fresh appends each turn
107
+ _baseSystemPrompt = '';
108
+ constructor(config) {
109
+ this.agent = config.agent;
110
+ this.sessionManager = config.sessionManager;
111
+ this.settingsManager = config.settingsManager;
112
+ this._resourceLoader = config.resourceLoader;
113
+ this._customTools = config.customTools ?? [];
114
+ this._cwd = config.cwd;
115
+ this._modelRegistry = config.modelRegistry;
116
+ this._extensionRunnerRef = config.extensionRunnerRef;
117
+ this._initialActiveToolNames = config.initialActiveToolNames;
118
+ this._baseToolsOverride = config.baseToolsOverride;
119
+ this._prePromptContext = config.prePromptContext;
120
+ // Forward extracted module events to session listeners
121
+ this._retry.onEvent((event) => this._emit(event));
122
+ this._compaction.onEvent((event) => this._emit(event));
123
+ // Always subscribe to agent events for internal handling
124
+ // (session persistence, extensions, auto-compaction, retry logic)
125
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
126
+ this._buildRuntime({
127
+ activeToolNames: this._initialActiveToolNames,
128
+ includeAllExtensionTools: true
129
+ });
130
+ }
131
+ /** Model registry for API key resolution and model discovery */
132
+ get modelRegistry() {
133
+ return this._modelRegistry;
134
+ }
135
+ // =========================================================================
136
+ // Event Subscription
137
+ // =========================================================================
138
+ /** Emit an event to all listeners */
139
+ _emit(event) {
140
+ for (const l of this._eventListeners) {
141
+ l(event);
142
+ }
143
+ }
144
+ // Track last assistant message for auto-compaction check
145
+ _lastAssistantMessage = undefined;
146
+ /** Internal handler for agent events - shared by subscribe and reconnect */
147
+ _handleAgentEvent = (event) => {
148
+ // Create retry promise synchronously before queueing async processing.
149
+ // Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()
150
+ // as soon as agent.prompt() resolves. If _retryPromise is created only inside
151
+ // _processAgentEvent, slow earlier queued events can delay agent_end processing
152
+ // and waitForRetry() can miss the in-flight retry.
153
+ this._createRetryPromiseForAgentEnd(event);
154
+ this._agentEventQueue = this._agentEventQueue.then(() => this._processAgentEvent(event), () => this._processAgentEvent(event));
155
+ // Keep queue alive if an event handler fails
156
+ this._agentEventQueue.catch(() => { });
157
+ };
158
+ _checkContextOverflow = (msg) => {
159
+ return isContextOverflow(msg, this.model?.contextWindow ?? 0);
160
+ };
161
+ _createRetryPromiseForAgentEnd(event) {
162
+ if (event.type !== 'agent_end')
163
+ return;
164
+ const lastAssistant = this._findLastAssistantInMessages(event.messages);
165
+ this._retry.prepareForAgentEnd(lastAssistant, this._checkContextOverflow, this.settingsManager.getRetrySettings());
166
+ }
167
+ _findLastAssistantInMessages(messages) {
168
+ for (let i = messages.length - 1; i >= 0; i--) {
169
+ const message = messages[i];
170
+ if (message.role === 'assistant') {
171
+ return message;
172
+ }
173
+ }
174
+ return undefined;
175
+ }
176
+ async _processAgentEvent(event) {
177
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
178
+ // This ensures the UI sees the updated queue state
179
+ if (event.type === 'message_start' && event.message.role === 'user') {
180
+ const messageText = this._getUserMessageText(event.message);
181
+ if (messageText) {
182
+ // Check steering queue first
183
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
184
+ if (steeringIndex !== -1) {
185
+ this._steeringMessages.splice(steeringIndex, 1);
186
+ }
187
+ else {
188
+ // Check follow-up queue
189
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
190
+ if (followUpIndex !== -1) {
191
+ this._followUpMessages.splice(followUpIndex, 1);
192
+ }
193
+ }
194
+ }
195
+ }
196
+ // Emit to extensions first
197
+ await this._emitExtensionEvent(event);
198
+ // Notify all listeners
199
+ this._emit(event);
200
+ // --- Timing + session persistence ---
201
+ if (event.type === 'agent_start') {
202
+ this._agentStartTime = Date.now();
203
+ this._toolStartTimes.clear();
204
+ // Snapshot system prompt and tool definitions at start of each agent invocation
205
+ this.sessionManager.appendSystemPrompt(this.systemPrompt);
206
+ this.sessionManager.appendToolDefinitions(this.agent.state.tools.map((t) => ({
207
+ name: t.name,
208
+ description: t.description,
209
+ parameters: t.parameters
210
+ })));
211
+ }
212
+ if (event.type === 'turn_start') {
213
+ this._turnStartTime = Date.now();
214
+ this.sessionManager.appendTurnStart(this._turnIndex);
215
+ }
216
+ if (event.type === 'tool_execution_start') {
217
+ this._toolStartTimes.set(event.toolCallId, Date.now());
218
+ }
219
+ if (event.type === 'tool_execution_end') {
220
+ // Duration is computed here but consumed when the toolResult message_end arrives.
221
+ // We keep the start time in the map — it's read in message_end(toolResult) below.
222
+ }
223
+ // Handle session persistence
224
+ if (event.type === 'message_end') {
225
+ // Check if this is a custom message from extensions
226
+ if (event.message.role === 'custom') {
227
+ // Persist as CustomMessageEntry
228
+ this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
229
+ }
230
+ else if (event.message.role === 'assistant') {
231
+ // LLM latency: time from turn start to assistant message complete
232
+ const durationMs = this._turnStartTime > 0 ? Date.now() - this._turnStartTime : undefined;
233
+ this.sessionManager.appendMessage(event.message, durationMs);
234
+ }
235
+ else if (event.message.role === 'toolResult') {
236
+ // Tool execution time: from tool_execution_start to now
237
+ const toolCallId = event.message.toolCallId;
238
+ let durationMs;
239
+ if (toolCallId) {
240
+ const startTime = this._toolStartTimes.get(toolCallId);
241
+ if (startTime) {
242
+ durationMs = Date.now() - startTime;
243
+ this._toolStartTimes.delete(toolCallId);
244
+ }
245
+ }
246
+ this.sessionManager.appendMessage(event.message, durationMs);
247
+ }
248
+ else if (event.message.role === 'user') {
249
+ this.sessionManager.appendMessage(event.message);
250
+ }
251
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
252
+ // Track assistant message for auto-compaction (checked on agent_end)
253
+ if (event.message.role === 'assistant') {
254
+ this._lastAssistantMessage = event.message;
255
+ // Reset retry counter immediately on successful assistant response
256
+ // This prevents accumulation across multiple LLM calls within a turn
257
+ const assistantMsg = event.message;
258
+ if (assistantMsg.stopReason !== 'error' && this._retry.attempt > 0) {
259
+ this._retry.onSuccess();
260
+ }
261
+ }
262
+ }
263
+ if (event.type === 'turn_end') {
264
+ const durationMs = this._turnStartTime > 0 ? Date.now() - this._turnStartTime : 0;
265
+ this.sessionManager.appendTurnEnd(this._turnIndex, durationMs);
266
+ this._turnIndex++;
267
+ }
268
+ // Check auto-retry and auto-compaction after agent completes
269
+ if (event.type === 'agent_end' && this._lastAssistantMessage) {
270
+ const msg = this._lastAssistantMessage;
271
+ this._lastAssistantMessage = undefined;
272
+ // Check for retryable errors first (overloaded, rate limit, server errors)
273
+ if (isRetryableError(msg, this._checkContextOverflow)) {
274
+ const didRetry = await this._retry.handleRetryableError(msg, this.settingsManager.getRetrySettings(), {
275
+ removeLastAssistantMessage: () => {
276
+ const messages = this.agent.state.messages;
277
+ if (messages.length > 0 && messages[messages.length - 1].role === 'assistant') {
278
+ this.agent.replaceMessages(messages.slice(0, -1));
279
+ }
280
+ },
281
+ continue: () => {
282
+ setTimeout(() => {
283
+ this.agent.continue().catch(() => { });
284
+ }, 0);
285
+ }
286
+ });
287
+ if (didRetry)
288
+ return; // Retry was initiated, don't proceed to compaction
289
+ }
290
+ await this._triggerCompactionIfNeeded(msg, true);
291
+ }
292
+ }
293
+ /** Extract text content from a message */
294
+ _getUserMessageText(message) {
295
+ if (message.role !== 'user')
296
+ return '';
297
+ const content = message.content;
298
+ if (typeof content === 'string')
299
+ return content;
300
+ const textBlocks = content.filter((c) => c.type === 'text');
301
+ return textBlocks.map((c) => c.text).join('');
302
+ }
303
+ /** Find the last assistant message in agent state (including aborted ones) */
304
+ _findLastAssistantMessage() {
305
+ const messages = this.agent.state.messages;
306
+ for (let i = messages.length - 1; i >= 0; i--) {
307
+ const msg = messages[i];
308
+ if (msg.role === 'assistant') {
309
+ return msg;
310
+ }
311
+ }
312
+ return undefined;
313
+ }
314
+ /** Emit extension events based on agent events */
315
+ async _emitExtensionEvent(event) {
316
+ if (!this._extensionRunner)
317
+ return;
318
+ if (event.type === 'agent_start') {
319
+ this._turnIndex = 0;
320
+ await this._extensionRunner.emit({ type: 'agent_start' });
321
+ }
322
+ else if (event.type === 'agent_end') {
323
+ await this._extensionRunner.emit({ type: 'agent_end', messages: event.messages });
324
+ }
325
+ else if (event.type === 'turn_start') {
326
+ const extensionEvent = {
327
+ type: 'turn_start',
328
+ turnIndex: this._turnIndex,
329
+ timestamp: Date.now()
330
+ };
331
+ await this._extensionRunner.emit(extensionEvent);
332
+ }
333
+ else if (event.type === 'turn_end') {
334
+ const extensionEvent = {
335
+ type: 'turn_end',
336
+ turnIndex: this._turnIndex,
337
+ message: event.message,
338
+ toolResults: event.toolResults
339
+ };
340
+ await this._extensionRunner.emit(extensionEvent);
341
+ // _turnIndex is incremented in _processAgentEvent after appendTurnEnd
342
+ }
343
+ else if (event.type === 'message_start') {
344
+ const extensionEvent = {
345
+ type: 'message_start',
346
+ message: event.message
347
+ };
348
+ await this._extensionRunner.emit(extensionEvent);
349
+ }
350
+ else if (event.type === 'message_update') {
351
+ const extensionEvent = {
352
+ type: 'message_update',
353
+ message: event.message,
354
+ assistantMessageEvent: event.assistantMessageEvent
355
+ };
356
+ await this._extensionRunner.emit(extensionEvent);
357
+ }
358
+ else if (event.type === 'message_end') {
359
+ const extensionEvent = {
360
+ type: 'message_end',
361
+ message: event.message
362
+ };
363
+ await this._extensionRunner.emit(extensionEvent);
364
+ }
365
+ else if (event.type === 'tool_execution_start') {
366
+ const extensionEvent = {
367
+ type: 'tool_execution_start',
368
+ toolCallId: event.toolCallId,
369
+ toolName: event.toolName,
370
+ args: event.args
371
+ };
372
+ await this._extensionRunner.emit(extensionEvent);
373
+ }
374
+ else if (event.type === 'tool_execution_update') {
375
+ const extensionEvent = {
376
+ type: 'tool_execution_update',
377
+ toolCallId: event.toolCallId,
378
+ toolName: event.toolName,
379
+ args: event.args,
380
+ partialResult: event.partialResult
381
+ };
382
+ await this._extensionRunner.emit(extensionEvent);
383
+ }
384
+ else if (event.type === 'tool_execution_end') {
385
+ const extensionEvent = {
386
+ type: 'tool_execution_end',
387
+ toolCallId: event.toolCallId,
388
+ toolName: event.toolName,
389
+ result: event.result,
390
+ isError: event.isError
391
+ };
392
+ await this._extensionRunner.emit(extensionEvent);
393
+ }
394
+ }
395
+ /**
396
+ * Subscribe to agent events.
397
+ * Session persistence is handled internally (saves messages on message_end).
398
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
399
+ */
400
+ subscribe(listener) {
401
+ this._eventListeners.push(listener);
402
+ // Return unsubscribe function for this specific listener
403
+ return () => {
404
+ const index = this._eventListeners.indexOf(listener);
405
+ if (index !== -1) {
406
+ this._eventListeners.splice(index, 1);
407
+ }
408
+ };
409
+ }
410
+ /**
411
+ * Temporarily disconnect from agent events.
412
+ * User listeners are preserved and will receive events again after resubscribe().
413
+ * Used internally during operations that need to pause event processing.
414
+ */
415
+ _disconnectFromAgent() {
416
+ if (this._unsubscribeAgent) {
417
+ this._unsubscribeAgent();
418
+ this._unsubscribeAgent = undefined;
419
+ }
420
+ }
421
+ /**
422
+ * Reconnect to agent events after _disconnectFromAgent().
423
+ * Preserves all existing listeners.
424
+ */
425
+ _reconnectToAgent() {
426
+ if (this._unsubscribeAgent)
427
+ return; // Already connected
428
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
429
+ }
430
+ /**
431
+ * Remove all listeners and disconnect from agent.
432
+ * Call this when completely done with the session.
433
+ */
434
+ dispose() {
435
+ this._disconnectFromAgent();
436
+ this._eventListeners = [];
437
+ }
438
+ // =========================================================================
439
+ // Read-only State Access
440
+ // =========================================================================
441
+ /** Full agent state */
442
+ get state() {
443
+ return this.agent.state;
444
+ }
445
+ /** Current model (may be undefined if not yet selected) */
446
+ get model() {
447
+ return this.agent.state.model;
448
+ }
449
+ /** Current thinking level */
450
+ get thinkingLevel() {
451
+ return this.agent.state.thinkingLevel;
452
+ }
453
+ /** Whether agent is currently streaming a response */
454
+ get isStreaming() {
455
+ return this.agent.state.isStreaming;
456
+ }
457
+ /** Current effective system prompt (includes any per-turn extension modifications) */
458
+ get systemPrompt() {
459
+ return this.agent.state.systemPrompt;
460
+ }
461
+ /** Current retry attempt (0 if not retrying) */
462
+ get retryAttempt() {
463
+ return this._retry.attempt;
464
+ }
465
+ /**
466
+ * Get the names of currently active tools.
467
+ * Returns the names of tools currently set on the agent.
468
+ */
469
+ getActiveToolNames() {
470
+ return this.agent.state.tools.map((t) => t.name);
471
+ }
472
+ /**
473
+ * Get all configured tools with name, description, and parameter schema.
474
+ */
475
+ get customTools() {
476
+ return this._customTools;
477
+ }
478
+ getAllTools() {
479
+ return Array.from(this._toolRegistry.values()).map((t) => ({
480
+ name: t.name,
481
+ description: t.description,
482
+ parameters: t.parameters
483
+ }));
484
+ }
485
+ /**
486
+ * Set active tools by name.
487
+ * Only tools in the registry can be enabled. Unknown tool names are ignored.
488
+ * Also rebuilds the system prompt to reflect the new tool set.
489
+ * Changes take effect on the next agent turn.
490
+ */
491
+ setActiveToolsByName(toolNames) {
492
+ const tools = [];
493
+ const validToolNames = [];
494
+ for (const name of toolNames) {
495
+ const tool = this._toolRegistry.get(name);
496
+ if (tool) {
497
+ tools.push(tool);
498
+ validToolNames.push(name);
499
+ }
500
+ }
501
+ this.agent.setTools(tools);
502
+ // Rebuild base system prompt with new tool set
503
+ this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
504
+ this.agent.setSystemPrompt(this._baseSystemPrompt);
505
+ }
506
+ // SHORTCUT PATCH: allow switching system prompt mid-session (for mode switching)
507
+ setBaseSystemPrompt(prompt) {
508
+ this._baseSystemPrompt = prompt;
509
+ this.agent.setSystemPrompt(prompt);
510
+ }
511
+ /** Whether compaction (manual or auto) is currently running */
512
+ get isCompacting() {
513
+ return this._compaction.isCompacting;
514
+ }
515
+ /** All messages including custom types like BashExecutionMessage */
516
+ get messages() {
517
+ return this.agent.state.messages;
518
+ }
519
+ /** Current steering mode */
520
+ get steeringMode() {
521
+ return this.agent.getSteeringMode();
522
+ }
523
+ /** Current follow-up mode */
524
+ get followUpMode() {
525
+ return this.agent.getFollowUpMode();
526
+ }
527
+ /** Current session file path, or undefined if sessions are disabled */
528
+ get sessionFile() {
529
+ return this.sessionManager.getSessionFile();
530
+ }
531
+ /** Current session ID */
532
+ get sessionId() {
533
+ return this.sessionManager.getSessionId();
534
+ }
535
+ /** Current session display name, if set */
536
+ get sessionName() {
537
+ return this.sessionManager.getSessionName();
538
+ }
539
+ /** File-based prompt templates */
540
+ get promptTemplates() {
541
+ return this._resourceLoader.getPrompts().prompts;
542
+ }
543
+ _normalizePromptSnippet(text) {
544
+ if (!text)
545
+ return undefined;
546
+ const oneLine = text
547
+ .replace(/[\r\n]+/g, ' ')
548
+ .replace(/\s+/g, ' ')
549
+ .trim();
550
+ return oneLine.length > 0 ? oneLine : undefined;
551
+ }
552
+ _normalizePromptGuidelines(guidelines) {
553
+ if (!guidelines || guidelines.length === 0) {
554
+ return [];
555
+ }
556
+ const unique = new Set();
557
+ for (const guideline of guidelines) {
558
+ const normalized = guideline.trim();
559
+ if (normalized.length > 0) {
560
+ unique.add(normalized);
561
+ }
562
+ }
563
+ return Array.from(unique);
564
+ }
565
+ _rebuildSystemPrompt(toolNames) {
566
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
567
+ const toolSnippets = {};
568
+ const promptGuidelines = [];
569
+ for (const name of validToolNames) {
570
+ const snippet = this._toolPromptSnippets.get(name);
571
+ if (snippet) {
572
+ toolSnippets[name] = snippet;
573
+ }
574
+ const toolGuidelines = this._toolPromptGuidelines.get(name);
575
+ if (toolGuidelines) {
576
+ promptGuidelines.push(...toolGuidelines);
577
+ }
578
+ }
579
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
580
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
581
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join('\n\n') : undefined;
582
+ const loadedSkills = this._resourceLoader.getSkills().skills;
583
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
584
+ return buildSystemPrompt({
585
+ cwd: this._cwd,
586
+ skills: loadedSkills,
587
+ contextFiles: loadedContextFiles,
588
+ customPrompt: loaderSystemPrompt,
589
+ appendSystemPrompt,
590
+ selectedTools: validToolNames,
591
+ toolSnippets,
592
+ promptGuidelines
593
+ });
594
+ }
595
+ // =========================================================================
596
+ // Prompting
597
+ // =========================================================================
598
+ /**
599
+ * Send a prompt to the agent.
600
+ * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
601
+ * - Expands file-based prompt templates by default
602
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
603
+ * - Validates model and API key before sending (when not streaming)
604
+ * @throws Error if streaming and no streamingBehavior specified
605
+ * @throws Error if no model selected or no API key available (when not streaming)
606
+ */
607
+ async prompt(text, options) {
608
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
609
+ // Handle extension commands first (execute immediately, even during streaming)
610
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
611
+ if (expandPromptTemplates && text.startsWith('/')) {
612
+ const handled = await this._tryExecuteExtensionCommand(text);
613
+ if (handled) {
614
+ // Extension command executed, no prompt to send
615
+ return;
616
+ }
617
+ }
618
+ // Emit input event for extension interception (before skill/template expansion)
619
+ let currentText = text;
620
+ let currentImages = options?.images;
621
+ if (this._extensionRunner?.hasHandlers('input')) {
622
+ const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? 'interactive');
623
+ if (inputResult.action === 'handled') {
624
+ return;
625
+ }
626
+ if (inputResult.action === 'transform') {
627
+ currentText = inputResult.text;
628
+ currentImages = inputResult.images ?? currentImages;
629
+ }
630
+ }
631
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
632
+ let expandedText = currentText;
633
+ if (expandPromptTemplates) {
634
+ expandedText = this._expandSkillCommand(expandedText);
635
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
636
+ }
637
+ // If streaming, queue via steer() or followUp() based on option
638
+ if (this.isStreaming) {
639
+ if (!options?.streamingBehavior) {
640
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
641
+ }
642
+ if (options.streamingBehavior === 'followUp') {
643
+ await this._queueFollowUp(expandedText, currentImages);
644
+ }
645
+ else {
646
+ await this._queueSteer(expandedText, currentImages);
647
+ }
648
+ return;
649
+ }
650
+ // Flush any pending bash messages before the new prompt
651
+ this._flushPendingBashMessages();
652
+ // Validate model
653
+ if (!this.model) {
654
+ throw new LoginRequiredError();
655
+ }
656
+ // Validate API key
657
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
658
+ if (!apiKey) {
659
+ throw new LoginRequiredError();
660
+ }
661
+ // Check if we need to compact before sending (catches aborted responses)
662
+ const lastAssistant = this._findLastAssistantMessage();
663
+ if (lastAssistant) {
664
+ await this._triggerCompactionIfNeeded(lastAssistant, false);
665
+ }
666
+ // Build messages array (custom message if any, then user message)
667
+ const messages = [];
668
+ // Add user message
669
+ const userContent = [{ type: 'text', text: expandedText }];
670
+ if (currentImages) {
671
+ userContent.push(...currentImages);
672
+ }
673
+ messages.push({
674
+ role: 'user',
675
+ content: userContent,
676
+ timestamp: Date.now()
677
+ });
678
+ // SHORTCUT PATCH: inject hidden context messages (e.g. workbook summary)
679
+ this.lastPrePromptDetails = undefined;
680
+ if (this._prePromptContext) {
681
+ const ctx = await this._prePromptContext();
682
+ if (ctx) {
683
+ this.lastPrePromptDetails = ctx.details;
684
+ messages.push({
685
+ role: 'custom',
686
+ customType: 'prePromptContext',
687
+ content: ctx.text,
688
+ display: false,
689
+ details: ctx.details,
690
+ timestamp: Date.now()
691
+ });
692
+ }
693
+ }
694
+ // Inject any pending "nextTurn" messages as context alongside the user message
695
+ for (const msg of this._pendingNextTurnMessages) {
696
+ messages.push(msg);
697
+ }
698
+ this._pendingNextTurnMessages = [];
699
+ // Emit before_agent_start extension event
700
+ if (this._extensionRunner) {
701
+ const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt);
702
+ // Add all custom messages from extensions
703
+ if (result?.messages) {
704
+ for (const msg of result.messages) {
705
+ messages.push({
706
+ role: 'custom',
707
+ customType: msg.customType,
708
+ content: msg.content,
709
+ display: msg.display,
710
+ details: msg.details,
711
+ timestamp: Date.now()
712
+ });
713
+ }
714
+ }
715
+ // Apply extension-modified system prompt, or reset to base
716
+ if (result?.systemPrompt) {
717
+ this.agent.setSystemPrompt(result.systemPrompt);
718
+ }
719
+ else {
720
+ // Ensure we're using the base prompt (in case previous turn had modifications)
721
+ this.agent.setSystemPrompt(this._baseSystemPrompt);
722
+ }
723
+ }
724
+ await this.agent.prompt(messages);
725
+ await this._retry.wait();
726
+ }
727
+ /**
728
+ * Try to execute an extension command. Returns true if command was found and executed.
729
+ */
730
+ async _tryExecuteExtensionCommand(text) {
731
+ if (!this._extensionRunner)
732
+ return false;
733
+ // Parse command name and args
734
+ const spaceIndex = text.indexOf(' ');
735
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
736
+ const args = spaceIndex === -1 ? '' : text.slice(spaceIndex + 1);
737
+ const command = this._extensionRunner.getCommand(commandName);
738
+ if (!command)
739
+ return false;
740
+ // Get command context from extension runner (includes session control methods)
741
+ const ctx = this._extensionRunner.createCommandContext();
742
+ try {
743
+ await command.handler(args, ctx);
744
+ return true;
745
+ }
746
+ catch (err) {
747
+ // Emit error via extension runner
748
+ this._extensionRunner.emitError({
749
+ extensionPath: `command:${commandName}`,
750
+ event: 'command',
751
+ error: err instanceof Error ? err.message : String(err)
752
+ });
753
+ return true;
754
+ }
755
+ }
756
+ /**
757
+ * Expand skill commands (/skill:name args) to their full content.
758
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
759
+ * Emits errors via extension runner if file read fails.
760
+ */
761
+ _expandSkillCommand(text) {
762
+ if (!text.startsWith('/skill:'))
763
+ return text;
764
+ const spaceIndex = text.indexOf(' ');
765
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
766
+ const args = spaceIndex === -1 ? '' : text.slice(spaceIndex + 1).trim();
767
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
768
+ if (!skill)
769
+ return text; // Unknown skill, pass through
770
+ try {
771
+ const content = readFileSync(skill.filePath, 'utf-8');
772
+ const body = stripFrontmatter(content).trim();
773
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
774
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
775
+ }
776
+ catch (err) {
777
+ // Emit error like extension commands do
778
+ this._extensionRunner?.emitError({
779
+ extensionPath: skill.filePath,
780
+ event: 'skill_expansion',
781
+ error: err instanceof Error ? err.message : String(err)
782
+ });
783
+ return text; // Return original on error
784
+ }
785
+ }
786
+ /**
787
+ * Queue a steering message to interrupt the agent mid-run.
788
+ * Delivered after current tool execution, skips remaining tools.
789
+ * Expands skill commands and prompt templates. Errors on extension commands.
790
+ * @param images Optional image attachments to include with the message
791
+ * @throws Error if text is an extension command
792
+ */
793
+ async steer(text, images) {
794
+ // Check for extension commands (cannot be queued)
795
+ if (text.startsWith('/')) {
796
+ this._throwIfExtensionCommand(text);
797
+ }
798
+ // Expand skill commands and prompt templates
799
+ let expandedText = this._expandSkillCommand(text);
800
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
801
+ await this._queueSteer(expandedText, images);
802
+ }
803
+ /**
804
+ * Queue a follow-up message to be processed after the agent finishes.
805
+ * Delivered only when agent has no more tool calls or steering messages.
806
+ * Expands skill commands and prompt templates. Errors on extension commands.
807
+ * @param images Optional image attachments to include with the message
808
+ * @throws Error if text is an extension command
809
+ */
810
+ async followUp(text, images) {
811
+ // Check for extension commands (cannot be queued)
812
+ if (text.startsWith('/')) {
813
+ this._throwIfExtensionCommand(text);
814
+ }
815
+ // Expand skill commands and prompt templates
816
+ let expandedText = this._expandSkillCommand(text);
817
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
818
+ await this._queueFollowUp(expandedText, images);
819
+ }
820
+ /**
821
+ * Internal: Queue a steering message (already expanded, no extension command check).
822
+ */
823
+ async _queueSteer(text, images) {
824
+ this._steeringMessages.push(text);
825
+ const content = [{ type: 'text', text }];
826
+ if (images) {
827
+ content.push(...images);
828
+ }
829
+ this.agent.steer({
830
+ role: 'user',
831
+ content,
832
+ timestamp: Date.now()
833
+ });
834
+ }
835
+ /**
836
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
837
+ */
838
+ async _queueFollowUp(text, images) {
839
+ this._followUpMessages.push(text);
840
+ const content = [{ type: 'text', text }];
841
+ if (images) {
842
+ content.push(...images);
843
+ }
844
+ this.agent.followUp({
845
+ role: 'user',
846
+ content,
847
+ timestamp: Date.now()
848
+ });
849
+ }
850
+ /**
851
+ * Throw an error if the text is an extension command.
852
+ */
853
+ _throwIfExtensionCommand(text) {
854
+ if (!this._extensionRunner)
855
+ return;
856
+ const spaceIndex = text.indexOf(' ');
857
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
858
+ const command = this._extensionRunner.getCommand(commandName);
859
+ if (command) {
860
+ throw new Error(`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
861
+ }
862
+ }
863
+ /**
864
+ * Send a custom message to the session. Creates a CustomMessageEntry.
865
+ *
866
+ * Handles three cases:
867
+ * - Streaming: queues message, processed when loop pulls from queue
868
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
869
+ * - Not streaming + no trigger: appends to state/session, no turn
870
+ *
871
+ * @param message Custom message with customType, content, display, details
872
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
873
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
874
+ */
875
+ async sendCustomMessage(message, options) {
876
+ const appMessage = {
877
+ role: 'custom',
878
+ customType: message.customType,
879
+ content: message.content,
880
+ display: message.display,
881
+ details: message.details,
882
+ timestamp: Date.now()
883
+ };
884
+ if (options?.deliverAs === 'nextTurn') {
885
+ this._pendingNextTurnMessages.push(appMessage);
886
+ }
887
+ else if (this.isStreaming) {
888
+ if (options?.deliverAs === 'followUp') {
889
+ this.agent.followUp(appMessage);
890
+ }
891
+ else {
892
+ this.agent.steer(appMessage);
893
+ }
894
+ }
895
+ else if (options?.triggerTurn) {
896
+ await this.agent.prompt(appMessage);
897
+ }
898
+ else {
899
+ this.agent.appendMessage(appMessage);
900
+ this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
901
+ this._emit({ type: 'message_start', message: appMessage });
902
+ this._emit({ type: 'message_end', message: appMessage });
903
+ }
904
+ }
905
+ /**
906
+ * Send a user message to the agent. Always triggers a turn.
907
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
908
+ *
909
+ * @param content User message content (string or content array)
910
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
911
+ */
912
+ async sendUserMessage(content, options) {
913
+ // Normalize content to text string + optional images
914
+ let text;
915
+ let images;
916
+ if (typeof content === 'string') {
917
+ text = content;
918
+ }
919
+ else {
920
+ const textParts = [];
921
+ images = [];
922
+ for (const part of content) {
923
+ if (part.type === 'text') {
924
+ textParts.push(part.text);
925
+ }
926
+ else {
927
+ images.push(part);
928
+ }
929
+ }
930
+ text = textParts.join('\n');
931
+ if (images.length === 0)
932
+ images = undefined;
933
+ }
934
+ // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
935
+ await this.prompt(text, {
936
+ expandPromptTemplates: false,
937
+ streamingBehavior: options?.deliverAs,
938
+ images,
939
+ source: 'extension'
940
+ });
941
+ }
942
+ /**
943
+ * Clear all queued messages and return them.
944
+ * Useful for restoring to editor when user aborts.
945
+ * @returns Object with steering and followUp arrays
946
+ */
947
+ clearQueue() {
948
+ const steering = [...this._steeringMessages];
949
+ const followUp = [...this._followUpMessages];
950
+ this._steeringMessages = [];
951
+ this._followUpMessages = [];
952
+ this.agent.clearAllQueues();
953
+ return { steering, followUp };
954
+ }
955
+ /** Number of pending messages (includes both steering and follow-up) */
956
+ get pendingMessageCount() {
957
+ return this._steeringMessages.length + this._followUpMessages.length;
958
+ }
959
+ /** Get pending steering messages (read-only) */
960
+ getSteeringMessages() {
961
+ return this._steeringMessages;
962
+ }
963
+ /** Get pending follow-up messages (read-only) */
964
+ getFollowUpMessages() {
965
+ return this._followUpMessages;
966
+ }
967
+ get resourceLoader() {
968
+ return this._resourceLoader;
969
+ }
970
+ /**
971
+ * Abort current operation and wait for agent to become idle.
972
+ */
973
+ async abort() {
974
+ this._retry.abort();
975
+ this.agent.abort();
976
+ await this.agent.waitForIdle();
977
+ }
978
+ /**
979
+ * Start a new session, optionally with initial messages and parent tracking.
980
+ * Clears all messages and starts a new session.
981
+ * Listeners are preserved and will continue receiving events.
982
+ * @param options.parentSession - Optional parent session path for tracking
983
+ * @param options.setup - Optional callback to initialize session (e.g., append messages)
984
+ * @returns true if completed, false if cancelled by extension
985
+ */
986
+ async newSession(options) {
987
+ const previousSessionFile = this.sessionFile;
988
+ // Emit session_before_switch event with reason "new" (can be cancelled)
989
+ if (this._extensionRunner?.hasHandlers('session_before_switch')) {
990
+ const result = (await this._extensionRunner.emit({
991
+ type: 'session_before_switch',
992
+ reason: 'new'
993
+ }));
994
+ if (result?.cancel) {
995
+ return false;
996
+ }
997
+ }
998
+ this._disconnectFromAgent();
999
+ await this.abort();
1000
+ this.agent.reset();
1001
+ this.sessionManager.newSession({ parentSession: options?.parentSession });
1002
+ this.agent.sessionId = this.sessionManager.getSessionId();
1003
+ this._steeringMessages = [];
1004
+ this._followUpMessages = [];
1005
+ this._pendingNextTurnMessages = [];
1006
+ this.sessionManager.appendThinkingLevelChange(this.thinkingLevel);
1007
+ // Run setup callback if provided (e.g., to append initial messages)
1008
+ if (options?.setup) {
1009
+ await options.setup(this.sessionManager);
1010
+ // Sync agent state with session manager after setup
1011
+ const sessionContext = this.sessionManager.buildSessionContext();
1012
+ this.agent.replaceMessages(sessionContext.messages);
1013
+ }
1014
+ this._reconnectToAgent();
1015
+ // Emit session_switch event with reason "new" to extensions
1016
+ if (this._extensionRunner) {
1017
+ await this._extensionRunner.emit({
1018
+ type: 'session_switch',
1019
+ reason: 'new',
1020
+ previousSessionFile
1021
+ });
1022
+ }
1023
+ // Emit session event to custom tools
1024
+ return true;
1025
+ }
1026
+ // =========================================================================
1027
+ // Model Management
1028
+ // =========================================================================
1029
+ async _emitModelSelect(nextModel, previousModel, source) {
1030
+ if (!this._extensionRunner)
1031
+ return;
1032
+ if (modelsAreEqual(previousModel, nextModel))
1033
+ return;
1034
+ await this._extensionRunner.emit({
1035
+ type: 'model_select',
1036
+ model: nextModel,
1037
+ previousModel,
1038
+ source
1039
+ });
1040
+ }
1041
+ /**
1042
+ * Set model directly.
1043
+ * Validates API key, saves to session and settings.
1044
+ * @throws Error if no API key available for the model
1045
+ */
1046
+ async setModel(model) {
1047
+ const apiKey = await this._modelRegistry.getApiKey(model);
1048
+ if (!apiKey) {
1049
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
1050
+ }
1051
+ const previousModel = this.model;
1052
+ this._applyModel(model);
1053
+ this.setThinkingLevel(this.thinkingLevel);
1054
+ await this._emitModelSelect(model, previousModel, 'set');
1055
+ }
1056
+ // SHORTCUT PATCH: simplified cycleModel — always cycles through all authed models
1057
+ async cycleModel(direction = 'forward') {
1058
+ const availableModels = await this._modelRegistry.getAvailable();
1059
+ const nextModel = computeNextModel(availableModels, this.model, direction);
1060
+ if (!nextModel)
1061
+ return undefined;
1062
+ const apiKey = await this._modelRegistry.getApiKey(nextModel);
1063
+ if (!apiKey) {
1064
+ throw new Error(`No API key for ${nextModel.provider}/${nextModel.id}`);
1065
+ }
1066
+ const previousModel = this.model;
1067
+ this._applyModel(nextModel);
1068
+ this.setThinkingLevel(this.thinkingLevel);
1069
+ await this._emitModelSelect(nextModel, previousModel, 'cycle');
1070
+ return { model: nextModel, thinkingLevel: this.thinkingLevel };
1071
+ }
1072
+ /** Apply a model change to agent + persistence (no validation). */
1073
+ _applyModel(model) {
1074
+ this.agent.setModel(model);
1075
+ this.sessionManager.appendModelChange(model.provider, model.id);
1076
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1077
+ }
1078
+ // =========================================================================
1079
+ // Thinking Level Management (delegated to session-models.ts)
1080
+ // =========================================================================
1081
+ setThinkingLevel(level) {
1082
+ const effectiveLevel = clampThinkingLevel(level, getAvailableThinkingLevels(this.model));
1083
+ const isChanging = effectiveLevel !== this.agent.state.thinkingLevel;
1084
+ this.agent.setThinkingLevel(effectiveLevel);
1085
+ if (isChanging) {
1086
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1087
+ this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1088
+ }
1089
+ }
1090
+ cycleThinkingLevel() {
1091
+ const nextLevel = computeNextThinkingLevel(this.thinkingLevel, this.model);
1092
+ if (nextLevel === undefined)
1093
+ return undefined;
1094
+ this.setThinkingLevel(nextLevel);
1095
+ return nextLevel;
1096
+ }
1097
+ getAvailableThinkingLevels() {
1098
+ return getAvailableThinkingLevels(this.model);
1099
+ }
1100
+ supportsXhighThinking() {
1101
+ return supportsXhighThinking(this.model);
1102
+ }
1103
+ supportsThinking() {
1104
+ return supportsThinking(this.model);
1105
+ }
1106
+ // =========================================================================
1107
+ // Queue Mode Management
1108
+ // =========================================================================
1109
+ // =========================================================================
1110
+ // Compaction (delegated to SessionCompaction)
1111
+ // =========================================================================
1112
+ /** Build CompactionActions that bridge SessionCompaction → AgentSession internals. */
1113
+ _compactionActions = {
1114
+ tryExtensionCompaction: async (preparation, branchEntries, customInstructions, signal) => {
1115
+ if (!this._extensionRunner?.hasHandlers('session_before_compact'))
1116
+ return {};
1117
+ const result = (await this._extensionRunner.emit({
1118
+ type: 'session_before_compact',
1119
+ preparation,
1120
+ branchEntries,
1121
+ customInstructions,
1122
+ signal
1123
+ }));
1124
+ if (result?.cancel)
1125
+ return { cancelled: true };
1126
+ if (result?.compaction)
1127
+ return { result: result.compaction };
1128
+ return {};
1129
+ },
1130
+ persistCompaction: async (result, fromExtension) => {
1131
+ this.sessionManager.appendCompaction(result.summary, result.firstKeptEntryId, result.tokensBefore, result.details, fromExtension);
1132
+ const newEntries = this.sessionManager.getEntries();
1133
+ const sessionContext = this.sessionManager.buildSessionContext();
1134
+ this.agent.replaceMessages(sessionContext.messages);
1135
+ const savedEntry = newEntries.find((e) => e.type === 'compaction' && e.summary === result.summary);
1136
+ if (this._extensionRunner && savedEntry) {
1137
+ await this._extensionRunner.emit({
1138
+ type: 'session_compact',
1139
+ compactionEntry: savedEntry,
1140
+ fromExtension
1141
+ });
1142
+ }
1143
+ },
1144
+ removeLastAssistantMessage: () => {
1145
+ const messages = this.agent.state.messages;
1146
+ const lastMsg = messages[messages.length - 1];
1147
+ if (lastMsg?.role === 'assistant' && lastMsg.stopReason === 'error') {
1148
+ this.agent.replaceMessages(messages.slice(0, -1));
1149
+ }
1150
+ },
1151
+ continueAgent: () => {
1152
+ setTimeout(() => {
1153
+ this.agent.continue().catch(() => { });
1154
+ }, 100);
1155
+ },
1156
+ hasQueuedMessages: () => this.agent.hasQueuedMessages()
1157
+ };
1158
+ /** Check compaction decision and trigger if needed. */
1159
+ async _triggerCompactionIfNeeded(msg, skipAbortedCheck) {
1160
+ const branchEntries = this.sessionManager.getBranch();
1161
+ const settings = this.settingsManager.getCompactionSettings();
1162
+ const decision = checkCompactionNeeded(msg, {
1163
+ currentModel: this.model,
1164
+ branchEntries,
1165
+ settings
1166
+ }, skipAbortedCheck);
1167
+ if (decision.action === 'overflow') {
1168
+ const messages = this.agent.state.messages;
1169
+ if (messages.length > 0 && messages[messages.length - 1].role === 'assistant') {
1170
+ this.agent.replaceMessages(messages.slice(0, -1));
1171
+ }
1172
+ await this._compaction.runAuto('overflow', true, this.model, await this._modelRegistry.getApiKey(this.model), branchEntries, settings, this._compactionActions);
1173
+ }
1174
+ else if (decision.action === 'threshold') {
1175
+ await this._compaction.runAuto('threshold', false, this.model, this.model ? await this._modelRegistry.getApiKey(this.model) : undefined, branchEntries, settings, this._compactionActions);
1176
+ }
1177
+ }
1178
+ async compact(customInstructions) {
1179
+ this._disconnectFromAgent();
1180
+ await this.abort();
1181
+ try {
1182
+ if (!this.model)
1183
+ throw new Error('No model selected');
1184
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
1185
+ if (!apiKey)
1186
+ throw new Error(`No API key for ${this.model.provider}`);
1187
+ return await this._compaction.runManual(this.model, apiKey, this.sessionManager.getBranch(), this.settingsManager.getCompactionSettings(), customInstructions, this._compactionActions);
1188
+ }
1189
+ finally {
1190
+ this._reconnectToAgent();
1191
+ }
1192
+ }
1193
+ abortCompaction() {
1194
+ this._compaction.abortAll();
1195
+ }
1196
+ /** Cancel in-progress branch summarization. */
1197
+ abortBranchSummary() {
1198
+ this._branchSummaryAbortController?.abort();
1199
+ }
1200
+ /** Auto-compaction is always enabled */
1201
+ get autoCompactionEnabled() {
1202
+ return true;
1203
+ }
1204
+ async bindExtensions(bindings) {
1205
+ if (bindings.uiContext !== undefined) {
1206
+ this._extensionUIContext = bindings.uiContext;
1207
+ }
1208
+ if (bindings.commandContextActions !== undefined) {
1209
+ this._extensionCommandContextActions = bindings.commandContextActions;
1210
+ }
1211
+ if (bindings.shutdownHandler !== undefined) {
1212
+ this._extensionShutdownHandler = bindings.shutdownHandler;
1213
+ }
1214
+ if (bindings.onError !== undefined) {
1215
+ this._extensionErrorListener = bindings.onError;
1216
+ }
1217
+ if (this._extensionRunner) {
1218
+ this._applyExtensionBindings(this._extensionRunner);
1219
+ await this._extensionRunner.emit({ type: 'session_start' });
1220
+ await this.extendResourcesFromExtensions('startup');
1221
+ }
1222
+ }
1223
+ async extendResourcesFromExtensions(reason) {
1224
+ if (!this._extensionRunner?.hasHandlers('resources_discover')) {
1225
+ return;
1226
+ }
1227
+ const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
1228
+ if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
1229
+ return;
1230
+ }
1231
+ const extensionPaths = {
1232
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
1233
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
1234
+ themePaths: this.buildExtensionResourcePaths(themePaths)
1235
+ };
1236
+ this._resourceLoader.extendResources(extensionPaths);
1237
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
1238
+ this.agent.setSystemPrompt(this._baseSystemPrompt);
1239
+ }
1240
+ buildExtensionResourcePaths(entries) {
1241
+ return entries.map((entry) => {
1242
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
1243
+ const baseDir = entry.extensionPath.startsWith('<')
1244
+ ? undefined
1245
+ : dirname(entry.extensionPath);
1246
+ return {
1247
+ path: entry.path,
1248
+ metadata: {
1249
+ source,
1250
+ scope: 'temporary',
1251
+ origin: 'top-level',
1252
+ baseDir
1253
+ }
1254
+ };
1255
+ });
1256
+ }
1257
+ getExtensionSourceLabel(extensionPath) {
1258
+ if (extensionPath.startsWith('<')) {
1259
+ return `extension:${extensionPath.replace(/[<>]/g, '')}`;
1260
+ }
1261
+ const base = basename(extensionPath);
1262
+ const name = base.replace(/\.(ts|js)$/, '');
1263
+ return `extension:${name}`;
1264
+ }
1265
+ _applyExtensionBindings(runner) {
1266
+ runner.setUIContext(this._extensionUIContext);
1267
+ runner.bindCommandContext(this._extensionCommandContextActions);
1268
+ this._extensionErrorUnsubscriber?.();
1269
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
1270
+ ? runner.onError(this._extensionErrorListener)
1271
+ : undefined;
1272
+ }
1273
+ _bindExtensionCore(runner) {
1274
+ const normalizeLocation = (source) => {
1275
+ if (source === 'user' || source === 'project' || source === 'path') {
1276
+ return source;
1277
+ }
1278
+ return undefined;
1279
+ };
1280
+ const reservedBuiltins = ALL_BUILTIN_SLASH_COMMAND_NAMES;
1281
+ const getCommands = () => {
1282
+ const extensionCommands = runner
1283
+ .getRegisteredCommandsWithPaths()
1284
+ .filter(({ command }) => !reservedBuiltins.has(command.name))
1285
+ .map(({ command, extensionPath }) => ({
1286
+ name: command.name,
1287
+ description: command.description,
1288
+ source: 'extension',
1289
+ path: extensionPath
1290
+ }));
1291
+ const templates = this.promptTemplates.map((template) => ({
1292
+ name: template.name,
1293
+ description: template.description,
1294
+ source: 'prompt',
1295
+ location: normalizeLocation(template.source),
1296
+ path: template.filePath
1297
+ }));
1298
+ const skills = this._resourceLoader.getSkills().skills.map((skill) => ({
1299
+ name: `skill:${skill.name}`,
1300
+ description: skill.description,
1301
+ source: 'skill',
1302
+ location: normalizeLocation(skill.source),
1303
+ path: skill.filePath
1304
+ }));
1305
+ return [...extensionCommands, ...templates, ...skills];
1306
+ };
1307
+ runner.bindCore({
1308
+ sendMessage: (message, options) => {
1309
+ this.sendCustomMessage(message, options).catch((err) => {
1310
+ runner.emitError({
1311
+ extensionPath: '<runtime>',
1312
+ event: 'send_message',
1313
+ error: err instanceof Error ? err.message : String(err)
1314
+ });
1315
+ });
1316
+ },
1317
+ sendUserMessage: (content, options) => {
1318
+ this.sendUserMessage(content, options).catch((err) => {
1319
+ runner.emitError({
1320
+ extensionPath: '<runtime>',
1321
+ event: 'send_user_message',
1322
+ error: err instanceof Error ? err.message : String(err)
1323
+ });
1324
+ });
1325
+ },
1326
+ appendEntry: (customType, data) => {
1327
+ this.sessionManager.appendCustomEntry(customType, data);
1328
+ },
1329
+ setSessionName: (name) => {
1330
+ this.sessionManager.appendSessionInfo(name);
1331
+ },
1332
+ getSessionName: () => {
1333
+ return this.sessionManager.getSessionName();
1334
+ },
1335
+ setLabel: (entryId, label) => {
1336
+ this.sessionManager.appendLabelChange(entryId, label);
1337
+ },
1338
+ getActiveTools: () => this.getActiveToolNames(),
1339
+ getAllTools: () => this.getAllTools(),
1340
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
1341
+ refreshTools: () => this._refreshToolRegistry(),
1342
+ getCommands,
1343
+ setModel: async (model) => {
1344
+ const key = await this.modelRegistry.getApiKey(model);
1345
+ if (!key)
1346
+ return false;
1347
+ await this.setModel(model);
1348
+ return true;
1349
+ },
1350
+ getThinkingLevel: () => this.thinkingLevel,
1351
+ setThinkingLevel: (level) => this.setThinkingLevel(level)
1352
+ }, {
1353
+ getModel: () => this.model,
1354
+ isIdle: () => !this.isStreaming,
1355
+ abort: () => this.abort(),
1356
+ hasPendingMessages: () => this.pendingMessageCount > 0,
1357
+ shutdown: () => {
1358
+ this._extensionShutdownHandler?.();
1359
+ },
1360
+ getContextUsage: () => this.getContextUsage(),
1361
+ compact: (options) => {
1362
+ void (async () => {
1363
+ try {
1364
+ const result = await this.compact(options?.customInstructions);
1365
+ options?.onComplete?.(result);
1366
+ }
1367
+ catch (error) {
1368
+ const err = error instanceof Error ? error : new Error(String(error));
1369
+ options?.onError?.(err);
1370
+ }
1371
+ })();
1372
+ },
1373
+ getSystemPrompt: () => this.systemPrompt
1374
+ });
1375
+ }
1376
+ _refreshToolRegistry(options) {
1377
+ const previousRegistryNames = new Set(this._toolRegistry.keys());
1378
+ const previousActiveToolNames = this.getActiveToolNames();
1379
+ const registeredTools = this._extensionRunner?.getAllRegisteredTools() ?? [];
1380
+ const allCustomTools = [
1381
+ ...registeredTools,
1382
+ ...this._customTools.map((def) => ({ definition: def, extensionPath: '<sdk>' }))
1383
+ ];
1384
+ this._toolPromptSnippets = new Map(allCustomTools
1385
+ .map((registeredTool) => {
1386
+ const snippet = this._normalizePromptSnippet(registeredTool.definition.promptSnippet ?? registeredTool.definition.description);
1387
+ return snippet ? [registeredTool.definition.name, snippet] : undefined;
1388
+ })
1389
+ .filter((entry) => entry !== undefined));
1390
+ this._toolPromptGuidelines = new Map(allCustomTools
1391
+ .map((registeredTool) => {
1392
+ const guidelines = this._normalizePromptGuidelines(registeredTool.definition.promptGuidelines);
1393
+ return guidelines.length > 0
1394
+ ? [registeredTool.definition.name, guidelines]
1395
+ : undefined;
1396
+ })
1397
+ .filter((entry) => entry !== undefined));
1398
+ const wrappedExtensionTools = this._extensionRunner
1399
+ ? wrapRegisteredTools(allCustomTools, this._extensionRunner)
1400
+ : [];
1401
+ const toolRegistry = new Map(this._baseToolRegistry);
1402
+ for (const tool of wrappedExtensionTools) {
1403
+ toolRegistry.set(tool.name, tool);
1404
+ }
1405
+ if (this._extensionRunner) {
1406
+ const wrappedAllTools = wrapToolsWithExtensions(Array.from(toolRegistry.values()), this._extensionRunner);
1407
+ this._toolRegistry = new Map(wrappedAllTools.map((tool) => [tool.name, tool]));
1408
+ }
1409
+ else {
1410
+ this._toolRegistry = toolRegistry;
1411
+ }
1412
+ const nextActiveToolNames = options?.activeToolNames
1413
+ ? [...options.activeToolNames]
1414
+ : [...previousActiveToolNames];
1415
+ if (options?.includeAllExtensionTools) {
1416
+ for (const tool of wrappedExtensionTools) {
1417
+ nextActiveToolNames.push(tool.name);
1418
+ }
1419
+ }
1420
+ else if (!options?.activeToolNames) {
1421
+ for (const toolName of this._toolRegistry.keys()) {
1422
+ if (!previousRegistryNames.has(toolName)) {
1423
+ nextActiveToolNames.push(toolName);
1424
+ }
1425
+ }
1426
+ }
1427
+ this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
1428
+ }
1429
+ _buildRuntime(options) {
1430
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
1431
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
1432
+ const baseTools = this._baseToolsOverride
1433
+ ? this._baseToolsOverride
1434
+ : createAllTools(this._cwd, {
1435
+ read: { autoResizeImages },
1436
+ bash: { commandPrefix: shellCommandPrefix }
1437
+ });
1438
+ this._baseToolRegistry = new Map(Object.entries(baseTools).map(([name, tool]) => [name, tool]));
1439
+ const extensionsResult = this._resourceLoader.getExtensions();
1440
+ if (options.flagValues) {
1441
+ for (const [name, value] of options.flagValues) {
1442
+ extensionsResult.runtime.flagValues.set(name, value);
1443
+ }
1444
+ }
1445
+ const hasExtensions = extensionsResult.extensions.length > 0;
1446
+ const hasCustomTools = this._customTools.length > 0;
1447
+ this._extensionRunner =
1448
+ hasExtensions || hasCustomTools
1449
+ ? new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry)
1450
+ : undefined;
1451
+ if (this._extensionRunnerRef) {
1452
+ this._extensionRunnerRef.current = this._extensionRunner;
1453
+ }
1454
+ if (this._extensionRunner) {
1455
+ this._bindExtensionCore(this._extensionRunner);
1456
+ this._applyExtensionBindings(this._extensionRunner);
1457
+ }
1458
+ // SHORTCUT PATCH: no default tools — every agent must explicitly declare its tools
1459
+ const baseActiveToolNames = options.activeToolNames ?? [];
1460
+ this._refreshToolRegistry({
1461
+ activeToolNames: baseActiveToolNames,
1462
+ includeAllExtensionTools: options.includeAllExtensionTools
1463
+ });
1464
+ }
1465
+ async reload() {
1466
+ const previousFlagValues = this._extensionRunner?.getFlagValues();
1467
+ await this._extensionRunner?.emit({ type: 'session_shutdown' });
1468
+ this.settingsManager.reload();
1469
+ // Use modelRegistry.refresh() instead of bare resetApiProviders() so that
1470
+ // dynamically registered providers (e.g. Shortcut) are re-applied after the
1471
+ // global API registry is cleared.
1472
+ this._modelRegistry.refresh();
1473
+ await this._resourceLoader.reload();
1474
+ this._buildRuntime({
1475
+ activeToolNames: this.getActiveToolNames(),
1476
+ flagValues: previousFlagValues,
1477
+ includeAllExtensionTools: true
1478
+ });
1479
+ const hasBindings = this._extensionUIContext ||
1480
+ this._extensionCommandContextActions ||
1481
+ this._extensionShutdownHandler ||
1482
+ this._extensionErrorListener;
1483
+ if (this._extensionRunner && hasBindings) {
1484
+ await this._extensionRunner.emit({ type: 'session_start' });
1485
+ await this.extendResourcesFromExtensions('reload');
1486
+ }
1487
+ }
1488
+ // =========================================================================
1489
+ // Auto-Retry (delegated to SessionRetry)
1490
+ // =========================================================================
1491
+ /** Cancel in-progress retry. */
1492
+ abortRetry() {
1493
+ this._retry.abort();
1494
+ }
1495
+ /** Whether auto-retry is currently in progress */
1496
+ get isRetrying() {
1497
+ return this._retry.isRetrying;
1498
+ }
1499
+ /** Whether auto-retry is enabled */
1500
+ get autoRetryEnabled() {
1501
+ return this.settingsManager.getRetryEnabled();
1502
+ }
1503
+ /** Toggle auto-retry setting. */
1504
+ setAutoRetryEnabled(enabled) {
1505
+ this.settingsManager.setRetryEnabled(enabled);
1506
+ }
1507
+ // =========================================================================
1508
+ // Bash Execution (delegated to SessionBash)
1509
+ // =========================================================================
1510
+ _bashActions = {
1511
+ appendToAgent: (msg) => this.agent.appendMessage(msg),
1512
+ persistToSession: (msg) => this.sessionManager.appendMessage(msg),
1513
+ isStreaming: () => this.isStreaming,
1514
+ getShellCommandPrefix: () => this.settingsManager.getShellCommandPrefix()
1515
+ };
1516
+ async executeBash(command, onChunk, options) {
1517
+ return this._bash.execute(command, this._bashActions, onChunk, options);
1518
+ }
1519
+ recordBashResult(command, result, options) {
1520
+ this._bash.record(command, result, this._bashActions, options);
1521
+ }
1522
+ abortBash() {
1523
+ this._bash.abort();
1524
+ }
1525
+ get isBashRunning() {
1526
+ return this._bash.isRunning;
1527
+ }
1528
+ get hasPendingBashMessages() {
1529
+ return this._bash.hasPendingMessages;
1530
+ }
1531
+ _flushPendingBashMessages() {
1532
+ this._bash.flush(this._bashActions);
1533
+ }
1534
+ // =========================================================================
1535
+ // Session Management
1536
+ // =========================================================================
1537
+ /**
1538
+ * Switch to a different session file.
1539
+ * Aborts current operation, loads messages, restores model/thinking.
1540
+ * Listeners are preserved and will continue receiving events.
1541
+ * @returns true if switch completed, false if cancelled by extension
1542
+ */
1543
+ async switchSession(sessionPath) {
1544
+ const previousSessionFile = this.sessionManager.getSessionFile();
1545
+ // Emit session_before_switch event (can be cancelled)
1546
+ if (this._extensionRunner?.hasHandlers('session_before_switch')) {
1547
+ const result = (await this._extensionRunner.emit({
1548
+ type: 'session_before_switch',
1549
+ reason: 'resume',
1550
+ targetSessionFile: sessionPath
1551
+ }));
1552
+ if (result?.cancel) {
1553
+ return false;
1554
+ }
1555
+ }
1556
+ this._disconnectFromAgent();
1557
+ await this.abort();
1558
+ this._steeringMessages = [];
1559
+ this._followUpMessages = [];
1560
+ this._pendingNextTurnMessages = [];
1561
+ // Set new session
1562
+ this.sessionManager.setSessionFile(sessionPath);
1563
+ this.agent.sessionId = this.sessionManager.getSessionId();
1564
+ // Reload messages
1565
+ const sessionContext = this.sessionManager.buildSessionContext();
1566
+ // Emit session_switch event to extensions
1567
+ if (this._extensionRunner) {
1568
+ await this._extensionRunner.emit({
1569
+ type: 'session_switch',
1570
+ reason: 'resume',
1571
+ previousSessionFile
1572
+ });
1573
+ }
1574
+ // Emit session event to custom tools
1575
+ this.agent.replaceMessages(sessionContext.messages);
1576
+ // Restore model if saved
1577
+ if (sessionContext.model) {
1578
+ const previousModel = this.model;
1579
+ const availableModels = await this._modelRegistry.getAvailable();
1580
+ const match = availableModels.find((m) => m.provider === sessionContext.model.provider && m.id === sessionContext.model.modelId);
1581
+ if (match) {
1582
+ this.agent.setModel(match);
1583
+ await this._emitModelSelect(match, previousModel, 'restore');
1584
+ }
1585
+ }
1586
+ const hasThinkingEntry = this.sessionManager
1587
+ .getBranch()
1588
+ .some((entry) => entry.type === 'thinking_level_change');
1589
+ const defaultThinkingLevel = this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
1590
+ if (hasThinkingEntry) {
1591
+ // Restore thinking level if saved (setThinkingLevel clamps to model capabilities)
1592
+ this.setThinkingLevel(sessionContext.thinkingLevel);
1593
+ }
1594
+ else {
1595
+ const effectiveLevel = clampThinkingLevel(defaultThinkingLevel, this.getAvailableThinkingLevels());
1596
+ this.agent.setThinkingLevel(effectiveLevel);
1597
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1598
+ }
1599
+ this._reconnectToAgent();
1600
+ return true;
1601
+ }
1602
+ /**
1603
+ * Set a display name for the current session.
1604
+ */
1605
+ setSessionName(name) {
1606
+ this.sessionManager.appendSessionInfo(name);
1607
+ }
1608
+ /**
1609
+ * Create a fork from a specific entry.
1610
+ * Emits before_fork/fork session events to extensions.
1611
+ *
1612
+ * @param entryId ID of the entry to fork from
1613
+ * @returns Object with:
1614
+ * - selectedText: The text of the selected user message (for editor pre-fill)
1615
+ * - cancelled: True if an extension cancelled the fork
1616
+ */
1617
+ async fork(entryId) {
1618
+ const previousSessionFile = this.sessionFile;
1619
+ const selectedEntry = this.sessionManager.getEntry(entryId);
1620
+ if (!selectedEntry ||
1621
+ selectedEntry.type !== 'message' ||
1622
+ selectedEntry.message.role !== 'user') {
1623
+ throw new Error('Invalid entry ID for forking');
1624
+ }
1625
+ const selectedText = this._extractUserMessageText(selectedEntry.message.content);
1626
+ let skipConversationRestore = false;
1627
+ // Emit session_before_fork event (can be cancelled)
1628
+ if (this._extensionRunner?.hasHandlers('session_before_fork')) {
1629
+ const result = (await this._extensionRunner.emit({
1630
+ type: 'session_before_fork',
1631
+ entryId
1632
+ }));
1633
+ if (result?.cancel) {
1634
+ return { selectedText, cancelled: true };
1635
+ }
1636
+ skipConversationRestore = result?.skipConversationRestore ?? false;
1637
+ }
1638
+ // Clear pending messages (bound to old session state)
1639
+ this._pendingNextTurnMessages = [];
1640
+ if (!selectedEntry.parentId) {
1641
+ this.sessionManager.newSession({ parentSession: previousSessionFile });
1642
+ }
1643
+ else {
1644
+ this.sessionManager.createBranchedSession(selectedEntry.parentId);
1645
+ }
1646
+ this.agent.sessionId = this.sessionManager.getSessionId();
1647
+ // Reload messages from entries (works for both file and in-memory mode)
1648
+ const sessionContext = this.sessionManager.buildSessionContext();
1649
+ // Emit session_fork event to extensions (after fork completes)
1650
+ if (this._extensionRunner) {
1651
+ await this._extensionRunner.emit({
1652
+ type: 'session_fork',
1653
+ previousSessionFile
1654
+ });
1655
+ }
1656
+ // Emit session event to custom tools (with reason "fork")
1657
+ if (!skipConversationRestore) {
1658
+ this.agent.replaceMessages(sessionContext.messages);
1659
+ }
1660
+ return { selectedText, cancelled: false };
1661
+ }
1662
+ // =========================================================================
1663
+ // Tree Navigation
1664
+ // =========================================================================
1665
+ /**
1666
+ * Navigate to a different node in the session tree.
1667
+ * Unlike fork() which creates a new session file, this stays in the same file.
1668
+ *
1669
+ * @param targetId The entry ID to navigate to
1670
+ * @param options.summarize Whether user wants to summarize abandoned branch
1671
+ * @param options.customInstructions Custom instructions for summarizer
1672
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
1673
+ * @param options.label Label to attach to the branch summary entry
1674
+ * @returns Result with editorText (if user message) and cancelled status
1675
+ */
1676
+ async navigateTree(targetId, options = {}) {
1677
+ const oldLeafId = this.sessionManager.getLeafId();
1678
+ // No-op if already at target
1679
+ if (targetId === oldLeafId) {
1680
+ return { cancelled: false };
1681
+ }
1682
+ // Model required for summarization
1683
+ if (options.summarize && !this.model) {
1684
+ throw new Error('No model available for summarization');
1685
+ }
1686
+ const targetEntry = this.sessionManager.getEntry(targetId);
1687
+ if (!targetEntry) {
1688
+ throw new Error(`Entry ${targetId} not found`);
1689
+ }
1690
+ // Collect entries to summarize (from old leaf to common ancestor)
1691
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
1692
+ // Prepare event data - mutable so extensions can override
1693
+ let customInstructions = options.customInstructions;
1694
+ let replaceInstructions = options.replaceInstructions;
1695
+ let label = options.label;
1696
+ const preparation = {
1697
+ targetId,
1698
+ oldLeafId,
1699
+ commonAncestorId,
1700
+ entriesToSummarize,
1701
+ userWantsSummary: options.summarize ?? false,
1702
+ customInstructions,
1703
+ replaceInstructions,
1704
+ label
1705
+ };
1706
+ // Set up abort controller for summarization
1707
+ this._branchSummaryAbortController = new AbortController();
1708
+ let extensionSummary;
1709
+ let fromExtension = false;
1710
+ // Emit session_before_tree event
1711
+ if (this._extensionRunner?.hasHandlers('session_before_tree')) {
1712
+ const result = (await this._extensionRunner.emit({
1713
+ type: 'session_before_tree',
1714
+ preparation,
1715
+ signal: this._branchSummaryAbortController.signal
1716
+ }));
1717
+ if (result?.cancel) {
1718
+ return { cancelled: true };
1719
+ }
1720
+ if (result?.summary && options.summarize) {
1721
+ extensionSummary = result.summary;
1722
+ fromExtension = true;
1723
+ }
1724
+ // Allow extensions to override instructions and label
1725
+ if (result?.customInstructions !== undefined) {
1726
+ customInstructions = result.customInstructions;
1727
+ }
1728
+ if (result?.replaceInstructions !== undefined) {
1729
+ replaceInstructions = result.replaceInstructions;
1730
+ }
1731
+ if (result?.label !== undefined) {
1732
+ label = result.label;
1733
+ }
1734
+ }
1735
+ // Run default summarizer if needed
1736
+ let summaryText;
1737
+ let summaryDetails;
1738
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
1739
+ const model = this.model;
1740
+ const apiKey = await this._modelRegistry.getApiKey(model);
1741
+ if (!apiKey) {
1742
+ throw new Error(`No API key for ${model.provider}`);
1743
+ }
1744
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
1745
+ const result = await generateBranchSummary(entriesToSummarize, {
1746
+ model,
1747
+ apiKey,
1748
+ signal: this._branchSummaryAbortController.signal,
1749
+ customInstructions,
1750
+ replaceInstructions,
1751
+ reserveTokens: branchSummarySettings.reserveTokens
1752
+ });
1753
+ this._branchSummaryAbortController = undefined;
1754
+ if (result.aborted) {
1755
+ return { cancelled: true, aborted: true };
1756
+ }
1757
+ if (result.error) {
1758
+ throw new Error(result.error);
1759
+ }
1760
+ summaryText = result.summary;
1761
+ summaryDetails = {
1762
+ readFiles: result.readFiles || [],
1763
+ modifiedFiles: result.modifiedFiles || []
1764
+ };
1765
+ }
1766
+ else if (extensionSummary) {
1767
+ summaryText = extensionSummary.summary;
1768
+ summaryDetails = extensionSummary.details;
1769
+ }
1770
+ // Determine the new leaf position based on target type
1771
+ let newLeafId;
1772
+ let editorText;
1773
+ if (targetEntry.type === 'message' && targetEntry.message.role === 'user') {
1774
+ // User message: leaf = parent (null if root), text goes to editor
1775
+ newLeafId = targetEntry.parentId;
1776
+ editorText = this._extractUserMessageText(targetEntry.message.content);
1777
+ }
1778
+ else if (targetEntry.type === 'custom_message') {
1779
+ // Custom message: leaf = parent (null if root), text goes to editor
1780
+ newLeafId = targetEntry.parentId;
1781
+ editorText =
1782
+ typeof targetEntry.content === 'string'
1783
+ ? targetEntry.content
1784
+ : targetEntry.content
1785
+ .filter((c) => c.type === 'text')
1786
+ .map((c) => c.text)
1787
+ .join('');
1788
+ }
1789
+ else {
1790
+ // Non-user message: leaf = selected node
1791
+ newLeafId = targetId;
1792
+ }
1793
+ // Switch leaf (with or without summary)
1794
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
1795
+ let summaryEntry;
1796
+ if (summaryText) {
1797
+ // Create summary at target position (can be null for root)
1798
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
1799
+ summaryEntry = this.sessionManager.getEntry(summaryId);
1800
+ // Attach label to the summary entry
1801
+ if (label) {
1802
+ this.sessionManager.appendLabelChange(summaryId, label);
1803
+ }
1804
+ }
1805
+ else if (newLeafId === null) {
1806
+ // No summary, navigating to root - reset leaf
1807
+ this.sessionManager.resetLeaf();
1808
+ }
1809
+ else {
1810
+ // No summary, navigating to non-root
1811
+ this.sessionManager.branch(newLeafId);
1812
+ }
1813
+ // Attach label to target entry when not summarizing (no summary entry to label)
1814
+ if (label && !summaryText) {
1815
+ this.sessionManager.appendLabelChange(targetId, label);
1816
+ }
1817
+ // Update agent state
1818
+ const sessionContext = this.sessionManager.buildSessionContext();
1819
+ this.agent.replaceMessages(sessionContext.messages);
1820
+ // Emit session_tree event
1821
+ if (this._extensionRunner) {
1822
+ await this._extensionRunner.emit({
1823
+ type: 'session_tree',
1824
+ newLeafId: this.sessionManager.getLeafId(),
1825
+ oldLeafId,
1826
+ summaryEntry,
1827
+ fromExtension: summaryText ? fromExtension : undefined
1828
+ });
1829
+ }
1830
+ // Emit to custom tools
1831
+ this._branchSummaryAbortController = undefined;
1832
+ return { editorText, cancelled: false, summaryEntry };
1833
+ }
1834
+ /**
1835
+ * Get all user messages from session for fork selector.
1836
+ */
1837
+ getUserMessagesForForking() {
1838
+ const entries = this.sessionManager.getEntries();
1839
+ const result = [];
1840
+ for (const entry of entries) {
1841
+ if (entry.type !== 'message')
1842
+ continue;
1843
+ if (entry.message.role !== 'user')
1844
+ continue;
1845
+ const text = this._extractUserMessageText(entry.message.content);
1846
+ if (text) {
1847
+ result.push({ entryId: entry.id, text });
1848
+ }
1849
+ }
1850
+ return result;
1851
+ }
1852
+ _extractUserMessageText(content) {
1853
+ if (typeof content === 'string')
1854
+ return content;
1855
+ if (Array.isArray(content)) {
1856
+ return content
1857
+ .filter((c) => c.type === 'text')
1858
+ .map((c) => c.text)
1859
+ .join('');
1860
+ }
1861
+ return '';
1862
+ }
1863
+ /**
1864
+ * Get session statistics.
1865
+ */
1866
+ getSessionStats() {
1867
+ const state = this.state;
1868
+ const userMessages = state.messages.filter((m) => m.role === 'user').length;
1869
+ const assistantMessages = state.messages.filter((m) => m.role === 'assistant').length;
1870
+ const toolResults = state.messages.filter((m) => m.role === 'toolResult').length;
1871
+ let toolCalls = 0;
1872
+ let totalInput = 0;
1873
+ let totalOutput = 0;
1874
+ let totalCacheRead = 0;
1875
+ let totalCacheWrite = 0;
1876
+ let totalCost = 0;
1877
+ for (const message of state.messages) {
1878
+ if (message.role === 'assistant') {
1879
+ const assistantMsg = message;
1880
+ toolCalls += assistantMsg.content.filter((c) => c.type === 'toolCall').length;
1881
+ totalInput += assistantMsg.usage.input;
1882
+ totalOutput += assistantMsg.usage.output;
1883
+ totalCacheRead += assistantMsg.usage.cacheRead;
1884
+ totalCacheWrite += assistantMsg.usage.cacheWrite;
1885
+ totalCost += assistantMsg.usage.cost.total;
1886
+ }
1887
+ }
1888
+ return {
1889
+ sessionFile: this.sessionFile,
1890
+ sessionId: this.sessionId,
1891
+ userMessages,
1892
+ assistantMessages,
1893
+ toolCalls,
1894
+ toolResults,
1895
+ totalMessages: state.messages.length,
1896
+ tokens: {
1897
+ input: totalInput,
1898
+ output: totalOutput,
1899
+ cacheRead: totalCacheRead,
1900
+ cacheWrite: totalCacheWrite,
1901
+ total: totalInput + totalOutput + totalCacheRead + totalCacheWrite
1902
+ },
1903
+ cost: totalCost
1904
+ };
1905
+ }
1906
+ getContextUsage() {
1907
+ const model = this.model;
1908
+ if (!model)
1909
+ return undefined;
1910
+ const contextWindow = model.contextWindow ?? 0;
1911
+ if (contextWindow <= 0)
1912
+ return undefined;
1913
+ // After compaction, the last assistant usage reflects pre-compaction context size.
1914
+ // We can only trust usage from an assistant that responded after the latest compaction.
1915
+ // If no such assistant exists, context token count is unknown until the next LLM response.
1916
+ const branchEntries = this.sessionManager.getBranch();
1917
+ const latestCompaction = getLatestCompactionEntry(branchEntries);
1918
+ if (latestCompaction) {
1919
+ // Check if there's a valid assistant usage after the compaction boundary
1920
+ const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
1921
+ let hasPostCompactionUsage = false;
1922
+ for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
1923
+ const entry = branchEntries[i];
1924
+ if (entry.type === 'message' && entry.message.role === 'assistant') {
1925
+ const assistant = entry.message;
1926
+ if (assistant.stopReason !== 'aborted' && assistant.stopReason !== 'error') {
1927
+ const contextTokens = calculateContextTokens(assistant.usage);
1928
+ if (contextTokens > 0) {
1929
+ hasPostCompactionUsage = true;
1930
+ }
1931
+ break;
1932
+ }
1933
+ }
1934
+ }
1935
+ if (!hasPostCompactionUsage) {
1936
+ return { tokens: null, contextWindow, percent: null };
1937
+ }
1938
+ }
1939
+ const estimate = estimateContextTokens(this.messages);
1940
+ const percent = (estimate.tokens / contextWindow) * 100;
1941
+ return {
1942
+ tokens: estimate.tokens,
1943
+ contextWindow,
1944
+ percent
1945
+ };
1946
+ }
1947
+ /**
1948
+ * Export session to HTML.
1949
+ * @param outputPath Optional output path (defaults to session directory)
1950
+ * @returns Path to exported file
1951
+ */
1952
+ async exportToHtml(outputPath) {
1953
+ const sessionFile = this.sessionManager.getSessionFile();
1954
+ if (!sessionFile) {
1955
+ throw new Error('Cannot export in-memory session to HTML');
1956
+ }
1957
+ const themeName = this.settingsManager.getTheme();
1958
+ // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
1959
+ let toolRenderer;
1960
+ if (this._extensionRunner) {
1961
+ toolRenderer = createToolHtmlRenderer({
1962
+ getToolDefinition: (name) => this._extensionRunner.getToolDefinition(name),
1963
+ theme
1964
+ });
1965
+ }
1966
+ return await exportFromFile(sessionFile, {
1967
+ outputPath,
1968
+ themeName,
1969
+ toolRenderer
1970
+ });
1971
+ }
1972
+ // =========================================================================
1973
+ // Utilities
1974
+ // =========================================================================
1975
+ /**
1976
+ * Get text content of last assistant message.
1977
+ * Useful for /copy command.
1978
+ * @returns Text content, or undefined if no assistant message exists
1979
+ */
1980
+ getLastAssistantText() {
1981
+ const lastAssistant = this.messages
1982
+ .slice()
1983
+ .reverse()
1984
+ .find((m) => {
1985
+ if (m.role !== 'assistant')
1986
+ return false;
1987
+ const msg = m;
1988
+ // Skip aborted messages with no content
1989
+ if (msg.stopReason === 'aborted' && msg.content.length === 0)
1990
+ return false;
1991
+ return true;
1992
+ });
1993
+ if (!lastAssistant)
1994
+ return undefined;
1995
+ let text = '';
1996
+ for (const content of lastAssistant.content) {
1997
+ if (content.type === 'text') {
1998
+ text += content.text;
1999
+ }
2000
+ }
2001
+ return text.trim() || undefined;
2002
+ }
2003
+ // =========================================================================
2004
+ // Extension System
2005
+ // =========================================================================
2006
+ /**
2007
+ * Check if extensions have handlers for a specific event type.
2008
+ */
2009
+ hasExtensionHandlers(eventType) {
2010
+ return this._extensionRunner?.hasHandlers(eventType) ?? false;
2011
+ }
2012
+ /**
2013
+ * Get the extension runner (for setting UI context and error handlers).
2014
+ */
2015
+ get extensionRunner() {
2016
+ return this._extensionRunner;
2017
+ }
2018
+ }
2019
+ //# sourceMappingURL=agent-session.js.map