@bastani/atomic 0.9.28-alpha.1 → 0.9.28-alpha.3

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 (332) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/native-client-licenses/NOTICE +2 -0
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/web-access/package.json +1 -1
  7. package/dist/builtin/workflows/CHANGELOG.md +34 -0
  8. package/dist/builtin/workflows/builtin/{chunk-wz8v67bn.js → chunk-aqv8ny38.js} +257 -259
  9. package/dist/builtin/workflows/builtin/{chunk-f61w0hpm.js → chunk-br4ac9a3.js} +1 -1
  10. package/dist/builtin/workflows/builtin/{chunk-tecnpe8j.js → chunk-p3xmajmj.js} +438 -39
  11. package/dist/builtin/workflows/builtin/chunk-p6jagvyf.js +8 -0
  12. package/dist/builtin/workflows/builtin/goal.js +2 -2
  13. package/dist/builtin/workflows/builtin/index.js +4 -4
  14. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  15. package/dist/builtin/workflows/package.json +1 -1
  16. package/dist/builtin/workflows/src/authoring.d.ts +14 -0
  17. package/dist/builtin/workflows/src/extension/index.bundle.mjs +111102 -110218
  18. package/dist/builtin/workflows/src/index.js +42284 -41141
  19. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +16 -11
  20. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +16 -1
  21. package/dist/cli/args.d.ts.map +1 -1
  22. package/dist/cli/args.js +8 -1
  23. package/dist/cli/args.js.map +1 -1
  24. package/dist/cli/credential-print.d.ts +1 -1
  25. package/dist/cli/credential-print.d.ts.map +1 -1
  26. package/dist/cli/credential-print.js +2 -56
  27. package/dist/cli/credential-print.js.map +1 -1
  28. package/dist/config.d.ts +2 -1
  29. package/dist/config.d.ts.map +1 -1
  30. package/dist/config.js +4 -2
  31. package/dist/config.js.map +1 -1
  32. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  33. package/dist/core/agent-session-accessors.js +6 -1
  34. package/dist/core/agent-session-accessors.js.map +1 -1
  35. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  36. package/dist/core/agent-session-compaction.js +20 -3
  37. package/dist/core/agent-session-compaction.js.map +1 -1
  38. package/dist/core/agent-session-events.d.ts.map +1 -1
  39. package/dist/core/agent-session-events.js +2 -1
  40. package/dist/core/agent-session-events.js.map +1 -1
  41. package/dist/core/agent-session-extension-bindings.d.ts +6 -0
  42. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  43. package/dist/core/agent-session-extension-bindings.js +90 -9
  44. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  45. package/dist/core/agent-session-methods.d.ts +3 -1
  46. package/dist/core/agent-session-methods.d.ts.map +1 -1
  47. package/dist/core/agent-session-methods.js.map +1 -1
  48. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  49. package/dist/core/agent-session-prompt.js +14 -1
  50. package/dist/core/agent-session-prompt.js.map +1 -1
  51. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  52. package/dist/core/agent-session-tool-registry.js +1 -0
  53. package/dist/core/agent-session-tool-registry.js.map +1 -1
  54. package/dist/core/agent-session-types.d.ts +2 -0
  55. package/dist/core/agent-session-types.d.ts.map +1 -1
  56. package/dist/core/agent-session-types.js.map +1 -1
  57. package/dist/core/agent-session.d.ts +1 -0
  58. package/dist/core/agent-session.d.ts.map +1 -1
  59. package/dist/core/agent-session.js +6 -1
  60. package/dist/core/agent-session.js.map +1 -1
  61. package/dist/core/bash-executor.d.ts.map +1 -1
  62. package/dist/core/bash-executor.js +22 -4
  63. package/dist/core/bash-executor.js.map +1 -1
  64. package/dist/core/child-session-options.d.ts.map +1 -1
  65. package/dist/core/child-session-options.js +17 -2
  66. package/dist/core/child-session-options.js.map +1 -1
  67. package/dist/core/compaction/classifier-compaction.d.ts +13 -0
  68. package/dist/core/compaction/classifier-compaction.d.ts.map +1 -0
  69. package/dist/core/compaction/classifier-compaction.js +110 -0
  70. package/dist/core/compaction/classifier-compaction.js.map +1 -0
  71. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  72. package/dist/core/compaction/compaction-boundary.js +2 -6
  73. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  74. package/dist/core/compaction/compaction-runner.d.ts +16 -1
  75. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  76. package/dist/core/compaction/compaction-runner.js +97 -12
  77. package/dist/core/compaction/compaction-runner.js.map +1 -1
  78. package/dist/core/compaction/compaction-types.d.ts +18 -1
  79. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  80. package/dist/core/compaction/compaction-types.js +1 -1
  81. package/dist/core/compaction/compaction-types.js.map +1 -1
  82. package/dist/core/compaction/fallback-planner.d.ts +1 -0
  83. package/dist/core/compaction/fallback-planner.d.ts.map +1 -1
  84. package/dist/core/compaction/fallback-planner.js +2 -0
  85. package/dist/core/compaction/fallback-planner.js.map +1 -1
  86. package/dist/core/compaction/index.d.ts +3 -0
  87. package/dist/core/compaction/index.d.ts.map +1 -1
  88. package/dist/core/compaction/index.js +3 -0
  89. package/dist/core/compaction/index.js.map +1 -1
  90. package/dist/core/compaction/model-resolver.d.ts +16 -0
  91. package/dist/core/compaction/model-resolver.d.ts.map +1 -0
  92. package/dist/core/compaction/model-resolver.js +18 -0
  93. package/dist/core/compaction/model-resolver.js.map +1 -0
  94. package/dist/core/compaction/morph-compaction.d.ts +14 -0
  95. package/dist/core/compaction/morph-compaction.d.ts.map +1 -0
  96. package/dist/core/compaction/morph-compaction.js +99 -0
  97. package/dist/core/compaction/morph-compaction.js.map +1 -0
  98. package/dist/core/compaction/pi-summary-fallback.d.ts +34 -0
  99. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -0
  100. package/dist/core/compaction/pi-summary-fallback.js +357 -0
  101. package/dist/core/compaction/pi-summary-fallback.js.map +1 -0
  102. package/dist/core/compaction/planner-outcome.d.ts +10 -6
  103. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  104. package/dist/core/compaction/planner-outcome.js +11 -4
  105. package/dist/core/compaction/planner-outcome.js.map +1 -1
  106. package/dist/core/compaction/range-planner-diagnostics.d.ts +3 -1
  107. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  108. package/dist/core/compaction/range-planner-diagnostics.js +11 -0
  109. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  110. package/dist/core/compaction/range-planner.d.ts +3 -3
  111. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  112. package/dist/core/compaction/range-planner.js +59 -28
  113. package/dist/core/compaction/range-planner.js.map +1 -1
  114. package/dist/core/compaction/region-trimming.d.ts.map +1 -1
  115. package/dist/core/compaction/region-trimming.js +7 -0
  116. package/dist/core/compaction/region-trimming.js.map +1 -1
  117. package/dist/core/compaction/structured-compaction-input.d.ts +19 -0
  118. package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -0
  119. package/dist/core/compaction/structured-compaction-input.js +70 -0
  120. package/dist/core/compaction/structured-compaction-input.js.map +1 -0
  121. package/dist/core/compaction/transcript-serialization.d.ts +1 -0
  122. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  123. package/dist/core/compaction/transcript-serialization.js +26 -0
  124. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  125. package/dist/core/extensions/api-types.d.ts +2 -2
  126. package/dist/core/extensions/api-types.d.ts.map +1 -1
  127. package/dist/core/extensions/api-types.js.map +1 -1
  128. package/dist/core/extensions/context-types.d.ts +1 -0
  129. package/dist/core/extensions/context-types.d.ts.map +1 -1
  130. package/dist/core/extensions/context-types.js.map +1 -1
  131. package/dist/core/extensions/loader-api.js.map +1 -1
  132. package/dist/core/extensions/loader-virtual-modules.d.ts +3 -4
  133. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  134. package/dist/core/extensions/loader-virtual-modules.js +14 -9
  135. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  136. package/dist/core/extensions/runner-context.d.ts +10 -4
  137. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  138. package/dist/core/extensions/runner-context.js +47 -3
  139. package/dist/core/extensions/runner-context.js.map +1 -1
  140. package/dist/core/extensions/runner.d.ts +10 -3
  141. package/dist/core/extensions/runner.d.ts.map +1 -1
  142. package/dist/core/extensions/runner.js +31 -7
  143. package/dist/core/extensions/runner.js.map +1 -1
  144. package/dist/core/extensions/tool-events.d.ts +1 -1
  145. package/dist/core/extensions/tool-events.js.map +1 -1
  146. package/dist/core/extensions/ts-source-specifiers.d.ts +18 -0
  147. package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -0
  148. package/dist/core/extensions/ts-source-specifiers.js +142 -0
  149. package/dist/core/extensions/ts-source-specifiers.js.map +1 -0
  150. package/dist/core/extensions/workflow-events.d.ts +49 -0
  151. package/dist/core/extensions/workflow-events.d.ts.map +1 -1
  152. package/dist/core/extensions/workflow-events.js.map +1 -1
  153. package/dist/core/extensions/workflow-run-control-hub.d.ts +16 -4
  154. package/dist/core/extensions/workflow-run-control-hub.d.ts.map +1 -1
  155. package/dist/core/extensions/workflow-run-control-hub.js +72 -1
  156. package/dist/core/extensions/workflow-run-control-hub.js.map +1 -1
  157. package/dist/core/extensions/workflow-run-control.d.ts +11 -3
  158. package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
  159. package/dist/core/extensions/workflow-run-control.js.map +1 -1
  160. package/dist/core/messages.d.ts +1 -0
  161. package/dist/core/messages.d.ts.map +1 -1
  162. package/dist/core/messages.js +5 -1
  163. package/dist/core/messages.js.map +1 -1
  164. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  165. package/dist/core/remote-catalog-provider.js +3 -0
  166. package/dist/core/remote-catalog-provider.js.map +1 -1
  167. package/dist/core/sdk-exports.d.ts +2 -2
  168. package/dist/core/sdk-exports.js.map +1 -1
  169. package/dist/core/sdk-types.d.ts +3 -0
  170. package/dist/core/sdk-types.d.ts.map +1 -1
  171. package/dist/core/sdk-types.js.map +1 -1
  172. package/dist/core/sdk.d.ts.map +1 -1
  173. package/dist/core/sdk.js +17 -8
  174. package/dist/core/sdk.js.map +1 -1
  175. package/dist/core/session-manager-history.d.ts.map +1 -1
  176. package/dist/core/session-manager-history.js +4 -2
  177. package/dist/core/session-manager-history.js.map +1 -1
  178. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  179. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  180. package/dist/core/settings-manager-basic-accessors.js +29 -0
  181. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  182. package/dist/core/settings-manager-core.js.map +1 -1
  183. package/dist/core/settings-merge.d.ts +3 -0
  184. package/dist/core/settings-merge.d.ts.map +1 -1
  185. package/dist/core/settings-merge.js +18 -4
  186. package/dist/core/settings-merge.js.map +1 -1
  187. package/dist/core/settings-storage.js.map +1 -1
  188. package/dist/core/settings-types.d.ts +1 -0
  189. package/dist/core/settings-types.d.ts.map +1 -1
  190. package/dist/core/settings-types.js.map +1 -1
  191. package/dist/core/transcript.d.ts +58 -0
  192. package/dist/core/transcript.d.ts.map +1 -0
  193. package/dist/core/transcript.js +185 -0
  194. package/dist/core/transcript.js.map +1 -0
  195. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  196. package/dist/extensions/codemode/execute.js +14 -1
  197. package/dist/extensions/codemode/execute.js.map +1 -1
  198. package/dist/extensions/codemode/tool.js +2 -2
  199. package/dist/extensions/codemode/tool.js.map +1 -1
  200. package/dist/extensions/herdr/index.d.ts.map +1 -1
  201. package/dist/extensions/herdr/index.js +15 -10
  202. package/dist/extensions/herdr/index.js.map +1 -1
  203. package/dist/extensions/herdr/pane-owner.d.ts +6 -2
  204. package/dist/extensions/herdr/pane-owner.d.ts.map +1 -1
  205. package/dist/extensions/herdr/pane-owner.js +19 -4
  206. package/dist/extensions/herdr/pane-owner.js.map +1 -1
  207. package/dist/extensions/llama/provider.d.ts.map +1 -1
  208. package/dist/extensions/llama/provider.js +19 -8
  209. package/dist/extensions/llama/provider.js.map +1 -1
  210. package/dist/extensions/mcp/cli.js +18 -24
  211. package/dist/extensions/mcp/cli.js.map +1 -1
  212. package/dist/extensions/mcp/client/auth-provider.d.ts +4 -0
  213. package/dist/extensions/mcp/client/auth-provider.d.ts.map +1 -1
  214. package/dist/extensions/mcp/client/auth-provider.js.map +1 -1
  215. package/dist/extensions/mcp/client/oauth/discovery.d.ts +3 -0
  216. package/dist/extensions/mcp/client/oauth/discovery.d.ts.map +1 -1
  217. package/dist/extensions/mcp/client/oauth/discovery.js +8 -5
  218. package/dist/extensions/mcp/client/oauth/discovery.js.map +1 -1
  219. package/dist/extensions/mcp/client/oauth/flow.d.ts +4 -0
  220. package/dist/extensions/mcp/client/oauth/flow.d.ts.map +1 -1
  221. package/dist/extensions/mcp/client/oauth/flow.js +12 -2
  222. package/dist/extensions/mcp/client/oauth/flow.js.map +1 -1
  223. package/dist/extensions/mcp/client/transports/streamable-http.d.ts +3 -0
  224. package/dist/extensions/mcp/client/transports/streamable-http.d.ts.map +1 -1
  225. package/dist/extensions/mcp/client/transports/streamable-http.js +17 -14
  226. package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
  227. package/dist/extensions/mcp/index.d.ts.map +1 -1
  228. package/dist/extensions/mcp/index.js +150 -72
  229. package/dist/extensions/mcp/index.js.map +1 -1
  230. package/dist/extensions/mcp/oauth.d.ts +5 -3
  231. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  232. package/dist/extensions/mcp/oauth.js +36 -10
  233. package/dist/extensions/mcp/oauth.js.map +1 -1
  234. package/dist/extensions/mcp/ui.d.ts +3 -3
  235. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  236. package/dist/extensions/mcp/ui.js +10 -2
  237. package/dist/extensions/mcp/ui.js.map +1 -1
  238. package/dist/index.d.ts +3 -1
  239. package/dist/index.d.ts.map +1 -1
  240. package/dist/index.js +2 -0
  241. package/dist/index.js.map +1 -1
  242. package/dist/main-deferred-startup.d.ts +1 -0
  243. package/dist/main-deferred-startup.d.ts.map +1 -1
  244. package/dist/main-deferred-startup.js +9 -21
  245. package/dist/main-deferred-startup.js.map +1 -1
  246. package/dist/main.d.ts.map +1 -1
  247. package/dist/main.js +8 -6
  248. package/dist/main.js.map +1 -1
  249. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
  250. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  251. package/dist/modes/interactive/components/compaction-boundary-message.js +15 -3
  252. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  253. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  254. package/dist/modes/interactive/components/settings-selector-items.js +43 -0
  255. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  256. package/dist/modes/interactive/components/settings-selector-types.d.ts +6 -0
  257. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  258. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  259. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  260. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  261. package/dist/modes/interactive/interactive-input-handling.js +1 -47
  262. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  263. package/dist/modes/interactive/interactive-mode-base.d.ts +0 -1
  264. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  265. package/dist/modes/interactive/interactive-mode-base.js +0 -1
  266. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  267. package/dist/modes/interactive/interactive-mode-surface.d.ts +0 -1
  268. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  269. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  270. package/dist/modes/interactive/interactive-prompt-restore.d.ts.map +1 -1
  271. package/dist/modes/interactive/interactive-prompt-restore.js +0 -5
  272. package/dist/modes/interactive/interactive-prompt-restore.js.map +1 -1
  273. package/dist/modes/interactive/interactive-prompt-turn.js +6 -4
  274. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  275. package/dist/modes/interactive/interactive-render-chat.js +13 -6
  276. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  277. package/dist/modes/interactive/interactive-selectors.js +8 -0
  278. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  279. package/dist/modes/interactive/interactive-session-runtime.js +2 -0
  280. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  281. package/dist/modes/interactive/interactive-startup.js +1 -1
  282. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  283. package/dist/modes/rpc/rpc-client-process.d.ts +7 -0
  284. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  285. package/dist/modes/rpc/rpc-client-process.js +20 -3
  286. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  287. package/dist/modes/rpc/rpc-command-timeouts.d.ts.map +1 -1
  288. package/dist/modes/rpc/rpc-command-timeouts.js +1 -0
  289. package/dist/modes/rpc/rpc-command-timeouts.js.map +1 -1
  290. package/dist/utils/ansi.d.ts +8 -0
  291. package/dist/utils/ansi.d.ts.map +1 -1
  292. package/dist/utils/ansi.js +29 -10
  293. package/dist/utils/ansi.js.map +1 -1
  294. package/dist/utils/clipboard.d.ts.map +1 -1
  295. package/dist/utils/clipboard.js +13 -3
  296. package/dist/utils/clipboard.js.map +1 -1
  297. package/dist/utils/credential-redaction.d.ts +2 -0
  298. package/dist/utils/credential-redaction.d.ts.map +1 -0
  299. package/dist/utils/credential-redaction.js +20 -0
  300. package/dist/utils/credential-redaction.js.map +1 -0
  301. package/dist/utils/image-resize-core.d.ts +8 -0
  302. package/dist/utils/image-resize-core.d.ts.map +1 -1
  303. package/dist/utils/image-resize-core.js +1 -0
  304. package/dist/utils/image-resize-core.js.map +1 -1
  305. package/dist/utils/image-resize-worker.js +3 -2
  306. package/dist/utils/image-resize-worker.js.map +1 -1
  307. package/dist/utils/image-resize.d.ts +2 -2
  308. package/dist/utils/image-resize.d.ts.map +1 -1
  309. package/dist/utils/image-resize.js +7 -10
  310. package/dist/utils/image-resize.js.map +1 -1
  311. package/docs/codemode.md +21 -1
  312. package/docs/compaction/reference.md +10 -4
  313. package/docs/compaction.md +40 -8
  314. package/docs/docs.json +1 -0
  315. package/docs/extensions/api-reference.md +4 -0
  316. package/docs/extensions/events.md +2 -2
  317. package/docs/llama-cpp.md +9 -2
  318. package/docs/mcp-servers.md +3 -3
  319. package/docs/models.md +10 -0
  320. package/docs/providers.md +39 -5
  321. package/docs/reference/cli.md +2 -2
  322. package/docs/sdk/reference.md +19 -4
  323. package/docs/sdk/web-server.md +325 -0
  324. package/docs/sdk.md +83 -1
  325. package/docs/security.md +1 -1
  326. package/docs/settings.md +2 -2
  327. package/docs/tools.md +1 -1
  328. package/docs/workflows/api-reference.md +71 -3
  329. package/docs/workflows/builtins.md +4 -0
  330. package/docs/workflows/operations.md +13 -5
  331. package/npm-shrinkwrap.json +32 -32
  332. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAU9F,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;AAC3F,OAAO,EAAE,wBA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AE,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, hasKeptTailTokenEstimate } 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\";\nimport { widenToWholeContextStats } from \"./whole-context-stats.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\n/**\n * Widen region-level transcript stats to whole-context stats (#2052).\n *\n * `result.stats` must be the symmetric region-only stats produced by\n * `reconstructCompactedTranscript`; this adds the independently estimated kept\n * tail to the heuristic before count on both sides — and, only when the tail is\n * kept, to the after count — via the shared `widenToWholeContextStats`. The\n * authoritative `preparation.tokensBefore` is deliberately absent from this\n * comparison and travels separately for budgeting/display.\n */\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\treturn {\n\t\t...result,\n\t\tstats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),\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\t// A kept tail with no registered estimate (a directly constructed\n\t// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).\n\tconst keptTail =\n\t\tpreparation.keptTailMessageCount === 0 ||\n\t\t(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);\n\treturn { transcript: buildFreshTranscript(preparation), keptTail };\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
