@bastani/atomic 0.9.20-alpha.2 → 0.9.20-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (787) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.md +15 -7
  3. package/dist/builtin/intercom/CHANGELOG.md +18 -0
  4. package/dist/builtin/intercom/README.md +2 -2
  5. package/dist/builtin/intercom/broker/send-handler.ts +59 -2
  6. package/dist/builtin/intercom/index.bundle.mjs +101 -16
  7. package/dist/builtin/intercom/package.json +3 -3
  8. package/dist/builtin/intercom/session-target.ts +34 -9
  9. package/dist/builtin/intercom/skills/intercom/SKILL.md +4 -4
  10. package/dist/builtin/mcp/CHANGELOG.md +13 -0
  11. package/dist/builtin/mcp/OAUTH.md +1 -1
  12. package/dist/builtin/mcp/README.md +3 -1
  13. package/dist/builtin/mcp/index.bundle.mjs +412 -64
  14. package/dist/builtin/mcp/package.json +3 -3
  15. package/dist/builtin/subagents/CHANGELOG.md +27 -0
  16. package/dist/builtin/subagents/README.md +2 -2
  17. package/dist/builtin/subagents/agents/code-simplifier.md +2 -3
  18. package/dist/builtin/subagents/agents/codebase-analyzer.md +2 -3
  19. package/dist/builtin/subagents/agents/codebase-locator.md +2 -3
  20. package/dist/builtin/subagents/agents/codebase-online-researcher.md +2 -3
  21. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -3
  22. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +2 -3
  23. package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -3
  24. package/dist/builtin/subagents/agents/debugger.md +1 -2
  25. package/dist/builtin/subagents/agents/worker.md +1 -2
  26. package/dist/builtin/subagents/package.json +4 -8
  27. package/dist/builtin/subagents/skills/subagent/SKILL.md +15 -13
  28. package/dist/builtin/subagents/src/extension/index.bundle.mjs +249 -63
  29. package/dist/builtin/web-access/CHANGELOG.md +18 -0
  30. package/dist/builtin/web-access/index.bundle.mjs +372 -300
  31. package/dist/builtin/web-access/package.json +3 -3
  32. package/dist/builtin/workflows/CHANGELOG.md +68 -0
  33. package/dist/builtin/workflows/README.md +29 -30
  34. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  35. package/dist/builtin/workflows/builtin/{chunk-yeee2jrc.js → chunk-119kxb28.js} +5 -46
  36. package/dist/builtin/workflows/builtin/chunk-1dydq7w3.js +9722 -0
  37. package/dist/builtin/workflows/builtin/{chunk-31j2gs7h.js → chunk-9y0f90rd.js} +4 -6
  38. package/dist/builtin/workflows/builtin/{chunk-z29qbehr.js → chunk-d1xqh1rd.js} +4 -6
  39. package/dist/builtin/workflows/builtin/{chunk-zqtm1d2c.js → chunk-hnbbb5r0.js} +12 -217
  40. package/dist/builtin/workflows/builtin/{chunk-wf741bv3.js → chunk-k18g9me8.js} +4 -6
  41. package/dist/builtin/workflows/builtin/{chunk-g0csgs7w.js → chunk-kf5xpbkz.js} +8 -10
  42. package/dist/builtin/workflows/builtin/{chunk-a2kdsqn8.js → chunk-n4yxrsm9.js} +1 -1
  43. package/dist/builtin/workflows/builtin/{chunk-xtxcq5tj.js → chunk-n8g2da69.js} +17 -1
  44. package/dist/builtin/workflows/builtin/{chunk-fg9esgkj.js → chunk-scgprmdj.js} +4 -6
  45. package/dist/builtin/workflows/builtin/{chunk-6w6cvk6b.js → chunk-sn5mchnx.js} +4 -6
  46. package/dist/builtin/workflows/builtin/{chunk-ewkkkbak.js → chunk-vt9zgr9d.js} +9 -91
  47. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  48. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  49. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  50. package/dist/builtin/workflows/builtin/goal.js +4 -4
  51. package/dist/builtin/workflows/builtin/index.js +12 -12
  52. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  53. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  54. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  55. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  56. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  57. package/dist/builtin/workflows/package.json +3 -3
  58. package/dist/builtin/workflows/src/authoring.d.ts +2 -0
  59. package/dist/builtin/workflows/src/durable/dependency-doctor-types.d.ts +42 -0
  60. package/dist/builtin/workflows/src/extension/index.bundle.mjs +82110 -78759
  61. package/dist/builtin/workflows/src/index.js +8900 -1200
  62. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +11 -0
  63. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +4 -1
  64. package/dist/bun/split-loader.js +13 -0
  65. package/dist/bun/split-loader.js.map +1 -1
  66. package/dist/cli/args.js +2 -2
  67. package/dist/cli/args.js.map +1 -1
  68. package/dist/config.d.ts +1 -0
  69. package/dist/config.d.ts.map +1 -1
  70. package/dist/config.js +1 -0
  71. package/dist/config.js.map +1 -1
  72. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  73. package/dist/core/agent-session-accessors.js +2 -1
  74. package/dist/core/agent-session-accessors.js.map +1 -1
  75. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  76. package/dist/core/agent-session-auto-compaction.js +9 -2
  77. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  78. package/dist/core/agent-session-bash.d.ts +3 -1
  79. package/dist/core/agent-session-bash.d.ts.map +1 -1
  80. package/dist/core/agent-session-bash.js +18 -6
  81. package/dist/core/agent-session-bash.js.map +1 -1
  82. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  83. package/dist/core/agent-session-compaction.js +37 -14
  84. package/dist/core/agent-session-compaction.js.map +1 -1
  85. package/dist/core/agent-session-events.d.ts +6 -6
  86. package/dist/core/agent-session-events.d.ts.map +1 -1
  87. package/dist/core/agent-session-events.js +145 -62
  88. package/dist/core/agent-session-events.js.map +1 -1
  89. package/dist/core/agent-session-export.d.ts +1 -1
  90. package/dist/core/agent-session-export.d.ts.map +1 -1
  91. package/dist/core/agent-session-export.js +18 -19
  92. package/dist/core/agent-session-export.js.map +1 -1
  93. package/dist/core/agent-session-extension-bindings.d.ts +3 -2
  94. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  95. package/dist/core/agent-session-extension-bindings.js +274 -70
  96. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  97. package/dist/core/agent-session-message-queue.d.ts +1 -1
  98. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  99. package/dist/core/agent-session-message-queue.js +30 -4
  100. package/dist/core/agent-session-message-queue.js.map +1 -1
  101. package/dist/core/agent-session-methods.d.ts +19 -11
  102. package/dist/core/agent-session-methods.d.ts.map +1 -1
  103. package/dist/core/agent-session-methods.js.map +1 -1
  104. package/dist/core/agent-session-models.d.ts +2 -2
  105. package/dist/core/agent-session-models.d.ts.map +1 -1
  106. package/dist/core/agent-session-models.js +38 -29
  107. package/dist/core/agent-session-models.js.map +1 -1
  108. package/dist/core/agent-session-persistent-custom-messages.d.ts +1 -1
  109. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  110. package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
  111. package/dist/core/agent-session-post-tool-compaction.js +18 -1
  112. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  113. package/dist/core/agent-session-prompt.d.ts +1 -1
  114. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  115. package/dist/core/agent-session-prompt.js +104 -22
  116. package/dist/core/agent-session-prompt.js.map +1 -1
  117. package/dist/core/agent-session-queue-pause.d.ts +2 -0
  118. package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
  119. package/dist/core/agent-session-queue-pause.js +13 -2
  120. package/dist/core/agent-session-queue-pause.js.map +1 -1
  121. package/dist/core/agent-session-retry.d.ts +0 -3
  122. package/dist/core/agent-session-retry.d.ts.map +1 -1
  123. package/dist/core/agent-session-retry.js +24 -11
  124. package/dist/core/agent-session-retry.js.map +1 -1
  125. package/dist/core/agent-session-runtime-auth.d.ts.map +1 -1
  126. package/dist/core/agent-session-runtime-auth.js +10 -0
  127. package/dist/core/agent-session-runtime-auth.js.map +1 -1
  128. package/dist/core/agent-session-runtime.d.ts +17 -1
  129. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  130. package/dist/core/agent-session-runtime.js +428 -197
  131. package/dist/core/agent-session-runtime.js.map +1 -1
  132. package/dist/core/agent-session-services.d.ts +4 -0
  133. package/dist/core/agent-session-services.d.ts.map +1 -1
  134. package/dist/core/agent-session-services.js +31 -2
  135. package/dist/core/agent-session-services.js.map +1 -1
  136. package/dist/core/agent-session-state.d.ts +10 -2
  137. package/dist/core/agent-session-state.d.ts.map +1 -1
  138. package/dist/core/agent-session-state.js +32 -22
  139. package/dist/core/agent-session-state.js.map +1 -1
  140. package/dist/core/agent-session-summary.d.ts.map +1 -1
  141. package/dist/core/agent-session-summary.js +9 -2
  142. package/dist/core/agent-session-summary.js.map +1 -1
  143. package/dist/core/agent-session-tasks.d.ts +1 -0
  144. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  145. package/dist/core/agent-session-tasks.js +24 -3
  146. package/dist/core/agent-session-tasks.js.map +1 -1
  147. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  148. package/dist/core/agent-session-tool-hooks.js +26 -3
  149. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  150. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  151. package/dist/core/agent-session-tool-registry.js +0 -2
  152. package/dist/core/agent-session-tool-registry.js.map +1 -1
  153. package/dist/core/agent-session-transfer.js.map +1 -1
  154. package/dist/core/agent-session-tree.d.ts.map +1 -1
  155. package/dist/core/agent-session-tree.js +6 -0
  156. package/dist/core/agent-session-tree.js.map +1 -1
  157. package/dist/core/agent-session-types.d.ts +5 -0
  158. package/dist/core/agent-session-types.d.ts.map +1 -1
  159. package/dist/core/agent-session-types.js.map +1 -1
  160. package/dist/core/agent-session.d.ts +15 -8
  161. package/dist/core/agent-session.d.ts.map +1 -1
  162. package/dist/core/agent-session.js +113 -66
  163. package/dist/core/agent-session.js.map +1 -1
  164. package/dist/core/auth-storage.d.ts +5 -3
  165. package/dist/core/auth-storage.d.ts.map +1 -1
  166. package/dist/core/auth-storage.js +18 -5
  167. package/dist/core/auth-storage.js.map +1 -1
  168. package/dist/core/builtin-diagnostics.d.ts +2 -0
  169. package/dist/core/builtin-diagnostics.d.ts.map +1 -0
  170. package/dist/core/builtin-diagnostics.js +14 -0
  171. package/dist/core/builtin-diagnostics.js.map +1 -0
  172. package/dist/core/builtin-packages.d.ts +5 -2
  173. package/dist/core/builtin-packages.d.ts.map +1 -1
  174. package/dist/core/builtin-packages.js +24 -3
  175. package/dist/core/builtin-packages.js.map +1 -1
  176. package/dist/core/builtin-resource-loader.d.ts +4 -0
  177. package/dist/core/builtin-resource-loader.d.ts.map +1 -0
  178. package/dist/core/builtin-resource-loader.js +239 -0
  179. package/dist/core/builtin-resource-loader.js.map +1 -0
  180. package/dist/core/cache-retention.d.ts +4 -0
  181. package/dist/core/cache-retention.d.ts.map +1 -0
  182. package/dist/core/cache-retention.js +58 -0
  183. package/dist/core/cache-retention.js.map +1 -0
  184. package/dist/core/cache-stats.d.ts.map +1 -1
  185. package/dist/core/cache-stats.js +11 -0
  186. package/dist/core/cache-stats.js.map +1 -1
  187. package/dist/core/cache-warmer.d.ts +66 -0
  188. package/dist/core/cache-warmer.d.ts.map +1 -0
  189. package/dist/core/cache-warmer.js +313 -0
  190. package/dist/core/cache-warmer.js.map +1 -0
  191. package/dist/core/child-session-options.d.ts +5 -0
  192. package/dist/core/child-session-options.d.ts.map +1 -0
  193. package/dist/core/child-session-options.js +30 -0
  194. package/dist/core/child-session-options.js.map +1 -0
  195. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  196. package/dist/core/compaction/branch-summarization.js +2 -2
  197. package/dist/core/compaction/branch-summarization.js.map +1 -1
  198. package/dist/core/compaction/compaction-boundary.d.ts +29 -1
  199. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  200. package/dist/core/compaction/compaction-boundary.js +37 -4
  201. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  202. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  203. package/dist/core/compaction/compaction-runner.js +18 -5
  204. package/dist/core/compaction/compaction-runner.js.map +1 -1
  205. package/dist/core/compaction/compaction-types.d.ts +7 -0
  206. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  207. package/dist/core/compaction/compaction-types.js.map +1 -1
  208. package/dist/core/compaction/compaction.d.ts.map +1 -1
  209. package/dist/core/compaction/compaction.js +18 -0
  210. package/dist/core/compaction/compaction.js.map +1 -1
  211. package/dist/core/compaction/fallback-planner.d.ts +1 -0
  212. package/dist/core/compaction/fallback-planner.d.ts.map +1 -1
  213. package/dist/core/compaction/fallback-planner.js +2 -0
  214. package/dist/core/compaction/fallback-planner.js.map +1 -1
  215. package/dist/core/compaction/index.d.ts +1 -0
  216. package/dist/core/compaction/index.d.ts.map +1 -1
  217. package/dist/core/compaction/index.js +1 -0
  218. package/dist/core/compaction/index.js.map +1 -1
  219. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  220. package/dist/core/compaction/range-planner.js +3 -3
  221. package/dist/core/compaction/range-planner.js.map +1 -1
  222. package/dist/core/compaction/session-summarization.d.ts.map +1 -1
  223. package/dist/core/compaction/session-summarization.js +2 -1
  224. package/dist/core/compaction/session-summarization.js.map +1 -1
  225. package/dist/core/compaction/whole-context-stats.d.ts +21 -0
  226. package/dist/core/compaction/whole-context-stats.d.ts.map +1 -0
  227. package/dist/core/compaction/whole-context-stats.js +32 -0
  228. package/dist/core/compaction/whole-context-stats.js.map +1 -0
  229. package/dist/core/credential-screening.d.ts +17 -0
  230. package/dist/core/credential-screening.d.ts.map +1 -0
  231. package/dist/core/credential-screening.js +30 -0
  232. package/dist/core/credential-screening.js.map +1 -0
  233. package/dist/core/decision-provider.d.ts +4 -0
  234. package/dist/core/decision-provider.d.ts.map +1 -0
  235. package/dist/core/decision-provider.js +12 -0
  236. package/dist/core/decision-provider.js.map +1 -0
  237. package/dist/core/execution-model-router.d.ts +28 -0
  238. package/dist/core/execution-model-router.d.ts.map +1 -0
  239. package/dist/core/execution-model-router.js +165 -0
  240. package/dist/core/execution-model-router.js.map +1 -0
  241. package/dist/core/extensions/agent-events.d.ts +4 -4
  242. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  243. package/dist/core/extensions/agent-events.js.map +1 -1
  244. package/dist/core/extensions/api-types.d.ts +46 -40
  245. package/dist/core/extensions/api-types.d.ts.map +1 -1
  246. package/dist/core/extensions/api-types.js.map +1 -1
  247. package/dist/core/extensions/context-types.d.ts +7 -1
  248. package/dist/core/extensions/context-types.d.ts.map +1 -1
  249. package/dist/core/extensions/context-types.js.map +1 -1
  250. package/dist/core/extensions/event-results.d.ts +7 -6
  251. package/dist/core/extensions/event-results.d.ts.map +1 -1
  252. package/dist/core/extensions/event-results.js.map +1 -1
  253. package/dist/core/extensions/event-types.d.ts +2 -1
  254. package/dist/core/extensions/event-types.d.ts.map +1 -1
  255. package/dist/core/extensions/event-types.js.map +1 -1
  256. package/dist/core/extensions/extension-work.d.ts +14 -0
  257. package/dist/core/extensions/extension-work.d.ts.map +1 -0
  258. package/dist/core/extensions/extension-work.js +73 -0
  259. package/dist/core/extensions/extension-work.js.map +1 -0
  260. package/dist/core/extensions/herdr-file-integration.d.ts +36 -0
  261. package/dist/core/extensions/herdr-file-integration.d.ts.map +1 -0
  262. package/dist/core/extensions/herdr-file-integration.js +60 -0
  263. package/dist/core/extensions/herdr-file-integration.js.map +1 -0
  264. package/dist/core/extensions/host-input.d.ts +51 -0
  265. package/dist/core/extensions/host-input.d.ts.map +1 -0
  266. package/dist/core/extensions/host-input.js +211 -0
  267. package/dist/core/extensions/host-input.js.map +1 -0
  268. package/dist/core/extensions/index.d.ts +4 -2
  269. package/dist/core/extensions/index.d.ts.map +1 -1
  270. package/dist/core/extensions/index.js +0 -3
  271. package/dist/core/extensions/index.js.map +1 -1
  272. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  273. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  274. package/dist/core/extensions/jiti-loader.js +3 -0
  275. package/dist/core/extensions/jiti-loader.js.map +1 -0
  276. package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
  277. package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
  278. package/dist/core/extensions/jiti-static-loader.js +3 -0
  279. package/dist/core/extensions/jiti-static-loader.js.map +1 -0
  280. package/dist/core/extensions/loader-api.d.ts +7 -0
  281. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  282. package/dist/core/extensions/loader-api.js +154 -28
  283. package/dist/core/extensions/loader-api.js.map +1 -1
  284. package/dist/core/extensions/loader-bindings.d.ts +24 -0
  285. package/dist/core/extensions/loader-bindings.d.ts.map +1 -0
  286. package/dist/core/extensions/loader-bindings.js +128 -0
  287. package/dist/core/extensions/loader-bindings.js.map +1 -0
  288. package/dist/core/extensions/loader-core.d.ts +2 -1
  289. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  290. package/dist/core/extensions/loader-core.js +91 -14
  291. package/dist/core/extensions/loader-core.js.map +1 -1
  292. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  293. package/dist/core/extensions/loader-host-modules.js +3 -1
  294. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  295. package/dist/core/extensions/loader-rollback.d.ts +14 -0
  296. package/dist/core/extensions/loader-rollback.d.ts.map +1 -0
  297. package/dist/core/extensions/loader-rollback.js +95 -0
  298. package/dist/core/extensions/loader-rollback.js.map +1 -0
  299. package/dist/core/extensions/loader-runtime.d.ts +3 -1
  300. package/dist/core/extensions/loader-runtime.d.ts.map +1 -1
  301. package/dist/core/extensions/loader-runtime.js +38 -14
  302. package/dist/core/extensions/loader-runtime.js.map +1 -1
  303. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  304. package/dist/core/extensions/loader-virtual-modules.js +9 -2
  305. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  306. package/dist/core/extensions/loader.d.ts +1 -1
  307. package/dist/core/extensions/loader.d.ts.map +1 -1
  308. package/dist/core/extensions/loader.js +1 -1
  309. package/dist/core/extensions/loader.js.map +1 -1
  310. package/dist/core/extensions/reactive-widget.d.ts +1 -1
  311. package/dist/core/extensions/reactive-widget.js.map +1 -1
  312. package/dist/core/extensions/runner-context.d.ts +4 -0
  313. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  314. package/dist/core/extensions/runner-context.js +25 -0
  315. package/dist/core/extensions/runner-context.js.map +1 -1
  316. package/dist/core/extensions/runner-events.d.ts +8 -4
  317. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  318. package/dist/core/extensions/runner-events.js +55 -53
  319. package/dist/core/extensions/runner-events.js.map +1 -1
  320. package/dist/core/extensions/runner-project-trust.d.ts.map +1 -1
  321. package/dist/core/extensions/runner-project-trust.js +2 -4
  322. package/dist/core/extensions/runner-project-trust.js.map +1 -1
  323. package/dist/core/extensions/runner.d.ts +31 -4
  324. package/dist/core/extensions/runner.d.ts.map +1 -1
  325. package/dist/core/extensions/runner.js +219 -23
  326. package/dist/core/extensions/runner.js.map +1 -1
  327. package/dist/core/extensions/runtime-types.d.ts +2 -0
  328. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  329. package/dist/core/extensions/runtime-types.js.map +1 -1
  330. package/dist/core/extensions/types.d.ts +3 -2
  331. package/dist/core/extensions/types.d.ts.map +1 -1
  332. package/dist/core/extensions/types.js +0 -12
  333. package/dist/core/extensions/types.js.map +1 -1
  334. package/dist/core/extensions/workflow-activity-hub.d.ts +2 -0
  335. package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -1
  336. package/dist/core/extensions/workflow-activity-hub.js +5 -3
  337. package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
  338. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  339. package/dist/core/extensions/wrapper.js +5 -3
  340. package/dist/core/extensions/wrapper.js.map +1 -1
  341. package/dist/core/fast-model-routing.d.ts +3 -3
  342. package/dist/core/fast-model-routing.d.ts.map +1 -1
  343. package/dist/core/fast-model-routing.js +3 -3
  344. package/dist/core/fast-model-routing.js.map +1 -1
  345. package/dist/core/fast-model-variants.d.ts +4 -0
  346. package/dist/core/fast-model-variants.d.ts.map +1 -1
  347. package/dist/core/fast-model-variants.js +3 -0
  348. package/dist/core/fast-model-variants.js.map +1 -1
  349. package/dist/core/index.d.ts +4 -1
  350. package/dist/core/index.d.ts.map +1 -1
  351. package/dist/core/index.js +2 -0
  352. package/dist/core/index.js.map +1 -1
  353. package/dist/core/mandatory-resource-loader.d.ts +4 -0
  354. package/dist/core/mandatory-resource-loader.d.ts.map +1 -1
  355. package/dist/core/mandatory-resource-loader.js +29 -1
  356. package/dist/core/mandatory-resource-loader.js.map +1 -1
  357. package/dist/core/mandatory-runtime-tools.d.ts +1 -4
  358. package/dist/core/mandatory-runtime-tools.d.ts.map +1 -1
  359. package/dist/core/mandatory-runtime-tools.js +1 -9
  360. package/dist/core/mandatory-runtime-tools.js.map +1 -1
  361. package/dist/core/messages.d.ts.map +1 -1
  362. package/dist/core/messages.js +19 -2
  363. package/dist/core/messages.js.map +1 -1
  364. package/dist/core/model-config.d.ts +126 -10
  365. package/dist/core/model-config.d.ts.map +1 -1
  366. package/dist/core/model-config.js +32 -19
  367. package/dist/core/model-config.js.map +1 -1
  368. package/dist/core/model-registry.d.ts +4 -2
  369. package/dist/core/model-registry.d.ts.map +1 -1
  370. package/dist/core/model-registry.js +6 -2
  371. package/dist/core/model-registry.js.map +1 -1
  372. package/dist/core/model-routing-constraints.d.ts +24 -0
  373. package/dist/core/model-routing-constraints.d.ts.map +1 -0
  374. package/dist/core/model-routing-constraints.js +46 -0
  375. package/dist/core/model-routing-constraints.js.map +1 -0
  376. package/dist/core/model-routing-task.d.ts +4 -0
  377. package/dist/core/model-routing-task.d.ts.map +1 -0
  378. package/dist/core/model-routing-task.js +76 -0
  379. package/dist/core/model-routing-task.js.map +1 -0
  380. package/dist/core/model-runtime-streaming.d.ts +13 -3
  381. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  382. package/dist/core/model-runtime-streaming.js +15 -5
  383. package/dist/core/model-runtime-streaming.js.map +1 -1
  384. package/dist/core/model-runtime-types.d.ts +2 -2
  385. package/dist/core/model-runtime-types.d.ts.map +1 -1
  386. package/dist/core/model-runtime-types.js.map +1 -1
  387. package/dist/core/model-runtime.d.ts +6 -3
  388. package/dist/core/model-runtime.d.ts.map +1 -1
  389. package/dist/core/model-runtime.js +29 -2
  390. package/dist/core/model-runtime.js.map +1 -1
  391. package/dist/core/provider-composer-internal.d.ts +3 -2
  392. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  393. package/dist/core/provider-composer-internal.js +2 -0
  394. package/dist/core/provider-composer-internal.js.map +1 -1
  395. package/dist/core/provider-composer.d.ts.map +1 -1
  396. package/dist/core/provider-composer.js.map +1 -1
  397. package/dist/core/resolve-config-value.d.ts +2 -0
  398. package/dist/core/resolve-config-value.d.ts.map +1 -1
  399. package/dist/core/resolve-config-value.js +23 -1
  400. package/dist/core/resolve-config-value.js.map +1 -1
  401. package/dist/core/resource-loader-core.d.ts +6 -0
  402. package/dist/core/resource-loader-core.d.ts.map +1 -1
  403. package/dist/core/resource-loader-core.js +37 -6
  404. package/dist/core/resource-loader-core.js.map +1 -1
  405. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  406. package/dist/core/resource-loader-extensions.js +2 -0
  407. package/dist/core/resource-loader-extensions.js.map +1 -1
  408. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  409. package/dist/core/resource-loader-reload.js +7 -2
  410. package/dist/core/resource-loader-reload.js.map +1 -1
  411. package/dist/core/resource-loader.d.ts +1 -1
  412. package/dist/core/resource-loader.d.ts.map +1 -1
  413. package/dist/core/resource-loader.js +1 -1
  414. package/dist/core/resource-loader.js.map +1 -1
  415. package/dist/core/runtime-credentials.d.ts +2 -0
  416. package/dist/core/runtime-credentials.d.ts.map +1 -1
  417. package/dist/core/runtime-credentials.js +15 -0
  418. package/dist/core/runtime-credentials.js.map +1 -1
  419. package/dist/core/sdk-types.d.ts +13 -5
  420. package/dist/core/sdk-types.d.ts.map +1 -1
  421. package/dist/core/sdk-types.js.map +1 -1
  422. package/dist/core/sdk.d.ts +3 -1
  423. package/dist/core/sdk.d.ts.map +1 -1
  424. package/dist/core/sdk.js +211 -37
  425. package/dist/core/sdk.js.map +1 -1
  426. package/dist/core/session-lifecycle-scope.d.ts +15 -0
  427. package/dist/core/session-lifecycle-scope.d.ts.map +1 -0
  428. package/dist/core/session-lifecycle-scope.js +13 -0
  429. package/dist/core/session-lifecycle-scope.js.map +1 -0
  430. package/dist/core/session-lifecycle-work.d.ts +17 -0
  431. package/dist/core/session-lifecycle-work.d.ts.map +1 -0
  432. package/dist/core/session-lifecycle-work.js +144 -0
  433. package/dist/core/session-lifecycle-work.js.map +1 -0
  434. package/dist/core/session-manager-core.d.ts +10 -4
  435. package/dist/core/session-manager-core.d.ts.map +1 -1
  436. package/dist/core/session-manager-core.js +53 -6
  437. package/dist/core/session-manager-core.js.map +1 -1
  438. package/dist/core/session-manager-history.d.ts.map +1 -1
  439. package/dist/core/session-manager-history.js +3 -0
  440. package/dist/core/session-manager-history.js.map +1 -1
  441. package/dist/core/session-manager-list.d.ts +3 -3
  442. package/dist/core/session-manager-list.d.ts.map +1 -1
  443. package/dist/core/session-manager-list.js +89 -74
  444. package/dist/core/session-manager-list.js.map +1 -1
  445. package/dist/core/session-manager-storage.d.ts.map +1 -1
  446. package/dist/core/session-manager-storage.js +10 -7
  447. package/dist/core/session-manager-storage.js.map +1 -1
  448. package/dist/core/session-manager-types.d.ts +13 -3
  449. package/dist/core/session-manager-types.d.ts.map +1 -1
  450. package/dist/core/session-manager-types.js.map +1 -1
  451. package/dist/core/session-manager.d.ts +1 -1
  452. package/dist/core/session-manager.d.ts.map +1 -1
  453. package/dist/core/session-manager.js.map +1 -1
  454. package/dist/core/session-startup-rollback.d.ts +5 -0
  455. package/dist/core/session-startup-rollback.d.ts.map +1 -0
  456. package/dist/core/session-startup-rollback.js +16 -0
  457. package/dist/core/session-startup-rollback.js.map +1 -0
  458. package/dist/core/settings-manager-basic-accessors.d.ts +5 -0
  459. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  460. package/dist/core/settings-manager-basic-accessors.js +35 -0
  461. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  462. package/dist/core/settings-manager-core.d.ts.map +1 -1
  463. package/dist/core/settings-manager-core.js +4 -0
  464. package/dist/core/settings-manager-core.js.map +1 -1
  465. package/dist/core/settings-manager.d.ts +1 -0
  466. package/dist/core/settings-manager.d.ts.map +1 -1
  467. package/dist/core/settings-manager.js +1 -0
  468. package/dist/core/settings-manager.js.map +1 -1
  469. package/dist/core/settings-types.d.ts +4 -0
  470. package/dist/core/settings-types.d.ts.map +1 -1
  471. package/dist/core/settings-types.js +1 -1
  472. package/dist/core/settings-types.js.map +1 -1
  473. package/dist/core/settings-write-ownership.d.ts +7 -0
  474. package/dist/core/settings-write-ownership.d.ts.map +1 -0
  475. package/dist/core/settings-write-ownership.js +24 -0
  476. package/dist/core/settings-write-ownership.js.map +1 -0
  477. package/dist/core/slash-commands.js +1 -1
  478. package/dist/core/slash-commands.js.map +1 -1
  479. package/dist/core/structured-output/index.d.ts +12 -0
  480. package/dist/core/structured-output/index.d.ts.map +1 -0
  481. package/dist/core/structured-output/index.js +251 -0
  482. package/dist/core/structured-output/index.js.map +1 -0
  483. package/dist/core/structured-output/invalid-output.d.ts +8 -0
  484. package/dist/core/structured-output/invalid-output.d.ts.map +1 -0
  485. package/dist/core/structured-output/invalid-output.js +4 -0
  486. package/dist/core/structured-output/invalid-output.js.map +1 -0
  487. package/dist/core/structured-output/jev-client.d.ts +20 -0
  488. package/dist/core/structured-output/jev-client.d.ts.map +1 -0
  489. package/dist/core/structured-output/jev-client.js +116 -0
  490. package/dist/core/structured-output/jev-client.js.map +1 -0
  491. package/dist/core/structured-output/jev.d.ts +5 -0
  492. package/dist/core/structured-output/jev.d.ts.map +1 -0
  493. package/dist/core/structured-output/jev.js +275 -0
  494. package/dist/core/structured-output/jev.js.map +1 -0
  495. package/dist/core/structured-output/resolver.d.ts +41 -0
  496. package/dist/core/structured-output/resolver.d.ts.map +1 -0
  497. package/dist/core/structured-output/resolver.js +56 -0
  498. package/dist/core/structured-output/resolver.js.map +1 -0
  499. package/dist/core/structured-output/types.d.ts +68 -0
  500. package/dist/core/structured-output/types.d.ts.map +1 -0
  501. package/dist/core/structured-output/types.js +2 -0
  502. package/dist/core/structured-output/types.js.map +1 -0
  503. package/dist/core/system-prompt.d.ts +48 -5
  504. package/dist/core/system-prompt.d.ts.map +1 -1
  505. package/dist/core/system-prompt.js +130 -99
  506. package/dist/core/system-prompt.js.map +1 -1
  507. package/dist/core/tasks/contracts.d.ts +6 -0
  508. package/dist/core/tasks/contracts.d.ts.map +1 -1
  509. package/dist/core/tasks/contracts.js.map +1 -1
  510. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  511. package/dist/core/tasks/supervisor.js +7 -0
  512. package/dist/core/tasks/supervisor.js.map +1 -1
  513. package/dist/core/tools/ask-user-question/ask-user-question.d.ts +4 -1
  514. package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -1
  515. package/dist/core/tools/ask-user-question/ask-user-question.js +31 -35
  516. package/dist/core/tools/ask-user-question/ask-user-question.js.map +1 -1
  517. package/dist/core/tools/ask-user-question/index.d.ts +1 -1
  518. package/dist/core/tools/ask-user-question/index.js.map +1 -1
  519. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts +1 -1
  520. package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -1
  521. package/dist/core/tools/ask-user-question/state/key-router.d.ts +1 -1
  522. package/dist/core/tools/ask-user-question/state/key-router.js.map +1 -1
  523. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts +1 -1
  524. package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -1
  525. package/dist/core/tools/ask-user-question/state/row-intent.d.ts +1 -1
  526. package/dist/core/tools/ask-user-question/state/row-intent.js.map +1 -1
  527. package/dist/core/tools/ask-user-question/state/selectors/contract.d.ts +1 -1
  528. package/dist/core/tools/ask-user-question/state/selectors/contract.js.map +1 -1
  529. package/dist/core/tools/ask-user-question/state/selectors/derivations.d.ts +1 -1
  530. package/dist/core/tools/ask-user-question/state/selectors/derivations.js.map +1 -1
  531. package/dist/core/tools/ask-user-question/state/state-reducer.d.ts +1 -1
  532. package/dist/core/tools/ask-user-question/state/state-reducer.js.map +1 -1
  533. package/dist/core/tools/ask-user-question/state/state.d.ts +1 -1
  534. package/dist/core/tools/ask-user-question/state/state.js.map +1 -1
  535. package/dist/core/tools/ask-user-question/tool/format-answer.d.ts +1 -1
  536. package/dist/core/tools/ask-user-question/tool/format-answer.js.map +1 -1
  537. package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts +1 -1
  538. package/dist/core/tools/ask-user-question/tool/response-envelope.js.map +1 -1
  539. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.d.ts +1 -1
  540. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.js.map +1 -1
  541. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts +1 -1
  542. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -1
  543. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.d.ts +1 -1
  544. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js.map +1 -1
  545. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts +1 -1
  546. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -1
  547. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.d.ts +1 -1
  548. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.js.map +1 -1
  549. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts +1 -1
  550. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js.map +1 -1
  551. package/dist/core/tools/ask-user-question/view/components/submit-picker.js.map +1 -1
  552. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js.map +1 -1
  553. package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts +1 -1
  554. package/dist/core/tools/ask-user-question/view/dialog-builder.js.map +1 -1
  555. package/dist/core/tools/ask-user-question/view/props-adapter.d.ts +1 -1
  556. package/dist/core/tools/ask-user-question/view/props-adapter.js.map +1 -1
  557. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts +1 -1
  558. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -1
  559. package/dist/core/tools/bash.d.ts.map +1 -1
  560. package/dist/core/tools/bash.js +16 -11
  561. package/dist/core/tools/bash.js.map +1 -1
  562. package/dist/core/tools/find.d.ts +2 -2
  563. package/dist/core/tools/find.d.ts.map +1 -1
  564. package/dist/core/tools/find.js +1 -1
  565. package/dist/core/tools/find.js.map +1 -1
  566. package/dist/core/usage-totals.d.ts.map +1 -1
  567. package/dist/core/usage-totals.js +4 -0
  568. package/dist/core/usage-totals.js.map +1 -1
  569. package/dist/extensions/herdr/index.d.ts.map +1 -1
  570. package/dist/extensions/herdr/index.js +0 -7
  571. package/dist/extensions/herdr/index.js.map +1 -1
  572. package/dist/extensions/llama/client.d.ts +2 -0
  573. package/dist/extensions/llama/client.d.ts.map +1 -1
  574. package/dist/extensions/llama/client.js +6 -2
  575. package/dist/extensions/llama/client.js.map +1 -1
  576. package/dist/extensions/llama/provider.d.ts.map +1 -1
  577. package/dist/extensions/llama/provider.js +18 -4
  578. package/dist/extensions/llama/provider.js.map +1 -1
  579. package/dist/index-extensions.d.ts +1 -1
  580. package/dist/index-extensions.d.ts.map +1 -1
  581. package/dist/index-extensions.js.map +1 -1
  582. package/dist/index.d.ts +10 -1
  583. package/dist/index.d.ts.map +1 -1
  584. package/dist/index.js +5 -0
  585. package/dist/index.js.map +1 -1
  586. package/dist/main-session.d.ts.map +1 -1
  587. package/dist/main-session.js +24 -16
  588. package/dist/main-session.js.map +1 -1
  589. package/dist/main.d.ts.map +1 -1
  590. package/dist/main.js +4 -5
  591. package/dist/main.js.map +1 -1
  592. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  593. package/dist/modes/interactive/components/branch-summary-message.js +12 -5
  594. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  595. package/dist/modes/interactive/components/chat-message-renderer.d.ts +5 -1
  596. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  597. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  598. package/dist/modes/interactive/components/chat-session-host-events.d.ts +2 -2
  599. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  600. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
  601. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  602. package/dist/modes/interactive/components/compaction-boundary-message.js +30 -12
  603. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  604. package/dist/modes/interactive/components/custom-editor.d.ts +6 -0
  605. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  606. package/dist/modes/interactive/components/custom-editor.js +17 -0
  607. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  608. package/dist/modes/interactive/components/host-input-form-mount.d.ts +1 -1
  609. package/dist/modes/interactive/components/host-input-form-mount.js.map +1 -1
  610. package/dist/modes/interactive/components/host-input-form.d.ts +1 -1
  611. package/dist/modes/interactive/components/host-input-form.js.map +1 -1
  612. package/dist/modes/interactive/components/host-session-picker.d.ts +1 -1
  613. package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
  614. package/dist/modes/interactive/components/reserved-bottom-overlay.d.ts +1 -1
  615. package/dist/modes/interactive/components/reserved-bottom-overlay.js.map +1 -1
  616. package/dist/modes/interactive/components/scroll-widget.d.ts +1 -1
  617. package/dist/modes/interactive/components/scroll-widget.js.map +1 -1
  618. package/dist/modes/interactive/components/settings-selector-handlers.d.ts.map +1 -1
  619. package/dist/modes/interactive/components/settings-selector-handlers.js +3 -0
  620. package/dist/modes/interactive/components/settings-selector-handlers.js.map +1 -1
  621. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  622. package/dist/modes/interactive/components/settings-selector-items.js +50 -1
  623. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  624. package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
  625. package/dist/modes/interactive/components/settings-selector-submenus.js +2 -1
  626. package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
  627. package/dist/modes/interactive/components/settings-selector-types.d.ts +6 -1
  628. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  629. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  630. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  631. package/dist/modes/interactive/components/skill-invocation-message.js +11 -4
  632. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  633. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  634. package/dist/modes/interactive/components/tool-execution.js +14 -9
  635. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  636. package/dist/modes/interactive/interactive-auth-login.js +1 -1
  637. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  638. package/dist/modes/interactive/interactive-auth-routing.js +2 -2
  639. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  640. package/dist/modes/interactive/interactive-autocomplete.js +4 -0
  641. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  642. package/dist/modes/interactive/interactive-bash-compact.d.ts.map +1 -1
  643. package/dist/modes/interactive/interactive-bash-compact.js +13 -6
  644. package/dist/modes/interactive/interactive-bash-compact.js.map +1 -1
  645. package/dist/modes/interactive/interactive-extension-runtime.js +5 -0
  646. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  647. package/dist/modes/interactive/interactive-input-handling.js +2 -2
  648. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  649. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  650. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  651. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  652. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  653. package/dist/modes/interactive/interactive-mode-surface.d.ts +1 -1
  654. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  655. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  656. package/dist/modes/interactive/interactive-render-chat.js +27 -25
  657. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  658. package/dist/modes/interactive/interactive-selectors.js +10 -0
  659. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  660. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  661. package/dist/modes/interactive/interactive-startup.js +2 -2
  662. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  663. package/dist/modes/interactive/interactive-tui.d.ts +3 -6
  664. package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
  665. package/dist/modes/interactive/interactive-tui.js +13 -5
  666. package/dist/modes/interactive/interactive-tui.js.map +1 -1
  667. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  668. package/dist/modes/interactive-engine/engine-custom-ui.js +3 -1
  669. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  670. package/dist/modes/interactive-engine/engine-input-form.d.ts +1 -1
  671. package/dist/modes/interactive-engine/engine-input-form.js.map +1 -1
  672. package/dist/modes/interactive-engine/engine-session-picker.d.ts +1 -1
  673. package/dist/modes/interactive-engine/engine-session-picker.js.map +1 -1
  674. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  675. package/dist/modes/interactive-engine/isolated-runtime.js +10 -1
  676. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  677. package/dist/modes/interactive-engine/protocol.d.ts +1 -1
  678. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  679. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  680. package/dist/modes/rpc/rpc-keybindings-reload.d.ts +1 -1
  681. package/dist/modes/rpc/rpc-keybindings-reload.js.map +1 -1
  682. package/dist/modes/rpc/rpc-provider-auth.d.ts +1 -1
  683. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  684. package/dist/session-id-target.d.ts +31 -0
  685. package/dist/session-id-target.d.ts.map +1 -0
  686. package/dist/session-id-target.js +57 -0
  687. package/dist/session-id-target.js.map +1 -0
  688. package/dist/utils/abort.d.ts.map +1 -1
  689. package/dist/utils/abort.js +29 -4
  690. package/dist/utils/abort.js.map +1 -1
  691. package/dist/utils/clipboard-image.d.ts.map +1 -1
  692. package/dist/utils/clipboard-image.js +1 -12
  693. package/dist/utils/clipboard-image.js.map +1 -1
  694. package/dist/utils/clipboard.d.ts.map +1 -1
  695. package/dist/utils/clipboard.js +88 -12
  696. package/dist/utils/clipboard.js.map +1 -1
  697. package/dist/utils/wsl.d.ts +3 -0
  698. package/dist/utils/wsl.d.ts.map +1 -0
  699. package/dist/utils/wsl.js +15 -0
  700. package/dist/utils/wsl.js.map +1 -0
  701. package/docs/background-tasks.md +24 -14
  702. package/docs/build.md +6 -16
  703. package/docs/compaction/reference.md +12 -12
  704. package/docs/compaction.md +30 -110
  705. package/docs/computer-use.md +1 -3
  706. package/docs/containerization.md +4 -5
  707. package/docs/custom-provider/api-reference.md +10 -1
  708. package/docs/custom-provider/oauth.md +4 -2
  709. package/docs/custom-provider/streaming.md +8 -3
  710. package/docs/custom-provider.md +1 -1
  711. package/docs/development.md +13 -138
  712. package/docs/docs.json +19 -5
  713. package/docs/environment-variables.md +20 -4
  714. package/docs/extensions/api-reference.md +6 -2
  715. package/docs/extensions/authoring.md +10 -7
  716. package/docs/extensions/events.md +14 -24
  717. package/docs/extensions/ui.md +3 -4
  718. package/docs/extensions.md +22 -18
  719. package/docs/getting-started/authentication.md +4 -1
  720. package/docs/getting-started/first-session.md +8 -6
  721. package/docs/getting-started/installation.md +8 -4
  722. package/docs/getting-started/project-instructions.md +5 -1
  723. package/docs/guides/configuration.md +10 -5
  724. package/docs/guides/non-interactive.md +2 -2
  725. package/docs/guides.md +8 -17
  726. package/docs/herdr.md +2 -1
  727. package/docs/index.md +2 -2
  728. package/docs/intercom/operations.md +16 -70
  729. package/docs/intercom/reference.md +15 -5
  730. package/docs/intercom.md +10 -6
  731. package/docs/json.md +12 -2
  732. package/docs/keybindings.md +15 -8
  733. package/docs/llama-cpp.md +5 -1
  734. package/docs/{mcp.md → mcp-servers.md} +21 -2
  735. package/docs/models/evals.md +133 -465
  736. package/docs/models/model-selection.md +27 -116
  737. package/docs/models/reference.md +39 -21
  738. package/docs/models.md +7 -4
  739. package/docs/packages/authoring.md +5 -1
  740. package/docs/packages/reference.md +5 -1
  741. package/docs/packages.md +5 -3
  742. package/docs/programmatic.md +3 -1
  743. package/docs/prompt-templates.md +2 -10
  744. package/docs/providers/reference.md +2 -2
  745. package/docs/providers.md +41 -16
  746. package/docs/quickstart.md +7 -3
  747. package/docs/reference/cli.md +19 -11
  748. package/docs/reference.md +3 -6
  749. package/docs/rpc/protocol.md +11 -13
  750. package/docs/rpc.md +5 -1
  751. package/docs/sdk/reference.md +59 -239
  752. package/docs/sdk/structured-decisions.md +132 -0
  753. package/docs/sdk.md +181 -17
  754. package/docs/security.md +7 -4
  755. package/docs/session-format.md +18 -5
  756. package/docs/sessions.md +12 -6
  757. package/docs/settings.md +68 -16
  758. package/docs/skills/authoring.md +7 -1
  759. package/docs/skills.md +25 -6
  760. package/docs/subagents/authoring.md +11 -1
  761. package/docs/subagents/reference.md +98 -10
  762. package/docs/subagents.md +45 -35
  763. package/docs/terminal-setup.md +4 -2
  764. package/docs/termux.md +3 -1
  765. package/docs/themes/reference.md +4 -1
  766. package/docs/themes.md +1 -1
  767. package/docs/tools.md +431 -20
  768. package/docs/tui/reference.md +13 -14
  769. package/docs/tui.md +10 -6
  770. package/docs/usage.md +19 -7
  771. package/docs/web-access.md +5 -1
  772. package/docs/windows.md +18 -11
  773. package/docs/workflows/api-reference.md +135 -25
  774. package/docs/workflows/authoring.md +48 -39
  775. package/docs/workflows/builtins.md +20 -26
  776. package/docs/workflows/operations.md +288 -137
  777. package/docs/workflows/reliable-design.md +62 -129
  778. package/docs/workflows.md +10 -16
  779. package/examples/extensions/custom-provider-anthropic/index.ts +15 -10
  780. package/examples/extensions/custom-provider-gitlab-duo/index.ts +2 -2
  781. package/examples/extensions/prompt-customizer.ts +17 -37
  782. package/npm-shrinkwrap.json +502 -709
  783. package/package.json +12 -10
  784. package/dist/builtin/workflows/builtin/chunk-m0xfsef8.js +0 -2813
  785. package/docs/models/artificial-analysis-index.md +0 -89
  786. package/docs/models/pareto-efficiency.md +0 -90
  787. package/docs/tools/edit.md +0 -378
