@bastani/atomic 0.9.20-alpha.1 → 0.9.20-alpha.11

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 (1175) hide show
  1. package/CHANGELOG.md +318 -0
  2. package/README.md +52 -7
  3. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  4. package/dist/builtin/intercom/README.md +2 -2
  5. package/dist/builtin/intercom/broker/broker.ts +110 -39
  6. package/dist/builtin/intercom/broker/client.ts +8 -1
  7. package/dist/builtin/intercom/broker/send-handler.ts +59 -2
  8. package/dist/builtin/intercom/index.bundle.mjs +162 -18
  9. package/dist/builtin/intercom/live-route-refusal.ts +69 -0
  10. package/dist/builtin/intercom/package.json +3 -5
  11. package/dist/builtin/intercom/recoverable-disconnect.ts +16 -4
  12. package/dist/builtin/intercom/session-target.ts +34 -9
  13. package/dist/builtin/intercom/skills/intercom/SKILL.md +47 -16
  14. package/dist/builtin/intercom/types.ts +3 -1
  15. package/dist/builtin/mcp/CHANGELOG.md +13 -0
  16. package/dist/builtin/mcp/OAUTH.md +1 -1
  17. package/dist/builtin/mcp/README.md +3 -1
  18. package/dist/builtin/mcp/index.bundle.mjs +412 -64
  19. package/dist/builtin/mcp/package.json +4 -4
  20. package/dist/builtin/subagents/CHANGELOG.md +69 -0
  21. package/dist/builtin/subagents/README.md +4 -2
  22. package/dist/builtin/subagents/agents/code-simplifier.md +3 -4
  23. package/dist/builtin/subagents/agents/codebase-analyzer.md +3 -4
  24. package/dist/builtin/subagents/agents/codebase-locator.md +2 -3
  25. package/dist/builtin/subagents/agents/codebase-online-researcher.md +5 -6
  26. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -3
  27. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +2 -3
  28. package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -3
  29. package/dist/builtin/subagents/agents/debugger.md +8 -7
  30. package/dist/builtin/subagents/agents/worker.md +5 -4
  31. package/dist/builtin/subagents/package.json +4 -4
  32. package/dist/builtin/subagents/skills/agent-browser/SKILL.md +56 -0
  33. package/dist/builtin/subagents/skills/cua-driver/BROWSER.md +494 -0
  34. package/dist/builtin/subagents/skills/cua-driver/EMBEDDING.md +578 -0
  35. package/dist/builtin/subagents/skills/cua-driver/LINUX.md +364 -0
  36. package/dist/builtin/subagents/skills/cua-driver/MACOS.md +509 -0
  37. package/dist/builtin/subagents/skills/cua-driver/README.md +113 -0
  38. package/dist/builtin/subagents/skills/cua-driver/RECORDING.md +162 -0
  39. package/dist/builtin/subagents/skills/cua-driver/SKILL.md +1105 -0
  40. package/dist/builtin/subagents/skills/cua-driver/WINDOWS.md +866 -0
  41. package/dist/builtin/subagents/skills/feedback/SKILL.md +49 -0
  42. package/dist/builtin/subagents/skills/feedback/scripts/scrub.mjs +498 -0
  43. package/dist/builtin/subagents/skills/subagent/SKILL.md +45 -19
  44. package/dist/builtin/subagents/src/extension/index.bundle.mjs +276 -68
  45. package/dist/builtin/web-access/CHANGELOG.md +18 -0
  46. package/dist/builtin/web-access/index.bundle.mjs +372 -300
  47. package/dist/builtin/web-access/package.json +3 -3
  48. package/dist/builtin/workflows/CHANGELOG.md +180 -0
  49. package/dist/builtin/workflows/README.md +20 -33
  50. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  51. package/dist/builtin/workflows/builtin/{chunk-g0csgs7w.js → chunk-18yz7r43.js} +8 -10
  52. package/dist/builtin/workflows/builtin/{chunk-31j2gs7h.js → chunk-1pd5zcfa.js} +4 -6
  53. package/dist/builtin/workflows/builtin/{chunk-ewkkkbak.js → chunk-1q7hfqzd.js} +40 -111
  54. package/dist/builtin/workflows/builtin/{chunk-xtxcq5tj.js → chunk-24c235x7.js} +17 -1
  55. package/dist/builtin/workflows/builtin/{chunk-6w6cvk6b.js → chunk-2jv44yz7.js} +4 -6
  56. package/dist/builtin/workflows/builtin/{chunk-yeee2jrc.js → chunk-2npg6daz.js} +76 -90
  57. package/dist/builtin/workflows/builtin/chunk-73c5tayt.js +10699 -0
  58. package/dist/builtin/workflows/builtin/{chunk-z29qbehr.js → chunk-7ps7bnb4.js} +4 -6
  59. package/dist/builtin/workflows/builtin/{chunk-fg9esgkj.js → chunk-f8jjd90r.js} +4 -6
  60. package/dist/builtin/workflows/builtin/{chunk-a2kdsqn8.js → chunk-gxrhbnaj.js} +5 -3
  61. package/dist/builtin/workflows/builtin/{chunk-zqtm1d2c.js → chunk-s2zgzs4j.js} +13 -218
  62. package/dist/builtin/workflows/builtin/{chunk-wf741bv3.js → chunk-z5xdqrs6.js} +4 -6
  63. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  64. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  65. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  66. package/dist/builtin/workflows/builtin/goal.js +4 -4
  67. package/dist/builtin/workflows/builtin/index.d.ts +1 -1
  68. package/dist/builtin/workflows/builtin/index.js +12 -12
  69. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  70. package/dist/builtin/workflows/builtin/open-claude-design.d.ts +1 -1
  71. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  72. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  73. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  74. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  75. package/dist/builtin/workflows/package.json +4 -4
  76. package/dist/builtin/workflows/skills/impeccable/SKILL.md +18 -11
  77. package/dist/builtin/workflows/skills/impeccable/reference/adapt.md +1 -1
  78. package/dist/builtin/workflows/skills/impeccable/reference/adapt.native.md +1 -1
  79. package/dist/builtin/workflows/skills/impeccable/reference/animate.md +1 -1
  80. package/dist/builtin/workflows/skills/impeccable/reference/audit.md +5 -5
  81. package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +6 -6
  82. package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +2 -2
  83. package/dist/builtin/workflows/skills/impeccable/reference/clarify.md +1 -1
  84. package/dist/builtin/workflows/skills/impeccable/reference/colorize.md +1 -1
  85. package/dist/builtin/workflows/skills/impeccable/reference/craft-floor.md +0 -6
  86. package/dist/builtin/workflows/skills/impeccable/reference/critique.md +19 -41
  87. package/dist/builtin/workflows/skills/impeccable/reference/degraded/asset-producer.md +11 -65
  88. package/dist/builtin/workflows/skills/impeccable/reference/degraded/documenter.md +3 -3
  89. package/dist/builtin/workflows/skills/impeccable/reference/degraded/finish-reviewer.md +4 -4
  90. package/dist/builtin/workflows/skills/impeccable/reference/degraded/manual-edit-applier.md +1 -1
  91. package/dist/builtin/workflows/skills/impeccable/reference/delight.md +1 -1
  92. package/dist/builtin/workflows/skills/impeccable/reference/distill.md +2 -2
  93. package/dist/builtin/workflows/skills/impeccable/reference/doctor.md +4 -4
  94. package/dist/builtin/workflows/skills/impeccable/reference/document.md +4 -4
  95. package/dist/builtin/workflows/skills/impeccable/reference/extract.md +1 -1
  96. package/dist/builtin/workflows/skills/impeccable/reference/harden.md +1 -1
  97. package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +21 -21
  98. package/dist/builtin/workflows/skills/impeccable/reference/init.md +8 -8
  99. package/dist/builtin/workflows/skills/impeccable/reference/layout.md +2 -2
  100. package/dist/builtin/workflows/skills/impeccable/reference/live-setup.md +10 -8
  101. package/dist/builtin/workflows/skills/impeccable/reference/live.md +39 -38
  102. package/dist/builtin/workflows/skills/impeccable/reference/new-work.md +48 -21
  103. package/dist/builtin/workflows/skills/impeccable/reference/onboard.md +1 -1
  104. package/dist/builtin/workflows/skills/impeccable/reference/optimize.md +1 -1
  105. package/dist/builtin/workflows/skills/impeccable/reference/overdrive.md +1 -1
  106. package/dist/builtin/workflows/skills/impeccable/reference/polish.md +11 -3
  107. package/dist/builtin/workflows/skills/impeccable/reference/quieter.md +2 -2
  108. package/dist/builtin/workflows/skills/impeccable/reference/routing.md +13 -7
  109. package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +2 -2
  110. package/dist/builtin/workflows/skills/impeccable/reference/visualize.md +13 -19
  111. package/dist/builtin/workflows/skills/impeccable/scripts/VERSION +1 -0
  112. package/dist/builtin/workflows/skills/impeccable/scripts/data/font-index-failures.json +121 -0
  113. package/dist/builtin/workflows/skills/impeccable/scripts/data/font-index.json +1 -0
  114. package/dist/builtin/workflows/skills/impeccable/scripts/impeccable +212 -0
  115. package/dist/builtin/workflows/skills/impeccable/scripts/impeccable.cmd +218 -0
  116. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-dom.js +21 -0
  117. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-ignores.js +242 -0
  118. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-session.js +25 -4
  119. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +666 -197
  120. package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +10 -9
  121. package/dist/builtin/workflows/skills/prompt-engineer/references/advanced_patterns.md +4 -4
  122. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_fable_5.md +96 -23
  123. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_fable_5_1.md +75 -27
  124. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_4_8.md +72 -26
  125. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_5.md +58 -22
  126. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_5_5.md +118 -0
  127. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_sonnet_5.md +70 -29
  128. package/dist/builtin/workflows/skills/prompt-engineer/references/core_prompting.md +1 -1
  129. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_5_5.md +95 -32
  130. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_5_6.md +79 -30
  131. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6.md +139 -0
  132. package/dist/builtin/workflows/skills/prompt-engineer/references/quality_improvement.md +4 -4
  133. package/dist/builtin/workflows/skills/research-codebase/SKILL.md +1 -1
  134. package/dist/builtin/workflows/src/authoring.d.ts +6 -1
  135. package/dist/builtin/workflows/src/extension/index.bundle.mjs +26549 -22500
  136. package/dist/builtin/workflows/src/index.js +43097 -6424
  137. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +11 -0
  138. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +17 -1
  139. package/dist/bun/split-loader.js +13 -0
  140. package/dist/bun/split-loader.js.map +1 -1
  141. package/dist/cli/args.d.ts.map +1 -1
  142. package/dist/cli/args.js +17 -6
  143. package/dist/cli/args.js.map +1 -1
  144. package/dist/cli/file-processor.d.ts +1 -1
  145. package/dist/cli/file-processor.d.ts.map +1 -1
  146. package/dist/cli/file-processor.js.map +1 -1
  147. package/dist/config.d.ts +1 -0
  148. package/dist/config.d.ts.map +1 -1
  149. package/dist/config.js +1 -0
  150. package/dist/config.js.map +1 -1
  151. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  152. package/dist/core/agent-session-accessors.js +2 -1
  153. package/dist/core/agent-session-accessors.js.map +1 -1
  154. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  155. package/dist/core/agent-session-auto-compaction.js +49 -14
  156. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  157. package/dist/core/agent-session-bash.d.ts +3 -1
  158. package/dist/core/agent-session-bash.d.ts.map +1 -1
  159. package/dist/core/agent-session-bash.js +27 -14
  160. package/dist/core/agent-session-bash.js.map +1 -1
  161. package/dist/core/agent-session-boundaries.d.ts +68 -0
  162. package/dist/core/agent-session-boundaries.d.ts.map +1 -0
  163. package/dist/core/agent-session-boundaries.js +339 -0
  164. package/dist/core/agent-session-boundaries.js.map +1 -0
  165. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  166. package/dist/core/agent-session-compaction.js +38 -15
  167. package/dist/core/agent-session-compaction.js.map +1 -1
  168. package/dist/core/agent-session-events.d.ts +6 -6
  169. package/dist/core/agent-session-events.d.ts.map +1 -1
  170. package/dist/core/agent-session-events.js +175 -74
  171. package/dist/core/agent-session-events.js.map +1 -1
  172. package/dist/core/agent-session-export.d.ts +1 -1
  173. package/dist/core/agent-session-export.d.ts.map +1 -1
  174. package/dist/core/agent-session-export.js +34 -39
  175. package/dist/core/agent-session-export.js.map +1 -1
  176. package/dist/core/agent-session-extension-bindings.d.ts +3 -2
  177. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  178. package/dist/core/agent-session-extension-bindings.js +274 -70
  179. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  180. package/dist/core/agent-session-message-queue.d.ts +1 -1
  181. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  182. package/dist/core/agent-session-message-queue.js +36 -7
  183. package/dist/core/agent-session-message-queue.js.map +1 -1
  184. package/dist/core/agent-session-methods.d.ts +55 -15
  185. package/dist/core/agent-session-methods.d.ts.map +1 -1
  186. package/dist/core/agent-session-methods.js.map +1 -1
  187. package/dist/core/agent-session-models.d.ts +2 -2
  188. package/dist/core/agent-session-models.d.ts.map +1 -1
  189. package/dist/core/agent-session-models.js +38 -29
  190. package/dist/core/agent-session-models.js.map +1 -1
  191. package/dist/core/agent-session-persistent-custom-messages.d.ts +1 -1
  192. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  193. package/dist/core/agent-session-persistent-custom-messages.js +2 -1
  194. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  195. package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
  196. package/dist/core/agent-session-post-tool-compaction.js +18 -1
  197. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  198. package/dist/core/agent-session-prompt.d.ts +1 -1
  199. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  200. package/dist/core/agent-session-prompt.js +186 -36
  201. package/dist/core/agent-session-prompt.js.map +1 -1
  202. package/dist/core/agent-session-queue-pause.d.ts +2 -0
  203. package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
  204. package/dist/core/agent-session-queue-pause.js +15 -3
  205. package/dist/core/agent-session-queue-pause.js.map +1 -1
  206. package/dist/core/agent-session-retry.d.ts +0 -3
  207. package/dist/core/agent-session-retry.d.ts.map +1 -1
  208. package/dist/core/agent-session-retry.js +28 -20
  209. package/dist/core/agent-session-retry.js.map +1 -1
  210. package/dist/core/agent-session-runtime-auth.d.ts.map +1 -1
  211. package/dist/core/agent-session-runtime-auth.js +10 -0
  212. package/dist/core/agent-session-runtime-auth.js.map +1 -1
  213. package/dist/core/agent-session-runtime.d.ts +21 -1
  214. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  215. package/dist/core/agent-session-runtime.js +434 -197
  216. package/dist/core/agent-session-runtime.js.map +1 -1
  217. package/dist/core/agent-session-services.d.ts +4 -0
  218. package/dist/core/agent-session-services.d.ts.map +1 -1
  219. package/dist/core/agent-session-services.js +31 -2
  220. package/dist/core/agent-session-services.js.map +1 -1
  221. package/dist/core/agent-session-state.d.ts +10 -2
  222. package/dist/core/agent-session-state.d.ts.map +1 -1
  223. package/dist/core/agent-session-state.js +32 -22
  224. package/dist/core/agent-session-state.js.map +1 -1
  225. package/dist/core/agent-session-summary.d.ts.map +1 -1
  226. package/dist/core/agent-session-summary.js +9 -2
  227. package/dist/core/agent-session-summary.js.map +1 -1
  228. package/dist/core/agent-session-tasks.d.ts +10 -0
  229. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  230. package/dist/core/agent-session-tasks.js +94 -21
  231. package/dist/core/agent-session-tasks.js.map +1 -1
  232. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  233. package/dist/core/agent-session-tool-hooks.js +41 -8
  234. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  235. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  236. package/dist/core/agent-session-tool-registry.js +13 -26
  237. package/dist/core/agent-session-tool-registry.js.map +1 -1
  238. package/dist/core/agent-session-transfer.js.map +1 -1
  239. package/dist/core/agent-session-tree.d.ts.map +1 -1
  240. package/dist/core/agent-session-tree.js +8 -3
  241. package/dist/core/agent-session-tree.js.map +1 -1
  242. package/dist/core/agent-session-types.d.ts +13 -0
  243. package/dist/core/agent-session-types.d.ts.map +1 -1
  244. package/dist/core/agent-session-types.js.map +1 -1
  245. package/dist/core/agent-session.d.ts +36 -10
  246. package/dist/core/agent-session.d.ts.map +1 -1
  247. package/dist/core/agent-session.js +137 -68
  248. package/dist/core/agent-session.js.map +1 -1
  249. package/dist/core/auth-storage.d.ts +5 -3
  250. package/dist/core/auth-storage.d.ts.map +1 -1
  251. package/dist/core/auth-storage.js +18 -5
  252. package/dist/core/auth-storage.js.map +1 -1
  253. package/dist/core/builtin-diagnostics.d.ts +2 -0
  254. package/dist/core/builtin-diagnostics.d.ts.map +1 -0
  255. package/dist/core/builtin-diagnostics.js +14 -0
  256. package/dist/core/builtin-diagnostics.js.map +1 -0
  257. package/dist/core/builtin-packages.d.ts +5 -2
  258. package/dist/core/builtin-packages.d.ts.map +1 -1
  259. package/dist/core/builtin-packages.js +24 -3
  260. package/dist/core/builtin-packages.js.map +1 -1
  261. package/dist/core/builtin-resource-loader.d.ts +4 -0
  262. package/dist/core/builtin-resource-loader.d.ts.map +1 -0
  263. package/dist/core/builtin-resource-loader.js +239 -0
  264. package/dist/core/builtin-resource-loader.js.map +1 -0
  265. package/dist/core/cache-retention.d.ts +4 -0
  266. package/dist/core/cache-retention.d.ts.map +1 -0
  267. package/dist/core/cache-retention.js +58 -0
  268. package/dist/core/cache-retention.js.map +1 -0
  269. package/dist/core/cache-stats.d.ts +7 -1
  270. package/dist/core/cache-stats.d.ts.map +1 -1
  271. package/dist/core/cache-stats.js +34 -4
  272. package/dist/core/cache-stats.js.map +1 -1
  273. package/dist/core/cache-warmer.d.ts +66 -0
  274. package/dist/core/cache-warmer.d.ts.map +1 -0
  275. package/dist/core/cache-warmer.js +313 -0
  276. package/dist/core/cache-warmer.js.map +1 -0
  277. package/dist/core/child-session-options.d.ts +5 -0
  278. package/dist/core/child-session-options.d.ts.map +1 -0
  279. package/dist/core/child-session-options.js +30 -0
  280. package/dist/core/child-session-options.js.map +1 -0
  281. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  282. package/dist/core/compaction/branch-summarization.js +3 -2
  283. package/dist/core/compaction/branch-summarization.js.map +1 -1
  284. package/dist/core/compaction/compaction-boundary.d.ts +29 -1
  285. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  286. package/dist/core/compaction/compaction-boundary.js +48 -10
  287. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  288. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  289. package/dist/core/compaction/compaction-runner.js +18 -5
  290. package/dist/core/compaction/compaction-runner.js.map +1 -1
  291. package/dist/core/compaction/compaction-types.d.ts +7 -0
  292. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  293. package/dist/core/compaction/compaction-types.js.map +1 -1
  294. package/dist/core/compaction/compaction.d.ts +3 -1
  295. package/dist/core/compaction/compaction.d.ts.map +1 -1
  296. package/dist/core/compaction/compaction.js +55 -0
  297. package/dist/core/compaction/compaction.js.map +1 -1
  298. package/dist/core/compaction/fallback-planner.d.ts +1 -0
  299. package/dist/core/compaction/fallback-planner.d.ts.map +1 -1
  300. package/dist/core/compaction/fallback-planner.js +2 -0
  301. package/dist/core/compaction/fallback-planner.js.map +1 -1
  302. package/dist/core/compaction/index.d.ts +1 -0
  303. package/dist/core/compaction/index.d.ts.map +1 -1
  304. package/dist/core/compaction/index.js +1 -0
  305. package/dist/core/compaction/index.js.map +1 -1
  306. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  307. package/dist/core/compaction/range-planner.js +3 -3
  308. package/dist/core/compaction/range-planner.js.map +1 -1
  309. package/dist/core/compaction/session-summarization.d.ts.map +1 -1
  310. package/dist/core/compaction/session-summarization.js +2 -1
  311. package/dist/core/compaction/session-summarization.js.map +1 -1
  312. package/dist/core/compaction/whole-context-stats.d.ts +21 -0
  313. package/dist/core/compaction/whole-context-stats.d.ts.map +1 -0
  314. package/dist/core/compaction/whole-context-stats.js +32 -0
  315. package/dist/core/compaction/whole-context-stats.js.map +1 -0
  316. package/dist/core/crash-log.d.ts +6 -0
  317. package/dist/core/crash-log.d.ts.map +1 -0
  318. package/dist/core/crash-log.js +69 -0
  319. package/dist/core/crash-log.js.map +1 -0
  320. package/dist/core/credential-screening.d.ts +17 -0
  321. package/dist/core/credential-screening.d.ts.map +1 -0
  322. package/dist/core/credential-screening.js +30 -0
  323. package/dist/core/credential-screening.js.map +1 -0
  324. package/dist/core/execution-model-router.d.ts +45 -0
  325. package/dist/core/execution-model-router.d.ts.map +1 -0
  326. package/dist/core/execution-model-router.js +249 -0
  327. package/dist/core/execution-model-router.js.map +1 -0
  328. package/dist/core/export-html/template-js/tree-filter-render.js +6 -1
  329. package/dist/core/export-html/template.js +6 -1
  330. package/dist/core/extensions/agent-events.d.ts +82 -8
  331. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  332. package/dist/core/extensions/agent-events.js.map +1 -1
  333. package/dist/core/extensions/api-types.d.ts +51 -42
  334. package/dist/core/extensions/api-types.d.ts.map +1 -1
  335. package/dist/core/extensions/api-types.js.map +1 -1
  336. package/dist/core/extensions/context-types.d.ts +7 -1
  337. package/dist/core/extensions/context-types.d.ts.map +1 -1
  338. package/dist/core/extensions/context-types.js.map +1 -1
  339. package/dist/core/extensions/event-results.d.ts +10 -6
  340. package/dist/core/extensions/event-results.d.ts.map +1 -1
  341. package/dist/core/extensions/event-results.js.map +1 -1
  342. package/dist/core/extensions/event-types.d.ts +3 -2
  343. package/dist/core/extensions/event-types.d.ts.map +1 -1
  344. package/dist/core/extensions/event-types.js.map +1 -1
  345. package/dist/core/extensions/extension-work.d.ts +14 -0
  346. package/dist/core/extensions/extension-work.d.ts.map +1 -0
  347. package/dist/core/extensions/extension-work.js +73 -0
  348. package/dist/core/extensions/extension-work.js.map +1 -0
  349. package/dist/core/extensions/herdr-file-integration.d.ts +36 -0
  350. package/dist/core/extensions/herdr-file-integration.d.ts.map +1 -0
  351. package/dist/core/extensions/herdr-file-integration.js +60 -0
  352. package/dist/core/extensions/herdr-file-integration.js.map +1 -0
  353. package/dist/core/extensions/host-input.d.ts +51 -0
  354. package/dist/core/extensions/host-input.d.ts.map +1 -0
  355. package/dist/core/extensions/host-input.js +211 -0
  356. package/dist/core/extensions/host-input.js.map +1 -0
  357. package/dist/core/extensions/index.d.ts +4 -2
  358. package/dist/core/extensions/index.d.ts.map +1 -1
  359. package/dist/core/extensions/index.js +0 -3
  360. package/dist/core/extensions/index.js.map +1 -1
  361. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  362. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  363. package/dist/core/extensions/jiti-loader.js +3 -0
  364. package/dist/core/extensions/jiti-loader.js.map +1 -0
  365. package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
  366. package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
  367. package/dist/core/extensions/jiti-static-loader.js +3 -0
  368. package/dist/core/extensions/jiti-static-loader.js.map +1 -0
  369. package/dist/core/extensions/loader-api.d.ts +7 -0
  370. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  371. package/dist/core/extensions/loader-api.js +154 -28
  372. package/dist/core/extensions/loader-api.js.map +1 -1
  373. package/dist/core/extensions/loader-bindings.d.ts +24 -0
  374. package/dist/core/extensions/loader-bindings.d.ts.map +1 -0
  375. package/dist/core/extensions/loader-bindings.js +128 -0
  376. package/dist/core/extensions/loader-bindings.js.map +1 -0
  377. package/dist/core/extensions/loader-core.d.ts +2 -1
  378. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  379. package/dist/core/extensions/loader-core.js +92 -14
  380. package/dist/core/extensions/loader-core.js.map +1 -1
  381. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  382. package/dist/core/extensions/loader-host-modules.js +3 -1
  383. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  384. package/dist/core/extensions/loader-rollback.d.ts +14 -0
  385. package/dist/core/extensions/loader-rollback.d.ts.map +1 -0
  386. package/dist/core/extensions/loader-rollback.js +95 -0
  387. package/dist/core/extensions/loader-rollback.js.map +1 -0
  388. package/dist/core/extensions/loader-runtime.d.ts +3 -1
  389. package/dist/core/extensions/loader-runtime.d.ts.map +1 -1
  390. package/dist/core/extensions/loader-runtime.js +38 -14
  391. package/dist/core/extensions/loader-runtime.js.map +1 -1
  392. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  393. package/dist/core/extensions/loader-virtual-modules.js +9 -2
  394. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  395. package/dist/core/extensions/loader.d.ts +1 -1
  396. package/dist/core/extensions/loader.d.ts.map +1 -1
  397. package/dist/core/extensions/loader.js +1 -1
  398. package/dist/core/extensions/loader.js.map +1 -1
  399. package/dist/core/extensions/provider-types.d.ts +34 -14
  400. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  401. package/dist/core/extensions/provider-types.js.map +1 -1
  402. package/dist/core/extensions/reactive-widget.d.ts +1 -1
  403. package/dist/core/extensions/reactive-widget.js.map +1 -1
  404. package/dist/core/extensions/runner-context.d.ts +4 -0
  405. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  406. package/dist/core/extensions/runner-context.js +25 -0
  407. package/dist/core/extensions/runner-context.js.map +1 -1
  408. package/dist/core/extensions/runner-events.d.ts +24 -6
  409. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  410. package/dist/core/extensions/runner-events.js +153 -58
  411. package/dist/core/extensions/runner-events.js.map +1 -1
  412. package/dist/core/extensions/runner-project-trust.d.ts.map +1 -1
  413. package/dist/core/extensions/runner-project-trust.js +2 -4
  414. package/dist/core/extensions/runner-project-trust.js.map +1 -1
  415. package/dist/core/extensions/runner.d.ts +34 -6
  416. package/dist/core/extensions/runner.d.ts.map +1 -1
  417. package/dist/core/extensions/runner.js +223 -24
  418. package/dist/core/extensions/runner.js.map +1 -1
  419. package/dist/core/extensions/runtime-types.d.ts +6 -0
  420. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  421. package/dist/core/extensions/runtime-types.js.map +1 -1
  422. package/dist/core/extensions/tool-types.d.ts +9 -0
  423. package/dist/core/extensions/tool-types.d.ts.map +1 -1
  424. package/dist/core/extensions/tool-types.js.map +1 -1
  425. package/dist/core/extensions/types.d.ts +3 -2
  426. package/dist/core/extensions/types.d.ts.map +1 -1
  427. package/dist/core/extensions/types.js +0 -12
  428. package/dist/core/extensions/types.js.map +1 -1
  429. package/dist/core/extensions/workflow-activity-hub.d.ts +2 -0
  430. package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -1
  431. package/dist/core/extensions/workflow-activity-hub.js +5 -3
  432. package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
  433. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  434. package/dist/core/extensions/wrapper.js +5 -3
  435. package/dist/core/extensions/wrapper.js.map +1 -1
  436. package/dist/core/fast-model-routing.d.ts +3 -3
  437. package/dist/core/fast-model-routing.d.ts.map +1 -1
  438. package/dist/core/fast-model-routing.js +4 -3
  439. package/dist/core/fast-model-routing.js.map +1 -1
  440. package/dist/core/fast-model-variants.d.ts +30 -0
  441. package/dist/core/fast-model-variants.d.ts.map +1 -1
  442. package/dist/core/fast-model-variants.js +43 -1
  443. package/dist/core/fast-model-variants.js.map +1 -1
  444. package/dist/core/index.d.ts +4 -1
  445. package/dist/core/index.d.ts.map +1 -1
  446. package/dist/core/index.js +2 -0
  447. package/dist/core/index.js.map +1 -1
  448. package/dist/core/mandatory-resource-loader.d.ts +4 -0
  449. package/dist/core/mandatory-resource-loader.d.ts.map +1 -1
  450. package/dist/core/mandatory-resource-loader.js +29 -1
  451. package/dist/core/mandatory-resource-loader.js.map +1 -1
  452. package/dist/core/mandatory-runtime-tools.d.ts +1 -4
  453. package/dist/core/mandatory-runtime-tools.d.ts.map +1 -1
  454. package/dist/core/mandatory-runtime-tools.js +1 -9
  455. package/dist/core/mandatory-runtime-tools.js.map +1 -1
  456. package/dist/core/messages.d.ts +10 -0
  457. package/dist/core/messages.d.ts.map +1 -1
  458. package/dist/core/messages.js +76 -2
  459. package/dist/core/messages.js.map +1 -1
  460. package/dist/core/model-config.d.ts +178 -10
  461. package/dist/core/model-config.d.ts.map +1 -1
  462. package/dist/core/model-config.js +48 -19
  463. package/dist/core/model-config.js.map +1 -1
  464. package/dist/core/model-registry.d.ts +6 -2
  465. package/dist/core/model-registry.d.ts.map +1 -1
  466. package/dist/core/model-registry.js +12 -2
  467. package/dist/core/model-registry.js.map +1 -1
  468. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  469. package/dist/core/model-resolver-defaults.js +2 -1
  470. package/dist/core/model-resolver-defaults.js.map +1 -1
  471. package/dist/core/model-routing-constraints.d.ts +24 -0
  472. package/dist/core/model-routing-constraints.d.ts.map +1 -0
  473. package/dist/core/model-routing-constraints.js +46 -0
  474. package/dist/core/model-routing-constraints.js.map +1 -0
  475. package/dist/core/model-routing-task.d.ts +4 -0
  476. package/dist/core/model-routing-task.d.ts.map +1 -0
  477. package/dist/core/model-routing-task.js +77 -0
  478. package/dist/core/model-routing-task.js.map +1 -0
  479. package/dist/core/model-runtime-auth.d.ts +2 -2
  480. package/dist/core/model-runtime-auth.d.ts.map +1 -1
  481. package/dist/core/model-runtime-auth.js.map +1 -1
  482. package/dist/core/model-runtime-streaming.d.ts +13 -3
  483. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  484. package/dist/core/model-runtime-streaming.js +16 -5
  485. package/dist/core/model-runtime-streaming.js.map +1 -1
  486. package/dist/core/model-runtime-types.d.ts +2 -2
  487. package/dist/core/model-runtime-types.d.ts.map +1 -1
  488. package/dist/core/model-runtime-types.js.map +1 -1
  489. package/dist/core/model-runtime.d.ts +29 -6
  490. package/dist/core/model-runtime.d.ts.map +1 -1
  491. package/dist/core/model-runtime.js +84 -7
  492. package/dist/core/model-runtime.js.map +1 -1
  493. package/dist/core/package-manager-npm.d.ts.map +1 -1
  494. package/dist/core/package-manager-npm.js +32 -8
  495. package/dist/core/package-manager-npm.js.map +1 -1
  496. package/dist/core/package-manager-resolver.js +3 -1
  497. package/dist/core/package-manager-resolver.js.map +1 -1
  498. package/dist/core/package-manager-types.d.ts +1 -0
  499. package/dist/core/package-manager-types.d.ts.map +1 -1
  500. package/dist/core/package-manager-types.js.map +1 -1
  501. package/dist/core/prompt-templates-async.d.ts +2 -2
  502. package/dist/core/prompt-templates-async.d.ts.map +1 -1
  503. package/dist/core/prompt-templates-async.js +57 -29
  504. package/dist/core/prompt-templates-async.js.map +1 -1
  505. package/dist/core/prompt-templates.d.ts +6 -1
  506. package/dist/core/prompt-templates.d.ts.map +1 -1
  507. package/dist/core/prompt-templates.js +61 -35
  508. package/dist/core/prompt-templates.js.map +1 -1
  509. package/dist/core/provider-composer-internal.d.ts +41 -20
  510. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  511. package/dist/core/provider-composer-internal.js +43 -20
  512. package/dist/core/provider-composer-internal.js.map +1 -1
  513. package/dist/core/provider-composer.d.ts +3 -3
  514. package/dist/core/provider-composer.d.ts.map +1 -1
  515. package/dist/core/provider-composer.js +54 -10
  516. package/dist/core/provider-composer.js.map +1 -1
  517. package/dist/core/remote-catalog-provider.d.ts +8 -1
  518. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  519. package/dist/core/remote-catalog-provider.js +46 -4
  520. package/dist/core/remote-catalog-provider.js.map +1 -1
  521. package/dist/core/resolve-config-value.d.ts +2 -0
  522. package/dist/core/resolve-config-value.d.ts.map +1 -1
  523. package/dist/core/resolve-config-value.js +23 -1
  524. package/dist/core/resolve-config-value.js.map +1 -1
  525. package/dist/core/resource-loader-assets.d.ts.map +1 -1
  526. package/dist/core/resource-loader-assets.js +6 -6
  527. package/dist/core/resource-loader-assets.js.map +1 -1
  528. package/dist/core/resource-loader-core.d.ts +6 -0
  529. package/dist/core/resource-loader-core.d.ts.map +1 -1
  530. package/dist/core/resource-loader-core.js +41 -6
  531. package/dist/core/resource-loader-core.js.map +1 -1
  532. package/dist/core/resource-loader-extension-warnings.d.ts +9 -0
  533. package/dist/core/resource-loader-extension-warnings.d.ts.map +1 -0
  534. package/dist/core/resource-loader-extension-warnings.js +54 -0
  535. package/dist/core/resource-loader-extension-warnings.js.map +1 -0
  536. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  537. package/dist/core/resource-loader-extensions.js +3 -0
  538. package/dist/core/resource-loader-extensions.js.map +1 -1
  539. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  540. package/dist/core/resource-loader-reload.js +13 -2
  541. package/dist/core/resource-loader-reload.js.map +1 -1
  542. package/dist/core/resource-loader.d.ts +1 -1
  543. package/dist/core/resource-loader.d.ts.map +1 -1
  544. package/dist/core/resource-loader.js +1 -1
  545. package/dist/core/resource-loader.js.map +1 -1
  546. package/dist/core/runtime-credentials.d.ts +2 -0
  547. package/dist/core/runtime-credentials.d.ts.map +1 -1
  548. package/dist/core/runtime-credentials.js +18 -1
  549. package/dist/core/runtime-credentials.js.map +1 -1
  550. package/dist/core/sdk-types.d.ts +18 -5
  551. package/dist/core/sdk-types.d.ts.map +1 -1
  552. package/dist/core/sdk-types.js.map +1 -1
  553. package/dist/core/sdk.d.ts +3 -1
  554. package/dist/core/sdk.d.ts.map +1 -1
  555. package/dist/core/sdk.js +231 -42
  556. package/dist/core/sdk.js.map +1 -1
  557. package/dist/core/session-lifecycle-scope.d.ts +15 -0
  558. package/dist/core/session-lifecycle-scope.d.ts.map +1 -0
  559. package/dist/core/session-lifecycle-scope.js +13 -0
  560. package/dist/core/session-lifecycle-scope.js.map +1 -0
  561. package/dist/core/session-lifecycle-work.d.ts +17 -0
  562. package/dist/core/session-lifecycle-work.d.ts.map +1 -0
  563. package/dist/core/session-lifecycle-work.js +144 -0
  564. package/dist/core/session-lifecycle-work.js.map +1 -0
  565. package/dist/core/session-manager-core.d.ts +19 -6
  566. package/dist/core/session-manager-core.d.ts.map +1 -1
  567. package/dist/core/session-manager-core.js +117 -12
  568. package/dist/core/session-manager-core.js.map +1 -1
  569. package/dist/core/session-manager-entries.d.ts +4 -1
  570. package/dist/core/session-manager-entries.d.ts.map +1 -1
  571. package/dist/core/session-manager-entries.js +8 -0
  572. package/dist/core/session-manager-entries.js.map +1 -1
  573. package/dist/core/session-manager-history.d.ts +16 -1
  574. package/dist/core/session-manager-history.d.ts.map +1 -1
  575. package/dist/core/session-manager-history.js +106 -40
  576. package/dist/core/session-manager-history.js.map +1 -1
  577. package/dist/core/session-manager-list.d.ts +3 -3
  578. package/dist/core/session-manager-list.d.ts.map +1 -1
  579. package/dist/core/session-manager-list.js +89 -74
  580. package/dist/core/session-manager-list.js.map +1 -1
  581. package/dist/core/session-manager-storage.d.ts.map +1 -1
  582. package/dist/core/session-manager-storage.js +10 -7
  583. package/dist/core/session-manager-storage.js.map +1 -1
  584. package/dist/core/session-manager-types.d.ts +41 -4
  585. package/dist/core/session-manager-types.d.ts.map +1 -1
  586. package/dist/core/session-manager-types.js.map +1 -1
  587. package/dist/core/session-manager.d.ts +2 -2
  588. package/dist/core/session-manager.d.ts.map +1 -1
  589. package/dist/core/session-manager.js +1 -1
  590. package/dist/core/session-manager.js.map +1 -1
  591. package/dist/core/session-startup-rollback.d.ts +5 -0
  592. package/dist/core/session-startup-rollback.d.ts.map +1 -0
  593. package/dist/core/session-startup-rollback.js +16 -0
  594. package/dist/core/session-startup-rollback.js.map +1 -0
  595. package/dist/core/settings-manager-basic-accessors.d.ts +5 -0
  596. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  597. package/dist/core/settings-manager-basic-accessors.js +35 -0
  598. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  599. package/dist/core/settings-manager-core.d.ts.map +1 -1
  600. package/dist/core/settings-manager-core.js +4 -0
  601. package/dist/core/settings-manager-core.js.map +1 -1
  602. package/dist/core/settings-manager.d.ts +1 -0
  603. package/dist/core/settings-manager.d.ts.map +1 -1
  604. package/dist/core/settings-manager.js +1 -0
  605. package/dist/core/settings-manager.js.map +1 -1
  606. package/dist/core/settings-types.d.ts +4 -0
  607. package/dist/core/settings-types.d.ts.map +1 -1
  608. package/dist/core/settings-types.js +1 -1
  609. package/dist/core/settings-types.js.map +1 -1
  610. package/dist/core/settings-write-ownership.d.ts +7 -0
  611. package/dist/core/settings-write-ownership.d.ts.map +1 -0
  612. package/dist/core/settings-write-ownership.js +24 -0
  613. package/dist/core/settings-write-ownership.js.map +1 -0
  614. package/dist/core/skill-catalog.d.ts.map +1 -1
  615. package/dist/core/skill-catalog.js +18 -6
  616. package/dist/core/skill-catalog.js.map +1 -1
  617. package/dist/core/slash-commands.js +1 -1
  618. package/dist/core/slash-commands.js.map +1 -1
  619. package/dist/core/structured-output/choice-schema.d.ts +8 -0
  620. package/dist/core/structured-output/choice-schema.d.ts.map +1 -0
  621. package/dist/core/structured-output/choice-schema.js +79 -0
  622. package/dist/core/structured-output/choice-schema.js.map +1 -0
  623. package/dist/core/structured-output/index.d.ts +10 -0
  624. package/dist/core/structured-output/index.d.ts.map +1 -0
  625. package/dist/core/structured-output/index.js +424 -0
  626. package/dist/core/structured-output/index.js.map +1 -0
  627. package/dist/core/structured-output/invalid-output.d.ts +8 -0
  628. package/dist/core/structured-output/invalid-output.d.ts.map +1 -0
  629. package/dist/core/structured-output/invalid-output.js +4 -0
  630. package/dist/core/structured-output/invalid-output.js.map +1 -0
  631. package/dist/core/structured-output/resolver.d.ts +3 -0
  632. package/dist/core/structured-output/resolver.d.ts.map +1 -0
  633. package/dist/core/structured-output/resolver.js +26 -0
  634. package/dist/core/structured-output/resolver.js.map +1 -0
  635. package/dist/core/structured-output/types.d.ts +76 -0
  636. package/dist/core/structured-output/types.d.ts.map +1 -0
  637. package/dist/core/structured-output/types.js +2 -0
  638. package/dist/core/structured-output/types.js.map +1 -0
  639. package/dist/core/system-prompt.d.ts +48 -5
  640. package/dist/core/system-prompt.d.ts.map +1 -1
  641. package/dist/core/system-prompt.js +141 -100
  642. package/dist/core/system-prompt.js.map +1 -1
  643. package/dist/core/tasks/child-command-owner.d.ts +34 -0
  644. package/dist/core/tasks/child-command-owner.d.ts.map +1 -0
  645. package/dist/core/tasks/child-command-owner.js +70 -0
  646. package/dist/core/tasks/child-command-owner.js.map +1 -0
  647. package/dist/core/tasks/contracts.d.ts +6 -0
  648. package/dist/core/tasks/contracts.d.ts.map +1 -1
  649. package/dist/core/tasks/contracts.js.map +1 -1
  650. package/dist/core/tasks/owner-store.d.ts +6 -0
  651. package/dist/core/tasks/owner-store.d.ts.map +1 -1
  652. package/dist/core/tasks/owner-store.js +16 -3
  653. package/dist/core/tasks/owner-store.js.map +1 -1
  654. package/dist/core/tasks/pause.js +1 -1
  655. package/dist/core/tasks/pause.js.map +1 -1
  656. package/dist/core/tasks/supervisor.d.ts +4 -2
  657. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  658. package/dist/core/tasks/supervisor.js +16 -3
  659. package/dist/core/tasks/supervisor.js.map +1 -1
  660. package/dist/core/tools/ask-user-question/ask-user-question.d.ts +4 -1
  661. package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -1
  662. package/dist/core/tools/ask-user-question/ask-user-question.js +32 -35
  663. package/dist/core/tools/ask-user-question/ask-user-question.js.map +1 -1
  664. package/dist/core/tools/ask-user-question/index.d.ts +1 -1
  665. package/dist/core/tools/ask-user-question/index.js.map +1 -1
  666. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts +1 -1
  667. package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -1
  668. package/dist/core/tools/ask-user-question/state/key-router.d.ts +1 -1
  669. package/dist/core/tools/ask-user-question/state/key-router.js.map +1 -1
  670. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts +1 -1
  671. package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -1
  672. package/dist/core/tools/ask-user-question/state/row-intent.d.ts +1 -1
  673. package/dist/core/tools/ask-user-question/state/row-intent.js.map +1 -1
  674. package/dist/core/tools/ask-user-question/state/selectors/contract.d.ts +1 -1
  675. package/dist/core/tools/ask-user-question/state/selectors/contract.js.map +1 -1
  676. package/dist/core/tools/ask-user-question/state/selectors/derivations.d.ts +1 -1
  677. package/dist/core/tools/ask-user-question/state/selectors/derivations.js.map +1 -1
  678. package/dist/core/tools/ask-user-question/state/state-reducer.d.ts +1 -1
  679. package/dist/core/tools/ask-user-question/state/state-reducer.js.map +1 -1
  680. package/dist/core/tools/ask-user-question/state/state.d.ts +1 -1
  681. package/dist/core/tools/ask-user-question/state/state.js.map +1 -1
  682. package/dist/core/tools/ask-user-question/tool/format-answer.d.ts +1 -1
  683. package/dist/core/tools/ask-user-question/tool/format-answer.js.map +1 -1
  684. package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts +1 -1
  685. package/dist/core/tools/ask-user-question/tool/response-envelope.js.map +1 -1
  686. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.d.ts +1 -1
  687. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.js.map +1 -1
  688. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts +1 -1
  689. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -1
  690. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.d.ts +1 -1
  691. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js.map +1 -1
  692. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts +1 -1
  693. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -1
  694. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.d.ts +1 -1
  695. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.js.map +1 -1
  696. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts +1 -1
  697. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js.map +1 -1
  698. package/dist/core/tools/ask-user-question/view/components/submit-picker.js.map +1 -1
  699. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js.map +1 -1
  700. package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts +1 -1
  701. package/dist/core/tools/ask-user-question/view/dialog-builder.js.map +1 -1
  702. package/dist/core/tools/ask-user-question/view/props-adapter.d.ts +1 -1
  703. package/dist/core/tools/ask-user-question/view/props-adapter.js.map +1 -1
  704. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts +1 -1
  705. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -1
  706. package/dist/core/tools/bash-pty-native.d.ts +5 -1
  707. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  708. package/dist/core/tools/bash-pty-native.js +15 -7
  709. package/dist/core/tools/bash-pty-native.js.map +1 -1
  710. package/dist/core/tools/bash.d.ts.map +1 -1
  711. package/dist/core/tools/bash.js +32 -24
  712. package/dist/core/tools/bash.js.map +1 -1
  713. package/dist/core/tools/edit.d.ts.map +1 -1
  714. package/dist/core/tools/edit.js +1 -0
  715. package/dist/core/tools/edit.js.map +1 -1
  716. package/dist/core/tools/file-mutation-coordinator.d.ts +4 -3
  717. package/dist/core/tools/file-mutation-coordinator.d.ts.map +1 -1
  718. package/dist/core/tools/file-mutation-coordinator.js +45 -38
  719. package/dist/core/tools/file-mutation-coordinator.js.map +1 -1
  720. package/dist/core/tools/find.d.ts +2 -2
  721. package/dist/core/tools/find.d.ts.map +1 -1
  722. package/dist/core/tools/find.js +1 -1
  723. package/dist/core/tools/find.js.map +1 -1
  724. package/dist/core/tools/kill.d.ts +2 -2
  725. package/dist/core/tools/kill.d.ts.map +1 -1
  726. package/dist/core/tools/kill.js +3 -4
  727. package/dist/core/tools/kill.js.map +1 -1
  728. package/dist/core/tools/powershell.d.ts +16 -0
  729. package/dist/core/tools/powershell.d.ts.map +1 -1
  730. package/dist/core/tools/read.d.ts +4 -0
  731. package/dist/core/tools/read.d.ts.map +1 -1
  732. package/dist/core/tools/read.js +5 -1
  733. package/dist/core/tools/read.js.map +1 -1
  734. package/dist/core/tools/structured-output.d.ts +9 -6
  735. package/dist/core/tools/structured-output.d.ts.map +1 -1
  736. package/dist/core/tools/structured-output.js +36 -8
  737. package/dist/core/tools/structured-output.js.map +1 -1
  738. package/dist/core/tools/todos.d.ts.map +1 -1
  739. package/dist/core/tools/todos.js +1 -0
  740. package/dist/core/tools/todos.js.map +1 -1
  741. package/dist/core/tools/tool-concurrency.d.ts +23 -0
  742. package/dist/core/tools/tool-concurrency.d.ts.map +1 -0
  743. package/dist/core/tools/tool-concurrency.js +58 -0
  744. package/dist/core/tools/tool-concurrency.js.map +1 -0
  745. package/dist/core/tools/tool-definition-wrapper.d.ts +4 -1
  746. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  747. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  748. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  749. package/dist/core/tools/write.d.ts.map +1 -1
  750. package/dist/core/tools/write.js +1 -0
  751. package/dist/core/tools/write.js.map +1 -1
  752. package/dist/core/usage-totals.d.ts.map +1 -1
  753. package/dist/core/usage-totals.js +4 -0
  754. package/dist/core/usage-totals.js.map +1 -1
  755. package/dist/extensions/herdr/index.d.ts.map +1 -1
  756. package/dist/extensions/herdr/index.js +0 -7
  757. package/dist/extensions/herdr/index.js.map +1 -1
  758. package/dist/extensions/llama/client.d.ts +2 -0
  759. package/dist/extensions/llama/client.d.ts.map +1 -1
  760. package/dist/extensions/llama/client.js +6 -2
  761. package/dist/extensions/llama/client.js.map +1 -1
  762. package/dist/extensions/llama/provider.d.ts.map +1 -1
  763. package/dist/extensions/llama/provider.js +18 -4
  764. package/dist/extensions/llama/provider.js.map +1 -1
  765. package/dist/index-extensions.d.ts +1 -1
  766. package/dist/index-extensions.d.ts.map +1 -1
  767. package/dist/index-extensions.js.map +1 -1
  768. package/dist/index.d.ts +13 -4
  769. package/dist/index.d.ts.map +1 -1
  770. package/dist/index.js +8 -3
  771. package/dist/index.js.map +1 -1
  772. package/dist/main-app-mode.d.ts +1 -1
  773. package/dist/main-app-mode.d.ts.map +1 -1
  774. package/dist/main-app-mode.js +3 -2
  775. package/dist/main-app-mode.js.map +1 -1
  776. package/dist/main-session.d.ts.map +1 -1
  777. package/dist/main-session.js +24 -16
  778. package/dist/main-session.js.map +1 -1
  779. package/dist/main.d.ts.map +1 -1
  780. package/dist/main.js +9 -6
  781. package/dist/main.js.map +1 -1
  782. package/dist/modes/interactive/components/atomic-banner.d.ts.map +1 -1
  783. package/dist/modes/interactive/components/atomic-banner.js +3 -2
  784. package/dist/modes/interactive/components/atomic-banner.js.map +1 -1
  785. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  786. package/dist/modes/interactive/components/branch-summary-message.js +12 -5
  787. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  788. package/dist/modes/interactive/components/chat-message-renderer.d.ts +5 -1
  789. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  790. package/dist/modes/interactive/components/chat-message-renderer.js +4 -0
  791. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  792. package/dist/modes/interactive/components/chat-session-host-events.d.ts +2 -2
  793. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  794. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
  795. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  796. package/dist/modes/interactive/components/compaction-boundary-message.js +30 -12
  797. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  798. package/dist/modes/interactive/components/custom-editor.d.ts +6 -0
  799. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  800. package/dist/modes/interactive/components/custom-editor.js +17 -0
  801. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  802. package/dist/modes/interactive/components/host-input-form-mount.d.ts +1 -1
  803. package/dist/modes/interactive/components/host-input-form-mount.js.map +1 -1
  804. package/dist/modes/interactive/components/host-input-form.d.ts +1 -1
  805. package/dist/modes/interactive/components/host-input-form.js.map +1 -1
  806. package/dist/modes/interactive/components/host-session-picker.d.ts +1 -1
  807. package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
  808. package/dist/modes/interactive/components/reserved-bottom-overlay.d.ts +1 -1
  809. package/dist/modes/interactive/components/reserved-bottom-overlay.js.map +1 -1
  810. package/dist/modes/interactive/components/scroll-widget.d.ts +1 -1
  811. package/dist/modes/interactive/components/scroll-widget.js.map +1 -1
  812. package/dist/modes/interactive/components/settings-selector-handlers.d.ts.map +1 -1
  813. package/dist/modes/interactive/components/settings-selector-handlers.js +3 -0
  814. package/dist/modes/interactive/components/settings-selector-handlers.js.map +1 -1
  815. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  816. package/dist/modes/interactive/components/settings-selector-items.js +52 -1
  817. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  818. package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
  819. package/dist/modes/interactive/components/settings-selector-submenus.js +2 -1
  820. package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
  821. package/dist/modes/interactive/components/settings-selector-types.d.ts +8 -2
  822. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  823. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  824. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  825. package/dist/modes/interactive/components/skill-invocation-message.js +11 -4
  826. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  827. package/dist/modes/interactive/components/startup-identity.d.ts +3 -0
  828. package/dist/modes/interactive/components/startup-identity.d.ts.map +1 -1
  829. package/dist/modes/interactive/components/startup-identity.js +11 -2
  830. package/dist/modes/interactive/components/startup-identity.js.map +1 -1
  831. package/dist/modes/interactive/components/task-inspector.d.ts +1 -0
  832. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  833. package/dist/modes/interactive/components/task-inspector.js +11 -11
  834. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  835. package/dist/modes/interactive/components/task-list.d.ts +9 -3
  836. package/dist/modes/interactive/components/task-list.d.ts.map +1 -1
  837. package/dist/modes/interactive/components/task-list.js +26 -2
  838. package/dist/modes/interactive/components/task-list.js.map +1 -1
  839. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  840. package/dist/modes/interactive/components/tool-execution.js +14 -9
  841. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  842. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  843. package/dist/modes/interactive/components/tree-selector-content.js +6 -0
  844. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  845. package/dist/modes/interactive/components/tree-selector-model.d.ts.map +1 -1
  846. package/dist/modes/interactive/components/tree-selector-model.js +1 -0
  847. package/dist/modes/interactive/components/tree-selector-model.js.map +1 -1
  848. package/dist/modes/interactive/interactive-agent-events.js +20 -10
  849. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  850. package/dist/modes/interactive/interactive-auth-login.js +3 -5
  851. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  852. package/dist/modes/interactive/interactive-auth-routing.js +2 -2
  853. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  854. package/dist/modes/interactive/interactive-autocomplete.js +4 -0
  855. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  856. package/dist/modes/interactive/interactive-bash-compact.d.ts.map +1 -1
  857. package/dist/modes/interactive/interactive-bash-compact.js +13 -6
  858. package/dist/modes/interactive/interactive-bash-compact.js.map +1 -1
  859. package/dist/modes/interactive/interactive-extension-runtime.js +5 -0
  860. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  861. package/dist/modes/interactive/interactive-input-handling.js +2 -2
  862. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  863. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  864. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  865. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  866. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  867. package/dist/modes/interactive/interactive-mode-helpers.d.ts +1 -0
  868. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  869. package/dist/modes/interactive/interactive-mode-helpers.js +16 -0
  870. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  871. package/dist/modes/interactive/interactive-mode-surface.d.ts +2 -1
  872. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  873. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  874. package/dist/modes/interactive/interactive-process-lifecycle.js +13 -1
  875. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  876. package/dist/modes/interactive/interactive-render-chat.js +30 -34
  877. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  878. package/dist/modes/interactive/interactive-resource-rendering.js +6 -9
  879. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  880. package/dist/modes/interactive/interactive-selectors.js +11 -0
  881. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  882. package/dist/modes/interactive/interactive-session-runtime.js +5 -1
  883. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  884. package/dist/modes/interactive/interactive-slash-commands.js +2 -4
  885. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  886. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  887. package/dist/modes/interactive/interactive-startup.js +2 -2
  888. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  889. package/dist/modes/interactive/interactive-tui.d.ts +3 -6
  890. package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
  891. package/dist/modes/interactive/interactive-tui.js +15 -5
  892. package/dist/modes/interactive/interactive-tui.js.map +1 -1
  893. package/dist/modes/interactive/overlay-line-composite.d.ts +7 -0
  894. package/dist/modes/interactive/overlay-line-composite.d.ts.map +1 -0
  895. package/dist/modes/interactive/overlay-line-composite.js +24 -0
  896. package/dist/modes/interactive/overlay-line-composite.js.map +1 -0
  897. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  898. package/dist/modes/interactive-engine/engine-custom-ui.js +3 -1
  899. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  900. package/dist/modes/interactive-engine/engine-input-form.d.ts +1 -1
  901. package/dist/modes/interactive-engine/engine-input-form.js.map +1 -1
  902. package/dist/modes/interactive-engine/engine-session-picker.d.ts +1 -1
  903. package/dist/modes/interactive-engine/engine-session-picker.js.map +1 -1
  904. package/dist/modes/interactive-engine/isolated-auth.d.ts +16 -0
  905. package/dist/modes/interactive-engine/isolated-auth.d.ts.map +1 -1
  906. package/dist/modes/interactive-engine/isolated-auth.js +27 -0
  907. package/dist/modes/interactive-engine/isolated-auth.js.map +1 -1
  908. package/dist/modes/interactive-engine/isolated-runtime.d.ts +5 -0
  909. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  910. package/dist/modes/interactive-engine/isolated-runtime.js +19 -2
  911. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  912. package/dist/modes/interactive-engine/protocol.d.ts +1 -1
  913. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  914. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  915. package/dist/modes/rpc/rpc-client-api.d.ts +2 -1
  916. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  917. package/dist/modes/rpc/rpc-client-api.js +7 -2
  918. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  919. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  920. package/dist/modes/rpc/rpc-command-handler.js +3 -1
  921. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  922. package/dist/modes/rpc/rpc-keybindings-reload.d.ts +1 -1
  923. package/dist/modes/rpc/rpc-keybindings-reload.js.map +1 -1
  924. package/dist/modes/rpc/rpc-provider-auth.d.ts +3 -2
  925. package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -1
  926. package/dist/modes/rpc/rpc-provider-auth.js +2 -2
  927. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  928. package/dist/modes/rpc/rpc-types.d.ts +2 -0
  929. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  930. package/dist/modes/rpc/rpc-types.js.map +1 -1
  931. package/dist/session-id-target.d.ts +31 -0
  932. package/dist/session-id-target.d.ts.map +1 -0
  933. package/dist/session-id-target.js +57 -0
  934. package/dist/session-id-target.js.map +1 -0
  935. package/dist/utils/abort.d.ts.map +1 -1
  936. package/dist/utils/abort.js +29 -4
  937. package/dist/utils/abort.js.map +1 -1
  938. package/dist/utils/child-process.d.ts +1 -0
  939. package/dist/utils/child-process.d.ts.map +1 -1
  940. package/dist/utils/child-process.js +7 -8
  941. package/dist/utils/child-process.js.map +1 -1
  942. package/dist/utils/clipboard-image.d.ts.map +1 -1
  943. package/dist/utils/clipboard-image.js +15 -29
  944. package/dist/utils/clipboard-image.js.map +1 -1
  945. package/dist/utils/clipboard.d.ts.map +1 -1
  946. package/dist/utils/clipboard.js +88 -12
  947. package/dist/utils/clipboard.js.map +1 -1
  948. package/dist/utils/mime.js +1 -1
  949. package/dist/utils/mime.js.map +1 -1
  950. package/dist/utils/shell.d.ts.map +1 -1
  951. package/dist/utils/shell.js +18 -1
  952. package/dist/utils/shell.js.map +1 -1
  953. package/dist/utils/tool-result-images.d.ts +3 -1
  954. package/dist/utils/tool-result-images.d.ts.map +1 -1
  955. package/dist/utils/tool-result-images.js +4 -1
  956. package/dist/utils/tool-result-images.js.map +1 -1
  957. package/dist/utils/wsl.d.ts +3 -0
  958. package/dist/utils/wsl.d.ts.map +1 -0
  959. package/dist/utils/wsl.js +15 -0
  960. package/dist/utils/wsl.js.map +1 -0
  961. package/docs/background-tasks.md +36 -16
  962. package/docs/build.md +6 -16
  963. package/docs/compaction/reference.md +12 -12
  964. package/docs/compaction.md +33 -109
  965. package/docs/computer-use.md +124 -76
  966. package/docs/containerization.md +4 -5
  967. package/docs/custom-provider/api-reference.md +10 -1
  968. package/docs/custom-provider/oauth.md +4 -2
  969. package/docs/custom-provider/registration.md +1 -1
  970. package/docs/custom-provider/streaming.md +8 -3
  971. package/docs/custom-provider.md +44 -2
  972. package/docs/development.md +13 -138
  973. package/docs/docs.json +19 -4
  974. package/docs/environment-variables.md +21 -5
  975. package/docs/extensions/api-reference.md +6 -2
  976. package/docs/extensions/authoring.md +29 -7
  977. package/docs/extensions/events.md +107 -31
  978. package/docs/extensions/examples.md +1 -0
  979. package/docs/extensions/ui.md +3 -4
  980. package/docs/extensions.md +28 -20
  981. package/docs/getting-started/authentication.md +4 -1
  982. package/docs/getting-started/first-session.md +11 -8
  983. package/docs/getting-started/installation.md +14 -6
  984. package/docs/getting-started/project-instructions.md +5 -1
  985. package/docs/guides/configuration.md +10 -5
  986. package/docs/guides/non-interactive.md +2 -2
  987. package/docs/guides.md +8 -17
  988. package/docs/herdr.md +2 -1
  989. package/docs/index.md +2 -2
  990. package/docs/intercom/operations.md +25 -67
  991. package/docs/intercom/reference.md +15 -5
  992. package/docs/intercom.md +16 -7
  993. package/docs/json.md +12 -2
  994. package/docs/keybindings.md +15 -8
  995. package/docs/llama-cpp.md +6 -2
  996. package/docs/mcp-servers.md +93 -0
  997. package/docs/models/evals.md +75 -465
  998. package/docs/models/model-selection.md +35 -116
  999. package/docs/models/reference.md +70 -24
  1000. package/docs/models.md +7 -4
  1001. package/docs/packages/authoring.md +8 -2
  1002. package/docs/packages/reference.md +5 -1
  1003. package/docs/packages.md +7 -3
  1004. package/docs/programmatic.md +3 -1
  1005. package/docs/prompt-templates.md +3 -2
  1006. package/docs/providers/reference.md +2 -2
  1007. package/docs/providers.md +55 -18
  1008. package/docs/quickstart.md +8 -4
  1009. package/docs/reference/cli.md +21 -13
  1010. package/docs/reference.md +3 -6
  1011. package/docs/rpc/examples.md +2 -0
  1012. package/docs/rpc/protocol.md +11 -13
  1013. package/docs/rpc.md +5 -1
  1014. package/docs/sdk/reference.md +62 -267
  1015. package/docs/sdk/structured-decisions.md +94 -0
  1016. package/docs/sdk.md +194 -19
  1017. package/docs/security.md +7 -4
  1018. package/docs/session-format.md +35 -7
  1019. package/docs/sessions.md +12 -6
  1020. package/docs/settings.md +68 -16
  1021. package/docs/skills/authoring.md +7 -1
  1022. package/docs/skills.md +33 -8
  1023. package/docs/subagents/authoring.md +11 -1
  1024. package/docs/subagents/reference.md +97 -10
  1025. package/docs/subagents.md +52 -36
  1026. package/docs/terminal-setup.md +4 -2
  1027. package/docs/termux.md +3 -1
  1028. package/docs/themes/reference.md +4 -1
  1029. package/docs/themes.md +1 -1
  1030. package/docs/tools.md +431 -20
  1031. package/docs/tui/reference.md +13 -14
  1032. package/docs/tui.md +10 -6
  1033. package/docs/usage.md +34 -7
  1034. package/docs/web-access.md +5 -1
  1035. package/docs/windows.md +18 -11
  1036. package/docs/workflows/api-reference.md +112 -27
  1037. package/docs/workflows/authoring.md +345 -33
  1038. package/docs/workflows/builtins.md +22 -28
  1039. package/docs/workflows/operations.md +255 -140
  1040. package/docs/workflows/reliable-design.md +59 -130
  1041. package/docs/workflows/verification.md +40 -14
  1042. package/docs/workflows.md +12 -17
  1043. package/examples/extensions/README.md +1 -0
  1044. package/examples/extensions/custom-provider-anthropic/index.ts +15 -10
  1045. package/examples/extensions/custom-provider-gitlab-duo/index.ts +2 -2
  1046. package/examples/extensions/debug-provider.ts +90 -0
  1047. package/examples/extensions/prompt-customizer.ts +17 -37
  1048. package/examples/extensions/structured-output.ts +6 -0
  1049. package/examples/rpc-client.ts +38 -0
  1050. package/examples/rpc-extension-ui.ts +19 -5
  1051. package/examples/sdk/README.md +1 -1
  1052. package/npm-shrinkwrap.json +506 -713
  1053. package/package.json +13 -11
  1054. package/dist/builtin/subagents/skills/playwright-cli/SKILL.md +0 -420
  1055. package/dist/builtin/subagents/skills/playwright-cli/references/element-attributes.md +0 -23
  1056. package/dist/builtin/subagents/skills/playwright-cli/references/playwright-tests.md +0 -39
  1057. package/dist/builtin/subagents/skills/playwright-cli/references/request-mocking.md +0 -87
  1058. package/dist/builtin/subagents/skills/playwright-cli/references/running-code.md +0 -241
  1059. package/dist/builtin/subagents/skills/playwright-cli/references/session-management.md +0 -225
  1060. package/dist/builtin/subagents/skills/playwright-cli/references/storage-state.md +0 -275
  1061. package/dist/builtin/subagents/skills/playwright-cli/references/test-generation.md +0 -433
  1062. package/dist/builtin/subagents/skills/playwright-cli/references/tracing.md +0 -139
  1063. package/dist/builtin/subagents/skills/playwright-cli/references/video-recording.md +0 -143
  1064. package/dist/builtin/workflows/builtin/chunk-m0xfsef8.js +0 -2813
  1065. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_asset_producer.toml +0 -94
  1066. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_documenter.toml +0 -27
  1067. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_finish_reviewer.toml +0 -41
  1068. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_manual_edit_applier.toml +0 -95
  1069. package/dist/builtin/workflows/skills/impeccable/agents/openai.yaml +0 -4
  1070. package/dist/builtin/workflows/skills/impeccable/scripts/concept-seed.mjs +0 -695
  1071. package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +0 -325
  1072. package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +0 -1503
  1073. package/dist/builtin/workflows/skills/impeccable/scripts/critique-storage.mjs +0 -222
  1074. package/dist/builtin/workflows/skills/impeccable/scripts/detect-csp.mjs +0 -198
  1075. package/dist/builtin/workflows/skills/impeccable/scripts/detect.mjs +0 -21
  1076. package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +0 -2073
  1077. package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +0 -432
  1078. package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +0 -1121
  1079. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +0 -8746
  1080. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns.mjs +0 -51
  1081. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs +0 -376
  1082. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +0 -1168
  1083. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/css-cascade.mjs +0 -1192
  1084. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs +0 -290
  1085. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/visual/screenshot-contrast.mjs +0 -189
  1086. package/dist/builtin/workflows/skills/impeccable/scripts/detector/findings.mjs +0 -18
  1087. package/dist/builtin/workflows/skills/impeccable/scripts/detector/node/file-system.mjs +0 -213
  1088. package/dist/builtin/workflows/skills/impeccable/scripts/detector/profile/profiler.mjs +0 -166
  1089. package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +0 -617
  1090. package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +0 -5534
  1091. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/color.mjs +0 -588
  1092. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/constants.mjs +0 -112
  1093. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/fonts.mjs +0 -30
  1094. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/inline-ignores.mjs +0 -148
  1095. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/page.mjs +0 -35
  1096. package/dist/builtin/workflows/skills/impeccable/scripts/doctor.mjs +0 -338
  1097. package/dist/builtin/workflows/skills/impeccable/scripts/embed-prompt.mjs +0 -270
  1098. package/dist/builtin/workflows/skills/impeccable/scripts/generate-image.mjs +0 -277
  1099. package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +0 -783
  1100. package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +0 -2305
  1101. package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +0 -78
  1102. package/dist/builtin/workflows/skills/impeccable/scripts/lib/artifact-schema.mjs +0 -93
  1103. package/dist/builtin/workflows/skills/impeccable/scripts/lib/composition-catalog.mjs +0 -200
  1104. package/dist/builtin/workflows/skills/impeccable/scripts/lib/concept-catalog.mjs +0 -395
  1105. package/dist/builtin/workflows/skills/impeccable/scripts/lib/design-parser.mjs +0 -925
  1106. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +0 -640
  1107. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-paths.mjs +0 -137
  1108. package/dist/builtin/workflows/skills/impeccable/scripts/lib/is-generated.mjs +0 -72
  1109. package/dist/builtin/workflows/skills/impeccable/scripts/lib/open-system-browser.mjs +0 -57
  1110. package/dist/builtin/workflows/skills/impeccable/scripts/lib/provider.mjs +0 -5
  1111. package/dist/builtin/workflows/skills/impeccable/scripts/lib/roll-selection.mjs +0 -369
  1112. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-deep.mjs +0 -483
  1113. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-notice.mjs +0 -169
  1114. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness.mjs +0 -528
  1115. package/dist/builtin/workflows/skills/impeccable/scripts/lib/surface-briefs.mjs +0 -151
  1116. package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-args.mjs +0 -42
  1117. package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-slug.mjs +0 -33
  1118. package/dist/builtin/workflows/skills/impeccable/scripts/lib/template-extensions.mjs +0 -146
  1119. package/dist/builtin/workflows/skills/impeccable/scripts/live/accept-css.mjs +0 -617
  1120. package/dist/builtin/workflows/skills/impeccable/scripts/live/accept-verify.mjs +0 -71
  1121. package/dist/builtin/workflows/skills/impeccable/scripts/live/browser-script-parts.mjs +0 -77
  1122. package/dist/builtin/workflows/skills/impeccable/scripts/live/completion.mjs +0 -28
  1123. package/dist/builtin/workflows/skills/impeccable/scripts/live/event-validation.mjs +0 -199
  1124. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/astro.mjs +0 -47
  1125. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/detect-utils.mjs +0 -157
  1126. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/index.mjs +0 -143
  1127. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/journal.mjs +0 -205
  1128. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/nextjs.mjs +0 -49
  1129. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/nuxt.mjs +0 -170
  1130. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/script-src.mjs +0 -26
  1131. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/static-html.mjs +0 -26
  1132. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/sveltekit.mjs +0 -71
  1133. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/tag-strategy.mjs +0 -247
  1134. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/tanstack-start.mjs +0 -70
  1135. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/vite-generic.mjs +0 -42
  1136. package/dist/builtin/workflows/skills/impeccable/scripts/live/generation-preflight.mjs +0 -149
  1137. package/dist/builtin/workflows/skills/impeccable/scripts/live/insert-ui.mjs +0 -458
  1138. package/dist/builtin/workflows/skills/impeccable/scripts/live/instructions.mjs +0 -169
  1139. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-apply.mjs +0 -939
  1140. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-edit-routes.mjs +0 -357
  1141. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-edits-buffer.mjs +0 -152
  1142. package/dist/builtin/workflows/skills/impeccable/scripts/live/poll-lanes.mjs +0 -14
  1143. package/dist/builtin/workflows/skills/impeccable/scripts/live/roots.mjs +0 -670
  1144. package/dist/builtin/workflows/skills/impeccable/scripts/live/session-store.mjs +0 -563
  1145. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-lock.mjs +0 -105
  1146. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-search.mjs +0 -105
  1147. package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-ast.mjs +0 -969
  1148. package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-component.mjs +0 -1401
  1149. package/dist/builtin/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs +0 -314
  1150. package/dist/builtin/workflows/skills/impeccable/scripts/live/tanstack-adapter.mjs +0 -280
  1151. package/dist/builtin/workflows/skills/impeccable/scripts/live/ui-surfaces.mjs +0 -75
  1152. package/dist/builtin/workflows/skills/impeccable/scripts/live/vocabulary.mjs +0 -171
  1153. package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +0 -961
  1154. package/dist/builtin/workflows/skills/impeccable/scripts/live-commit-manual-edits.mjs +0 -1244
  1155. package/dist/builtin/workflows/skills/impeccable/scripts/live-complete.mjs +0 -107
  1156. package/dist/builtin/workflows/skills/impeccable/scripts/live-copy-edit-agent.mjs +0 -800
  1157. package/dist/builtin/workflows/skills/impeccable/scripts/live-discard-manual-edits.mjs +0 -51
  1158. package/dist/builtin/workflows/skills/impeccable/scripts/live-inject.mjs +0 -515
  1159. package/dist/builtin/workflows/skills/impeccable/scripts/live-insert.mjs +0 -292
  1160. package/dist/builtin/workflows/skills/impeccable/scripts/live-manual-edit-evidence.mjs +0 -371
  1161. package/dist/builtin/workflows/skills/impeccable/scripts/live-poll.mjs +0 -427
  1162. package/dist/builtin/workflows/skills/impeccable/scripts/live-resume.mjs +0 -123
  1163. package/dist/builtin/workflows/skills/impeccable/scripts/live-server.mjs +0 -1675
  1164. package/dist/builtin/workflows/skills/impeccable/scripts/live-status.mjs +0 -71
  1165. package/dist/builtin/workflows/skills/impeccable/scripts/live-target.mjs +0 -30
  1166. package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +0 -927
  1167. package/dist/builtin/workflows/skills/impeccable/scripts/live.mjs +0 -365
  1168. package/dist/builtin/workflows/skills/impeccable/scripts/palette.mjs +0 -628
  1169. package/dist/builtin/workflows/skills/impeccable/scripts/pin.mjs +0 -224
  1170. package/dist/builtin/workflows/skills/impeccable/scripts/serve-question.mjs +0 -1540
  1171. package/dist/builtin/workflows/skills/impeccable/scripts/surface-brief.mjs +0 -74
  1172. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_astra.md +0 -58
  1173. package/docs/models/artificial-analysis-index.md +0 -89
  1174. package/docs/models/pareto-efficiency.md +0 -90
  1175. package/docs/tools/edit.md +0 -378
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAUpE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAsC3F,SAAS,QAAQ,CAAC,KAAwB,EAAE,KAAY;IACvD,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,YAAY,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC,CAAC;IAC5E,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC;IACnE,OAAO;QACN,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK;QACxC,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,IAAI,C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etryCallbacks, 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,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3F,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAsCpE,SAAS,QAAQ,CAAC,KAAwB,EAAE,KAAY;IACvD,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,YAAY,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC,CAAC;IAC5E,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC;IACnE,OAAO;QACN,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK;QACxC,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,MAAM;QAC3C,SAAS,EAAE,CAAC,KAAK,EAAE,SAAS,IAAI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,eAAe,EAAE,OAAO,CAAC,eAAe;oBACxC,KAAK,EAAE,OAAO,CAAC,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, 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,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B,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,uBAAuB,CAAC;IAC/B,UAAU,EAAE,4BAA4B,CAAC;IACzC,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,iFAAiF;IACjF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
1
+ {"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,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;IACr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M,CAAC;IACrB,UAAU,EAAE,4BAA4B,CAAC;IACzC,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,uBAAuB,CAAC;IAC/B,UAAU,EAAE,4BAA4B,CAAC;IACzC,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,iFAAiF;IACjF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, 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"]}
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import type { Api, Usage } from "@bastani/pi-ai/compat";
5
5
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
6
- import type { SessionEntry } from "../session-manager.ts";
6
+ import type { SessionEntry, SessionProjection } from "../session-manager.ts";
7
7
  export interface CompactionSettings {
8
8
  enabled: boolean;
9
9
  reserveTokens: number;
@@ -41,6 +41,8 @@ export interface ContextUsageEstimate {
41
41
  * If there are messages after the last usage, estimate their tokens with estimateTokens.
42
42
  */
43
43
  export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;
44
+ /** Estimate projected context without trusting usage captured before a later edit or compaction. */
45
+ export declare function estimateProjectedContextTokens(projection: SessionProjection, branchEntries: SessionEntry[]): ContextUsageEstimate;
44
46
  /**
45
47
  * Check if compaction should trigger based on context usage.
46
48
  */
@@ -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,iBAAiB,EAAE,MAAM,CAAC;IAC1B,+EAA+E;IAC/E,eAAe,EAAE,MAAM,CAAC;IACxB,+FAA+F;IAC/F,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,eAAO,MAAM,2BAA2B,EAAE,kBAKzC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE,GAAG,GAAG,MAAM,CAiBtE;AAgBD;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EA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AM,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,CAkD5D"}
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Neutral context-usage metrics for deciding when a session needs compaction.
3
3
  */
4
+ import { getCurrentSystemMessage } from "@bastani/pi-ai";
4
5
  import { messageIsLlmVisible, userLikeContentBlockIsLlmVisible } from "../messages.js";
5
6
  export const DEFAULT_COMPACTION_SETTINGS = {
6
7
  enabled: true,
@@ -108,6 +109,40 @@ export function estimateContextTokens(messages) {
108
109
  lastUsageIndex: usageInfo.index,
109
110
  };
110
111
  }
112
+ /** Estimate projected context without trusting usage captured before a later edit or compaction. */
113
+ export function estimateProjectedContextTokens(projection, branchEntries) {
114
+ const estimate = estimateContextTokens(projection.messages);
115
+ if (estimate.lastUsageIndex !== null) {
116
+ let projectedMessageIndex = 0;
117
+ let usageEntryId;
118
+ for (const entry of projection.entries) {
119
+ const nextMessageIndex = projectedMessageIndex + entry.messages.length;
120
+ if (estimate.lastUsageIndex < nextMessageIndex) {
121
+ usageEntryId = entry.sourceEntry.id;
122
+ break;
123
+ }
124
+ projectedMessageIndex = nextMessageIndex;
125
+ }
126
+ const usageEntryIndex = usageEntryId ? branchEntries.findIndex((entry) => entry.id === usageEntryId) : -1;
127
+ let latestInvalidatingEntryIndex = -1;
128
+ for (let i = branchEntries.length - 1; i >= 0; i--) {
129
+ const entry = branchEntries[i];
130
+ if (entry.type === "context_edit" || entry.type === "compaction") {
131
+ latestInvalidatingEntryIndex = i;
132
+ break;
133
+ }
134
+ }
135
+ if (usageEntryIndex > latestInvalidatingEntryIndex)
136
+ return estimate;
137
+ }
138
+ const currentSystem = getCurrentSystemMessage(projection.messages);
139
+ let tokens = currentSystem ? estimateTokens(currentSystem) : 0;
140
+ for (const message of projection.messages) {
141
+ if (message.role !== "system")
142
+ tokens += estimateTokens(message);
143
+ }
144
+ return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
145
+ }
111
146
  /**
112
147
  * Check if compaction should trigger based on context usage.
113
148
  */
@@ -209,6 +244,26 @@ export function estimateTokens(message) {
209
244
  if (!message || typeof message !== "object" || !messageIsLlmVisible(message))
210
245
  return 0;
211
246
  switch (message.role) {
247
+ case "system": {
248
+ const system = message;
249
+ let chars = 0;
250
+ if (typeof system.content === "string")
251
+ chars += system.content.length;
252
+ else if (Array.isArray(system.content)) {
253
+ for (const block of system.content) {
254
+ if (block && typeof block === "object" && "text" in block && typeof block.text === "string") {
255
+ chars += block.text.length;
256
+ }
257
+ }
258
+ }
259
+ for (const value of Object.values(system.sections ?? {})) {
260
+ if (typeof value === "string")
261
+ chars += value.length;
262
+ }
263
+ if (system.toolsAdded)
264
+ chars += safeSerializedPayloadLength(system.toolsAdded, "");
265
+ return chars > 0 ? Math.ceil(chars / 4) : 0;
266
+ }
212
267
  case "user":
213
268
  case "custom":
214
269
  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,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,sBAA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O,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;AAEH,OAAO,EAAE,uBAAuB,EAAE,MA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;QAC7C,CAAC;QACD,KAAK,eAAe,EAAE,CAAC;YACtB,MAAM,OAAO,GAAG,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3E,MAAM,MAAM,GAAG,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,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 { getCurrentSystemMessage } from \"@bastani/pi-ai\";\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, SessionProjection } 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/** Estimate projected context without trusting usage captured before a later edit or compaction. */\nexport function estimateProjectedContextTokens(\n\tprojection: SessionProjection,\n\tbranchEntries: SessionEntry[],\n): ContextUsageEstimate {\n\tconst estimate = estimateContextTokens(projection.messages);\n\tif (estimate.lastUsageIndex !== null) {\n\t\tlet projectedMessageIndex = 0;\n\t\tlet usageEntryId: string | undefined;\n\t\tfor (const entry of projection.entries) {\n\t\t\tconst nextMessageIndex = projectedMessageIndex + entry.messages.length;\n\t\t\tif (estimate.lastUsageIndex < nextMessageIndex) {\n\t\t\t\tusageEntryId = entry.sourceEntry.id;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprojectedMessageIndex = nextMessageIndex;\n\t\t}\n\n\t\tconst usageEntryIndex = usageEntryId ? branchEntries.findIndex((entry) => entry.id === usageEntryId) : -1;\n\t\tlet latestInvalidatingEntryIndex = -1;\n\t\tfor (let i = branchEntries.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branchEntries[i];\n\t\t\tif (entry.type === \"context_edit\" || entry.type === \"compaction\") {\n\t\t\t\tlatestInvalidatingEntryIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (usageEntryIndex > latestInvalidatingEntryIndex) return estimate;\n\t}\n\n\tconst currentSystem = getCurrentSystemMessage(projection.messages);\n\tlet tokens = currentSystem ? estimateTokens(currentSystem) : 0;\n\tfor (const message of projection.messages) {\n\t\tif (message.role !== \"system\") tokens += estimateTokens(message);\n\t}\n\treturn { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };\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 {\n\t\t\t\tcontent?: unknown;\n\t\t\t\tsections?: Record<string, string | null>;\n\t\t\t\ttoolsAdded?: unknown;\n\t\t\t};\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\tif (system.toolsAdded) chars += safeSerializedPayloadLength(system.toolsAdded, \"\");\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,MA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ACH,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,iBAAiB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/C,2EAA2E;IAC3E,QAAQ,CAAC,oBAAoB,EAAE,aAAa,GAAG,SAAS,CAAC;IACzD,QAAQ,CAAC,sBAAsB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC;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,EA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,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,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}\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,EA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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"}
@@ -16,4 +16,5 @@ export * from "./region-trimming.js";
16
16
  export * from "./session-summarization.js";
17
17
  export * from "./transcript-serialization.js";
18
18
  export * from "./utils.js";
19
+ export * from "./whole-context-stats.js";
19
20
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC","sourcesContent":["/**\n * Compaction support utilities.\n */\n\nexport * from \"./branch-summarization.ts\";\nexport * from \"./compaction.ts\";\nexport * from \"./compaction-boundary.js\";\nexport * from \"./compaction-parameters.js\";\nexport * from \"./compaction-runner.js\";\nexport * from \"./compaction-types.js\";\nexport * from \"./deleted-ranges.js\";\nexport * from \"./fallback-planner.js\";\nexport * from \"./planner-outcome.js\";\nexport * from \"./range-planner.js\";\nexport * from \"./range-planner-diagnostics.js\";\nexport * from \"./region-trimming.js\";\nexport * from \"./session-summarization.ts\";\nexport * from \"./transcript-serialization.js\";\nexport * from \"./utils.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC","sourcesContent":["/**\n * Compaction support utilities.\n */\n\nexport * from \"./branch-summarization.ts\";\nexport * from \"./compaction.ts\";\nexport * from \"./compaction-boundary.js\";\nexport * from \"./compaction-parameters.js\";\nexport * from \"./compaction-runner.js\";\nexport * from \"./compaction-types.js\";\nexport * from \"./deleted-ranges.js\";\nexport * from \"./fallback-planner.js\";\nexport * from \"./planner-outcome.js\";\nexport * from \"./range-planner.js\";\nexport * from \"./range-planner-diagnostics.js\";\nexport * from \"./region-trimming.js\";\nexport * from \"./session-summarization.ts\";\nexport * from \"./transcript-serialization.js\";\nexport * from \"./utils.ts\";\nexport * from \"./whole-context-stats.js\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"range-planner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/range-planner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,WAAW,EAA8B,MAAM,gBAAgB,CAAC;AACnG,OAAO,KAAK,EAAE,GAAG,EAAoB,KAAK,EAAuB,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAEtG,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,KAAK,EACX,eAAe,EACf,cAAc,EACd,aAAa,EACb,YAAY,EACZ,4BAA4B,EAC5B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAMnF,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,eAAO,MAAM,2BAA2B,8fAE+N,CAAC;AAExQ,qBAAa,cAAe,SAAQ,KAAK;IACxC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,gBAAgB,EAAE,OAAO,CAAC;IACnC,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5C,4EAA4E;IAC5E,QAAQ,CAAC,OAAO,EAAE,sBAAsB,GAAG,SAAS,CAAC;IAErD,YACC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,mBAAmB,EAAE,MAAM,EAC3B,gBAAgB,EAAE,OAAO,EACzB,cAAc,CAAC,EAAE,MAAM,EACvB,OAAO,CAAC,EAAE,sBAAsB,EAShC;CACD;AAED,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,QAAQ,CAAC;IACnB,qFAAqF;IACrF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,KAAK,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gBAAgB,EAAE,CAAC;AAO5B,wBAAgB,uBAAuB,CACtC,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,4BAA4B,EACxC,eAAe,SAAiE,GAC9E,MAAM,CAsDR;AAWD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CACpC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,oBAAoB,EAAE,aAAa,GAAG,SAAS,EAC/C,sBAAsB,CAAC,EAAE,aAAa,GACpC,aAAa,CAGf;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,eAAe,GAAG,KAAK,CAAC,GAAG,CAAC,CAIxE;AAED,eAAO,MAAM,wBAAwB,gEAAgE,CAAC;AACtG,eAAO,MAAM,wBAAwB,wDAAwD,CAAC;AAyE9F;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CAC1C,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,4BAA4B,EACxC,OAAO,EAAE,eAAe,EACxB,eAAe,EAAE,MAAM,EACvB,OAAO,EAAE,mBAAmB,GAAG;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GACrD,OAAO,CAAC,cAAc,CAAC,CAyFzB"}
@@ -1,4 +1,4 @@
1
- import { retryAssistantCall, uuidv7 } from "@bastani/pi-ai";
1
+ import { normalizeContext, retryAssistantCall, uuidv7 } from "@bastani/pi-ai";
2
2
  import { isContextOverflow } from "@bastani/pi-ai/compat";
3
3
  import { validateDeletedRanges } from "./deleted-ranges.js";
4
4
  import { classifyPlannerFailure, isReasoningStarved, syntheticErrorResponse } from "./planner-outcome.js";
@@ -187,10 +187,10 @@ export async function planDeletedLineRanges(region, parameters, planner, targetK
187
187
  throw new Error("Compaction cancelled");
188
188
  const prompt = buildRangePlannerPrompt(region, parameters, targetKeepLines);
189
189
  const model = plannerRequestModel(planner);
190
- const context = {
190
+ const context = normalizeContext({
191
191
  systemPrompt: RANGE_PLANNER_SYSTEM_PROMPT,
192
192
  messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }],
193
- };
193
+ });
194
194
  const reasoning = planner.budget.reasoning;
195
195
  // No `maxTokens` property is constructed at all: pi-ai's context clamp is the
196
196
  // only bound on planner output.