@bastani/atomic 0.9.16-alpha.4 → 0.9.16-alpha.6

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 (404) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +11 -6
  3. package/dist/builtin/intercom/CHANGELOG.md +15 -0
  4. package/dist/builtin/intercom/README.md +6 -4
  5. package/dist/builtin/intercom/broker/broker.ts +34 -8
  6. package/dist/builtin/intercom/broker/client.ts +13 -0
  7. package/dist/builtin/intercom/broker/pending-question-index.ts +50 -0
  8. package/dist/builtin/intercom/broker/send-handler.ts +8 -0
  9. package/dist/builtin/intercom/index.bundle.mjs +2045 -1211
  10. package/dist/builtin/intercom/package.json +2 -2
  11. package/dist/builtin/intercom/skills/intercom/SKILL.md +20 -19
  12. package/dist/builtin/mcp/index.bundle.mjs +1778 -1026
  13. package/dist/builtin/mcp/package.json +2 -2
  14. package/dist/builtin/subagents/CHANGELOG.md +11 -0
  15. package/dist/builtin/subagents/README.md +3 -3
  16. package/dist/builtin/subagents/package.json +3 -3
  17. package/dist/builtin/subagents/skills/subagent/SKILL.md +4 -4
  18. package/dist/builtin/subagents/src/extension/index.bundle.mjs +2645 -1506
  19. package/dist/builtin/web-access/index.bundle.mjs +1754 -1002
  20. package/dist/builtin/web-access/package.json +2 -2
  21. package/dist/builtin/workflows/CHANGELOG.md +28 -0
  22. package/dist/builtin/workflows/README.md +3 -1
  23. package/dist/builtin/workflows/builtin/goal-ledger.ts +54 -10
  24. package/dist/builtin/workflows/builtin/goal-runner.ts +57 -12
  25. package/dist/builtin/workflows/package.json +2 -2
  26. package/dist/builtin/workflows/src/extension/index.bundle.mjs +13626 -12023
  27. package/dist/builtin/workflows/src/index.bundle.mjs +2338 -1279
  28. package/dist/bun/split-loader.js +2 -1
  29. package/dist/bun/split-loader.js.map +1 -1
  30. package/dist/cli/args.d.ts.map +1 -1
  31. package/dist/cli/args.js +6 -1
  32. package/dist/cli/args.js.map +1 -1
  33. package/dist/cli/file-processor.d.ts.map +1 -1
  34. package/dist/cli/file-processor.js +2 -1
  35. package/dist/cli/file-processor.js.map +1 -1
  36. package/dist/config-package-identity.d.ts.map +1 -1
  37. package/dist/config-package-identity.js +2 -1
  38. package/dist/config-package-identity.js.map +1 -1
  39. package/dist/config.d.ts.map +1 -1
  40. package/dist/config.js +2 -1
  41. package/dist/config.js.map +1 -1
  42. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  43. package/dist/core/agent-session-auto-compaction.js +64 -28
  44. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  45. package/dist/core/agent-session-compaction.d.ts +2 -0
  46. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  47. package/dist/core/agent-session-compaction.js +25 -5
  48. package/dist/core/agent-session-compaction.js.map +1 -1
  49. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  50. package/dist/core/agent-session-custom-message-commit.js +12 -0
  51. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  52. package/dist/core/agent-session-events.d.ts.map +1 -1
  53. package/dist/core/agent-session-events.js +2 -0
  54. package/dist/core/agent-session-events.js.map +1 -1
  55. package/dist/core/agent-session-export.d.ts +3 -1
  56. package/dist/core/agent-session-export.d.ts.map +1 -1
  57. package/dist/core/agent-session-export.js +22 -2
  58. package/dist/core/agent-session-export.js.map +1 -1
  59. package/dist/core/agent-session-message-queue.d.ts +3 -0
  60. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  61. package/dist/core/agent-session-message-queue.js +10 -0
  62. package/dist/core/agent-session-message-queue.js.map +1 -1
  63. package/dist/core/agent-session-methods.d.ts +15 -9
  64. package/dist/core/agent-session-methods.d.ts.map +1 -1
  65. package/dist/core/agent-session-methods.js.map +1 -1
  66. package/dist/core/agent-session-models.d.ts +8 -13
  67. package/dist/core/agent-session-models.d.ts.map +1 -1
  68. package/dist/core/agent-session-models.js +53 -19
  69. package/dist/core/agent-session-models.js.map +1 -1
  70. package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
  71. package/dist/core/agent-session-post-tool-compaction.js +12 -0
  72. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  73. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  74. package/dist/core/agent-session-prompt.js +3 -1
  75. package/dist/core/agent-session-prompt.js.map +1 -1
  76. package/dist/core/agent-session-tool-registry.js +3 -3
  77. package/dist/core/agent-session-tool-registry.js.map +1 -1
  78. package/dist/core/agent-session-transfer.d.ts.map +1 -1
  79. package/dist/core/agent-session-transfer.js +1 -0
  80. package/dist/core/agent-session-transfer.js.map +1 -1
  81. package/dist/core/agent-session-tree.d.ts.map +1 -1
  82. package/dist/core/agent-session-tree.js +1 -1
  83. package/dist/core/agent-session-tree.js.map +1 -1
  84. package/dist/core/agent-session-types.d.ts +3 -0
  85. package/dist/core/agent-session-types.d.ts.map +1 -1
  86. package/dist/core/agent-session-types.js.map +1 -1
  87. package/dist/core/agent-session.d.ts +2 -0
  88. package/dist/core/agent-session.d.ts.map +1 -1
  89. package/dist/core/agent-session.js +2 -0
  90. package/dist/core/agent-session.js.map +1 -1
  91. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  92. package/dist/core/auth-storage-backends.js +10 -6
  93. package/dist/core/auth-storage-backends.js.map +1 -1
  94. package/dist/core/auth-storage.d.ts.map +1 -1
  95. package/dist/core/auth-storage.js +4 -3
  96. package/dist/core/auth-storage.js.map +1 -1
  97. package/dist/core/builtin-packages.d.ts.map +1 -1
  98. package/dist/core/builtin-packages.js +2 -1
  99. package/dist/core/builtin-packages.js.map +1 -1
  100. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  101. package/dist/core/compaction/branch-summarization.js +6 -0
  102. package/dist/core/compaction/branch-summarization.js.map +1 -1
  103. package/dist/core/compaction/compaction-runner.d.ts +3 -1
  104. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  105. package/dist/core/compaction/compaction-runner.js +30 -4
  106. package/dist/core/compaction/compaction-runner.js.map +1 -1
  107. package/dist/core/compaction/compaction-types.d.ts +3 -1
  108. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  109. package/dist/core/compaction/compaction-types.js.map +1 -1
  110. package/dist/core/compaction/range-planner.d.ts +3 -1
  111. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  112. package/dist/core/compaction/range-planner.js +11 -1
  113. package/dist/core/compaction/range-planner.js.map +1 -1
  114. package/dist/core/compaction/session-summarization.d.ts.map +1 -1
  115. package/dist/core/compaction/session-summarization.js +6 -0
  116. package/dist/core/compaction/session-summarization.js.map +1 -1
  117. package/dist/core/extensions/api-types.d.ts +8 -3
  118. package/dist/core/extensions/api-types.d.ts.map +1 -1
  119. package/dist/core/extensions/api-types.js.map +1 -1
  120. package/dist/core/extensions/index.d.ts +2 -2
  121. package/dist/core/extensions/index.d.ts.map +1 -1
  122. package/dist/core/extensions/index.js +1 -1
  123. package/dist/core/extensions/index.js.map +1 -1
  124. package/dist/core/extensions/loader-api.d.ts +5 -1
  125. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  126. package/dist/core/extensions/loader-api.js +124 -36
  127. package/dist/core/extensions/loader-api.js.map +1 -1
  128. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  129. package/dist/core/extensions/loader-core.js +18 -4
  130. package/dist/core/extensions/loader-core.js.map +1 -1
  131. package/dist/core/extensions/loader-runtime.d.ts.map +1 -1
  132. package/dist/core/extensions/loader-runtime.js +10 -2
  133. package/dist/core/extensions/loader-runtime.js.map +1 -1
  134. package/dist/core/extensions/session-events.d.ts +11 -2
  135. package/dist/core/extensions/session-events.d.ts.map +1 -1
  136. package/dist/core/extensions/session-events.js.map +1 -1
  137. package/dist/core/extensions/tool-events.d.ts +13 -3
  138. package/dist/core/extensions/tool-events.d.ts.map +1 -1
  139. package/dist/core/extensions/tool-events.js +3 -0
  140. package/dist/core/extensions/tool-events.js.map +1 -1
  141. package/dist/core/extensions/types.d.ts +1 -1
  142. package/dist/core/extensions/types.d.ts.map +1 -1
  143. package/dist/core/extensions/types.js +1 -1
  144. package/dist/core/extensions/types.js.map +1 -1
  145. package/dist/core/extensions/ui-types.d.ts +2 -2
  146. package/dist/core/extensions/ui-types.js.map +1 -1
  147. package/dist/core/footer-data-provider.d.ts +1 -1
  148. package/dist/core/footer-data-provider.js +1 -1
  149. package/dist/core/footer-data-provider.js.map +1 -1
  150. package/dist/core/keybindings.d.ts +17 -16
  151. package/dist/core/keybindings.d.ts.map +1 -1
  152. package/dist/core/keybindings.js +23 -6
  153. package/dist/core/keybindings.js.map +1 -1
  154. package/dist/core/model-config.d.ts.map +1 -1
  155. package/dist/core/model-config.js +2 -1
  156. package/dist/core/model-config.js.map +1 -1
  157. package/dist/core/model-resolver-initial.d.ts +1 -0
  158. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  159. package/dist/core/model-resolver-initial.js +9 -5
  160. package/dist/core/model-resolver-initial.js.map +1 -1
  161. package/dist/core/models-store.d.ts.map +1 -1
  162. package/dist/core/models-store.js +2 -1
  163. package/dist/core/models-store.js.map +1 -1
  164. package/dist/core/package-manager-git.d.ts.map +1 -1
  165. package/dist/core/package-manager-git.js +2 -1
  166. package/dist/core/package-manager-git.js.map +1 -1
  167. package/dist/core/package-manager-manifest.d.ts.map +1 -1
  168. package/dist/core/package-manager-manifest.js +2 -1
  169. package/dist/core/package-manager-manifest.js.map +1 -1
  170. package/dist/core/package-manager-npm.d.ts.map +1 -1
  171. package/dist/core/package-manager-npm.js +4 -3
  172. package/dist/core/package-manager-npm.js.map +1 -1
  173. package/dist/core/package-manager-operations.d.ts.map +1 -1
  174. package/dist/core/package-manager-operations.js +2 -1
  175. package/dist/core/package-manager-operations.js.map +1 -1
  176. package/dist/core/package-manager-resource-collector.d.ts.map +1 -1
  177. package/dist/core/package-manager-resource-collector.js +2 -1
  178. package/dist/core/package-manager-resource-collector.js.map +1 -1
  179. package/dist/core/package-manager-resource-files.d.ts.map +1 -1
  180. package/dist/core/package-manager-resource-files.js +7 -2
  181. package/dist/core/package-manager-resource-files.js.map +1 -1
  182. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  183. package/dist/core/remote-catalog-provider.js +2 -1
  184. package/dist/core/remote-catalog-provider.js.map +1 -1
  185. package/dist/core/resource-loader-context-files.d.ts.map +1 -1
  186. package/dist/core/resource-loader-context-files.js +3 -2
  187. package/dist/core/resource-loader-context-files.js.map +1 -1
  188. package/dist/core/sdk-exports.d.ts +5 -3
  189. package/dist/core/sdk-exports.d.ts.map +1 -1
  190. package/dist/core/sdk-exports.js +4 -2
  191. package/dist/core/sdk-exports.js.map +1 -1
  192. package/dist/core/sdk.d.ts.map +1 -1
  193. package/dist/core/sdk.js +7 -3
  194. package/dist/core/sdk.js.map +1 -1
  195. package/dist/core/session-manager-core.d.ts +2 -2
  196. package/dist/core/session-manager-core.d.ts.map +1 -1
  197. package/dist/core/session-manager-core.js +4 -4
  198. package/dist/core/session-manager-core.js.map +1 -1
  199. package/dist/core/session-manager-entries.d.ts +2 -2
  200. package/dist/core/session-manager-entries.d.ts.map +1 -1
  201. package/dist/core/session-manager-entries.js +4 -3
  202. package/dist/core/session-manager-entries.js.map +1 -1
  203. package/dist/core/session-manager-storage.d.ts.map +1 -1
  204. package/dist/core/session-manager-storage.js +4 -2
  205. package/dist/core/session-manager-storage.js.map +1 -1
  206. package/dist/core/session-manager-types.d.ts +2 -0
  207. package/dist/core/session-manager-types.d.ts.map +1 -1
  208. package/dist/core/session-manager-types.js.map +1 -1
  209. package/dist/core/settings-diagnostics.d.ts +4 -0
  210. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  211. package/dist/core/settings-diagnostics.js +12 -0
  212. package/dist/core/settings-diagnostics.js.map +1 -0
  213. package/dist/core/settings-manager-basic-accessors.d.ts +4 -0
  214. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  215. package/dist/core/settings-manager-basic-accessors.js +23 -0
  216. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  217. package/dist/core/settings-manager-core.d.ts.map +1 -1
  218. package/dist/core/settings-manager-core.js +10 -2
  219. package/dist/core/settings-manager-core.js.map +1 -1
  220. package/dist/core/settings-storage.d.ts.map +1 -1
  221. package/dist/core/settings-storage.js +10 -3
  222. package/dist/core/settings-storage.js.map +1 -1
  223. package/dist/core/settings-types.d.ts +2 -0
  224. package/dist/core/settings-types.d.ts.map +1 -1
  225. package/dist/core/settings-types.js.map +1 -1
  226. package/dist/core/skills.d.ts.map +1 -1
  227. package/dist/core/skills.js +51 -33
  228. package/dist/core/skills.js.map +1 -1
  229. package/dist/core/slash-commands.d.ts.map +1 -1
  230. package/dist/core/slash-commands.js +3 -2
  231. package/dist/core/slash-commands.js.map +1 -1
  232. package/dist/core/system-prompt.d.ts.map +1 -1
  233. package/dist/core/system-prompt.js +15 -3
  234. package/dist/core/system-prompt.js.map +1 -1
  235. package/dist/core/tools/ask-user-question/config.d.ts.map +1 -1
  236. package/dist/core/tools/ask-user-question/config.js +2 -1
  237. package/dist/core/tools/ask-user-question/config.js.map +1 -1
  238. package/dist/core/tools/bash.d.ts +13 -1
  239. package/dist/core/tools/bash.d.ts.map +1 -1
  240. package/dist/core/tools/bash.js +9 -5
  241. package/dist/core/tools/bash.js.map +1 -1
  242. package/dist/core/tools/index.d.ts +21 -5
  243. package/dist/core/tools/index.d.ts.map +1 -1
  244. package/dist/core/tools/index.js +45 -13
  245. package/dist/core/tools/index.js.map +1 -1
  246. package/dist/core/tools/powershell.d.ts +83 -0
  247. package/dist/core/tools/powershell.d.ts.map +1 -0
  248. package/dist/core/tools/powershell.js +89 -0
  249. package/dist/core/tools/powershell.js.map +1 -0
  250. package/dist/core/usage-totals.d.ts.map +1 -1
  251. package/dist/core/usage-totals.js +2 -1
  252. package/dist/core/usage-totals.js.map +1 -1
  253. package/dist/extensions/llama/client.d.ts +6 -0
  254. package/dist/extensions/llama/client.d.ts.map +1 -1
  255. package/dist/extensions/llama/client.js +12 -0
  256. package/dist/extensions/llama/client.js.map +1 -1
  257. package/dist/extensions/llama/index.d.ts.map +1 -1
  258. package/dist/extensions/llama/index.js +2 -0
  259. package/dist/extensions/llama/index.js.map +1 -1
  260. package/dist/extensions/llama/provider.d.ts +3 -1
  261. package/dist/extensions/llama/provider.d.ts.map +1 -1
  262. package/dist/extensions/llama/provider.js +25 -8
  263. package/dist/extensions/llama/provider.js.map +1 -1
  264. package/dist/index-extensions.d.ts +2 -2
  265. package/dist/index-extensions.d.ts.map +1 -1
  266. package/dist/index-extensions.js +1 -1
  267. package/dist/index-extensions.js.map +1 -1
  268. package/dist/index.d.ts +4 -3
  269. package/dist/index.d.ts.map +1 -1
  270. package/dist/index.js +4 -3
  271. package/dist/index.js.map +1 -1
  272. package/dist/main-stdio.d.ts.map +1 -1
  273. package/dist/main-stdio.js +4 -2
  274. package/dist/main-stdio.js.map +1 -1
  275. package/dist/main.d.ts.map +1 -1
  276. package/dist/main.js +10 -3
  277. package/dist/main.js.map +1 -1
  278. package/dist/migrations-config-values.d.ts.map +1 -1
  279. package/dist/migrations-config-values.js +2 -1
  280. package/dist/migrations-config-values.js.map +1 -1
  281. package/dist/migrations.d.ts.map +1 -1
  282. package/dist/migrations.js +5 -4
  283. package/dist/migrations.js.map +1 -1
  284. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  285. package/dist/modes/interactive/components/footer.js +2 -1
  286. package/dist/modes/interactive/components/footer.js.map +1 -1
  287. package/dist/modes/interactive/components/model-selector.d.ts +2 -2
  288. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  289. package/dist/modes/interactive/components/model-selector.js +27 -16
  290. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  291. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  292. package/dist/modes/interactive/components/settings-selector-items.js +67 -14
  293. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  294. package/dist/modes/interactive/components/settings-selector-submenus.d.ts +7 -1
  295. package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
  296. package/dist/modes/interactive/components/settings-selector-submenus.js +38 -3
  297. package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
  298. package/dist/modes/interactive/components/settings-selector-types.d.ts +5 -1
  299. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  300. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  301. package/dist/modes/interactive/components/thinking-selector.d.ts +15 -6
  302. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  303. package/dist/modes/interactive/components/thinking-selector.js +65 -27
  304. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  305. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  306. package/dist/modes/interactive/external-editor.js +2 -1
  307. package/dist/modes/interactive/external-editor.js.map +1 -1
  308. package/dist/modes/interactive/interactive-agent-events.js +2 -0
  309. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  310. package/dist/modes/interactive/interactive-auth-login.d.ts +1 -1
  311. package/dist/modes/interactive/interactive-auth-login.d.ts.map +1 -1
  312. package/dist/modes/interactive/interactive-auth-login.js +9 -1
  313. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  314. package/dist/modes/interactive/interactive-autocomplete.js +9 -0
  315. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  316. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  317. package/dist/modes/interactive/interactive-deferred-startup.js +2 -0
  318. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  319. package/dist/modes/interactive/interactive-editor-actions.js +11 -10
  320. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  321. package/dist/modes/interactive/interactive-input-handling.js +6 -0
  322. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  323. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -0
  324. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  325. package/dist/modes/interactive/interactive-mode-deps.js +1 -0
  326. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  327. package/dist/modes/interactive/interactive-mode-surface.d.ts +7 -0
  328. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  329. package/dist/modes/interactive/interactive-mode-surface.js +0 -1
  330. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  331. package/dist/modes/interactive/interactive-mode-types.d.ts +3 -0
  332. package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
  333. package/dist/modes/interactive/interactive-mode-types.js.map +1 -1
  334. package/dist/modes/interactive/interactive-model-routing.d.ts +16 -1
  335. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  336. package/dist/modes/interactive/interactive-model-routing.js +62 -3
  337. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  338. package/dist/modes/interactive/interactive-render-chat.js +18 -0
  339. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  340. package/dist/modes/interactive/interactive-selectors.js +10 -8
  341. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  342. package/dist/modes/interactive/interactive-slash-commands.js +6 -5
  343. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  344. package/dist/modes/interactive/interactive-startup.js +9 -1
  345. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  346. package/dist/modes/interactive/theme/theme-parse.d.ts.map +1 -1
  347. package/dist/modes/interactive/theme/theme-parse.js +2 -1
  348. package/dist/modes/interactive/theme/theme-parse.js.map +1 -1
  349. package/dist/modes/json-event.d.ts +15 -18
  350. package/dist/modes/json-event.d.ts.map +1 -1
  351. package/dist/modes/json-event.js +21 -17
  352. package/dist/modes/json-event.js.map +1 -1
  353. package/dist/modes/rpc/rpc-client-api.d.ts +4 -0
  354. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  355. package/dist/modes/rpc/rpc-client-api.js +3 -0
  356. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  357. package/dist/utils/frontmatter.d.ts.map +1 -1
  358. package/dist/utils/frontmatter.js +2 -1
  359. package/dist/utils/frontmatter.js.map +1 -1
  360. package/dist/utils/management-http.d.ts +2 -0
  361. package/dist/utils/management-http.d.ts.map +1 -1
  362. package/dist/utils/management-http.js +11 -7
  363. package/dist/utils/management-http.js.map +1 -1
  364. package/dist/utils/shell.d.ts +3 -0
  365. package/dist/utils/shell.d.ts.map +1 -1
  366. package/dist/utils/shell.js +41 -10
  367. package/dist/utils/shell.js.map +1 -1
  368. package/dist/utils/syntax-highlight.d.ts +1 -0
  369. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  370. package/dist/utils/syntax-highlight.js +61 -1
  371. package/dist/utils/syntax-highlight.js.map +1 -1
  372. package/dist/utils/text.d.ts +8 -0
  373. package/dist/utils/text.d.ts.map +1 -0
  374. package/dist/utils/text.js +9 -0
  375. package/dist/utils/text.js.map +1 -0
  376. package/docs/changelog.mdx +1 -1
  377. package/docs/compaction.md +16 -3
  378. package/docs/containerization.md +17 -0
  379. package/docs/custom-provider.md +1 -1
  380. package/docs/environment-variables.md +3 -3
  381. package/docs/extensions.md +22 -5
  382. package/docs/index.md +12 -10
  383. package/docs/intercom.md +5 -3
  384. package/docs/keybindings.md +1 -1
  385. package/docs/llama-cpp.md +1 -1
  386. package/docs/models.md +2 -0
  387. package/docs/quickstart.md +80 -9
  388. package/docs/rpc.md +24 -1
  389. package/docs/sdk.md +11 -0
  390. package/docs/settings.md +16 -7
  391. package/docs/skills.md +3 -2
  392. package/docs/subagents.md +7 -0
  393. package/docs/termux.md +1 -1
  394. package/docs/usage.md +4 -3
  395. package/docs/windows.md +33 -3
  396. package/docs/workflows.md +22 -10
  397. package/examples/extensions/border-status-editor.ts +1 -1
  398. package/examples/extensions/git-checkpoint.ts +1 -1
  399. package/examples/extensions/notify.ts +1 -1
  400. package/examples/extensions/titlebar-spinner.ts +1 -1
  401. package/examples/rpc-extension-ui.ts +1 -1
  402. package/examples/sdk/README.md +1 -1
  403. package/npm-shrinkwrap.json +73 -65
  404. package/package.json +11 -13