@@ -6,14 +6,47 @@ import { COMPACTION_AUTO_QUERY, normalizeCompactionParameters, normalizeCompacti
6
6
  import { MIN_COMPACTABLE_REGION_LINES, VERBATIM_COMPACTION_STRATEGY, } from "./compaction-types.js";
7
7
  import { createNumberedRegion, serializeConversationForCompaction } from "./transcript-serialization.js";
8
8
  const keptTailTokensByPreparation = new WeakMap();
9
- /** Return the independently estimated cost of the protected tail. */
9
+ /**
10
+ * Return the independently estimated cost of the protected tail.
11
+ *
12
+ * Only the explicit estimate recorded by `prepareCompactionBoundary` (or a test)
13
+ * is returned. The old fallback of `tokensBefore - region.tokenEstimate` was
14
+ * removed because it mixed the authoritative whole-context count with the
15
+ * heuristic region estimate; when no explicit estimate exists the tail simply
16
+ * contributes nothing rather than a wrong-numbered value. Whether an estimate is
17
+ * registered at all is visible through `hasKeptTailTokenEstimate`, which the
18
+ * fresh rung uses to decide a tail whose size is unknown (P1 #3010).
19
+ */
10
20
  export function getKeptTailTokenEstimate(preparation) {
11
- return (keptTailTokensByPreparation.get(preparation) ??
12
- Math.max(0, preparation.tokensBefore - preparation.region.tokenEstimate));
21
+ const registered = keptTailTokensByPreparation.get(preparation);
22
+ return registered === undefined ? 0 : registered;
23
+ }
24
+ /**
25
+ * Whether an independent tail estimate is registered for this preparation.
26
+ *
27
+ * A preparation built by `prepareCompactionBoundary` always has one. A directly
28
+ * constructed preparation may not; the fresh rung treats a kept tail whose size
29
+ * is unregistered as unknown and drops it conservatively rather than assuming it
30
+ * fits (P1 #3010).
31
+ */
32
+ export function hasKeptTailTokenEstimate(preparation) {
33
+ return keptTailTokensByPreparation.has(preparation);
34
+ }
35
+ /**
36
+ * Record the independent tail estimate for a preparation.
37
+ *
38
+ * `prepareCompactionBoundary` does this itself from the kept-tail messages;
39
+ * this setter is for test preparations built directly and for any other code
40
+ * that constructs a `VerbatimCompactionPreparation` without the boundary
41
+ * preparer. The estimate lives in a module-private map and is never persisted.
42
+ */
43
+ export function setKeptTailTokenEstimate(preparation, estimate) {
44
+ keptTailTokensByPreparation.set(preparation, Math.max(0, estimate));
13
45
  }
14
46
  function messageFromEntry(entry) {
47
+ // Prompt state is replayed separately at the boundary, never offered for deletion.
15
48
  if (entry.type === "message")
16
- return entry.message;
49
+ return entry.message.role === "system" ? undefined : entry.message;
17
50
  if (entry.type === "custom_message") {
18
51
  return createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp, entry.excludeFromContext);
19
52
  }
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,mCAAmC,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAA2B,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjG,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;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,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,IAAI,IAAI;QACnD,MAAM;QACN,cAAc,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,oBAAoB,EAAE,YAAY,CAAC,MAAM;QACzC,YAAY,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM;QACjF,UAAU;QACV,QAAQ;KACR,CAAC;IACF,2BAA2B,CAAC,GAAG,CAC9B,WAAW,EACX,YAAY,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport { buildSessionContext } from \"../session-manager-history.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { type CompactionSettings, estimateContextTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { createNumberedRegion, serializeConversationForCompaction } from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/** Return the independently estimated cost of the protected tail. */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\treturn (\n\t\tkeptTailTokensByPreparation.get(preparation) ??\n\t\tMath.max(0, preparation.tokensBefore - preparation.region.tokenEstimate)\n\t);\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\nfunction visibleEntries(entries: SessionEntry[], start = 0): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart);\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst serialized = serializeConversationForCompaction(convertToLlm(regionMessages.map((item) => item.message)));\n\tconst regionText = [previous?.entry.summary, serialized]\n\t\t.filter((text): text is string => typeof text === \"string\" && text.length > 0)\n\t\t.join(\"\\n\");\n\tconst region = createNumberedRegion(regionText);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateContextTokens(buildSessionContext(entries).messages).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
1
+ {"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,mCAAmC,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAA2B,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjG,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,GACx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Q,EAAE,KAAK,CAAC,OAAO,EAAE,UAAU,CAAC;SACtD,MAAM,CAAC,CAAC,IAAI,EAAkB,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;SAC7E,IAAI,CAAC,IAAI,CAAC,CAAC;IACb,MAAM,MAAM,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;IAChD,IAAI,CAAC,OAAO,CAAC,gBAAgB,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,4BAA4B;QAAE,OAAO,SAAS,CAAC;IAEtG,MAAM,WAAW,GAAkC;QAClD,gBAAgB,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,IAAI,IAAI;QACnD,MAAM;QACN,cAAc,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,oBAAoB,EAAE,YAAY,CAAC,MAAM;QACzC,YAAY,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM;QACjF,UAAU;QACV,QAAQ;KACR,CAAC;IACF,2BAA2B,CAAC,GAAG,CAC9B,WAAW,EACX,YAAY,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport { buildSessionContext } from \"../session-manager-history.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { type CompactionSettings, estimateContextTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { createNumberedRegion, serializeConversationForCompaction } from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/**\n * Return the independently estimated cost of the protected tail.\n *\n * Only the explicit estimate recorded by `prepareCompactionBoundary` (or a test)\n * is returned. The old fallback of `tokensBefore - region.tokenEstimate` was\n * removed because it mixed the authoritative whole-context count with the\n * heuristic region estimate; when no explicit estimate exists the tail simply\n * contributes nothing rather than a wrong-numbered value. Whether an estimate is\n * registered at all is visible through `hasKeptTailTokenEstimate`, which the\n * fresh rung uses to decide a tail whose size is unknown (P1 #3010).\n */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\tconst registered = keptTailTokensByPreparation.get(preparation);\n\treturn registered === undefined ? 0 : registered;\n}\n\n/**\n * Whether an independent tail estimate is registered for this preparation.\n *\n * A preparation built by `prepareCompactionBoundary` always has one. A directly\n * constructed preparation may not; the fresh rung treats a kept tail whose size\n * is unregistered as unknown and drops it conservatively rather than assuming it\n * fits (P1 #3010).\n */\nexport function hasKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): boolean {\n\treturn keptTailTokensByPreparation.has(preparation);\n}\n\n/**\n * Record the independent tail estimate for a preparation.\n *\n * `prepareCompactionBoundary` does this itself from the kept-tail messages;\n * this setter is for test preparations built directly and for any other code\n * that constructs a `VerbatimCompactionPreparation` without the boundary\n * preparer. The estimate lives in a module-private map and is never persisted.\n */\nexport function setKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation, estimate: number): void {\n\tkeptTailTokensByPreparation.set(preparation, Math.max(0, estimate));\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\t// Prompt state is replayed separately at the boundary, never offered for deletion.\n\tif (entry.type === \"message\") return entry.message.role === \"system\" ? undefined : entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\nfunction visibleEntries(entries: SessionEntry[], start = 0): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart);\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst serialized = serializeConversationForCompaction(convertToLlm(regionMessages.map((item) => item.message)));\n\tconst regionText = [previous?.entry.summary, serialized]\n\t\t.filter((text): text is string => typeof text === \"string\" && text.length > 0)\n\t\t.join(\"\\n\");\n\tconst region = createNumberedRegion(regionText);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateContextTokens(buildSessionContext(entries).messages).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE7E,OAAO,KAAK,EAEX,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,WAAW,EAEX,6BAA6B,EAC7B,MAAM,uBAAuB,CAAC;AAG/B,O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AAO,CAAC;IAClB,0EAA0E;IAC1E,KAAK,CAAC,EAAE,KAAK,CAAC;CACd,CAAC;AA6BF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAAC,WAAW,EAAE,6BAA6B,GAAG,MAAM,CAGlF;AAwDD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,6BAA6B,GAAG,mBAAmB,CAErG;AAyID;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CAC1C,WAAW,EAAE,6BAA6B,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,oBAAoB,GAC3B,OAAO,CAAC,oBAAoB,CAAC,CAuE/B"}
@@ -1,10 +1,11 @@
1
- import { getKeptTailTokenEstimate } from "./compaction-boundary.js";
1
+ import { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } from "./compaction-boundary.js";
2
2
  import { MIN_COMPACTABLE_REGION_LINES } from "./compaction-types.js";
3
3
  import { reconstructCompactedTranscript, validateDeletedRanges } from "./deleted-ranges.js";
4
4
  import { createFallbackPlannerBorrower, plannerAttemptKey, } from "./fallback-planner.js";
5
5
  import { MALFORMED_OUTPUT_MESSAGE, NO_USABLE_RANGES_MESSAGE, planDeletedLineRanges, RangePlanError, resolvePlannerRequest, } from "./range-planner.js";
6
6
  import { writeSuccessDiagnosticSidecar } from "./range-planner-diagnostics.js";
7
7
  import { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from "./region-trimming.js";
8
+ import { widenToWholeContextStats } from "./whole-context-stats.js";
8
9
  function addUsage(total, usage) {
9
10
  const cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);
10
11
  const reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);
@@ -47,12 +48,20 @@ export function targetKeepLines(preparation) {
47
48
  function hardInputLimitFor(model) {
48
49
  return model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;
49
50
  }
51
+ /**
52
+ * Widen region-level transcript stats to whole-context stats (#2052).
53
+ *
54
+ * `result.stats` must be the symmetric region-only stats produced by
55
+ * `reconstructCompactedTranscript`; this adds the independently estimated kept
56
+ * tail to the heuristic before count on both sides — and, only when the tail is
57
+ * kept, to the after count — via the shared `widenToWholeContextStats`. The
58
+ * authoritative `preparation.tokensBefore` is deliberately absent from this
59
+ * comparison and travels separately for budgeting/display.
60
+ */
50
61
  function withWholeContextStats(result, preparation, keptTail) {
51
- const tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);
52
- const percentReduction = preparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;
53
62
  return {
54
63
  ...result,
55
- stats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },
64
+ stats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),
56
65
  };