+ {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAU9F,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,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEhE,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,2BAA2B,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C;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;gBAC7D,YAAY,GAAG,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3G,CAAC;QACF,CAAC;QACD,SAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1C,OAAO,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 {\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tRetryCallbacks,\n\tRetryPolicy,\n} 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 type { SessionEntry } from \"../session-manager-types.ts\";\nimport { planClassifierRanges } from \"./classifier-compaction.js\";\nimport { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } 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 { CompactionModelSelection } from \"./model-resolver.js\";\nimport { planMorphRanges } from \"./morph-compaction.js\";\nimport { runPiSummaryFallback } from \"./pi-summary-fallback.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 { writeMorphDiagnosticSidecar, writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\nimport { widenToWholeContextStats } from \"./whole-context-stats.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\tcompactionModel?: CompactionModelSelection;\n\tresolveMorphApiKey?: () => Promise<string | undefined>;\n\tmorphFetchFn?: typeof fetch;\n\tclassify?: (\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t) => Promise<ClassifierResult>;\n\tsummaryEntries?: SessionEntry[];\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\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\tsummaryFirstKeptEntryId?: string;\n\tsummaryTokensBefore?: number;\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\n/**\n * Widen region-level transcript stats to whole-context stats (#2052).\n *\n * `result.stats` must be the symmetric region-only stats produced by\n * `reconstructCompactedTranscript`; this adds the independently estimated kept\n * tail to the heuristic before count on both sides — and, only when the tail is\n * kept, to the after count — via the shared `widenToWholeContextStats`. The\n * authoritative `preparation.tokensBefore` is deliberately absent from this\n * comparison and travels separately for budgeting/display.\n */\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\treturn {\n\t\t...result,\n\t\tstats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),\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\t// A kept tail with no registered estimate (a directly constructed\n\t// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).\n\tconst keptTail =\n\t\tpreparation.keptTailMessageCount === 0 ||\n\t\t(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);\n\treturn { transcript: buildFreshTranscript(preparation), keptTail };\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\tmodel: string,\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\tbackend: \"planner\",\n\t\tmodel,\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\" || outcome.kind === \"policyRefusal\") {\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 selection = request.compactionModel ?? { kind: \"chat\", fullId: `${model.provider}/${model.id}`, model };\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, selectedModelId: selection.fullId })\n\t\t: undefined;\n\tlet backendFailure: TerminalPlannerOutcome | undefined;\n\tif (selection.kind === \"classifier\") {\n\t\ttry {\n\t\t\tconst classify = request.classify;\n\t\t\tif (!classify) throw new Error(\"Compaction classifier is unavailable\");\n\t\t\tconst ranges = await planClassifierRanges(\n\t\t\t\tpreparation.region,\n\t\t\t\tpreparation.parameters,\n\t\t\t\t(context) => classify(selection.model, context, { signal }),\n\t\t\t\tplannerOptions,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, plannerUsage, selection.fullId),\n\t\t\t\tbackend: \"classifier\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tif (selection.kind === \"morph\") {\n\t\ttry {\n\t\t\tconst ranges = await planMorphRanges(preparation.region, preparation.parameters, {\n\t\t\t\tapiKey: await request.resolveMorphApiKey?.(),\n\t\t\t\tsignal,\n\t\t\t\tfetchFn: request.morphFetchFn,\n\t\t\t\tonDiagnostics: (diagnostics) => writeMorphDiagnosticSidecar(request.sessionFilePath, diagnostics),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, undefined, selection.fullId),\n\t\t\t\tbackend: \"morph\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tconst primaryModel = selection.kind === \"chat\" ? selection.model : undefined;\n\tconst primaryBudget = resolvePlannerRequest(primaryModel ?? model, request.thinkingLevel);\n\tconst primaryAuth = primaryModel\n\t\t? await resolvePlannerAuth(request.resolveAuth, primaryModel)\n\t\t: {\n\t\t\t\tfailure: {\n\t\t\t\t\tkind: \"providerError\" as const,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\tbackendFailure?.kind === \"providerError\"\n\t\t\t\t\t\t\t? backendFailure.message\n\t\t\t\t\t\t\t: `Compaction backend ${selection.kind} is not yet available`,\n\t\t\t\t},\n\t\t\t};\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = primaryModel !== model;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (primaryModel && \"auth\" in primaryAuth) {\n\t\tplanner = { model: primaryModel, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\tif (primaryModel) attempted.add(plannerAttemptKey({ model: primaryModel, 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(\n\t\t\t\tpreparation,\n\t\t\t\tattempt.ranges,\n\t\t\t\tplannerModel,\n\t\t\t\tplannerUsage,\n\t\t\t\t`${planner.model.provider}/${planner.model.id}`,\n\t\t\t);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tif (attempt.outcome.kind === \"policyRefusal\" && request.summaryEntries) {\n\t\t\ttry {\n\t\t\t\tconst summary = await runPiSummaryFallback(\n\t\t\t\t\trequest.summaryEntries,\n\t\t\t\t\tpreparation.settings,\n\t\t\t\t\tplanner,\n\t\t\t\t\tplannerOptions,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext: summary.summary,\n\t\t\t\t\tranges: [],\n\t\t\t\t\tkeptRanges: [],\n\t\t\t\t\tstats: {\n\t\t\t\t\t\tlinesBefore: preparation.region.lines.length,\n\t\t\t\t\t\tlinesDeleted: 0,\n\t\t\t\t\t\tlinesKept: summary.summary.split(\"\\n\").length,\n\t\t\t\t\t\trangeCount: 0,\n\t\t\t\t\t\ttokensBefore: summary.tokensBefore,\n\t\t\t\t\t\ttokensAfter: summary.tokensAfter,\n\t\t\t\t\t\tpercentReduction:\n\t\t\t\t\t\t\tsummary.tokensBefore > 0 ? 100 * (1 - summary.tokensAfter / summary.tokensBefore) : 0,\n\t\t\t\t\t},\n\t\t\t\t\trung: \"planned\",\n\t\t\t\t\tkeptTail: true,\n\t\t\t\t\tbackend: \"summary\",\n\t\t\t\t\tmodel: `${planner.model.provider}/${planner.model.id}`,\n\t\t\t\t\tsummary: { readFiles: summary.readFiles, modifiedFiles: summary.modifiedFiles },\n\t\t\t\t\tsummaryFirstKeptEntryId: summary.firstKeptEntryId,\n\t\t\t\t\tsummaryTokensBefore: summary.tokensBefore,\n\t\t\t\t\t...(plannerUsage ? { usage: plannerUsage } : {}),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\tlastTerminal = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t}\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"]}
@@ -2,7 +2,7 @@ import type { ProviderHeaders } from "@bastani/pi-ai";
2
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
- export declare const VERBATIM_COMPACTION_PROMPT_VERSION: 3;
5
+ export declare const VERBATIM_COMPACTION_PROMPT_VERSION: 4;
6
6
  export declare const VERBATIM_COMPACTION_STRATEGY: "verbatim-lines";
