@hyperspaceng/neural-coding-agent 0.61.2 → 0.61.4

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 (494) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +10 -0
  3. package/dist/bun/cli.d.ts +3 -0
  4. package/dist/bun/cli.d.ts.map +1 -0
  5. package/dist/bun/cli.js +7 -0
  6. package/dist/bun/cli.js.map +1 -0
  7. package/dist/bun/register-bedrock.d.ts +2 -0
  8. package/dist/bun/register-bedrock.d.ts.map +1 -0
  9. package/dist/bun/register-bedrock.js +4 -0
  10. package/dist/bun/register-bedrock.js.map +1 -0
  11. package/dist/cli/args.d.ts +49 -0
  12. package/dist/cli/args.d.ts.map +1 -0
  13. package/dist/cli/args.js +304 -0
  14. package/dist/cli/args.js.map +1 -0
  15. package/dist/cli/config-selector.d.ts +14 -0
  16. package/dist/cli/config-selector.d.ts.map +1 -0
  17. package/dist/cli/config-selector.js +31 -0
  18. package/dist/cli/config-selector.js.map +1 -0
  19. package/dist/cli/file-processor.d.ts +15 -0
  20. package/dist/cli/file-processor.d.ts.map +1 -0
  21. package/dist/cli/file-processor.js +79 -0
  22. package/dist/cli/file-processor.js.map +1 -0
  23. package/dist/cli/initial-message.d.ts +18 -0
  24. package/dist/cli/initial-message.d.ts.map +1 -0
  25. package/dist/cli/initial-message.js +22 -0
  26. package/dist/cli/initial-message.js.map +1 -0
  27. package/dist/cli/list-models.d.ts +9 -0
  28. package/dist/cli/list-models.d.ts.map +1 -0
  29. package/dist/cli/list-models.js +92 -0
  30. package/dist/cli/list-models.js.map +1 -0
  31. package/dist/cli/session-picker.d.ts +9 -0
  32. package/dist/cli/session-picker.d.ts.map +1 -0
  33. package/dist/cli/session-picker.js +35 -0
  34. package/dist/cli/session-picker.js.map +1 -0
  35. package/dist/cli.d.ts +3 -0
  36. package/dist/cli.d.ts.map +1 -0
  37. package/dist/cli.js +14 -0
  38. package/dist/cli.js.map +1 -0
  39. package/dist/config.d.ts +68 -0
  40. package/dist/config.d.ts.map +1 -0
  41. package/dist/config.js +203 -0
  42. package/dist/config.js.map +1 -0
  43. package/dist/core/agent-session.d.ts +607 -0
  44. package/dist/core/agent-session.d.ts.map +1 -0
  45. package/dist/core/agent-session.js +2617 -0
  46. package/dist/core/agent-session.js.map +1 -0
  47. package/dist/core/auth-storage.d.ts +130 -0
  48. package/dist/core/auth-storage.d.ts.map +1 -0
  49. package/dist/core/auth-storage.js +419 -0
  50. package/dist/core/auth-storage.js.map +1 -0
  51. package/dist/core/bash-executor.d.ts +46 -0
  52. package/dist/core/bash-executor.d.ts.map +1 -0
  53. package/dist/core/bash-executor.js +113 -0
  54. package/dist/core/bash-executor.js.map +1 -0
  55. package/dist/core/compaction/branch-summarization.d.ts +86 -0
  56. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  57. package/dist/core/compaction/branch-summarization.js +243 -0
  58. package/dist/core/compaction/branch-summarization.js.map +1 -0
  59. package/dist/core/compaction/compaction.d.ts +121 -0
  60. package/dist/core/compaction/compaction.d.ts.map +1 -0
  61. package/dist/core/compaction/compaction.js +612 -0
  62. package/dist/core/compaction/compaction.js.map +1 -0
  63. package/dist/core/compaction/index.d.ts +7 -0
  64. package/dist/core/compaction/index.d.ts.map +1 -0
  65. package/dist/core/compaction/index.js +7 -0
  66. package/dist/core/compaction/index.js.map +1 -0
  67. package/dist/core/compaction/utils.d.ts +38 -0
  68. package/dist/core/compaction/utils.d.ts.map +1 -0
  69. package/dist/core/compaction/utils.js +153 -0
  70. package/dist/core/compaction/utils.js.map +1 -0
  71. package/dist/core/defaults.d.ts +3 -0
  72. package/dist/core/defaults.d.ts.map +1 -0
  73. package/dist/core/defaults.js +2 -0
  74. package/dist/core/defaults.js.map +1 -0
  75. package/dist/core/diagnostics.d.ts +15 -0
  76. package/dist/core/diagnostics.d.ts.map +1 -0
  77. package/dist/core/diagnostics.js +2 -0
  78. package/dist/core/diagnostics.js.map +1 -0
  79. package/dist/core/event-bus.d.ts +9 -0
  80. package/dist/core/event-bus.d.ts.map +1 -0
  81. package/dist/core/event-bus.js +25 -0
  82. package/dist/core/event-bus.js.map +1 -0
  83. package/dist/core/exec.d.ts +29 -0
  84. package/dist/core/exec.d.ts.map +1 -0
  85. package/dist/core/exec.js +75 -0
  86. package/dist/core/exec.js.map +1 -0
  87. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  88. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  89. package/dist/core/export-html/ansi-to-html.js +249 -0
  90. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  91. package/dist/core/export-html/index.d.ts +37 -0
  92. package/dist/core/export-html/index.d.ts.map +1 -0
  93. package/dist/core/export-html/index.js +223 -0
  94. package/dist/core/export-html/index.js.map +1 -0
  95. package/dist/core/export-html/template.css +1001 -0
  96. package/dist/core/export-html/template.html +55 -0
  97. package/dist/core/export-html/template.js +1690 -0
  98. package/dist/core/export-html/tool-renderer.d.ts +38 -0
  99. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  100. package/dist/core/export-html/tool-renderer.js +70 -0
  101. package/dist/core/export-html/tool-renderer.js.map +1 -0
  102. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  103. package/dist/core/export-html/vendor/marked.min.js +6 -0
  104. package/dist/core/extensions/index.d.ts +11 -0
  105. package/dist/core/extensions/index.d.ts.map +1 -0
  106. package/dist/core/extensions/index.js +9 -0
  107. package/dist/core/extensions/index.js.map +1 -0
  108. package/dist/core/extensions/loader.d.ts +25 -0
  109. package/dist/core/extensions/loader.d.ts.map +1 -0
  110. package/dist/core/extensions/loader.js +426 -0
  111. package/dist/core/extensions/loader.js.map +1 -0
  112. package/dist/core/extensions/runner.d.ts +150 -0
  113. package/dist/core/extensions/runner.d.ts.map +1 -0
  114. package/dist/core/extensions/runner.js +707 -0
  115. package/dist/core/extensions/runner.js.map +1 -0
  116. package/dist/core/extensions/types.d.ts +1037 -0
  117. package/dist/core/extensions/types.d.ts.map +1 -0
  118. package/dist/core/extensions/types.js +35 -0
  119. package/dist/core/extensions/types.js.map +1 -0
  120. package/dist/core/extensions/wrapper.d.ts +20 -0
  121. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  122. package/dist/core/extensions/wrapper.js +28 -0
  123. package/dist/core/extensions/wrapper.js.map +1 -0
  124. package/dist/core/footer-data-provider.d.ts +44 -0
  125. package/dist/core/footer-data-provider.d.ts.map +1 -0
  126. package/dist/core/footer-data-provider.js +252 -0
  127. package/dist/core/footer-data-provider.js.map +1 -0
  128. package/dist/core/index.d.ts +9 -0
  129. package/dist/core/index.d.ts.map +1 -0
  130. package/dist/core/index.js +9 -0
  131. package/dist/core/index.js.map +1 -0
  132. package/dist/core/keybindings.d.ts +275 -0
  133. package/dist/core/keybindings.d.ts.map +1 -0
  134. package/dist/core/keybindings.js +241 -0
  135. package/dist/core/keybindings.js.map +1 -0
  136. package/dist/core/messages.d.ts +77 -0
  137. package/dist/core/messages.d.ts.map +1 -0
  138. package/dist/core/messages.js +123 -0
  139. package/dist/core/messages.js.map +1 -0
  140. package/dist/core/model-registry.d.ts +114 -0
  141. package/dist/core/model-registry.d.ts.map +1 -0
  142. package/dist/core/model-registry.js +563 -0
  143. package/dist/core/model-registry.js.map +1 -0
  144. package/dist/core/model-resolver.d.ts +110 -0
  145. package/dist/core/model-resolver.d.ts.map +1 -0
  146. package/dist/core/model-resolver.js +486 -0
  147. package/dist/core/model-resolver.js.map +1 -0
  148. package/dist/core/package-manager.d.ts +171 -0
  149. package/dist/core/package-manager.d.ts.map +1 -0
  150. package/dist/core/package-manager.js +1700 -0
  151. package/dist/core/package-manager.js.map +1 -0
  152. package/dist/core/prompt-templates.d.ts +50 -0
  153. package/dist/core/prompt-templates.d.ts.map +1 -0
  154. package/dist/core/prompt-templates.js +251 -0
  155. package/dist/core/prompt-templates.js.map +1 -0
  156. package/dist/core/resolve-config-value.d.ts +17 -0
  157. package/dist/core/resolve-config-value.d.ts.map +1 -0
  158. package/dist/core/resolve-config-value.js +94 -0
  159. package/dist/core/resolve-config-value.js.map +1 -0
  160. package/dist/core/resource-loader.d.ts +184 -0
  161. package/dist/core/resource-loader.d.ts.map +1 -0
  162. package/dist/core/resource-loader.js +670 -0
  163. package/dist/core/resource-loader.js.map +1 -0
  164. package/dist/core/sdk.d.ts +90 -0
  165. package/dist/core/sdk.d.ts.map +1 -0
  166. package/dist/core/sdk.js +242 -0
  167. package/dist/core/sdk.js.map +1 -0
  168. package/dist/core/session-manager.d.ts +329 -0
  169. package/dist/core/session-manager.d.ts.map +1 -0
  170. package/dist/core/session-manager.js +1097 -0
  171. package/dist/core/session-manager.js.map +1 -0
  172. package/dist/core/settings-manager.d.ts +235 -0
  173. package/dist/core/settings-manager.d.ts.map +1 -0
  174. package/dist/core/settings-manager.js +699 -0
  175. package/dist/core/settings-manager.js.map +1 -0
  176. package/dist/core/skills.d.ts +59 -0
  177. package/dist/core/skills.d.ts.map +1 -0
  178. package/dist/core/skills.js +385 -0
  179. package/dist/core/skills.js.map +1 -0
  180. package/dist/core/slash-commands.d.ts +15 -0
  181. package/dist/core/slash-commands.d.ts.map +1 -0
  182. package/dist/core/slash-commands.js +23 -0
  183. package/dist/core/slash-commands.js.map +1 -0
  184. package/dist/core/system-prompt.d.ts +28 -0
  185. package/dist/core/system-prompt.d.ts.map +1 -0
  186. package/dist/core/system-prompt.js +151 -0
  187. package/dist/core/system-prompt.js.map +1 -0
  188. package/dist/core/timings.d.ts +7 -0
  189. package/dist/core/timings.d.ts.map +1 -0
  190. package/dist/core/timings.js +25 -0
  191. package/dist/core/timings.js.map +1 -0
  192. package/dist/core/tools/bash.d.ts +63 -0
  193. package/dist/core/tools/bash.d.ts.map +1 -0
  194. package/dist/core/tools/bash.js +250 -0
  195. package/dist/core/tools/bash.js.map +1 -0
  196. package/dist/core/tools/edit-diff.d.ts +63 -0
  197. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  198. package/dist/core/tools/edit-diff.js +244 -0
  199. package/dist/core/tools/edit-diff.js.map +1 -0
  200. package/dist/core/tools/edit.d.ts +39 -0
  201. package/dist/core/tools/edit.d.ts.map +1 -0
  202. package/dist/core/tools/edit.js +147 -0
  203. package/dist/core/tools/edit.js.map +1 -0
  204. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  205. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  206. package/dist/core/tools/file-mutation-queue.js +37 -0
  207. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  208. package/dist/core/tools/find.d.ts +39 -0
  209. package/dist/core/tools/find.d.ts.map +1 -0
  210. package/dist/core/tools/find.js +209 -0
  211. package/dist/core/tools/find.js.map +1 -0
  212. package/dist/core/tools/grep.d.ts +45 -0
  213. package/dist/core/tools/grep.d.ts.map +1 -0
  214. package/dist/core/tools/grep.js +239 -0
  215. package/dist/core/tools/grep.js.map +1 -0
  216. package/dist/core/tools/index.d.ts +74 -0
  217. package/dist/core/tools/index.d.ts.map +1 -0
  218. package/dist/core/tools/index.js +62 -0
  219. package/dist/core/tools/index.js.map +1 -0
  220. package/dist/core/tools/ls.d.ts +40 -0
  221. package/dist/core/tools/ls.d.ts.map +1 -0
  222. package/dist/core/tools/ls.js +118 -0
  223. package/dist/core/tools/ls.js.map +1 -0
  224. package/dist/core/tools/path-utils.d.ts +8 -0
  225. package/dist/core/tools/path-utils.d.ts.map +1 -0
  226. package/dist/core/tools/path-utils.js +81 -0
  227. package/dist/core/tools/path-utils.js.map +1 -0
  228. package/dist/core/tools/read.d.ts +39 -0
  229. package/dist/core/tools/read.d.ts.map +1 -0
  230. package/dist/core/tools/read.js +166 -0
  231. package/dist/core/tools/read.js.map +1 -0
  232. package/dist/core/tools/truncate.d.ts +70 -0
  233. package/dist/core/tools/truncate.d.ts.map +1 -0
  234. package/dist/core/tools/truncate.js +205 -0
  235. package/dist/core/tools/truncate.js.map +1 -0
  236. package/dist/core/tools/write.d.ts +29 -0
  237. package/dist/core/tools/write.d.ts.map +1 -0
  238. package/dist/core/tools/write.js +81 -0
  239. package/dist/core/tools/write.js.map +1 -0
  240. package/dist/index.d.ts +27 -0
  241. package/dist/index.d.ts.map +1 -0
  242. package/dist/index.js +42 -0
  243. package/dist/index.js.map +1 -0
  244. package/dist/main.d.ts +8 -0
  245. package/dist/main.d.ts.map +1 -0
  246. package/dist/main.js +736 -0
  247. package/dist/main.js.map +1 -0
  248. package/dist/migrations.d.ts +33 -0
  249. package/dist/migrations.d.ts.map +1 -0
  250. package/dist/migrations.js +261 -0
  251. package/dist/migrations.js.map +1 -0
  252. package/dist/modes/index.d.ts +9 -0
  253. package/dist/modes/index.d.ts.map +1 -0
  254. package/dist/modes/index.js +8 -0
  255. package/dist/modes/index.js.map +1 -0
  256. package/dist/modes/interactive/components/armin.d.ts +34 -0
  257. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  258. package/dist/modes/interactive/components/armin.js +333 -0
  259. package/dist/modes/interactive/components/armin.js.map +1 -0
  260. package/dist/modes/interactive/components/assistant-message.d.ts +16 -0
  261. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  262. package/dist/modes/interactive/components/assistant-message.js +96 -0
  263. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  264. package/dist/modes/interactive/components/bash-execution.d.ts +35 -0
  265. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  266. package/dist/modes/interactive/components/bash-execution.js +162 -0
  267. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  268. package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  269. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  270. package/dist/modes/interactive/components/bordered-loader.js +51 -0
  271. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  272. package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  273. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  274. package/dist/modes/interactive/components/branch-summary-message.js +44 -0
  275. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  276. package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  277. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  278. package/dist/modes/interactive/components/compaction-summary-message.js +45 -0
  279. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  280. package/dist/modes/interactive/components/config-selector.d.ts +71 -0
  281. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  282. package/dist/modes/interactive/components/config-selector.js +479 -0
  283. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  284. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  285. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  286. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  287. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  288. package/dist/modes/interactive/components/custom-editor.d.ts +21 -0
  289. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  290. package/dist/modes/interactive/components/custom-editor.js +70 -0
  291. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  292. package/dist/modes/interactive/components/custom-message.d.ts +20 -0
  293. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  294. package/dist/modes/interactive/components/custom-message.js +79 -0
  295. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  296. package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  297. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
  298. package/dist/modes/interactive/components/daxnuts.js +140 -0
  299. package/dist/modes/interactive/components/daxnuts.js.map +1 -0
  300. package/dist/modes/interactive/components/diff.d.ts +12 -0
  301. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  302. package/dist/modes/interactive/components/diff.js +133 -0
  303. package/dist/modes/interactive/components/diff.js.map +1 -0
  304. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  305. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  306. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  307. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  308. package/dist/modes/interactive/components/extension-editor.d.ts +20 -0
  309. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  310. package/dist/modes/interactive/components/extension-editor.js +111 -0
  311. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  312. package/dist/modes/interactive/components/extension-input.d.ts +23 -0
  313. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  314. package/dist/modes/interactive/components/extension-input.js +61 -0
  315. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  316. package/dist/modes/interactive/components/extension-selector.d.ts +24 -0
  317. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  318. package/dist/modes/interactive/components/extension-selector.js +78 -0
  319. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  320. package/dist/modes/interactive/components/footer.d.ts +26 -0
  321. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  322. package/dist/modes/interactive/components/footer.js +198 -0
  323. package/dist/modes/interactive/components/footer.js.map +1 -0
  324. package/dist/modes/interactive/components/index.d.ts +32 -0
  325. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  326. package/dist/modes/interactive/components/index.js +33 -0
  327. package/dist/modes/interactive/components/index.js.map +1 -0
  328. package/dist/modes/interactive/components/keybinding-hints.d.ts +8 -0
  329. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  330. package/dist/modes/interactive/components/keybinding-hints.js +22 -0
  331. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  332. package/dist/modes/interactive/components/login-dialog.d.ts +42 -0
  333. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  334. package/dist/modes/interactive/components/login-dialog.js +145 -0
  335. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  336. package/dist/modes/interactive/components/model-selector.d.ts +47 -0
  337. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  338. package/dist/modes/interactive/components/model-selector.js +275 -0
  339. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  340. package/dist/modes/interactive/components/oauth-selector.d.ts +19 -0
  341. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  342. package/dist/modes/interactive/components/oauth-selector.js +97 -0
  343. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  344. package/dist/modes/interactive/components/scoped-models-selector.d.ts +49 -0
  345. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  346. package/dist/modes/interactive/components/scoped-models-selector.js +275 -0
  347. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  348. package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  349. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  350. package/dist/modes/interactive/components/session-selector-search.js +155 -0
  351. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  352. package/dist/modes/interactive/components/session-selector.d.ts +95 -0
  353. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  354. package/dist/modes/interactive/components/session-selector.js +848 -0
  355. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  356. package/dist/modes/interactive/components/settings-selector.d.ts +58 -0
  357. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  358. package/dist/modes/interactive/components/settings-selector.js +301 -0
  359. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  360. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  361. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  362. package/dist/modes/interactive/components/show-images-selector.js +39 -0
  363. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  364. package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  365. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  366. package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
  367. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  368. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  369. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  370. package/dist/modes/interactive/components/theme-selector.js +50 -0
  371. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  372. package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  373. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  374. package/dist/modes/interactive/components/thinking-selector.js +51 -0
  375. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  376. package/dist/modes/interactive/components/tool-execution.d.ts +84 -0
  377. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  378. package/dist/modes/interactive/components/tool-execution.js +832 -0
  379. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  380. package/dist/modes/interactive/components/tree-selector.d.ts +87 -0
  381. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  382. package/dist/modes/interactive/components/tree-selector.js +1051 -0
  383. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  384. package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  385. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  386. package/dist/modes/interactive/components/user-message-selector.js +113 -0
  387. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  388. package/dist/modes/interactive/components/user-message.d.ts +9 -0
  389. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  390. package/dist/modes/interactive/components/user-message.js +28 -0
  391. package/dist/modes/interactive/components/user-message.js.map +1 -0
  392. package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  393. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  394. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  395. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  396. package/dist/modes/interactive/interactive-mode.d.ts +319 -0
  397. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  398. package/dist/modes/interactive/interactive-mode.js +3868 -0
  399. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  400. package/dist/modes/interactive/theme/dark.json +85 -0
  401. package/dist/modes/interactive/theme/light.json +84 -0
  402. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  403. package/dist/modes/interactive/theme/theme.d.ts +78 -0
  404. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  405. package/dist/modes/interactive/theme/theme.js +961 -0
  406. package/dist/modes/interactive/theme/theme.js.map +1 -0
  407. package/dist/modes/print-mode.d.ts +28 -0
  408. package/dist/modes/print-mode.d.ts.map +1 -0
  409. package/dist/modes/print-mode.js +101 -0
  410. package/dist/modes/print-mode.js.map +1 -0
  411. package/dist/modes/rpc/jsonl.d.ts +17 -0
  412. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  413. package/dist/modes/rpc/jsonl.js +49 -0
  414. package/dist/modes/rpc/jsonl.js.map +1 -0
  415. package/dist/modes/rpc/rpc-client.d.ts +217 -0
  416. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  417. package/dist/modes/rpc/rpc-client.js +401 -0
  418. package/dist/modes/rpc/rpc-client.js.map +1 -0
  419. package/dist/modes/rpc/rpc-mode.d.ts +20 -0
  420. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  421. package/dist/modes/rpc/rpc-mode.js +512 -0
  422. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  423. package/dist/modes/rpc/rpc-types.d.ts +409 -0
  424. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  425. package/dist/modes/rpc/rpc-types.js +8 -0
  426. package/dist/modes/rpc/rpc-types.js.map +1 -0
  427. package/dist/utils/changelog.d.ts +21 -0
  428. package/dist/utils/changelog.d.ts.map +1 -0
  429. package/dist/utils/changelog.js +87 -0
  430. package/dist/utils/changelog.js.map +1 -0
  431. package/dist/utils/child-process.d.ts +11 -0
  432. package/dist/utils/child-process.d.ts.map +1 -0
  433. package/dist/utils/child-process.js +78 -0
  434. package/dist/utils/child-process.js.map +1 -0
  435. package/dist/utils/clipboard-image.d.ts +11 -0
  436. package/dist/utils/clipboard-image.d.ts.map +1 -0
  437. package/dist/utils/clipboard-image.js +245 -0
  438. package/dist/utils/clipboard-image.js.map +1 -0
  439. package/dist/utils/clipboard-native.d.ts +8 -0
  440. package/dist/utils/clipboard-native.d.ts.map +1 -0
  441. package/dist/utils/clipboard-native.js +14 -0
  442. package/dist/utils/clipboard-native.js.map +1 -0
  443. package/dist/utils/clipboard.d.ts +2 -0
  444. package/dist/utils/clipboard.d.ts.map +1 -0
  445. package/dist/utils/clipboard.js +78 -0
  446. package/dist/utils/clipboard.js.map +1 -0
  447. package/dist/utils/exif-orientation.d.ts +5 -0
  448. package/dist/utils/exif-orientation.d.ts.map +1 -0
  449. package/dist/utils/exif-orientation.js +158 -0
  450. package/dist/utils/exif-orientation.js.map +1 -0
  451. package/dist/utils/frontmatter.d.ts +8 -0
  452. package/dist/utils/frontmatter.d.ts.map +1 -0
  453. package/dist/utils/frontmatter.js +26 -0
  454. package/dist/utils/frontmatter.js.map +1 -0
  455. package/dist/utils/git.d.ts +26 -0
  456. package/dist/utils/git.d.ts.map +1 -0
  457. package/dist/utils/git.js +163 -0
  458. package/dist/utils/git.js.map +1 -0
  459. package/dist/utils/image-convert.d.ts +9 -0
  460. package/dist/utils/image-convert.d.ts.map +1 -0
  461. package/dist/utils/image-convert.js +39 -0
  462. package/dist/utils/image-convert.js.map +1 -0
  463. package/dist/utils/image-resize.d.ts +36 -0
  464. package/dist/utils/image-resize.d.ts.map +1 -0
  465. package/dist/utils/image-resize.js +186 -0
  466. package/dist/utils/image-resize.js.map +1 -0
  467. package/dist/utils/mime.d.ts +2 -0
  468. package/dist/utils/mime.d.ts.map +1 -0
  469. package/dist/utils/mime.js +26 -0
  470. package/dist/utils/mime.js.map +1 -0
  471. package/dist/utils/photon.d.ts +21 -0
  472. package/dist/utils/photon.d.ts.map +1 -0
  473. package/dist/utils/photon.js +121 -0
  474. package/dist/utils/photon.js.map +1 -0
  475. package/dist/utils/shell.d.ts +26 -0
  476. package/dist/utils/shell.d.ts.map +1 -0
  477. package/dist/utils/shell.js +186 -0
  478. package/dist/utils/shell.js.map +1 -0
  479. package/dist/utils/sleep.d.ts +5 -0
  480. package/dist/utils/sleep.d.ts.map +1 -0
  481. package/dist/utils/sleep.js +17 -0
  482. package/dist/utils/sleep.js.map +1 -0
  483. package/dist/utils/tools-manager.d.ts +3 -0
  484. package/dist/utils/tools-manager.d.ts.map +1 -0
  485. package/dist/utils/tools-manager.js +252 -0
  486. package/dist/utils/tools-manager.js.map +1 -0
  487. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  488. package/examples/extensions/custom-provider-anthropic/package.json +17 -17
  489. package/examples/extensions/custom-provider-gitlab-duo/package.json +14 -14
  490. package/examples/extensions/custom-provider-qwen-cli/package.json +14 -14
  491. package/examples/extensions/subagent/index.ts +21 -1
  492. package/examples/extensions/with-deps/package-lock.json +2 -2
  493. package/examples/extensions/with-deps/package.json +20 -20
  494. package/package.json +4 -4
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Bash command execution with streaming support and cancellation.
3
+ *
4
+ * This module provides a unified bash execution implementation used by:
5
+ * - AgentSession.executeBash() for interactive and RPC modes
6
+ * - Direct calls from modes that need bash execution
7
+ */
8
+ import { randomBytes } from "node:crypto";
9
+ import { createWriteStream } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import stripAnsi from "strip-ansi";
13
+ import { sanitizeBinaryOutput } from "../utils/shell.js";
14
+ import { createLocalBashOperations } from "./tools/bash.js";
15
+ import { DEFAULT_MAX_BYTES, truncateTail } from "./tools/truncate.js";
16
+ // ============================================================================
17
+ // Implementation
18
+ // ============================================================================
19
+ /**
20
+ * Execute a bash command with optional streaming and cancellation support.
21
+ *
22
+ * Uses the same local BashOperations backend as createBashTool() so interactive
23
+ * user bash and tool-invoked bash share the same process spawning behavior.
24
+ * Sanitization, newline normalization, temp-file capture, and truncation still
25
+ * happen in executeBashWithOperations(), so reusing the local backend does not
26
+ * change output processing behavior.
27
+ *
28
+ * @param command - The bash command to execute
29
+ * @param options - Optional streaming callback and abort signal
30
+ * @returns Promise resolving to execution result
31
+ */
32
+ export function executeBash(command, options) {
33
+ return executeBashWithOperations(command, process.cwd(), createLocalBashOperations(), options);
34
+ }
35
+ /**
36
+ * Execute a bash command using custom BashOperations.
37
+ * Used for remote execution (SSH, containers, etc.).
38
+ */
39
+ export async function executeBashWithOperations(command, cwd, operations, options) {
40
+ const outputChunks = [];
41
+ let outputBytes = 0;
42
+ const maxOutputBytes = DEFAULT_MAX_BYTES * 2;
43
+ let tempFilePath;
44
+ let tempFileStream;
45
+ let totalBytes = 0;
46
+ const decoder = new TextDecoder();
47
+ const onData = (data) => {
48
+ totalBytes += data.length;
49
+ // Sanitize: strip ANSI, replace binary garbage, normalize newlines
50
+ const text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\r/g, "");
51
+ // Start writing to temp file if exceeds threshold
52
+ if (totalBytes > DEFAULT_MAX_BYTES && !tempFilePath) {
53
+ const id = randomBytes(8).toString("hex");
54
+ tempFilePath = join(tmpdir(), `pi-bash-${id}.log`);
55
+ tempFileStream = createWriteStream(tempFilePath);
56
+ for (const chunk of outputChunks) {
57
+ tempFileStream.write(chunk);
58
+ }
59
+ }
60
+ if (tempFileStream) {
61
+ tempFileStream.write(text);
62
+ }
63
+ // Keep rolling buffer
64
+ outputChunks.push(text);
65
+ outputBytes += text.length;
66
+ while (outputBytes > maxOutputBytes && outputChunks.length > 1) {
67
+ const removed = outputChunks.shift();
68
+ outputBytes -= removed.length;
69
+ }
70
+ // Stream to callback
71
+ if (options?.onChunk) {
72
+ options.onChunk(text);
73
+ }
74
+ };
75
+ try {
76
+ const result = await operations.exec(command, cwd, {
77
+ onData,
78
+ signal: options?.signal,
79
+ });
80
+ if (tempFileStream) {
81
+ tempFileStream.end();
82
+ }
83
+ const fullOutput = outputChunks.join("");
84
+ const truncationResult = truncateTail(fullOutput);
85
+ const cancelled = options?.signal?.aborted ?? false;
86
+ return {
87
+ output: truncationResult.truncated ? truncationResult.content : fullOutput,
88
+ exitCode: cancelled ? undefined : (result.exitCode ?? undefined),
89
+ cancelled,
90
+ truncated: truncationResult.truncated,
91
+ fullOutputPath: tempFilePath,
92
+ };
93
+ }
94
+ catch (err) {
95
+ if (tempFileStream) {
96
+ tempFileStream.end();
97
+ }
98
+ // Check if it was an abort
99
+ if (options?.signal?.aborted) {
100
+ const fullOutput = outputChunks.join("");
101
+ const truncationResult = truncateTail(fullOutput);
102
+ return {
103
+ output: truncationResult.truncated ? truncationResult.content : fullOutput,
104
+ exitCode: undefined,
105
+ cancelled: true,
106
+ truncated: truncationResult.truncated,
107
+ fullOutputPath: tempFilePath,
108
+ };
109
+ }
110
+ throw err;
111
+ }
112
+ }
113
+ //# sourceMappingURL=bash-executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAoB,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAuB,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA0BtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,WAAW,CAAC,OAAe,EAAE,OAA6B,EAAuB;IAChG,OAAO,yBAAyB,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,EAAE,yBAAyB,EAAE,EAAE,OAAO,CAAC,CAAC;AAAA,CAC/F;AAED;;;GAGG;AACH,MAAM,CAA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MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport stripAnsi from \"strip-ansi\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.js\";\nimport { type BashOperations, createLocalBashOperations } from \"./tools/bash.js\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command with optional streaming and cancellation support.\n *\n * Uses the same local BashOperations backend as createBashTool() so interactive\n * user bash and tool-invoked bash share the same process spawning behavior.\n * Sanitization, newline normalization, temp-file capture, and truncation still\n * happen in executeBashWithOperations(), so reusing the local backend does not\n * change output processing behavior.\n *\n * @param command - The bash command to execute\n * @param options - Optional streaming callback and abort signal\n * @returns Promise resolving to execution result\n */\nexport function executeBash(command: string, options?: BashExecutorOptions): Promise<BashResult> {\n\treturn executeBashWithOperations(command, process.cwd(), createLocalBashOperations(), options);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES && !tempFilePath) {\n\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\ttempFileStream = createWriteStream(tempFilePath);\n\t\t\tfor (const chunk of outputChunks) {\n\t\t\t\ttempFileStream.write(chunk);\n\t\t\t}\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Branch summarization for tree navigation.
3
+ *
4
+ * When navigating to a different point in the session tree, this generates
5
+ * a summary of the branch being left so context isn't lost.
6
+ */
7
+ import type { AgentMessage } from "@mariozechner/pi-agent-core";
8
+ import type { Model } from "@mariozechner/pi-ai";
9
+ import type { ReadonlySessionManager, SessionEntry } from "../session-manager.js";
10
+ import { type FileOperations } from "./utils.js";
11
+ export interface BranchSummaryResult {
12
+ summary?: string;
13
+ readFiles?: string[];
14
+ modifiedFiles?: string[];
15
+ aborted?: boolean;
16
+ error?: string;
17
+ }
18
+ /** Details stored in BranchSummaryEntry.details for file tracking */
19
+ export interface BranchSummaryDetails {
20
+ readFiles: string[];
21
+ modifiedFiles: string[];
22
+ }
23
+ export type { FileOperations } from "./utils.js";
24
+ export interface BranchPreparation {
25
+ /** Messages extracted for summarization, in chronological order */
26
+ messages: AgentMessage[];
27
+ /** File operations extracted from tool calls */
28
+ fileOps: FileOperations;
29
+ /** Total estimated tokens in messages */
30
+ totalTokens: number;
31
+ }
32
+ export interface CollectEntriesResult {
33
+ /** Entries to summarize, in chronological order */
34
+ entries: SessionEntry[];
35
+ /** Common ancestor between old and new position, if any */
36
+ commonAncestorId: string | null;
37
+ }
38
+ export interface GenerateBranchSummaryOptions {
39
+ /** Model to use for summarization */
40
+ model: Model<any>;
41
+ /** API key for the model */
42
+ apiKey: string;
43
+ /** Abort signal for cancellation */
44
+ signal: AbortSignal;
45
+ /** Optional custom instructions for summarization */
46
+ customInstructions?: string;
47
+ /** If true, customInstructions replaces the default prompt instead of being appended */
48
+ replaceInstructions?: boolean;
49
+ /** Tokens reserved for prompt + LLM response (default 16384) */
50
+ reserveTokens?: number;
51
+ }
52
+ /**
53
+ * Collect entries that should be summarized when navigating from one position to another.
54
+ *
55
+ * Walks from oldLeafId back to the common ancestor with targetId, collecting entries
56
+ * along the way. Does NOT stop at compaction boundaries - those are included and their
57
+ * summaries become context.
58
+ *
59
+ * @param session - Session manager (read-only access)
60
+ * @param oldLeafId - Current position (where we're navigating from)
61
+ * @param targetId - Target position (where we're navigating to)
62
+ * @returns Entries to summarize and the common ancestor
63
+ */
64
+ export declare function collectEntriesForBranchSummary(session: ReadonlySessionManager, oldLeafId: string | null, targetId: string): CollectEntriesResult;
65
+ /**
66
+ * Prepare entries for summarization with token budget.
67
+ *
68
+ * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.
69
+ * This ensures we keep the most recent context when the branch is too long.
70
+ *
71
+ * Also collects file operations from:
72
+ * - Tool calls in assistant messages
73
+ * - Existing branch_summary entries' details (for cumulative tracking)
74
+ *
75
+ * @param entries - Entries in chronological order
76
+ * @param tokenBudget - Maximum tokens to include (0 = no limit)
77
+ */
78
+ export declare function prepareBranchEntries(entries: SessionEntry[], tokenBudget?: number): BranchPreparation;
79
+ /**
80
+ * Generate a summary of abandoned branch entries.
81
+ *
82
+ * @param entries - Session entries to summarize (chronological order)
83
+ * @param options - Generation options
84
+ */
85
+ export declare function generateBranchSummary(entries: SessionEntry[], options: GenerateBranchSummaryOptions): Promise<BranchSummaryResult>;
86
+ //# sourceMappingURL=branch-summarization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"branch-summarization.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAQjD,OAAO,KAAK,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAElF,OAAO,EAIN,KAAK,cAAc,EAInB,MAAM,YAAY,CAAC;AAMpB,MAAM,WAAW,mBAAmB;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,qEAAqE;AACrE,MAAM,WAAW,oBAAoB;IACpC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,aAAa,EAAE,MAAM,EAAE,CAAC;CACxB;AAED,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,WAAW,iBAAiB;IACjC,mEAAmE;IACnE,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,gDAAgD;IAChD,OAAO,EAAE,cAAc,CAAC;IACxB,yCAAyC;IACzC,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,oBAAoB;IACpC,mDAAmD;IACnD,OAAO,EAAE,YAAY,EAAE,CAAC;IACxB,2DAA2D;IAC3D,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,MAAM,WAAW,4BAA4B;IAC5C,qCAAqC;IACrC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,4BAA4B;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,oCAAoC;IACpC,MAAM,EAAE,WAAW,CAAC;IACpB,qDAAqD;IACrD,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,wFAAwF;IACxF,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,gEAAgE;IAChE,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,sBAAsB,EAC/B,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,EAAE,MAAM,GACd,oBAAoB,CAkCtB;AAoCD;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,WAAW,GAAE,MAAU,GAAG,iBAAiB,CAoDxG;AAwCD;;;;;GAKG;AACH,wBAAsB,qBAAqB,CAC1C,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,4BAA4B,GACnC,OAAO,CAAC,mBAAmB,CAAC,CAqE9B","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { Model } from \"@mariozechner/pi-ai\";\nimport { completeSimple } from \"@mariozechner/pi-ai\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.js\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.js\";\nimport { estimateTokens } from \"./compaction.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.js\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<any>;\n\t/** API key for the model */\n\tapiKey: string;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at compaction boundaries - those are included and their\n * summaries become context.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst { model, apiKey, signal, customInstructions, replaceInstructions, reserveTokens = 16384 } = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization\n\tconst response = await completeSimple(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\t{ apiKey, signal, maxTokens: 2048 },\n\t);\n\n\t// Check if aborted or errored\n\tif (response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Branch summarization for tree navigation.
3
+ *
4
+ * When navigating to a different point in the session tree, this generates
5
+ * a summary of the branch being left so context isn't lost.
6
+ */
7
+ import { completeSimple } from "@mariozechner/pi-ai";
8
+ import { convertToLlm, createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "../messages.js";
9
+ import { estimateTokens } from "./compaction.js";
10
+ import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
11
+ // ============================================================================
12
+ // Entry Collection
13
+ // ============================================================================
14
+ /**
15
+ * Collect entries that should be summarized when navigating from one position to another.
16
+ *
17
+ * Walks from oldLeafId back to the common ancestor with targetId, collecting entries
18
+ * along the way. Does NOT stop at compaction boundaries - those are included and their
19
+ * summaries become context.
20
+ *
21
+ * @param session - Session manager (read-only access)
22
+ * @param oldLeafId - Current position (where we're navigating from)
23
+ * @param targetId - Target position (where we're navigating to)
24
+ * @returns Entries to summarize and the common ancestor
25
+ */
26
+ export function collectEntriesForBranchSummary(session, oldLeafId, targetId) {
27
+ // If no old position, nothing to summarize
28
+ if (!oldLeafId) {
29
+ return { entries: [], commonAncestorId: null };
30
+ }
31
+ // Find common ancestor (deepest node that's on both paths)
32
+ const oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));
33
+ const targetPath = session.getBranch(targetId);
34
+ // targetPath is root-first, so iterate backwards to find deepest common ancestor
35
+ let commonAncestorId = null;
36
+ for (let i = targetPath.length - 1; i >= 0; i--) {
37
+ if (oldPath.has(targetPath[i].id)) {
38
+ commonAncestorId = targetPath[i].id;
39
+ break;
40
+ }
41
+ }
42
+ // Collect entries from old leaf back to common ancestor
43
+ const entries = [];
44
+ let current = oldLeafId;
45
+ while (current && current !== commonAncestorId) {
46
+ const entry = session.getEntry(current);
47
+ if (!entry)
48
+ break;
49
+ entries.push(entry);
50
+ current = entry.parentId;
51
+ }
52
+ // Reverse to get chronological order
53
+ entries.reverse();
54
+ return { entries, commonAncestorId };
55
+ }
56
+ // ============================================================================
57
+ // Entry to Message Conversion
58
+ // ============================================================================
59
+ /**
60
+ * Extract AgentMessage from a session entry.
61
+ * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.
62
+ */
63
+ function getMessageFromEntry(entry) {
64
+ switch (entry.type) {
65
+ case "message":
66
+ // Skip tool results - context is in assistant's tool call
67
+ if (entry.message.role === "toolResult")
68
+ return undefined;
69
+ return entry.message;
70
+ case "custom_message":
71
+ return createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);
72
+ case "branch_summary":
73
+ return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);
74
+ case "compaction":
75
+ return createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);
76
+ // These don't contribute to conversation content
77
+ case "thinking_level_change":
78
+ case "model_change":
79
+ case "custom":
80
+ case "label":
81
+ case "session_info":
82
+ return undefined;
83
+ }
84
+ }
85
+ /**
86
+ * Prepare entries for summarization with token budget.
87
+ *
88
+ * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.
89
+ * This ensures we keep the most recent context when the branch is too long.
90
+ *
91
+ * Also collects file operations from:
92
+ * - Tool calls in assistant messages
93
+ * - Existing branch_summary entries' details (for cumulative tracking)
94
+ *
95
+ * @param entries - Entries in chronological order
96
+ * @param tokenBudget - Maximum tokens to include (0 = no limit)
97
+ */
98
+ export function prepareBranchEntries(entries, tokenBudget = 0) {
99
+ const messages = [];
100
+ const fileOps = createFileOps();
101
+ let totalTokens = 0;
102
+ // First pass: collect file ops from ALL entries (even if they don't fit in token budget)
103
+ // This ensures we capture cumulative file tracking from nested branch summaries
104
+ // Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones
105
+ for (const entry of entries) {
106
+ if (entry.type === "branch_summary" && !entry.fromHook && entry.details) {
107
+ const details = entry.details;
108
+ if (Array.isArray(details.readFiles)) {
109
+ for (const f of details.readFiles)
110
+ fileOps.read.add(f);
111
+ }
112
+ if (Array.isArray(details.modifiedFiles)) {
113
+ // Modified files go into both edited and written for proper deduplication
114
+ for (const f of details.modifiedFiles) {
115
+ fileOps.edited.add(f);
116
+ }
117
+ }
118
+ }
119
+ }
120
+ // Second pass: walk from newest to oldest, adding messages until token budget
121
+ for (let i = entries.length - 1; i >= 0; i--) {
122
+ const entry = entries[i];
123
+ const message = getMessageFromEntry(entry);
124
+ if (!message)
125
+ continue;
126
+ // Extract file ops from assistant messages (tool calls)
127
+ extractFileOpsFromMessage(message, fileOps);
128
+ const tokens = estimateTokens(message);
129
+ // Check budget before adding
130
+ if (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {
131
+ // If this is a summary entry, try to fit it anyway as it's important context
132
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
133
+ if (totalTokens < tokenBudget * 0.9) {
134
+ messages.unshift(message);
135
+ totalTokens += tokens;
136
+ }
137
+ }
138
+ // Stop - we've hit the budget
139
+ break;
140
+ }
141
+ messages.unshift(message);
142
+ totalTokens += tokens;
143
+ }
144
+ return { messages, fileOps, totalTokens };
145
+ }
146
+ // ============================================================================
147
+ // Summary Generation
148
+ // ============================================================================
149
+ const BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.
150
+ Summary of that exploration:
151
+
152
+ `;
153
+ const BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.
154
+
155
+ Use this EXACT format:
156
+
157
+ ## Goal
158
+ [What was the user trying to accomplish in this branch?]
159
+
160
+ ## Constraints & Preferences
161
+ - [Any constraints, preferences, or requirements mentioned]
162
+ - [Or "(none)" if none were mentioned]
163
+
164
+ ## Progress
165
+ ### Done
166
+ - [x] [Completed tasks/changes]
167
+
168
+ ### In Progress
169
+ - [ ] [Work that was started but not finished]
170
+
171
+ ### Blocked
172
+ - [Issues preventing progress, if any]
173
+
174
+ ## Key Decisions
175
+ - **[Decision]**: [Brief rationale]
176
+
177
+ ## Next Steps
178
+ 1. [What should happen next to continue this work]
179
+
180
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`;
181
+ /**
182
+ * Generate a summary of abandoned branch entries.
183
+ *
184
+ * @param entries - Session entries to summarize (chronological order)
185
+ * @param options - Generation options
186
+ */
187
+ export async function generateBranchSummary(entries, options) {
188
+ const { model, apiKey, signal, customInstructions, replaceInstructions, reserveTokens = 16384 } = options;
189
+ // Token budget = context window minus reserved space for prompt + response
190
+ const contextWindow = model.contextWindow || 128000;
191
+ const tokenBudget = contextWindow - reserveTokens;
192
+ const { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);
193
+ if (messages.length === 0) {
194
+ return { summary: "No content to summarize" };
195
+ }
196
+ // Transform to LLM-compatible messages, then serialize to text
197
+ // Serialization prevents the model from treating it as a conversation to continue
198
+ const llmMessages = convertToLlm(messages);
199
+ const conversationText = serializeConversation(llmMessages);
200
+ // Build prompt
201
+ let instructions;
202
+ if (replaceInstructions && customInstructions) {
203
+ instructions = customInstructions;
204
+ }
205
+ else if (customInstructions) {
206
+ instructions = `${BRANCH_SUMMARY_PROMPT}\n\nAdditional focus: ${customInstructions}`;
207
+ }
208
+ else {
209
+ instructions = BRANCH_SUMMARY_PROMPT;
210
+ }
211
+ const promptText = `<conversation>\n${conversationText}\n</conversation>\n\n${instructions}`;
212
+ const summarizationMessages = [
213
+ {
214
+ role: "user",
215
+ content: [{ type: "text", text: promptText }],
216
+ timestamp: Date.now(),
217
+ },
218
+ ];
219
+ // Call LLM for summarization
220
+ const response = await completeSimple(model, { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages }, { apiKey, signal, maxTokens: 2048 });
221
+ // Check if aborted or errored
222
+ if (response.stopReason === "aborted") {
223
+ return { aborted: true };
224
+ }
225
+ if (response.stopReason === "error") {
226
+ return { error: response.errorMessage || "Summarization failed" };
227
+ }
228
+ let summary = response.content
229
+ .filter((c) => c.type === "text")
230
+ .map((c) => c.text)
231
+ .join("\n");
232
+ // Prepend preamble to provide context about the branch summary
233
+ summary = BRANCH_SUMMARY_PREAMBLE + summary;
234
+ // Compute file lists and append to summary
235
+ const { readFiles, modifiedFiles } = computeFileLists(fileOps);
236
+ summary += formatFileOperations(readFiles, modifiedFiles);
237
+ return {
238
+ summary: summary || "No summary generated",
239
+ readFiles,
240
+ modifiedFiles,
241
+ };
242
+ }
243
+ //# sourceMappingURL=branch-summarization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"branch-summarization.js","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,8BAA8B,EAC9B,mBAAmB,GACnB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAqDpB,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,8BAA8B,CAC7C,OAA+B,EAC/B,SAAwB,EACxB,QAAgB,EACO;IACvB,2CAA2C;IAC3C,IAAI,CAAC,SAAS,EAAE,CAAC;QAChB,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC;IAChD,CAAC;IAED,2DAA2D;IAC3D,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACvE,MAAM,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC,QA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E,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;YACtD,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACrB;KACD,CAAC;IAEF,6BAA6B;IAC7B,MAAM,QAAQ,GAAG,MAAM,cAAc,CACpC,KAAK,EACL,EAAE,YAAY,EAAE,2BAA2B,EAAE,QAAQ,EAAE,qBAAqB,EAAE,EAC9E,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,CACnC,CAAC;IAEF,8BAA8B;IAC9B,IAAI,QAAQ,CAAC,UAAU,KAAK,SAAS,EAAE,CAAC;QACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;IACD,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;QACrC,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,YAAY,IAAI,sBAAsB,EAAE,CAAC;IACnE,CAAC;IAED,IAAI,OAAO,GAAG,QAAQ,CAAC,OAAO;SAC5B,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IAEb,+DAA+D;IAC/D,OAAO,GAAG,uBAAuB,GAAG,OAAO,CAAC;IAE5C,2CAA2C;IAC3C,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC/D,OAAO,IAAI,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAE1D,OAAO;QACN,OAAO,EAAE,OAAO,IAAI,sBAAsB;QAC1C,SAAS;QACT,aAAa;KACb,CAAC;AAAA,CACF","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { Model } from \"@mariozechner/pi-ai\";\nimport { completeSimple } from \"@mariozechner/pi-ai\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.js\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.js\";\nimport { estimateTokens } from \"./compaction.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.js\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<any>;\n\t/** API key for the model */\n\tapiKey: string;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at compaction boundaries - those are included and their\n * summaries become context.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst { model, apiKey, signal, customInstructions, replaceInstructions, reserveTokens = 16384 } = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization\n\tconst response = await completeSimple(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\t{ apiKey, signal, maxTokens: 2048 },\n\t);\n\n\t// Check if aborted or errored\n\tif (response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Context compaction for long sessions.
3
+ *
4
+ * Pure functions for compaction logic. The session manager handles I/O,
5
+ * and after compaction the session is reloaded.
6
+ */
7
+ import type { AgentMessage } from "@mariozechner/pi-agent-core";
8
+ import type { Model, Usage } from "@mariozechner/pi-ai";
9
+ import type { SessionEntry } from "../session-manager.js";
10
+ import { type FileOperations } from "./utils.js";
11
+ /** Details stored in CompactionEntry.details for file tracking */
12
+ export interface CompactionDetails {
13
+ readFiles: string[];
14
+ modifiedFiles: string[];
15
+ }
16
+ /** Result from compact() - SessionManager adds uuid/parentUuid when saving */
17
+ export interface CompactionResult<T = unknown> {
18
+ summary: string;
19
+ firstKeptEntryId: string;
20
+ tokensBefore: number;
21
+ /** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
22
+ details?: T;
23
+ }
24
+ export interface CompactionSettings {
25
+ enabled: boolean;
26
+ reserveTokens: number;
27
+ keepRecentTokens: number;
28
+ }
29
+ export declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings;
30
+ /**
31
+ * Calculate total context tokens from usage.
32
+ * Uses the native totalTokens field when available, falls back to computing from components.
33
+ */
34
+ export declare function calculateContextTokens(usage: Usage): number;
35
+ /**
36
+ * Find the last non-aborted assistant message usage from session entries.
37
+ */
38
+ export declare function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined;
39
+ export interface ContextUsageEstimate {
40
+ tokens: number;
41
+ usageTokens: number;
42
+ trailingTokens: number;
43
+ lastUsageIndex: number | null;
44
+ }
45
+ /**
46
+ * Estimate context tokens from messages, using the last assistant usage when available.
47
+ * If there are messages after the last usage, estimate their tokens with estimateTokens.
48
+ */
49
+ export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;
50
+ /**
51
+ * Check if compaction should trigger based on context usage.
52
+ */
53
+ export declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean;
54
+ /**
55
+ * Estimate token count for a message using chars/4 heuristic.
56
+ * This is conservative (overestimates tokens).
57
+ */
58
+ export declare function estimateTokens(message: AgentMessage): number;
59
+ /**
60
+ * Find the user message (or bashExecution) that starts the turn containing the given entry index.
61
+ * Returns -1 if no turn start found before the index.
62
+ * BashExecutionMessage is treated like a user message for turn boundaries.
63
+ */
64
+ export declare function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number;
65
+ export interface CutPointResult {
66
+ /** Index of first entry to keep */
67
+ firstKeptEntryIndex: number;
68
+ /** Index of user message that starts the turn being split, or -1 if not splitting */
69
+ turnStartIndex: number;
70
+ /** Whether this cut splits a turn (cut point is not a user message) */
71
+ isSplitTurn: boolean;
72
+ }
73
+ /**
74
+ * Find the cut point in session entries that keeps approximately `keepRecentTokens`.
75
+ *
76
+ * Algorithm: Walk backwards from newest, accumulating estimated message sizes.
77
+ * Stop when we've accumulated >= keepRecentTokens. Cut at that point.
78
+ *
79
+ * Can cut at user OR assistant messages (never tool results). When cutting at an
80
+ * assistant message with tool calls, its tool results come after and will be kept.
81
+ *
82
+ * Returns CutPointResult with:
83
+ * - firstKeptEntryIndex: the entry index to start keeping from
84
+ * - turnStartIndex: if cutting mid-turn, the user message that started that turn
85
+ * - isSplitTurn: whether we're cutting in the middle of a turn
86
+ *
87
+ * Only considers entries between `startIndex` and `endIndex` (exclusive).
88
+ */
89
+ export declare function findCutPoint(entries: SessionEntry[], startIndex: number, endIndex: number, keepRecentTokens: number): CutPointResult;
90
+ /**
91
+ * Generate a summary of the conversation using the LLM.
92
+ * If previousSummary is provided, uses the update prompt to merge.
93
+ */
94
+ export declare function generateSummary(currentMessages: AgentMessage[], model: Model<any>, reserveTokens: number, apiKey: string, signal?: AbortSignal, customInstructions?: string, previousSummary?: string): Promise<string>;
95
+ export interface CompactionPreparation {
96
+ /** UUID of first entry to keep */
97
+ firstKeptEntryId: string;
98
+ /** Messages that will be summarized and discarded */
99
+ messagesToSummarize: AgentMessage[];
100
+ /** Messages that will be turned into turn prefix summary (if splitting) */
101
+ turnPrefixMessages: AgentMessage[];
102
+ /** Whether this is a split turn (cut point in middle of turn) */
103
+ isSplitTurn: boolean;
104
+ tokensBefore: number;
105
+ /** Summary from previous compaction, for iterative update */
106
+ previousSummary?: string;
107
+ /** File operations extracted from messagesToSummarize */
108
+ fileOps: FileOperations;
109
+ /** Compaction settions from settings.jsonl */
110
+ settings: CompactionSettings;
111
+ }
112
+ export declare function prepareCompaction(pathEntries: SessionEntry[], settings: CompactionSettings): CompactionPreparation | undefined;
113
+ /**
114
+ * Generate summaries for compaction using prepared data.
115
+ * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.
116
+ *
117
+ * @param preparation - Pre-calculated preparation from prepareCompaction()
118
+ * @param customInstructions - Optional custom focus for the summary
119
+ */
120
+ export declare function compact(preparation: CompactionPreparation, model: Model<any>, apiKey: string, customInstructions?: string, signal?: AbortSignal): Promise<CompactionResult>;
121
+ //# sourceMappingURL=compaction.d.ts.map