57
66
  }
58
67
  /**
@@ -75,7 +84,11 @@ function buildFreshContextWindow(preparation, hardInputLimit) {
75
84
  // way, and counting the reconstructed protected/marker text here would drop a
76
85
  // tail that fits. A rebuilt context that still cannot be sent is the post-tool
77
86
  // gate's problem, not a reason for this rung to discard more.
78
- return { transcript: buildFreshTranscript(preparation), keptTail: getKeptTailTokenEstimate(preparation) <= limit };
87
+ // A kept tail with no registered estimate (a directly constructed
88
+ // preparation) is dropped conservatively rather than assumed to fit (P1 #3010).
89
+ const keptTail = preparation.keptTailMessageCount === 0 ||
90
+ (hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);
91
+ return { transcript: buildFreshTranscript(preparation), keptTail };
79
92
  }
80
93
  /**
81
94
  * Discard every compactable line and start a fresh context window.
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;A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,KAAK;oBACpB,eAAe,EAAE,kBAAkB;oBACnC,GAAG,CAAC,YAAY,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,YAAY,CAAC,aAAa,EAAE,CAAC;iBAClG,CAAC,CAAC;YACJ,CAAC;YACD,OAAO,aAAa,CAAC,WAAW,EAAE,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;QAC/E,CAAC;QACD,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,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 { RetryCallbacks, RetryPolicy } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\tconst tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);\n\tconst percentReduction =\n\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;\n\treturn {\n\t\t...result,\n\t\tstats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\treturn { transcript: buildFreshTranscript(preparation), keptTail: getKeptTailTokenEstimate(preparation) <= limit };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower(request.fallback)\n\t\t: undefined;\n\tconst primaryBudget = resolvePlannerRequest(model, request.thinkingLevel);\n\tconst primaryAuth = await resolvePlannerAuth(request.resolveAuth, model);\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = false;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (\"auth\" in primaryAuth) {\n\t\tplanner = { model, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\t// No request was made, but this candidate must not be retried.\n\t\tattempted.add(plannerAttemptKey({ model, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(preparation, attempt.ranges, plannerModel, plannerUsage);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage);\n}\n"]}
1
+ {"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,EAE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QACD,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,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 { 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"]}
@@ -108,6 +108,13 @@ export interface VerbatimCompactionDetails {
108
108
  parameters: VerbatimCompactionParameters;
109
109
  stats: VerbatimCompactionStats;
110
110
  rung: CompactionRung;
111
+ /**
112
+ * Authoritative whole-context count, projected for display only. Populated by
113
+ * `createVerbatimCompactionMessage` on the rendered message; it is not
114
+ * persisted here — the durable entry already carries it as
115
+ * `CompactionEntry.tokensBefore`.
116
+ */
117
+ tokensBefore?: number;
111
118
  /** Present only when a borrowed fallback model ranked the lines. */