7
7
  export declare const DEFAULT_COMPRESSION_RATIO = 0.5;
8
8
  export declare const DEFAULT_PRESERVE_RECENT = 2;
@@ -29,6 +29,11 @@ export interface RawLineRange {
29
29
  export interface NumberedRegion {
30
30
  readonly __brand: "NumberedRegion";
31
31
  lines: string[];
32
+ messageSpans?: {
33
+ role: "user" | "assistant" | "tool";
34
+ start: number;
35
+ end: number;
36
+ }[];
32
37
  headerLineNumbers: ReadonlySet<number>;
33
38
  priorMarkerNs: ReadonlyMap<number, number>;
34
39
  /** Optional future protected spans, expressed as one-based line numbers. */
@@ -108,6 +113,12 @@ export interface VerbatimCompactionDetails {
108
113
  parameters: VerbatimCompactionParameters;
109
114
  stats: VerbatimCompactionStats;
110
115
  rung: CompactionRung;
116
+ backend?: "planner" | "classifier" | "morph" | "summary";
117
+ model?: string;
118
+ summary?: {
119
+ readFiles: string[];
120
+ modifiedFiles: string[];
121
+ };
111
122
  /**
112
123
  * Authoritative whole-context count, projected for display only. Populated by
113
124
  * `createVerbatimCompactionMessage` on the rendered message; it is not
@@ -137,6 +148,12 @@ export interface VerbatimCompactionResult {
137
148
  parameters: VerbatimCompactionParameters;
138
149
  promptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;
139
150
  rung: CompactionRung;
151
+ backend?: "planner" | "classifier" | "morph" | "summary";
152
+ model?: string;
153
+ summary?: {
154
+ readFiles: string[];
155
+ modifiedFiles: string[];
156
+ };
140
157
  /** Present only when a borrowed fallback model ranked the lines. */
141
158
  plannerModel?: CompactionPlannerModel;
142
159
  /** Aggregate usage across every planner request and retry in this compaction. */
@@ -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,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,eAAO,MAAM,kCAAkC,EAAG,CAAU,CAAC;AAC7D,eAAO,MAAM,4BAA4B,EA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AAC;IAC/B,IAAI,EAAE,cAAc,CAAC;IACrB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,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
+ {"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+B,CAAC;AACnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,eA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AAG,SAAS,CAAC;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,EAAE,CAAC;QAAC,aAAa,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAC3D,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,iFAAiF;IACjF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
@@ -1,4 +1,4 @@
1
- export const VERBATIM_COMPACTION_PROMPT_VERSION = 3;
1
+ export const VERBATIM_COMPACTION_PROMPT_VERSION = 4;
2
2
  export const VERBATIM_COMPACTION_STRATEGY = "verbatim-lines";
3
3
  export const DEFAULT_COMPRESSION_RATIO = 0.5;
4
4
  export const DEFAULT_PRESERVE_RECENT = 2;
@@ -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, 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/**\n\t * Authoritative whole-context count, projected for display only. Populated by\n\t * `createVerbatimCompactionMessage` on the rendered message; it is not\n\t * persisted here — the durable entry already carries it as\n\t * `CompactionEntry.tokensBefore`.\n\t */\n\ttokensBefore?: number;\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
+ {"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 = 4 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\tmessageSpans?: { role: \"user\" | \"assistant\" | \"tool\"; start: number; end: number }[];\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\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/**\n\t * Authoritative whole-context count, projected for display only. Populated by\n\t * `createVerbatimCompactionMessage` on the rendered message; it is not\n\t * persisted here — the durable entry already carries it as\n\t * `CompactionEntry.tokensBefore`.\n\t */\n\ttokensBefore?: number;\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\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\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"]}
@@ -33,6 +33,7 @@ export interface FallbackPlannerContext {
33
33
  /** Session level inherited when a candidate carries no `:level` suffix. */
34
34
  readonly sessionThinkingLevel: ThinkingLevel | undefined;
35
35
  readonly isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;
36
+ readonly selectedModelId?: string;
36
37
  }
37
38
  /**
38
39
  * Identity of one planner attempt: `provider/model:<effective reasoning>`.
@@ -1 +1 @@
1
- {"version":3,"file":"fallback-planner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/fallback-planner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,KAAK,mBAAmB,EAAqC,MAAM,uBAAuB,CAAC;AACpG,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAG1E;;;;;;;GAOG;AACH,MAAM,WAAW,sBAAsB;IACtC,qEAAqE;IACrE,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,kEAAkE;IAClE,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAC;IACvC,iEAAiE;IACjE,QAA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AAC;IACvC,iEAAiE;IACjE,QAAQ,CAAC,iBAAiB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/C,2EAA2E;IAC3E,QAAQ,CAAC,oBAAoB,EAAE,aAAa,GAAG,SAAS,CAAC;IACzD,QAAQ,CAAC,sBAAsB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC;IAC7F,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CAClC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,CAElE;AAeD,+EAA+E;AAC/E,MAAM,MAAM,qBAAqB,GAAG,CACnC,SAAS,EAAE,WAAW,CAAC,MAAM,CAAC,EAC9B,WAAW,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,KAChE,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAAC;AAE1C;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,sBAAsB,GAAG,qBAAqB,CAgCpG"}
@@ -50,6 +50,8 @@ export function createFallbackPlannerBorrower(context) {
50
50
  const candidate = resolveFallbackModel(entry, context.registry, context.preferredProvider);
51
51
  if (!candidate)
52
52
  continue;
53
+ if (`${candidate.model.provider}/${candidate.model.id}` === context.selectedModelId)
54
+ continue;
53
55
  // Resolve the budget first: the identity depends on the effective
54
56
  // reasoning level, which inheritance may supply.
55
57
  const budget = resolvePlannerRequest(candidate.model, context.sessionThinkingLevel, candidate.thinkingLevel);
@@ -1 +1 @@
1
- {"version":3,"file":"fallback-planner.js","sourceRoot":"","sources":["../../../src/core/compaction/fallback-planner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAA4B,WAAW,EAAE,oBAAoB,EAAE,MA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,CAAC;YAEvB,IAAI,IAA6B,CAAC;YAClC,IAAI,CAAC;gBACJ,IAAI,GAAG,MAAM,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;YAC3C,CAAC;YAAC,MAAM,CAAC;gBACR,uEAAuE;gBACvE,IAAI,GAAG,SAAS,CAAC;YAClB,CAAC;YACD,IAAI,CAAC,IAAI;gBAAE,SAAS;YACpB,IAAI,OAAO,CAAC,sBAAsB,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,SAAS,CAAC;gBACvG,SAAS;YACV,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QACjD,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC,CAAC;AACH,CAAC","sourcesContent":["/**\n * Borrow a configured fallback model for one compaction planner request.\n *\n * This is deliberately a *weaker* capability than main-chat model fallback. The\n * borrowing door returns a `BorrowedPlanner` **value**: it holds no session\n * handle, so it cannot write `agent.state.model`, append a model-change entry,\n * change the session thinking level, refresh the system prompt, emit\n * `model_changed`/`model_select`, or call `agent.continue()`.\n * `_trySwitchToFallbackModel` does all of those and is not reused or modified.\n *\n * The attempted-key set belongs to the compaction run and is read-only here, so\n * borrowing never touches the main chat's `_fallbackAttemptedKeys`.\n */\n\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { type FallbackModelLookup, fallbackKey, resolveFallbackModel } from \"../fallback-models.ts\";\nimport type { BorrowedPlanner, PlannerAuth } from \"./compaction-types.js\";\nimport { resolvePlannerRequest } from \"./range-planner.js\";\n\n/**\n * Everything candidate selection needs.\n *\n * The RFC's §5.1 signature takes only `attempted` and `resolveAuth`, which\n * cannot select a candidate on its own: it names no fallback list, no model\n * registry, no preferred provider, and no inherited reasoning level. Those\n * inputs travel in this context object rather than through hidden state.\n */\nexport interface FallbackPlannerContext {\n\t/** The session's effective `fallbackModels`, in configured order. */\n\treadonly fallbackModels: readonly string[];\n\t/** Model registry used to resolve and authenticate candidates. */\n\treadonly registry: FallbackModelLookup;\n\t/** Provider preferred when an unqualified entry is ambiguous. */\n\treadonly preferredProvider: string | undefined;\n\t/** Session level inherited when a candidate carries no `:level` suffix. */\n\treadonly sessionThinkingLevel: ThinkingLevel | undefined;\n\treadonly isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n}\n\n/**\n * Identity of one planner attempt: `provider/model:<effective reasoning>`.\n *\n * The key must be derived from the *effective* level the request will carry,\n * not from the raw optional `model:level` suffix. An unsuffixed entry for the\n * session model inherits the session level, so keying it as `provider/model:`\n * would let the identical request run a second time.\n */\nexport function plannerAttemptKey(planner: BorrowedPlanner): string {\n\treturn fallbackKey(planner.model, planner.budget.reasoning);\n}\n\n/**\n * Run-local traversal state for one compaction's fallback walk.\n *\n * Kept out of the borrower's arguments and out of module scope: concurrent\n * compactions each own one of these, so nothing is shared.\n */\ninterface FallbackPlannerWalk {\n\t/** Next configured list position to inspect. Only ever advances. */\n\tnextIndex: number;\n\t/** Effective `provider/model:level` identities already inspected this run. */\n\tconsumed: Set<string>;\n}\n\n/** The exact two-argument borrowing door, bound to one run's configuration. */\nexport type BorrowFallbackPlanner = (\n\tattempted: ReadonlySet<string>,\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>,\n) => Promise<BorrowedPlanner | undefined>;\n\n/**\n * Build the borrowing door for one compaction run.\n *\n * The RFC's top-level two-argument signature names no fallback list, registry,\n * preferred provider, inherited reasoning level, or traversal cursor, so a\n * stateless exported function cannot select a candidate without hidden shared\n * state — unsafe under concurrent compactions. Binding the configuration and the\n * run-local cursor in a closure keeps the returned door exactly two arguments\n * while `attempted` stays a `ReadonlySet` the borrower never writes.\n *\n * The walk is one monotonic pass. Each list position is inspected at most once,\n * whether it fails to resolve, has no usable credentials, duplicates an earlier\n * identity, or yields a planner. Without the cursor, an entry that could not\n * resolve earlier could be returned after a later candidate once the registry\n * changed, producing a B→A order the configured list never asked for.\n */\nexport function createFallbackPlannerBorrower(context: FallbackPlannerContext): BorrowFallbackPlanner {\n\tconst walk: FallbackPlannerWalk = { nextIndex: 0, consumed: new Set<string>() };\n\treturn async (attempted, resolveAuth) => {\n\t\twhile (walk.nextIndex < context.fallbackModels.length) {\n\t\t\tconst entry = context.fallbackModels[walk.nextIndex];\n\t\t\t// Advance before any work: this list position is spent either way.\n\t\t\twalk.nextIndex += 1;\n\n\t\t\tconst candidate = resolveFallbackModel(entry, context.registry, context.preferredProvider);\n\t\t\tif (!candidate) continue;\n\t\t\t// Resolve the budget first: the identity depends on the effective\n\t\t\t// reasoning level, which inheritance may supply.\n\t\t\tconst budget = resolvePlannerRequest(candidate.model, context.sessionThinkingLevel, candidate.thinkingLevel);\n\t\t\tconst key = fallbackKey(candidate.model, budget.reasoning);\n\t\t\tif (attempted.has(key) || walk.consumed.has(key)) continue;\n\t\t\twalk.consumed.add(key);\n\n\t\t\tlet auth: PlannerAuth | undefined;\n\t\t\ttry {\n\t\t\t\tauth = await resolveAuth(candidate.model);\n\t\t\t} catch {\n\t\t\t\t// A candidate whose credentials cannot be resolved is simply unusable.\n\t\t\t\tauth = undefined;\n\t\t\t}\n\t\t\tif (!auth) continue;\n\t\t\tif (context.isFallbackModelAllowed && !context.isFallbackModelAllowed(candidate.model, budget.reasoning))\n\t\t\t\tcontinue;\n\t\t\treturn { model: candidate.model, budget, auth };\n\t\t}\n\t\treturn undefined;\n\t};\n}\n"]}
1
+ {"version":3,"file":"fallback-planner.js","sourceRoot":"","sources":["../../../src/core/compaction/fallback-planner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAA4B,WAAW,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEpG,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAuB3D;;;;;;;GAOG;AACH,MAAM,UAAU,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G,CAAC,GAAG,CAAC,CAAC;YAEvB,IAAI,IAA6B,CAAC;YAClC,IAAI,CAAC;gBACJ,IAAI,GAAG,MAAM,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;YAC3C,CAAC;YAAC,MAAM,CAAC;gBACR,uEAAuE;gBACvE,IAAI,GAAG,SAAS,CAAC;YAClB,CAAC;YACD,IAAI,CAAC,IAAI;gBAAE,SAAS;YACpB,IAAI,OAAO,CAAC,sBAAsB,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,SAAS,CAAC;gBACvG,SAAS;YACV,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QACjD,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC,CAAC;AACH,CAAC","sourcesContent":["/**\n * Borrow a configured fallback model for one compaction planner request.\n *\n * This is deliberately a *weaker* capability than main-chat model fallback. The\n * borrowing door returns a `BorrowedPlanner` **value**: it holds no session\n * handle, so it cannot write `agent.state.model`, append a model-change entry,\n * change the session thinking level, refresh the system prompt, emit\n * `model_changed`/`model_select`, or call `agent.continue()`.\n * `_trySwitchToFallbackModel` does all of those and is not reused or modified.\n *\n * The attempted-key set belongs to the compaction run and is read-only here, so\n * borrowing never touches the main chat's `_fallbackAttemptedKeys`.\n */\n\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { type FallbackModelLookup, fallbackKey, resolveFallbackModel } from \"../fallback-models.ts\";\nimport type { BorrowedPlanner, PlannerAuth } from \"./compaction-types.js\";\nimport { resolvePlannerRequest } from \"./range-planner.js\";\n\n/**\n * Everything candidate selection needs.\n *\n * The RFC's §5.1 signature takes only `attempted` and `resolveAuth`, which\n * cannot select a candidate on its own: it names no fallback list, no model\n * registry, no preferred provider, and no inherited reasoning level. Those\n * inputs travel in this context object rather than through hidden state.\n */\nexport interface FallbackPlannerContext {\n\t/** The session's effective `fallbackModels`, in configured order. */\n\treadonly fallbackModels: readonly string[];\n\t/** Model registry used to resolve and authenticate candidates. */\n\treadonly registry: FallbackModelLookup;\n\t/** Provider preferred when an unqualified entry is ambiguous. */\n\treadonly preferredProvider: string | undefined;\n\t/** Session level inherited when a candidate carries no `:level` suffix. */\n\treadonly sessionThinkingLevel: ThinkingLevel | undefined;\n\treadonly isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n\treadonly selectedModelId?: string;\n}\n\n/**\n * Identity of one planner attempt: `provider/model:<effective reasoning>`.\n *\n * The key must be derived from the *effective* level the request will carry,\n * not from the raw optional `model:level` suffix. An unsuffixed entry for the\n * session model inherits the session level, so keying it as `provider/model:`\n * would let the identical request run a second time.\n */\nexport function plannerAttemptKey(planner: BorrowedPlanner): string {\n\treturn fallbackKey(planner.model, planner.budget.reasoning);\n}\n\n/**\n * Run-local traversal state for one compaction's fallback walk.\n *\n * Kept out of the borrower's arguments and out of module scope: concurrent\n * compactions each own one of these, so nothing is shared.\n */\ninterface FallbackPlannerWalk {\n\t/** Next configured list position to inspect. Only ever advances. */\n\tnextIndex: number;\n\t/** Effective `provider/model:level` identities already inspected this run. */\n\tconsumed: Set<string>;\n}\n\n/** The exact two-argument borrowing door, bound to one run's configuration. */\nexport type BorrowFallbackPlanner = (\n\tattempted: ReadonlySet<string>,\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>,\n) => Promise<BorrowedPlanner | undefined>;\n\n/**\n * Build the borrowing door for one compaction run.\n *\n * The RFC's top-level two-argument signature names no fallback list, registry,\n * preferred provider, inherited reasoning level, or traversal cursor, so a\n * stateless exported function cannot select a candidate without hidden shared\n * state — unsafe under concurrent compactions. Binding the configuration and the\n * run-local cursor in a closure keeps the returned door exactly two arguments\n * while `attempted` stays a `ReadonlySet` the borrower never writes.\n *\n * The walk is one monotonic pass. Each list position is inspected at most once,\n * whether it fails to resolve, has no usable credentials, duplicates an earlier\n * identity, or yields a planner. Without the cursor, an entry that could not\n * resolve earlier could be returned after a later candidate once the registry\n * changed, producing a B→A order the configured list never asked for.\n */\nexport function createFallbackPlannerBorrower(context: FallbackPlannerContext): BorrowFallbackPlanner {\n\tconst walk: FallbackPlannerWalk = { nextIndex: 0, consumed: new Set<string>() };\n\treturn async (attempted, resolveAuth) => {\n\t\twhile (walk.nextIndex < context.fallbackModels.length) {\n\t\t\tconst entry = context.fallbackModels[walk.nextIndex];\n\t\t\t// Advance before any work: this list position is spent either way.\n\t\t\twalk.nextIndex += 1;\n\n\t\t\tconst candidate = resolveFallbackModel(entry, context.registry, context.preferredProvider);\n\t\t\tif (!candidate) continue;\n\t\t\tif (`${candidate.model.provider}/${candidate.model.id}` === context.selectedModelId) continue;\n\t\t\t// Resolve the budget first: the identity depends on the effective\n\t\t\t// reasoning level, which inheritance may supply.\n\t\t\tconst budget = resolvePlannerRequest(candidate.model, context.sessionThinkingLevel, candidate.thinkingLevel);\n\t\t\tconst key = fallbackKey(candidate.model, budget.reasoning);\n\t\t\tif (attempted.has(key) || walk.consumed.has(key)) continue;\n\t\t\twalk.consumed.add(key);\n\n\t\t\tlet auth: PlannerAuth | undefined;\n\t\t\ttry {\n\t\t\t\tauth = await resolveAuth(candidate.model);\n\t\t\t} catch {\n\t\t\t\t// A candidate whose credentials cannot be resolved is simply unusable.\n\t\t\t\tauth = undefined;\n\t\t\t}\n\t\t\tif (!auth) continue;\n\t\t\tif (context.isFallbackModelAllowed && !context.isFallbackModelAllowed(candidate.model, budget.reasoning))\n\t\t\t\tcontinue;\n\t\t\treturn { model: candidate.model, budget, auth };\n\t\t}\n\t\treturn undefined;\n\t};\n}\n"]}
@@ -9,11 +9,14 @@ export * from "./compaction-runner.js";
9
9
  export * from "./compaction-types.js";
10
10
  export * from "./deleted-ranges.js";
11
11
  export * from "./fallback-planner.js";
12
+ export * from "./model-resolver.js";
13
+ export * from "./pi-summary-fallback.js";
12
14
  export * from "./planner-outcome.js";
13
15
  export * from "./range-planner.js";
14
16
  export * from "./range-planner-diagnostics.js";
15
17
  export * from "./region-trimming.js";
16
18
  export * from "./session-summarization.ts";
19
+ export * from "./structured-compaction-input.js";
17
20
  export * from "./transcript-serialization.js";
18
21
  export * from "./utils.ts";
19
22
  export * from "./whole-context-stats.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,0BAA0B,CAAC;AACzC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,kCAAkC,CAAC;AACjD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC"}
@@ -9,11 +9,14 @@ export * from "./compaction-runner.js";
9
9
  export * from "./compaction-types.js";
10
10
  export * from "./deleted-ranges.js";
11
11
  export * from "./fallback-planner.js";
12
+ export * from "./model-resolver.js";
13
+ export * from "./pi-summary-fallback.js";
12
14
  export * from "./planner-outcome.js";
13
15
  export * from "./range-planner.js";
14
16
  export * from "./range-planner-diagnostics.js";
15
17
  export * from "./region-trimming.js";
16
18
  export * from "./session-summarization.js";
19
+ export * from "./structured-compaction-input.js";
17
20
  export * from "./transcript-serialization.js";
18
21
  export * from "./utils.js";
19
22
  export * from "./whole-context-stats.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC","sourcesContent":["/**\n * Compaction support utilities.\n */\n\nexport * from \"./branch-summarization.ts\";\nexport * from \"./compaction.ts\";\nexport * from \"./compaction-boundary.js\";\nexport * from \"./compaction-parameters.js\";\nexport * from \"./compaction-runner.js\";\nexport * from \"./compaction-types.js\";\nexport * from \"./deleted-ranges.js\";\nexport * from \"./fallback-planner.js\";\nexport * from \"./planner-outcome.js\";\nexport * from \"./range-planner.js\";\nexport * from \"./range-planner-diagnostics.js\";\nexport * from \"./region-trimming.js\";\nexport * from \"./session-summarization.ts\";\nexport * from \"./transcript-serialization.js\";\nexport * from \"./utils.ts\";\nexport * from \"./whole-context-stats.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,0BAA0B,CAAC;AACzC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,kCAAkC,CAAC;AACjD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC","sourcesContent":["/**\n * Compaction support utilities.\n */\n\nexport * from \"./branch-summarization.ts\";\nexport * from \"./compaction.ts\";\nexport * from \"./compaction-boundary.js\";\nexport * from \"./compaction-parameters.js\";\nexport * from \"./compaction-runner.js\";\nexport * from \"./compaction-types.js\";\nexport * from \"./deleted-ranges.js\";\nexport * from \"./fallback-planner.js\";\nexport * from \"./model-resolver.js\";\nexport * from \"./pi-summary-fallback.js\";\nexport * from \"./planner-outcome.js\";\nexport * from \"./range-planner.js\";\nexport * from \"./range-planner-diagnostics.js\";\nexport * from \"./region-trimming.js\";\nexport * from \"./session-summarization.ts\";\nexport * from \"./structured-compaction-input.js\";\nexport * from \"./transcript-serialization.js\";\nexport * from \"./utils.ts\";\nexport * from \"./whole-context-stats.js\";\n"]}
@@ -0,0 +1,16 @@
1
+ import { type AnyModel, type ClassifierApi, type ClassifierModel } from "@bastani/pi-ai";
2
+ import type { Api, Model } from "@bastani/pi-ai/compat";
3
+ export type CompactionModelSelection = {
4
+ kind: "chat";
5
+ fullId: string;
6
+ model: Model<Api>;
7
+ } | {
8
+ kind: "classifier";
9
+ fullId: string;
10
+ model: ClassifierModel<ClassifierApi>;
11
+ } | {
12
+ kind: "morph";
13
+ fullId: string;
14
+ };
15
+ export declare function resolveCompactionModel(configured: string, currentModel: Model<Api>, models: readonly AnyModel[]): CompactionModelSelection;
16
+ //# sourceMappingURL=model-resolver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-resolver.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/model-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAE,KAAK,aAAa,EAAE,KAAK,eAAe,EAAe,MAAM,gBAAgB,CAAC;AACtG,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAExD,MAAM,MAAM,wBAAwB,GACjC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;CAAE,GACnD;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,eAAe,CAAC,aAAa,CAAC,CAAA;CAAE,GAC7E;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAErC,wBAAgB,sBAAsB,CACrC,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,EACxB,MAAM,EAAE,SAAS,QAAQ,EAAE,GACzB,wBAAwB,CAe1B"}
@@ -0,0 +1,18 @@
1
+ import { isModelType } from "@bastani/pi-ai";
2
+ export function resolveCompactionModel(configured, currentModel, models) {
3
+ if (typeof configured !== "string" || configured.trim() !== configured) {
4
+ throw new Error("Invalid compactionModel: use an exact provider/model ID, auto, or an empty string.");
5
+ }
6
+ if (configured === "" || configured === "auto") {
7
+ return { kind: "chat", fullId: `${currentModel.provider}/${currentModel.id}`, model: currentModel };
8
+ }
9
+ const model = models.find((candidate) => `${candidate.provider}/${candidate.id}` === configured);
10
+ if (model && isModelType(model, "chat"))
11
+ return { kind: "chat", fullId: configured, model };
12
+ if (model && isModelType(model, "classifier"))
13
+ return { kind: "classifier", fullId: configured, model };
14
+ if (model && isModelType(model, "compactor") && configured === "morph/morph-compactor")
15
+ return { kind: "morph", fullId: configured };
16
+ throw new Error("Invalid compactionModel: the exact model is not in the current chat, classifier, or compactor catalog.");
17
+ }
18
+ //# sourceMappingURL=model-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../../src/core/compaction/model-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2D,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAQtG,MAAM,UAAU,sBAAsB,CACrC,UAAkB,EAClB,YAAwB,EACxB,MAA2B;IAE3B,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,IAAI,EAAE,KAAK,UAAU,EAAE,CAAC;QACxE,MAAM,IAAI,KAAK,CAAC,oFAAoF,CAAC,CAAC;IACvG,CAAC;IACD,IAAI,UAAU,KAAK,EAAE,IAAI,UAAU,KAAK,MAAM,EAAE,CAAC;QAChD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,YAAY,CAAC,QAAQ,IAAI,YAAY,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;IACrG,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,GAAG,SAAS,CAAC,QAAQ,IAAI,SAAS,CAAC,EAAE,EAAE,KAAK,UAAU,CAAC,CAAC;IACjG,IAAI,KAAK,IAAI,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC5F,IAAI,KAAK,IAAI,WAAW,CAAC,KAAK,EAAE,YAAY,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IACxG,IAAI,KAAK,IAAI,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,IAAI,UAAU,KAAK,uBAAuB;QACrF,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAC9C,MAAM,IAAI,KAAK,CACd,wGAAwG,CACxG,CAAC;AACH,CAAC","sourcesContent":["import { type AnyModel, type ClassifierApi, type ClassifierModel, isModelType } from \"@bastani/pi-ai\";\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\n\nexport type CompactionModelSelection =\n\t| { kind: \"chat\"; fullId: string; model: Model<Api> }\n\t| { kind: \"classifier\"; fullId: string; model: ClassifierModel<ClassifierApi> }\n\t| { kind: \"morph\"; fullId: string };\n\nexport function resolveCompactionModel(\n\tconfigured: string,\n\tcurrentModel: Model<Api>,\n\tmodels: readonly AnyModel[],\n): CompactionModelSelection {\n\tif (typeof configured !== \"string\" || configured.trim() !== configured) {\n\t\tthrow new Error(\"Invalid compactionModel: use an exact provider/model ID, auto, or an empty string.\");\n\t}\n\tif (configured === \"\" || configured === \"auto\") {\n\t\treturn { kind: \"chat\", fullId: `${currentModel.provider}/${currentModel.id}`, model: currentModel };\n\t}\n\tconst model = models.find((candidate) => `${candidate.provider}/${candidate.id}` === configured);\n\tif (model && isModelType(model, \"chat\")) return { kind: \"chat\", fullId: configured, model };\n\tif (model && isModelType(model, \"classifier\")) return { kind: \"classifier\", fullId: configured, model };\n\tif (model && isModelType(model, \"compactor\") && configured === \"morph/morph-compactor\")\n\t\treturn { kind: \"morph\", fullId: configured };\n\tthrow new Error(\n\t\t\"Invalid compactionModel: the exact model is not in the current chat, classifier, or compactor catalog.\",\n\t);\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import type { LineRange, NumberedRegion, VerbatimCompactionParameters } from "./compaction-types.js";
2
+ export interface MorphRangeDiagnostics {
3
+ droppedRangeCount: number;
4
+ acceptedRangeCount: number;
5
+ failureCategory?: "provider_error" | "policy_refusal";
6
+ failureMessage?: string;
7
+ }
8
+ export declare function planMorphRanges(region: NumberedRegion, parameters: VerbatimCompactionParameters, options: {
9
+ apiKey: string | undefined;
10
+ signal?: AbortSignal;
11
+ fetchFn?: typeof fetch;
12
+ onDiagnostics?: (diagnostics: MorphRangeDiagnostics) => void;
13
+ }): Promise<LineRange[]>;
14
+ //# sourceMappingURL=morph-compaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"morph-compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/morph-compaction.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAarG,MAAM,WAAW,qBAAqB;IACrC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,eAAe,CAAC,EAAE,gBAAgB,GAAG,gBAAgB,CAAC;IACtD,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAuCD,wBAAsB,eAAe,CACpC,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,4BAA4B,EACxC,OAAO,EAAE;IACR,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,OAAO,CAAC,EAAE,OAAO,KAAK,CAAC;IACvB,aAAa,CAAC,EAAE,CAAC,WAAW,EAAE,qBAAqB,KAAK,IAAI,CAAC;CAC7D,GACC,OAAO,CAAC,SAAS,EAAE,CAAC,CAiDtB"}
@@ -0,0 +1,99 @@
1
+ import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
3
+ import { redactCredentialShapes } from "../../utils/credential-redaction.js";
4
+ import { validateDeletedRanges } from "./deleted-ranges.js";
5
+ import { isProviderPolicyRefusal } from "./planner-outcome.js";
6
+ import { buildStructuredCompactionInput, mapMessageRanges } from "./structured-compaction-input.js";
7
+ const responseSchema = Type.Object({
8
+ messages: Type.Array(Type.Object({
9
+ compacted_line_ranges: Type.Array(Type.Object({ start: Type.Number(), end: Type.Number() })),
10
+ })),
11
+ });
12
+ const HTTP_ERROR_EXCERPT_MAX_CHARS = 500;
13
+ const HTTP_ERROR_BODY_MAX_BYTES = 8192;
14
+ async function readHttpErrorBody(response) {
15
+ if (!response.body)
16
+ return "";
17
+ const reader = response.body.getReader();
18
+ const decoder = new TextDecoder();
19
+ let bytes = 0;
20
+ let text = "";
21
+ try {
22
+ while (bytes < HTTP_ERROR_BODY_MAX_BYTES) {
23
+ const { done, value } = await reader.read();
24
+ if (done)
25
+ return text + decoder.decode();
26
+ const remaining = HTTP_ERROR_BODY_MAX_BYTES - bytes;
27
+ text += decoder.decode(value.subarray(0, remaining), { stream: true });
28
+ bytes += value.length;
29
+ }
30
+ const completeLinesEnd = Math.max(0, text.lastIndexOf("\n"));
31
+ return text.slice(0, completeLinesEnd);
32
+ }
33
+ catch {
34
+ return "";
35
+ }
36
+ finally {
37
+ await reader.cancel().catch(() => { });
38
+ reader.releaseLock();
39
+ }
40
+ }
41
+ async function morphHttpErrorMessage(response, apiKey) {
42
+ const body = await readHttpErrorBody(response);
43
+ const excerpt = redactCredentialShapes(body.replaceAll(apiKey, "[redacted]"))
44
+ .replace(/[\x00-\x1f\x7f-\x9f]/g, " ")
45
+ .replace(/\s+/g, " ")
46
+ .trim()
47
+ .slice(0, HTTP_ERROR_EXCERPT_MAX_CHARS);
48
+ return `Morph compaction HTTP ${response.status}${excerpt ? `: ${excerpt}` : ""}`;
49
+ }
50
+ export async function planMorphRanges(region, parameters, options) {
51
+ if (options.signal?.aborted)
52
+ throw new Error("Compaction cancelled");
53
+ if (!options.apiKey)
54
+ throw new Error("Morph compaction requires /login morph or MORPH_API_KEY");
55
+ const input = buildStructuredCompactionInput(region, parameters);
56
+ const response = await (options.fetchFn ?? fetch)("https://api.morphllm.com/v1/compact", {
57
+ method: "POST",
58
+ headers: { Authorization: `Bearer ${options.apiKey}`, "Content-Type": "application/json" },
59
+ body: JSON.stringify({
60
+ messages: input.messages.map((message) => ({ role: message.role, content: message.lines.join("\n") })),
61
+ query: input.query,
62
+ compression_ratio: input.compression_ratio,
63
+ preserve_recent: 0,
64
+ include_markers: false,
65
+ }),
66
+ signal: options.signal,
67
+ });
68
+ if (!response.ok) {
69
+ const message = await morphHttpErrorMessage(response, options.apiKey);
70
+ options.onDiagnostics?.({
71
+ droppedRangeCount: 0,
72
+ acceptedRangeCount: 0,
73
+ failureCategory: isProviderPolicyRefusal(message) ? "policy_refusal" : "provider_error",
74
+ failureMessage: message,
75
+ });
76
+ throw new Error(message);
77
+ }
78
+ const body = await response.json();
79
+ if (!Value.Check(responseSchema, body) || body.messages.length !== input.messages.length)
80
+ throw new Error("Malformed Morph compaction response");
81
+ let droppedRangeCount = 0;
82
+ const records = body.messages.flatMap((message, index) => message.compacted_line_ranges.flatMap((range) => {
83
+ if (!Number.isSafeInteger(range.start) ||
84
+ !Number.isSafeInteger(range.end) ||
85
+ range.start < 1 ||
86
+ range.end < range.start ||
87
+ range.end > input.messages[index].lines.length) {
88
+ droppedRangeCount++;
89
+ return [];
90
+ }
91
+ return [{ id: input.messages[index].id, ...range }];
92
+ }));
93
+ options.onDiagnostics?.({ droppedRangeCount, acceptedRangeCount: records.length });
94
+ const ranges = validateDeletedRanges(mapMessageRanges(records, input), region);
95
+ if (!ranges.length)
96
+ throw new Error("Morph compaction produced no usable ranges");
97
+ return [...ranges];
98
+ }
99
+ //# sourceMappingURL=morph-compaction.js.map
@@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AkB,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IACnF,MAAM,MAAM,GAAG,qBAAqB,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,CAAC,CAAC;IAC/E,IAAI,CAAC,MAAM,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC;AACpB,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport { Value } from \"typebox/value\";\nimport { redactCredentialShapes } from \"../../utils/credential-redaction.js\";\nimport type { LineRange, NumberedRegion, VerbatimCompactionParameters } from \"./compaction-types.js\";\nimport { validateDeletedRanges } from \"./deleted-ranges.js\";\nimport { isProviderPolicyRefusal } from \"./planner-outcome.js\";\nimport { buildStructuredCompactionInput, mapMessageRanges } from \"./structured-compaction-input.js\";\n\nconst responseSchema = Type.Object({\n\tmessages: Type.Array(\n\t\tType.Object({\n\t\t\tcompacted_line_ranges: Type.Array(Type.Object({ start: Type.Number(), end: Type.Number() })),\n\t\t}),\n\t),\n});\n\nexport interface MorphRangeDiagnostics {\n\tdroppedRangeCount: number;\n\tacceptedRangeCount: number;\n\tfailureCategory?: \"provider_error\" | \"policy_refusal\";\n\tfailureMessage?: string;\n}\n\nconst HTTP_ERROR_EXCERPT_MAX_CHARS = 500;\nconst HTTP_ERROR_BODY_MAX_BYTES = 8192;\n\nasync function readHttpErrorBody(response: Response): Promise<string> {\n\tif (!response.body) return \"\";\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet bytes = 0;\n\tlet text = \"\";\n\ttry {\n\t\twhile (bytes < HTTP_ERROR_BODY_MAX_BYTES) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) return text + decoder.decode();\n\t\t\tconst remaining = HTTP_ERROR_BODY_MAX_BYTES - bytes;\n\t\t\ttext += decoder.decode(value.subarray(0, remaining), { stream: true });\n\t\t\tbytes += value.length;\n\t\t}\n\t\tconst completeLinesEnd = Math.max(0, text.lastIndexOf(\"\\n\"));\n\t\treturn text.slice(0, completeLinesEnd);\n\t} catch {\n\t\treturn \"\";\n\t} finally {\n\t\tawait reader.cancel().catch(() => {});\n\t\treader.releaseLock();\n\t}\n}\n\nasync function morphHttpErrorMessage(response: Response, apiKey: string): Promise<string> {\n\tconst body = await readHttpErrorBody(response);\n\tconst excerpt = redactCredentialShapes(body.replaceAll(apiKey, \"[redacted]\"))\n\t\t.replace(/[\\x00-\\x1f\\x7f-\\x9f]/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim()\n\t\t.slice(0, HTTP_ERROR_EXCERPT_MAX_CHARS);\n\treturn `Morph compaction HTTP ${response.status}${excerpt ? `: ${excerpt}` : \"\"}`;\n}\n\nexport async function planMorphRanges(\n\tregion: NumberedRegion,\n\tparameters: VerbatimCompactionParameters,\n\toptions: {\n\t\tapiKey: string | undefined;\n\t\tsignal?: AbortSignal;\n\t\tfetchFn?: typeof fetch;\n\t\tonDiagnostics?: (diagnostics: MorphRangeDiagnostics) => void;\n\t},\n): Promise<LineRange[]> {\n\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tif (!options.apiKey) throw new Error(\"Morph compaction requires /login morph or MORPH_API_KEY\");\n\tconst input = buildStructuredCompactionInput(region, parameters);\n\tconst response = await (options.fetchFn ?? fetch)(\"https://api.morphllm.com/v1/compact\", {\n\t\tmethod: \"POST\",\n\t\theaders: { Authorization: `Bearer ${options.apiKey}`, \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({\n\t\t\tmessages: input.messages.map((message) => ({ role: message.role, content: message.lines.join(\"\\n\") })),\n\t\t\tquery: input.query,\n\t\t\tcompression_ratio: input.compression_ratio,\n\t\t\tpreserve_recent: 0,\n\t\t\tinclude_markers: false,\n\t\t}),\n\t\tsignal: options.signal,\n\t});\n\tif (!response.ok) {\n\t\tconst message = await morphHttpErrorMessage(response, options.apiKey);\n\t\toptions.onDiagnostics?.({\n\t\t\tdroppedRangeCount: 0,\n\t\t\tacceptedRangeCount: 0,\n\t\t\tfailureCategory: isProviderPolicyRefusal(message) ? \"policy_refusal\" : \"provider_error\",\n\t\t\tfailureMessage: message,\n\t\t});\n\t\tthrow new Error(message);\n\t}\n\tconst body: Static<typeof responseSchema> = await response.json();\n\tif (!Value.Check(responseSchema, body) || body.messages.length !== input.messages.length)\n\t\tthrow new Error(\"Malformed Morph compaction response\");\n\tlet droppedRangeCount = 0;\n\tconst records = body.messages.flatMap((message, index) =>\n\t\tmessage.compacted_line_ranges.flatMap((range) => {\n\t\t\tif (\n\t\t\t\t!Number.isSafeInteger(range.start) ||\n\t\t\t\t!Number.isSafeInteger(range.end) ||\n\t\t\t\trange.start < 1 ||\n\t\t\t\trange.end < range.start ||\n\t\t\t\trange.end > input.messages[index].lines.length\n\t\t\t) {\n\t\t\t\tdroppedRangeCount++;\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn [{ id: input.messages[index].id, ...range }];\n\t\t}),\n\t);\n\toptions.onDiagnostics?.({ droppedRangeCount, acceptedRangeCount: records.length });\n\tconst ranges = validateDeletedRanges(mapMessageRanges(records, input), region);\n\tif (!ranges.length) throw new Error(\"Morph compaction produced no usable ranges\");\n\treturn [...ranges];\n}\n"]}