@@ -1 +1 @@
1
- {"version":3,"file":"bran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AAC;QACH,CAAC;IACF,CAAC,CAAC,EAAE,CAAC;IAEL,8BAA8B;IAC9B,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,UAAU,KAAK,SAAS,EAAE,CAAC;QACpD,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,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,SAAS;QACT,aAAa;KACb,CAAC;AACH,CAAC","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 {\n\ttype ProviderHeaders,\n\ttype RetryCallbacks,\n\ttype RetryPolicy,\n\tretryAssistantCall,\n\tuuidv7,\n} from \"@bastani/pi-ai\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"@bastani/pi-ai/compat\";\nimport { completeSimple } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { convertToLlm, createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport { resolvePlannerRequest } from \"./range-planner.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\tusage?: Usage;\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.ts\";\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<Api>;\n\t/** API key for the model; omitted for header-only bearer authentication. */\n\tapiKey?: string;\n\t/** Request headers for the model */\n\theaders?: ProviderHeaders;\n\t/** Credential-specific request endpoint for the model */\n\tbaseUrl?: 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\t/**\n\t * Session reasoning level, inherited by the summarization request.\n\t * No output cap is sent, so thinking has no artificial budget to exhaust.\n\t */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Optional session stream function. Used to preserve SDK request behavior without mutating agent state. */\n\tstreamFn?: StreamFn;\n\t/** Retry policy for transient summarization failures. */\n\tretry?: RetryPolicy;\n\t/** Retry lifecycle callbacks. */\n\tcallbacks?: RetryCallbacks;\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 legacy compaction entries, but those entries are\n * inert and are not fed into branch summarization prompts.\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, with legacy compaction entries kept inert.\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(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\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 undefined;\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\tcase \"session_summary\":\n\t\tcase \"context_compaction\":\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\tconst filteredEntries = entries;\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 filteredEntries) {\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 = filteredEntries.length - 1; i >= 0; i--) {\n\t\tconst entry = filteredEntries[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 branch summary entry, try to fit it anyway as it's important context\n\t\t\tif (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 {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tbaseUrl,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tthinkingLevel,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t} = 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. Prefer the session stream function so SDK\n\t// request behavior stays consistent without mutating agent state.\n\tconst context = { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages };\n\tconst requestModel = baseUrl === undefined || baseUrl === model.baseUrl ? model : { ...model, baseUrl };\n\t// Same budget rule as the compaction planner: no output cap is sent, so\n\t// pi-ai's context clamp is the only bound and the inherited reasoning level\n\t// has no artificial budget to exhaust. `reserveTokens` keeps its input-side\n\t// meaning above, unchanged.\n\tconst budget = resolvePlannerRequest(requestModel, thinkingLevel);\n\tconst requestOptions: SimpleStreamOptions = {\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t\t...(budget.reasoning && budget.reasoning !== \"off\" ? { reasoning: budget.reasoning } : {}),\n\t};\n\tconst response = await (async () => {\n\t\ttry {\n\t\t\treturn await retryAssistantCall(\n\t\t\t\tasync () =>\n\t\t\t\t\tstreamFn\n\t\t\t\t\t\t? (await streamFn(requestModel, context, requestOptions)).result()\n\t\t\t\t\t\t: completeSimple(requestModel, context, requestOptions),\n\t\t\t\tretry,\n\t\t\t\tsignal,\n\t\t\t\tcallbacks,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) return undefined;\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\" as const,\n\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t}\n\t})();\n\n\t// Check if aborted or errored\n\tif (!response || 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\tusage: response.usage,\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
1
+ {"version":3,"file":"branch-summarization.js","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAIN,kBAAkB,EAClB,MAAM,GACN,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE/F,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAqEpB,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,8BAA8B,CAC7C,OAA+B,EAC/B,SAAwB,EACxB,QAAgB;IAEhB,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,C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A2C;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,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,SAAS;QACT,aAAa;KACb,CAAC;AACH,CAAC","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 {\n\ttype ProviderHeaders,\n\ttype RetryCallbacks,\n\ttype RetryPolicy,\n\tretryAssistantCall,\n\tuuidv7,\n} from \"@bastani/pi-ai\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"@bastani/pi-ai/compat\";\nimport { completeSimple } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { convertToLlm, createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport { resolvePlannerRequest } from \"./range-planner.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\tusage?: Usage;\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.ts\";\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<Api>;\n\t/** API key for the model; omitted for header-only bearer authentication. */\n\tapiKey?: string;\n\t/** Request headers for the model */\n\theaders?: ProviderHeaders;\n\t/** Credential-specific request endpoint for the model */\n\tbaseUrl?: 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\t/**\n\t * Session reasoning level, inherited by the summarization request.\n\t * No output cap is sent, so thinking has no artificial budget to exhaust.\n\t */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Optional session stream function. Used to preserve SDK request behavior without mutating agent state. */\n\tstreamFn?: StreamFn;\n\t/** Retry policy for transient summarization failures. */\n\tretry?: RetryPolicy;\n\t/** Retry lifecycle callbacks. */\n\tcallbacks?: RetryCallbacks;\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 legacy compaction entries, but those entries are\n * inert and are not fed into branch summarization prompts.\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, with legacy compaction entries kept inert.\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(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\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 undefined;\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\tcase \"session_summary\":\n\t\tcase \"context_compaction\":\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\tconst filteredEntries = entries;\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 filteredEntries) {\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 = filteredEntries.length - 1; i >= 0; i--) {\n\t\tconst entry = filteredEntries[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 branch summary entry, try to fit it anyway as it's important context\n\t\t\tif (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 {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tbaseUrl,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tthinkingLevel,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t} = 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. Prefer the session stream function so SDK\n\t// request behavior stays consistent without mutating agent state.\n\tconst context = { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages };\n\tconst requestModel = baseUrl === undefined || baseUrl === model.baseUrl ? model : { ...model, baseUrl };\n\t// Same budget rule as the compaction planner: no output cap is sent, so\n\t// pi-ai's context clamp is the only bound and the inherited reasoning level\n\t// has no artificial budget to exhaust. `reserveTokens` keeps its input-side\n\t// meaning above, unchanged.\n\tconst budget = resolvePlannerRequest(requestModel, thinkingLevel);\n\tconst requestOptions: SimpleStreamOptions = {\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t\t...(budget.reasoning && budget.reasoning !== \"off\" ? { reasoning: budget.reasoning } : {}),\n\t};\n\tconst response = await (async () => {\n\t\ttry {\n\t\t\treturn await retryAssistantCall(\n\t\t\t\tasync () =>\n\t\t\t\t\tstreamFn\n\t\t\t\t\t\t? (await streamFn(requestModel, context, requestOptions)).result()\n\t\t\t\t\t\t: completeSimple(requestModel, context, requestOptions),\n\t\t\t\tretry,\n\t\t\t\tsignal,\n\t\t\t\tcallbacks,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) return undefined;\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\" as const,\n\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t}\n\t})();\n\n\t// Check if aborted or errored\n\tif (!response || 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\tif (response.stopReason === \"length\") {\n\t\treturn { error: \"Branch summarization failed: generation hit the token cap and the summary is incomplete\" };\n\t}\n\tif (response.content.some((block) => block.type === \"toolCall\")) {\n\t\treturn { error: \"Branch summarization attempted to call a tool\" };\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\tusage: response.usage,\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { RetryCallbacks, RetryPolicy } from "@bastani/pi-ai";
2
- import type { Api, Model } from "@bastani/pi-ai/compat";
2
+ import type { Api, Model, Usage } from "@bastani/pi-ai/compat";
3
3
  import type { StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";
4
4
  import type { CompactedTranscript, CompactionPlannerModel, CompactionUrgency, PlannerAuth, VerbatimCompactionPreparation } from "./compaction-types.js";
5
5
  import { type FallbackPlannerContext } from "./fallback-planner.js";
@@ -27,6 +27,8 @@ export type CompactionRungResult = CompactedTranscript & {
27
27
  plannerModel?: CompactionPlannerModel;
28
28
  /** False only when the fresh rung had to drop the protected tail. */
29
29
  keptTail: boolean;
30
+ /** Aggregate usage across every planner request and retry in this run. */
31
+ usage?: Usage;
30
32
  };
31
33
  /**
32
34
  * Calculate the single global line threshold from the prepared setting.
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE7E,OAAO,KAAK,EAEX,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,WAAW,EAEX,6BAA6B,EAC7B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAGN,KAAK,sBAAsB,EAE3B,MAAM,uBAAuB,CAAC;AAY/B,MAAM,WAAW,qBAAqB;IACrC,QAAQ,EAAE,QAAQ,CAAC;IACnB,qFAAqF;IACrF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,cAAc,CAAC;CAC3B;AAED,8EAA8E;AAC9E,MAAM,WAAW,oBAAqB,SAAQ,qBAAqB;IAClE,2FAA2F;IAC3F,WAAW,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAAC;IACrE,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,mEAAmE;IACnE,aAAa,EAAE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T_MESSAGE, NO_USABLE_RANGES_MESSAGE, planDeletedLineRanges, RangePlanError, resolvePlannerRequest, } from "./range-planner.js";
6
6
  import { writeSuccessDiagnosticSidecar } from "./range-planner-diagnostics.js";
7
7
  import { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from "./region-trimming.js";
8
+ function addUsage(total, usage) {
9
+ const cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);
10
+ const reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);
11
+ return {
12
+ input: (total?.input ?? 0) + usage.input,
13
+ output: (total?.output ?? 0) + usage.output,
14
+ cacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,
15
+ cacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,
16
+ ...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),
17
+ ...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),
18
+ totalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,
19
+ cost: {
20
+ input: (total?.cost.input ?? 0) + usage.cost.input,
21
+ output: (total?.cost.output ?? 0) + usage.cost.output,
22
+ cacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,
23
+ cacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,
24
+ total: (total?.cost.total ?? 0) + usage.cost.total,
25
+ },
26
+ };
27
+ }
8
28
  /**
9
29
  * Calculate the single global line threshold from the prepared setting.
10
30
  *
@@ -77,13 +97,14 @@ function buildFreshContextWindow(preparation, hardInputLimit) {
77
97
  export function startNewContextWindow(preparation) {
78
98
  return buildFreshTranscript(preparation);
79
99
  }
80
- function plannedResult(preparation, ranges, plannerModel) {
100
+ function plannedResult(preparation, ranges, plannerModel, usage) {
81
101
  const reconstructed = reconstructCompactedTranscript(preparation.region, validateDeletedRanges(ranges, preparation.region));
82
102
  return {
83
103
  ...withWholeContextStats(reconstructed, preparation, true),
84
104
  rung: "planned",
85
105
  ...(plannerModel ? { plannerModel } : {}),
86
106
  keptTail: true,
107
+ ...(usage ? { usage } : {}),
87
108
  };
88
109
  }
89
110
  function borrowedIdentity(planner) {
@@ -168,12 +189,13 @@ async function resolvePlannerAuth(resolveAuth, model) {
168
189
  return { failure: authFailureOutcome(error) };
169
190
  }
170
191
  }
171
- function freshResult(preparation, hardInputLimit) {
192
+ function freshResult(preparation, hardInputLimit, usage) {
172
193
  const fresh = buildFreshContextWindow(preparation, hardInputLimit);
173
194
  return {
174
195
  ...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),
175
196
  rung: "fresh",
176
197
  keptTail: fresh.keptTail,
198
+ ...(usage ? { usage } : {}),
177
199
  };
178
200
  }
179
201
  /**
@@ -192,12 +214,16 @@ export async function runVerbatimCompaction(preparation, model, request) {
192
214
  const signal = request.signal;
193
215
  if (signal?.aborted)
194
216
  throw new Error("Compaction cancelled");
217
+ let plannerUsage;
195
218
  const plannerOptions = {
196
219
  streamFn: request.streamFn,
197
220
  sessionFilePath: request.sessionFilePath,
198
221
  retry: request.retry,
199
222
  callbacks: request.callbacks,
200
223
  signal,
224
+ onUsage: (usage) => {
225
+ plannerUsage = addUsage(plannerUsage, usage);
226
+ },
201
227
  };
202
228
  const hardInputLimit = hardInputLimitFor(model);
203
229
  // A region below the planner minimum cannot be made rankable by changing
@@ -244,7 +270,7 @@ export async function runVerbatimCompaction(preparation, model, request) {
244
270
  ...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),
245
271
  });
246
272
  }
247
- return plannedResult(preparation, attempt.ranges, plannerModel);
273
+ return plannedResult(preparation, attempt.ranges, plannerModel, plannerUsage);
248
274
  }
249
275
  lastTerminal = attempt.outcome;
250
276
  attempted.add(plannerAttemptKey(planner));
@@ -255,6 +281,6 @@ export async function runVerbatimCompaction(preparation, model, request) {
255
281
  }
256
282
  if (request.urgency !== "load_bearing")
257
283
  throw terminalError(lastTerminal);
258
- return freshResult(preparation, hardInputLimit);
284
+ return freshResult(preparation, hardInputLimit, plannerUsage);
259
285
  }
260
286
  //# sourceMappingURL=compaction-runner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAUpE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAoC3F;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,eAAe,CAAC,WAA0C;IACzE,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;IAClC,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,WAAW,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAiB;IAC3C,OAAO,KAAK,CAAC,aAAa,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;AACjF,CAAC;AAED,SAAS,qBAAqB,CAC7B,MAA2B,EAC3B,WAA0C,EAC1C,QAAiB;IAEjB,MAAM,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,GAAG,CAAC,QAAQ,CAAC,CAAC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AO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5E,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import type { RetryCallbacks, RetryPolicy } from \"@bastani/pi-ai\";\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\tconst tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);\n\tconst percentReduction =\n\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;\n\treturn {\n\t\t...result,\n\t\tstats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\treturn { transcript: buildFreshTranscript(preparation), keptTail: getKeptTailTokenEstimate(preparation) <= limit };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(preparation: VerbatimCompactionPreparation, hardInputLimit: number): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower(request.fallback)\n\t\t: undefined;\n\tconst primaryBudget = resolvePlannerRequest(model, request.thinkingLevel);\n\tconst primaryAuth = await resolvePlannerAuth(request.resolveAuth, model);\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = false;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (\"auth\" in primaryAuth) {\n\t\tplanner = { model, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\t// No request was made, but this candidate must not be retried.\n\t\tattempted.add(plannerAttemptKey({ model, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(preparation, attempt.ranges, plannerModel);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit);\n}\n"]}
1
+ {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAUpE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AA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GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5E,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { RetryCallbacks, RetryPolicy } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\tconst tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);\n\tconst percentReduction =\n\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;\n\treturn {\n\t\t...result,\n\t\tstats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\treturn { transcript: buildFreshTranscript(preparation), keptTail: getKeptTailTokenEstimate(preparation) <= limit };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower(request.fallback)\n\t\t: undefined;\n\tconst primaryBudget = resolvePlannerRequest(model, request.thinkingLevel);\n\tconst primaryAuth = await resolvePlannerAuth(request.resolveAuth, model);\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = false;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (\"auth\" in primaryAuth) {\n\t\tplanner = { model, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\t// No request was made, but this candidate must not be retried.\n\t\tattempted.add(plannerAttemptKey({ model, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(preparation, attempt.ranges, plannerModel, plannerUsage);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { ProviderHeaders } from "@bastani/pi-ai";
2
- import type { Api, Model } from "@bastani/pi-ai/compat";
2
+ import type { Api, Model, Usage } from "@bastani/pi-ai/compat";
3
3
  import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
4
4
  import type { CompactionSettings } from "./compaction.ts";
5
5
  export declare const VERBATIM_COMPACTION_PROMPT_VERSION: 3;
@@ -132,6 +132,8 @@ export interface VerbatimCompactionResult {
132
132
  rung: CompactionRung;
133
133
  /** Present only when a borrowed fallback model ranked the lines. */
134
134
  plannerModel?: CompactionPlannerModel;
135
+ /** Aggregate usage across every planner request and retry in this compaction. */
136
+ usage?: Usage;
135
137
  backupPath?: string;
136
138
  }
137
139
  //# sourceMappingURL=compaction-types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,K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CAAC;CAC9B;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,EAAE,OAAO,4BAA4B,CAAC;IAC9C,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,UAAU,EAAE,4BAA4B,CAAC;IACzC,KAAK,EAAE,uBAAuB,CAAC;IAC/B,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,6BAA6B;IAC7C,0FAA0F;IAC1F,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,MAAM,EAAE,cAAc,CAAC;IACvB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,4BAA4B,CAAC;IACzC,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,uBAAuB,CAAC;IAC/B,UAAU,EAAE,4BAA4B,CAAC;IACzC,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
1
+ {"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+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yB;IACzC,QAAQ,EAAE,OAAO,4BAA4B,CAAC;IAC9C,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,UAAU,EAAE,4BAA4B,CAAC;IACzC,KAAK,EAAE,uBAAuB,CAAC;IAC/B,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,6BAA6B;IAC7C,0FAA0F;IAC1F,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,MAAM,EAAE,cAAc,CAAC;IACvB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,4BAA4B,CAAC;IACzC,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,uBAAuB,CAAC;IAC/B,UAAU,EAAE,4BAA4B,CAAC;IACzC,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,iFAAiF;IACjF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 3 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n"]}
1
+ {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 3 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { type RetryCallbacks, type RetryPolicy } from "@bastani/pi-ai";
2
- import type { Api, Model } from "@bastani/pi-ai/compat";
2
+ import type { Api, Model, Usage } from "@bastani/pi-ai/compat";
3
3
  import type { StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";
4
4
  import type { BorrowedPlanner, NumberedRegion, PlannerBudget, RawLineRange, VerbatimCompactionParameters } from "./compaction-types.js";
5
5
  import type { PlannerOutcome, TerminalPlannerOutcome } from "./planner-outcome.js";
@@ -20,6 +20,8 @@ export interface RangePlannerOptions {
20
20
  sessionFilePath?: string;
21
21
  retry?: RetryPolicy;
22
22
  callbacks?: RetryCallbacks;
23
+ /** Observe each completed provider attempt, including retries and overflow responses. */
24
+ onUsage?: (usage: Usage) => void;
23
25
  }
24
26
  /**
25
27
  * Parse the complete planner response text into deletion ranges.
@@ -1 +1 @@
1
- {"version":3,"file":"range-planner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/range-planner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,WAAW,EAA8B,MAAM,gBAAgB,CAAC;AACnG,OAAO,KAAK,EAAE,GAAG,EAAoB,KAAK,EAAuB,MAAM,uBAAuB,CAAC;AAE/F,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,KAAK,EACX,eAAe,EACf,cAAc,EACd,aAAa,EACb,YAAY,EACZ,4BAA4B,EAC5B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,c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,EAAE,4BAA4B,EACxC,OAAO,EAAE,eAAe,EACxB,eAAe,EAAE,MAAM,EACvB,OAAO,EAAE,mBAAmB,GAAG;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GACrD,OAAO,CAAC,cAAc,CAAC,CAyFzB"}
@@ -205,7 +205,11 @@ export async function planDeletedLineRanges(region, parameters, planner, targetK
205
205
  const retry = observeRetryActivity(options.callbacks);
206
206
  let response;
207
207
  try {
208
- response = await retryAssistantCall(async () => (await options.streamFn(model, context, request)).result(), options.retry, signal, retry.callbacks);
208
+ response = await retryAssistantCall(async () => {
209
+ const attemptResponse = await (await options.streamFn(model, context, request)).result();
210
+ options.onUsage?.(attemptResponse.usage);
211
+ return attemptResponse;
212
+ }, options.retry, signal, retry.callbacks);
209
213
  }
210
214
  catch (error) {
211
215
  if (signal?.aborted)
@@ -229,6 +233,12 @@ export async function planDeletedLineRanges(region, parameters, planner, targetK
229
233
  const message = response.errorMessage || "Compaction planner request exceeded the model context window";
230
234
  return providerFailureOutcome(options, model, response, text, message, false, retry.scheduled());
231
235
  }
236
+ // Deliberately before truncated-range recovery, unlike upstream 97fa14e39c:
237
+ // the planner request defines no tools, so a tool call is a derailed response
238
+ // and none of its partial ranges are salvaged.
239
+ if (response.content.some((block) => block.type === "toolCall")) {
240
+ return unusableOutcome(options, model, response, text, "malformed_output", "Compaction range planning attempted to call a tool");
241
+ }
232
242
  if (response.stopReason === "length") {
233
243
  const recovery = recoverTruncatedRecords(text);
234
244
  // The airlock returns validated line numbers, never raw model output.