112
119
  plannerModel?: CompactionPlannerModel;
113
120
  backupPath?: string;
@@ -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,EAAG,gBAAyB,CAAC;AAEtE,eAAO,MAAM,yBAAyB,MAAM,CAAC;AAC7C,eAAO,MAAM,uBAAuB,IAAI,CAAC;AACzC,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAE/C,MAAM,WAAW,4BAA4B;IAC5C,oDAAoD;IACpD,iBAAiB,EAAE,MAAM,CAAC;IAC1B,gFAAgF;IAChF,eAAe,EAAE,MAAM,CAAC;IACxB,iDAAiD;IACjD,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,SAAS;IACzB,sCAAsC;IACtC,KAAK,EAAE,MAAM,CAAC;IACd,qCAAqC;IACrC,GAAG,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAE/D,MAAM,WAAW,YAAY;IAC5B,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,GAAG,CAAC,EAAE,eAAe,CAAC;CACtB;AAED,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,OAAO,EAAE,gBAAgB,CAAC;IACnC,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,iBAAiB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACvC,aAAa,E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AY,CAAC,EAAE,sBAAsB,CAAC;IACtC,iFAAiF;IACjF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 3 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
1
+ {"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 +1 @@
1
- {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,GAAG,EAAoB,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAElE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1D,MAAM,WAAW,kBAAkB;IAClC,OAAO,EAAE,OAAO,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,gFAAgF;IAChF,iB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GAAG,OAAO,CAGjH;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAC1C,eAAO,MAAM,sBAAsB,QAAuC,CAAC;AAgC3E,mFAAmF;AACnF,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,UAAO,GAAG,MAAM,CAIjF;AAYD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAOzF;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAE5F;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,CA6C5D"}
@@ -209,6 +209,24 @@ export function estimateTokens(message) {
209
209
  if (!message || typeof message !== "object" || !messageIsLlmVisible(message))
210
210
  return 0;
211
211
  switch (message.role) {
212
+ case "system": {
213
+ const system = message;
214
+ let chars = 0;
215
+ if (typeof system.content === "string")
216
+ chars += system.content.length;
217
+ else if (Array.isArray(system.content)) {
218
+ for (const block of system.content) {
219
+ if (block && typeof block === "object" && "text" in block && typeof block.text === "string") {
220
+ chars += block.text.length;
221
+ }
222
+ }
223
+ }
224
+ for (const value of Object.values(system.sections ?? {})) {
225
+ if (typeof value === "string")
226
+ chars += value.length;
227
+ }
228
+ return chars > 0 ? Math.ceil(chars / 4) : 0;
229
+ }
212
230
  case "user":
213
231
  case "custom":
214
232
  return estimateUserLikeContentTokens(message.content);
@@ -1 +1 @@
1
- {"version":3,"file":"compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EAAE,mBAAmB,EAAE,gCAAgC,EAAE,MAAM,gBAAgB,CAAC;AAcvF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AAE,CAAC;YACxE,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QACxD,CAAC;QACD,KAAK,eAAe;YACnB,OAAO,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACzF,CAAC;IAED,OAAO,CAAC,CAAC;AACV,CAAC","sourcesContent":["/**\n * Neutral context-usage metrics for deciding when a session needs compaction.\n */\n\nimport type { Api, AssistantMessage, Usage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { messageIsLlmVisible, userLikeContentBlockIsLlmVisible } from \"../messages.ts\";\nimport type { SessionEntry } from \"../session-manager.ts\";\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\t/** Fraction of compactable context to keep. 0.3 is aggressive, 0.7 is light. */\n\tcompression_ratio: number;\n\t/** Number of recent context-eligible messages to preserve in standard mode. */\n\tpreserve_recent: number;\n\t/** Focus query for relevance-based pruning; auto-detected when omitted in settings/options. */\n\tquery?: string;\n}\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tcompression_ratio: 0.5,\n\tpreserve_recent: 2,\n};\n\n/**\n * Calculate active context-window tokens from provider usage.\n *\n * Prefer normalized component fields over `totalTokens`: some providers expose\n * `totalTokens` as a billing/cumulative total, while the footer needs an active\n * context estimate. Some Anthropic-compatible endpoints mirror cached input in\n * both `input` and `cacheRead`/`cacheWrite`; only Anthropic Messages usage uses\n * the near-equal-bucket guard because OpenAI APIs expose disjoint normalized\n * components that must always be summed.\n */\nexport function calculateContextTokens(usage: Usage, api?: Api): number {\n\tconst input = Math.max(0, usage.input || 0);\n\tconst output = Math.max(0, usage.output || 0);\n\tconst cacheRead = Math.max(0, usage.cacheRead || 0);\n\tconst cacheWrite = Math.max(0, usage.cacheWrite || 0);\n\tconst cacheTokens = cacheRead + cacheWrite;\n\tconst hasComponents = input > 0 || output > 0 || cacheTokens > 0;\n\tif (!hasComponents) return Math.max(0, usage.totalTokens || 0);\n\n\tconst cacheMirrorsInput =\n\t\tapi === \"anthropic-messages\" &&\n\t\tinput > 0 &&\n\t\tcacheTokens > 0 &&\n\t\tcacheTokens >= input * 0.9 &&\n\t\tcacheTokens <= input * 1.1;\n\tconst promptTokens = cacheMirrorsInput ? input : input + cacheTokens;\n\treturn promptTokens + output;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; api: Api; index: number } | undefined {\n\tlet latestPrefixTimestamp = Number.NEGATIVE_INFINITY;\n\tlet usageInfo: { usage: Usage; api: Api; index: number } | undefined;\n\n\tfor (let i = 0; i < messages.length; i++) {\n\t\tconst message = messages[i];\n\t\tconst usage = getAssistantUsage(message);\n\t\tif (\n\t\t\tusage &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.timestamp >= latestPrefixTimestamp &&\n\t\t\tcalculateContextTokens(usage, message.api) > 0\n\t\t) {\n\t\t\tusageInfo = { usage, api: message.api, index: i };\n\t\t}\n\t\tlatestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);\n\t}\n\n\treturn usageInfo;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage, usageInfo.api);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tif (!settings.enabled) return false;\n\treturn contextTokens > contextWindow - settings.reserveTokens;\n}\n\n/**\n * Shared image-token estimation used by every compaction/context-accounting path.\n *\n * Providers fold image tokens into their reported prompt/input usage, so usage-based\n * accounting already captures actual image cost. For heuristic paths (trailing\n * messages without usage, transcript content-block estimates) a single conservative\n * fixed estimate keeps both the context-window threshold check and the transcript\n * planner consistent.\n */\nexport const ESTIMATED_IMAGE_CHARS = 4800;\nexport const ESTIMATED_IMAGE_TOKENS = Math.ceil(ESTIMATED_IMAGE_CHARS / 4);\n\nfunction safeSerializedPayloadLength(value: unknown, fallback: string): number {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\tif (typeof serialized === \"string\") return serialized.length;\n\t} catch {\n\t\t// Cyclic and otherwise unserializable future blocks use a conservative marker below.\n\t}\n\treturn fallback.length;\n}\n\nfunction nonEmptyBlockType(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst type = (block as { type?: unknown }).type;\n\treturn typeof type === \"string\" && type.trim().length > 0 ? type : undefined;\n}\n\nfunction estimateContentBlockChars(block: unknown): number {\n\tconst type = nonEmptyBlockType(block);\n\tif (!type) return 0;\n\tconst record = block as Record<string, unknown>;\n\tif (type === \"image\") return ESTIMATED_IMAGE_CHARS;\n\tif (type === \"text\") return typeof record.text === \"string\" ? record.text.length : 0;\n\tif (type === \"thinking\") return typeof record.thinking === \"string\" ? record.thinking.length : 0;\n\tif (type === \"toolCall\") {\n\t\tconst nameLength = typeof record.name === \"string\" ? record.name.length : 0;\n\t\treturn nameLength + safeSerializedPayloadLength(record.arguments, \"[unserializable tool arguments]\");\n\t}\n\treturn safeSerializedPayloadLength(block, `[unserializable ${type} block]`);\n}\n\n/** Estimate one raw content block after the caller applies provider visibility. */\nexport function estimateContentBlockTokens(block: unknown, visible = true): number {\n\tif (!visible) return 0;\n\tconst chars = estimateContentBlockChars(block);\n\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n}\n\nfunction estimateUserLikeContentTokens(content: unknown): number {\n\tif (typeof content === \"string\") return content.trim().length > 0 ? Math.ceil(content.length / 4) : 0;\n\tif (!Array.isArray(content)) return 0;\n\tconst chars = content.reduce(\n\t\t(total, block) => total + (userLikeContentBlockIsLlmVisible(block) ? estimateContentBlockChars(block) : 0),\n\t\t0,\n\t);\n\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n}\n\n/**\n * Count image content blocks in a message content array (text or block array).\n *\n * Exported as the canonical image-counting contract so tests can verify the\n * heuristic independently of the transcript-based estimation used in production.\n */\nexport function countImageContentBlocks(content: string | Array<{ type: string }>): number {\n\tif (typeof content === \"string\" || !Array.isArray(content)) return 0;\n\tlet count = 0;\n\tfor (const block of content) {\n\t\tif (block && typeof block === \"object\" && block.type === \"image\") count += 1;\n\t}\n\treturn count;\n}\n\n/**\n * Estimate the token cost of only the image content blocks in a message content array.\n *\n * Exported as the canonical image-token-estimation contract so tests can verify\n * the heuristic independently of the transcript-based estimation used in production.\n */\nexport function estimateImageContentTokens(content: string | Array<{ type: string }>): number {\n\treturn countImageContentBlocks(content) * ESTIMATED_IMAGE_TOKENS;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tif (!message || typeof message !== \"object\" || !messageIsLlmVisible(message)) return 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"custom\":\n\t\t\treturn estimateUserLikeContentTokens((message as { content?: unknown }).content);\n\t\tcase \"assistant\": {\n\t\t\tconst content = (message as { content?: unknown }).content;\n\t\t\tif (!Array.isArray(content)) return 0;\n\t\t\tconst chars = content.reduce((total, block) => total + estimateContentBlockChars(block), 0);\n\t\t\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n\t\t}\n\t\tcase \"toolResult\": {\n\t\t\tconst content = (message as { content?: unknown }).content;\n\t\t\tif (!Array.isArray(content)) return 0;\n\t\t\tconst chars = content.reduce((total, block) => total + estimateContentBlockChars(block), 0);\n\t\t\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tconst command = typeof message.command === \"string\" ? message.command : \"\";\n\t\t\tconst output = typeof message.output === \"string\" ? message.output : \"\";\n\t\t\treturn Math.ceil((command.length + output.length) / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\t\treturn typeof message.summary === \"string\" ? Math.ceil(message.summary.length / 4) : 0;\n\t}\n\n\treturn 0;\n}\n"]}
1
+ {"version":3,"file":"compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EAAE,mBAAmB,EAAE,gCAAgC,EAAE,MAAM,gBAAgB,CAAC;AAcvF,MAAM,CAAC,MAAM,2BAA2B,GAAuB;IAC9D,OAAO,EAAE,IAAI;IACb,aAAa,EAAE,KAAK;IACpB,iBAAiB,EAAE,GAAG;IACtB,eAAe,EAAE,CAAC;CAClB,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAAY,EAAE,GAAS;IAC7D,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;IAC5C,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC;IAC9C,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC;IACpD,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC;IACtD,MAAM,WAAW,GAAG,SAAS,GAAG,UAAU,CAAC;IAC3C,MAAM,aAAa,GAAG,KAAK,GAAG,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,CAAC;IACjE,IAAI,CAAC,aAAa;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,IAAI,CAAC,CAAC,CAAC;IAE/D,MAAM,iBAAiB,GACtB,GAAG,KAAK,oBAAoB;QAC5B,KAAK,GAAG,CAAC;QACT,WAAW,GAAG,CAAC;QACf,WAAW,IAAI,KAAK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G,CAAC,CAAC,CAAC;QACxD,CAAC;QACD,KAAK,eAAe;YACnB,OAAO,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACzF,CAAC;IAED,OAAO,CAAC,CAAC;AACV,CAAC","sourcesContent":["/**\n * Neutral context-usage metrics for deciding when a session needs compaction.\n */\n\nimport type { Api, AssistantMessage, Usage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { messageIsLlmVisible, userLikeContentBlockIsLlmVisible } from \"../messages.ts\";\nimport type { SessionEntry } from \"../session-manager.ts\";\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\t/** Fraction of compactable context to keep. 0.3 is aggressive, 0.7 is light. */\n\tcompression_ratio: number;\n\t/** Number of recent context-eligible messages to preserve in standard mode. */\n\tpreserve_recent: number;\n\t/** Focus query for relevance-based pruning; auto-detected when omitted in settings/options. */\n\tquery?: string;\n}\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tcompression_ratio: 0.5,\n\tpreserve_recent: 2,\n};\n\n/**\n * Calculate active context-window tokens from provider usage.\n *\n * Prefer normalized component fields over `totalTokens`: some providers expose\n * `totalTokens` as a billing/cumulative total, while the footer needs an active\n * context estimate. Some Anthropic-compatible endpoints mirror cached input in\n * both `input` and `cacheRead`/`cacheWrite`; only Anthropic Messages usage uses\n * the near-equal-bucket guard because OpenAI APIs expose disjoint normalized\n * components that must always be summed.\n */\nexport function calculateContextTokens(usage: Usage, api?: Api): number {\n\tconst input = Math.max(0, usage.input || 0);\n\tconst output = Math.max(0, usage.output || 0);\n\tconst cacheRead = Math.max(0, usage.cacheRead || 0);\n\tconst cacheWrite = Math.max(0, usage.cacheWrite || 0);\n\tconst cacheTokens = cacheRead + cacheWrite;\n\tconst hasComponents = input > 0 || output > 0 || cacheTokens > 0;\n\tif (!hasComponents) return Math.max(0, usage.totalTokens || 0);\n\n\tconst cacheMirrorsInput =\n\t\tapi === \"anthropic-messages\" &&\n\t\tinput > 0 &&\n\t\tcacheTokens > 0 &&\n\t\tcacheTokens >= input * 0.9 &&\n\t\tcacheTokens <= input * 1.1;\n\tconst promptTokens = cacheMirrorsInput ? input : input + cacheTokens;\n\treturn promptTokens + output;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; api: Api; index: number } | undefined {\n\tlet latestPrefixTimestamp = Number.NEGATIVE_INFINITY;\n\tlet usageInfo: { usage: Usage; api: Api; index: number } | undefined;\n\n\tfor (let i = 0; i < messages.length; i++) {\n\t\tconst message = messages[i];\n\t\tconst usage = getAssistantUsage(message);\n\t\tif (\n\t\t\tusage &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.timestamp >= latestPrefixTimestamp &&\n\t\t\tcalculateContextTokens(usage, message.api) > 0\n\t\t) {\n\t\t\tusageInfo = { usage, api: message.api, index: i };\n\t\t}\n\t\tlatestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);\n\t}\n\n\treturn usageInfo;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage, usageInfo.api);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tif (!settings.enabled) return false;\n\treturn contextTokens > contextWindow - settings.reserveTokens;\n}\n\n/**\n * Shared image-token estimation used by every compaction/context-accounting path.\n *\n * Providers fold image tokens into their reported prompt/input usage, so usage-based\n * accounting already captures actual image cost. For heuristic paths (trailing\n * messages without usage, transcript content-block estimates) a single conservative\n * fixed estimate keeps both the context-window threshold check and the transcript\n * planner consistent.\n */\nexport const ESTIMATED_IMAGE_CHARS = 4800;\nexport const ESTIMATED_IMAGE_TOKENS = Math.ceil(ESTIMATED_IMAGE_CHARS / 4);\n\nfunction safeSerializedPayloadLength(value: unknown, fallback: string): number {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\tif (typeof serialized === \"string\") return serialized.length;\n\t} catch {\n\t\t// Cyclic and otherwise unserializable future blocks use a conservative marker below.\n\t}\n\treturn fallback.length;\n}\n\nfunction nonEmptyBlockType(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst type = (block as { type?: unknown }).type;\n\treturn typeof type === \"string\" && type.trim().length > 0 ? type : undefined;\n}\n\nfunction estimateContentBlockChars(block: unknown): number {\n\tconst type = nonEmptyBlockType(block);\n\tif (!type) return 0;\n\tconst record = block as Record<string, unknown>;\n\tif (type === \"image\") return ESTIMATED_IMAGE_CHARS;\n\tif (type === \"text\") return typeof record.text === \"string\" ? record.text.length : 0;\n\tif (type === \"thinking\") return typeof record.thinking === \"string\" ? record.thinking.length : 0;\n\tif (type === \"toolCall\") {\n\t\tconst nameLength = typeof record.name === \"string\" ? record.name.length : 0;\n\t\treturn nameLength + safeSerializedPayloadLength(record.arguments, \"[unserializable tool arguments]\");\n\t}\n\treturn safeSerializedPayloadLength(block, `[unserializable ${type} block]`);\n}\n\n/** Estimate one raw content block after the caller applies provider visibility. */\nexport function estimateContentBlockTokens(block: unknown, visible = true): number {\n\tif (!visible) return 0;\n\tconst chars = estimateContentBlockChars(block);\n\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n}\n\nfunction estimateUserLikeContentTokens(content: unknown): number {\n\tif (typeof content === \"string\") return content.trim().length > 0 ? Math.ceil(content.length / 4) : 0;\n\tif (!Array.isArray(content)) return 0;\n\tconst chars = content.reduce(\n\t\t(total, block) => total + (userLikeContentBlockIsLlmVisible(block) ? estimateContentBlockChars(block) : 0),\n\t\t0,\n\t);\n\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n}\n\n/**\n * Count image content blocks in a message content array (text or block array).\n *\n * Exported as the canonical image-counting contract so tests can verify the\n * heuristic independently of the transcript-based estimation used in production.\n */\nexport function countImageContentBlocks(content: string | Array<{ type: string }>): number {\n\tif (typeof content === \"string\" || !Array.isArray(content)) return 0;\n\tlet count = 0;\n\tfor (const block of content) {\n\t\tif (block && typeof block === \"object\" && block.type === \"image\") count += 1;\n\t}\n\treturn count;\n}\n\n/**\n * Estimate the token cost of only the image content blocks in a message content array.\n *\n * Exported as the canonical image-token-estimation contract so tests can verify\n * the heuristic independently of the transcript-based estimation used in production.\n */\nexport function estimateImageContentTokens(content: string | Array<{ type: string }>): number {\n\treturn countImageContentBlocks(content) * ESTIMATED_IMAGE_TOKENS;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tif (!message || typeof message !== \"object\" || !messageIsLlmVisible(message)) return 0;\n\n\tswitch (message.role) {\n\t\tcase \"system\": {\n\t\t\tconst system = message as { content?: unknown; sections?: Record<string, string | null> };\n\t\t\tlet chars = 0;\n\t\t\tif (typeof system.content === \"string\") chars += system.content.length;\n\t\t\telse if (Array.isArray(system.content)) {\n\t\t\t\tfor (const block of system.content) {\n\t\t\t\t\tif (block && typeof block === \"object\" && \"text\" in block && typeof block.text === \"string\") {\n\t\t\t\t\t\tchars += block.text.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const value of Object.values(system.sections ?? {})) {\n\t\t\t\tif (typeof value === \"string\") chars += value.length;\n\t\t\t}\n\t\t\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n\t\t}\n\t\tcase \"user\":\n\t\tcase \"custom\":\n\t\t\treturn estimateUserLikeContentTokens((message as { content?: unknown }).content);\n\t\tcase \"assistant\": {\n\t\t\tconst content = (message as { content?: unknown }).content;\n\t\t\tif (!Array.isArray(content)) return 0;\n\t\t\tconst chars = content.reduce((total, block) => total + estimateContentBlockChars(block), 0);\n\t\t\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n\t\t}\n\t\tcase \"toolResult\": {\n\t\t\tconst content = (message as { content?: unknown }).content;\n\t\t\tif (!Array.isArray(content)) return 0;\n\t\t\tconst chars = content.reduce((total, block) => total + estimateContentBlockChars(block), 0);\n\t\t\treturn chars > 0 ? Math.ceil(chars / 4) : 0;\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tconst command = typeof message.command === \"string\" ? message.command : \"\";\n\t\t\tconst output = typeof message.output === \"string\" ? message.output : \"\";\n\t\t\treturn Math.ceil((command.length + output.length) / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\t\treturn typeof message.summary === \"string\" ? Math.ceil(message.summary.length / 4) : 0;\n\t}\n\n\treturn 0;\n}\n"]}
@@ -32,6 +32,7 @@ export interface FallbackPlannerContext {
32
32
  readonly preferredProvider: string | undefined;
33
33
  /** Session level inherited when a candidate carries no `:level` suffix. */
34
34
  readonly sessionThinkingLevel: ThinkingLevel | undefined;
35
+ readonly isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;
35
36
  }
36
37
  /**
37
38
  * 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,QAAQ,CAAC,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AAC;IACzD,QAAQ,CAAC,sBAAsB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC;CAC7F;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,CA+BpG"}
@@ -67,6 +67,8 @@ export function createFallbackPlannerBorrower(context) {
67
67
  }
68
68
  if (!auth)
69
69
  continue;
70
+ if (context.isFallbackModelAllowed && !context.isFallbackModelAllowed(candidate.model, budget.reasoning))
71
+ continue;
70
72
  return { model: candidate.model, budget, auth };
71
73
  }
72
74
  return undefined;
@@ -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,MAAM,uBAAuB,CAAC;AAEpG,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAqB3D;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAwB;IACzD,OAAO,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC7D,CAAC;AAqBD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,6BAA6B,C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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}\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\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;AAsB3D;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAwB;IACzD,OAAO,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC7D,CAAC;AAqBD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,6BAA6B,CAAC,OAA+B;IAC5E,MAAM,IAAI,GAAwB,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAU,EAAE,CAAC;IAChF,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,EAAE;QACvC,OAAO,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC;YACvD,MAAM,KAAK,GAAG,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACrD,mEAAmE;YACnE,IAAI,CAAC,SAAS,IAAI,CAAC,CAAC;YAEpB,MAAM,SAAS,GAAG,oBAAoB,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;YAC3F,IAAI,CAAC,SAAS;gBAAE,SAAS;YACzB,kEAAkE;YAClE,iDAAiD;YACjD,MAAM,MAAM,GAAG,qBAAqB,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC,oBAAoB,EAAE,SAAS,CAAC,aAAa,CAAC,CAAC;YAC7G,MAAM,GAAG,GAAG,WAAW,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;YAC3D,IAAI,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC;gBAAE,SAAS;YAC3D,IAAI,CAAC,QAAQ,CAAC,GAAG,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}\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"]}
@@ -16,4 +16,5 @@ export * from "./region-trimming.js";
16
16
  export * from "./session-summarization.ts";
17
17
  export * from "./transcript-serialization.js";
18
18
  export * from "./utils.ts";
19
+ export * from "./whole-context-stats.js";
19
20
  //# sourceMappingURL=index.d.ts.map
@@ -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"}
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"}