@code-yeongyu/senpi 2026.9.7 → 2026.9.9-2

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 (470) hide show
  1. package/CHANGELOG.md +122 -3
  2. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  3. package/dist/core/agent-session-runtime.js +2 -0
  4. package/dist/core/agent-session-runtime.js.map +1 -1
  5. package/dist/core/agent-session.d.ts +48 -4
  6. package/dist/core/agent-session.d.ts.map +1 -1
  7. package/dist/core/agent-session.js +192 -40
  8. package/dist/core/agent-session.js.map +1 -1
  9. package/dist/core/compaction/compaction-execution.d.ts.map +1 -1
  10. package/dist/core/compaction/compaction-execution.js +5 -5
  11. package/dist/core/compaction/compaction-execution.js.map +1 -1
  12. package/dist/core/compaction/compaction-settings.d.ts +2 -0
  13. package/dist/core/compaction/compaction-settings.d.ts.map +1 -1
  14. package/dist/core/compaction/compaction-settings.js.map +1 -1
  15. package/dist/core/compaction/compaction.d.ts +3 -3
  16. package/dist/core/compaction/compaction.d.ts.map +1 -1
  17. package/dist/core/compaction/compaction.js +14 -8
  18. package/dist/core/compaction/compaction.js.map +1 -1
  19. package/dist/core/compaction/stream-watchdog.d.ts +29 -0
  20. package/dist/core/compaction/stream-watchdog.d.ts.map +1 -1
  21. package/dist/core/compaction/stream-watchdog.js +35 -0
  22. package/dist/core/compaction/stream-watchdog.js.map +1 -1
  23. package/dist/core/compaction-settings-access.d.ts +6 -0
  24. package/dist/core/compaction-settings-access.d.ts.map +1 -1
  25. package/dist/core/compaction-settings-access.js.map +1 -1
  26. package/dist/core/compaction-settings-resolver.d.ts +2 -0
  27. package/dist/core/compaction-settings-resolver.d.ts.map +1 -1
  28. package/dist/core/compaction-settings-resolver.js +5 -0
  29. package/dist/core/compaction-settings-resolver.js.map +1 -1
  30. package/dist/core/dynamic-prompt/working-task.js +1 -1
  31. package/dist/core/dynamic-prompt/working-task.js.map +1 -1
  32. package/dist/core/extensions/builtin/cache-keepalive/index.d.ts.map +1 -1
  33. package/dist/core/extensions/builtin/cache-keepalive/index.js +4 -21
  34. package/dist/core/extensions/builtin/cache-keepalive/index.js.map +1 -1
  35. package/dist/core/extensions/builtin/claude-sdk-oauth/account-command.d.ts +2 -0
  36. package/dist/core/extensions/builtin/claude-sdk-oauth/account-command.d.ts.map +1 -1
  37. package/dist/core/extensions/builtin/claude-sdk-oauth/account-command.js +10 -25
  38. package/dist/core/extensions/builtin/claude-sdk-oauth/account-command.js.map +1 -1
  39. package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.d.ts.map +1 -1
  40. package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js +36 -19
  41. package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js.map +1 -1
  42. package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.d.ts.map +1 -1
  43. package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.js +21 -10
  44. package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.js.map +1 -1
  45. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts +4 -17
  46. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts.map +1 -1
  47. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js +23 -33
  48. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js.map +1 -1
  49. package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.d.ts.map +1 -1
  50. package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js +5 -1
  51. package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js.map +1 -1
  52. package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.d.ts.map +1 -1
  53. package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js +5 -3
  54. package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js.map +1 -1
  55. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.d.ts.map +1 -1
  56. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.js +8 -3
  57. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.js.map +1 -1
  58. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.d.ts +6 -5
  59. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.d.ts.map +1 -1
  60. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.js +6 -5
  61. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.js.map +1 -1
  62. package/dist/core/extensions/builtin/compaction/circuit-breaker.d.ts +8 -0
  63. package/dist/core/extensions/builtin/compaction/circuit-breaker.d.ts.map +1 -1
  64. package/dist/core/extensions/builtin/compaction/circuit-breaker.js +8 -0
  65. package/dist/core/extensions/builtin/compaction/circuit-breaker.js.map +1 -1
  66. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +8 -0
  67. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
  68. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +125 -20
  69. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
  70. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.d.ts +18 -0
  71. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.d.ts.map +1 -0
  72. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.js +20 -0
  73. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.js.map +1 -0
  74. package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
  75. package/dist/core/extensions/builtin/compaction/index.js +54 -11
  76. package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
  77. package/dist/core/extensions/builtin/compaction/lane-policy.d.ts +3 -0
  78. package/dist/core/extensions/builtin/compaction/lane-policy.d.ts.map +1 -1
  79. package/dist/core/extensions/builtin/compaction/lane-policy.js +47 -23
  80. package/dist/core/extensions/builtin/compaction/lane-policy.js.map +1 -1
  81. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts +1 -1
  82. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts.map +1 -1
  83. package/dist/core/extensions/builtin/compaction/model-usability-budget.js +23 -3
  84. package/dist/core/extensions/builtin/compaction/model-usability-budget.js.map +1 -1
  85. package/dist/core/extensions/builtin/compaction/resume-admission.d.ts +7 -0
  86. package/dist/core/extensions/builtin/compaction/resume-admission.d.ts.map +1 -0
  87. package/dist/core/extensions/builtin/compaction/resume-admission.js +7 -0
  88. package/dist/core/extensions/builtin/compaction/resume-admission.js.map +1 -0
  89. package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts +2 -0
  90. package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts.map +1 -1
  91. package/dist/core/extensions/builtin/compaction/speculative-summary.js +5 -2
  92. package/dist/core/extensions/builtin/compaction/speculative-summary.js.map +1 -1
  93. package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
  94. package/dist/core/extensions/builtin/compaction/speculative.js +9 -3
  95. package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
  96. package/dist/core/extensions/builtin/compaction/summarization-retry.d.ts +10 -4
  97. package/dist/core/extensions/builtin/compaction/summarization-retry.d.ts.map +1 -1
  98. package/dist/core/extensions/builtin/compaction/summarization-retry.js +14 -5
  99. package/dist/core/extensions/builtin/compaction/summarization-retry.js.map +1 -1
  100. package/dist/core/extensions/builtin/goal/agent-end-continuation.d.ts.map +1 -1
  101. package/dist/core/extensions/builtin/goal/agent-end-continuation.js +11 -0
  102. package/dist/core/extensions/builtin/goal/agent-end-continuation.js.map +1 -1
  103. package/dist/core/extensions/builtin/goal/cache-warm-renderer.js +6 -4
  104. package/dist/core/extensions/builtin/goal/cache-warm-renderer.js.map +1 -1
  105. package/dist/core/extensions/builtin/goal/cache-warm.d.ts +25 -1
  106. package/dist/core/extensions/builtin/goal/cache-warm.d.ts.map +1 -1
  107. package/dist/core/extensions/builtin/goal/cache-warm.js +29 -10
  108. package/dist/core/extensions/builtin/goal/cache-warm.js.map +1 -1
  109. package/dist/core/extensions/builtin/goal/continuation.d.ts +3 -1
  110. package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
  111. package/dist/core/extensions/builtin/goal/continuation.js +17 -2
  112. package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
  113. package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts.map +1 -1
  114. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +1 -0
  115. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js.map +1 -1
  116. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts +1 -1
  117. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  118. package/dist/core/extensions/builtin/goal/monitor-continuation.js +8 -3
  119. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  120. package/dist/core/extensions/builtin/gpt-account.d.ts +5 -1
  121. package/dist/core/extensions/builtin/gpt-account.d.ts.map +1 -1
  122. package/dist/core/extensions/builtin/gpt-account.js +9 -26
  123. package/dist/core/extensions/builtin/gpt-account.js.map +1 -1
  124. package/dist/core/extensions/builtin/hooks/plugin-manifest.js +2 -2
  125. package/dist/core/extensions/builtin/hooks/plugin-manifest.js.map +1 -1
  126. package/dist/core/extensions/builtin/hooks/safety.js +2 -2
  127. package/dist/core/extensions/builtin/hooks/safety.js.map +1 -1
  128. package/dist/core/extensions/builtin/imagegen/params.d.ts +36 -0
  129. package/dist/core/extensions/builtin/imagegen/params.d.ts.map +1 -0
  130. package/dist/core/extensions/builtin/imagegen/params.js +55 -0
  131. package/dist/core/extensions/builtin/imagegen/params.js.map +1 -0
  132. package/dist/core/extensions/builtin/imagegen/reference-images.d.ts +11 -0
  133. package/dist/core/extensions/builtin/imagegen/reference-images.d.ts.map +1 -0
  134. package/dist/core/extensions/builtin/imagegen/reference-images.js +55 -0
  135. package/dist/core/extensions/builtin/imagegen/reference-images.js.map +1 -0
  136. package/dist/core/extensions/builtin/imagegen/skill/SKILL.md +47 -4
  137. package/dist/core/extensions/builtin/imagegen/tool.d.ts +10 -19
  138. package/dist/core/extensions/builtin/imagegen/tool.d.ts.map +1 -1
  139. package/dist/core/extensions/builtin/imagegen/tool.js +21 -45
  140. package/dist/core/extensions/builtin/imagegen/tool.js.map +1 -1
  141. package/dist/core/extensions/builtin/monitor-state-event.d.ts +18 -0
  142. package/dist/core/extensions/builtin/monitor-state-event.d.ts.map +1 -1
  143. package/dist/core/extensions/builtin/monitor-state-event.js +23 -0
  144. package/dist/core/extensions/builtin/monitor-state-event.js.map +1 -1
  145. package/dist/core/extensions/builtin/oauth-login-interaction.d.ts +24 -0
  146. package/dist/core/extensions/builtin/oauth-login-interaction.d.ts.map +1 -0
  147. package/dist/core/extensions/builtin/oauth-login-interaction.js +77 -0
  148. package/dist/core/extensions/builtin/oauth-login-interaction.js.map +1 -0
  149. package/dist/core/extensions/builtin/permission-system/external-dir.d.ts.map +1 -1
  150. package/dist/core/extensions/builtin/permission-system/external-dir.js +5 -51
  151. package/dist/core/extensions/builtin/permission-system/external-dir.js.map +1 -1
  152. package/dist/core/extensions/builtin/permission-system/parsers.d.ts.map +1 -1
  153. package/dist/core/extensions/builtin/permission-system/parsers.js +5 -7
  154. package/dist/core/extensions/builtin/permission-system/parsers.js.map +1 -1
  155. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +1 -1
  156. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js.map +1 -1
  157. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +1 -1
  158. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js.map +1 -1
  159. package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts +14 -7
  160. package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts.map +1 -1
  161. package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js +34 -13
  162. package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js.map +1 -1
  163. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.d.ts +6 -10
  164. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.d.ts.map +1 -1
  165. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +14 -9
  166. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js.map +1 -1
  167. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts +15 -15
  168. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts.map +1 -1
  169. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +49 -21
  170. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js.map +1 -1
  171. package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +1 -1
  172. package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js.map +1 -1
  173. package/dist/core/extensions/builtin/service-tier.d.ts +2 -0
  174. package/dist/core/extensions/builtin/service-tier.d.ts.map +1 -1
  175. package/dist/core/extensions/builtin/service-tier.js +17 -1
  176. package/dist/core/extensions/builtin/service-tier.js.map +1 -1
  177. package/dist/core/extensions/builtin/terminal/durable-command.d.ts.map +1 -1
  178. package/dist/core/extensions/builtin/terminal/durable-command.js +3 -0
  179. package/dist/core/extensions/builtin/terminal/durable-command.js.map +1 -1
  180. package/dist/core/extensions/builtin/terminal/durable-file.d.ts.map +1 -1
  181. package/dist/core/extensions/builtin/terminal/durable-file.js +2 -0
  182. package/dist/core/extensions/builtin/terminal/durable-file.js.map +1 -1
  183. package/dist/core/extensions/builtin/terminal/extension.d.ts.map +1 -1
  184. package/dist/core/extensions/builtin/terminal/extension.js +14 -2
  185. package/dist/core/extensions/builtin/terminal/extension.js.map +1 -1
  186. package/dist/core/extensions/builtin/terminal/monitor-notify.d.ts.map +1 -1
  187. package/dist/core/extensions/builtin/terminal/monitor-notify.js +27 -5
  188. package/dist/core/extensions/builtin/terminal/monitor-notify.js.map +1 -1
  189. package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts +17 -0
  190. package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts.map +1 -1
  191. package/dist/core/extensions/builtin/terminal/monitor-registry.js +76 -14
  192. package/dist/core/extensions/builtin/terminal/monitor-registry.js.map +1 -1
  193. package/dist/core/extensions/builtin/terminal/notify.d.ts +2 -0
  194. package/dist/core/extensions/builtin/terminal/notify.d.ts.map +1 -1
  195. package/dist/core/extensions/builtin/terminal/notify.js +6 -1
  196. package/dist/core/extensions/builtin/terminal/notify.js.map +1 -1
  197. package/dist/core/extensions/builtin/terminal/session-bundle.d.ts +3 -1
  198. package/dist/core/extensions/builtin/terminal/session-bundle.d.ts.map +1 -1
  199. package/dist/core/extensions/builtin/terminal/session-bundle.js +13 -0
  200. package/dist/core/extensions/builtin/terminal/session-bundle.js.map +1 -1
  201. package/dist/core/extensions/builtin/terminal/shared.d.ts +13 -2
  202. package/dist/core/extensions/builtin/terminal/shared.d.ts.map +1 -1
  203. package/dist/core/extensions/builtin/terminal/shared.js +15 -2
  204. package/dist/core/extensions/builtin/terminal/shared.js.map +1 -1
  205. package/dist/core/extensions/builtin/terminal/tools/monitor.d.ts.map +1 -1
  206. package/dist/core/extensions/builtin/terminal/tools/monitor.js +8 -1
  207. package/dist/core/extensions/builtin/terminal/tools/monitor.js.map +1 -1
  208. package/dist/core/extensions/builtin/tool-search/index.d.ts.map +1 -1
  209. package/dist/core/extensions/builtin/tool-search/index.js +1 -0
  210. package/dist/core/extensions/builtin/tool-search/index.js.map +1 -1
  211. package/dist/core/extensions/builtin/tool-search/service.d.ts +4 -0
  212. package/dist/core/extensions/builtin/tool-search/service.d.ts.map +1 -1
  213. package/dist/core/extensions/builtin/tool-search/service.js +11 -0
  214. package/dist/core/extensions/builtin/tool-search/service.js.map +1 -1
  215. package/dist/core/extensions/loader.d.ts +2 -1
  216. package/dist/core/extensions/loader.d.ts.map +1 -1
  217. package/dist/core/extensions/loader.js +17 -8
  218. package/dist/core/extensions/loader.js.map +1 -1
  219. package/dist/core/extensions/runner.d.ts +1 -0
  220. package/dist/core/extensions/runner.d.ts.map +1 -1
  221. package/dist/core/extensions/runner.js +8 -1
  222. package/dist/core/extensions/runner.js.map +1 -1
  223. package/dist/core/extensions/types.d.ts +14 -0
  224. package/dist/core/extensions/types.d.ts.map +1 -1
  225. package/dist/core/extensions/types.js.map +1 -1
  226. package/dist/core/high-reasoning-warning.d.ts.map +1 -1
  227. package/dist/core/high-reasoning-warning.js +4 -6
  228. package/dist/core/high-reasoning-warning.js.map +1 -1
  229. package/dist/core/resource-loader.d.ts +2 -0
  230. package/dist/core/resource-loader.d.ts.map +1 -1
  231. package/dist/core/resource-loader.js +11 -7
  232. package/dist/core/resource-loader.js.map +1 -1
  233. package/dist/core/sdk.d.ts +1 -1
  234. package/dist/core/sdk.d.ts.map +1 -1
  235. package/dist/core/sdk.js +38 -7
  236. package/dist/core/sdk.js.map +1 -1
  237. package/dist/core/session-manager.d.ts.map +1 -1
  238. package/dist/core/session-manager.js +11 -1
  239. package/dist/core/session-manager.js.map +1 -1
  240. package/dist/core/session-write-reservation.d.ts +4 -0
  241. package/dist/core/session-write-reservation.d.ts.map +1 -0
  242. package/dist/core/session-write-reservation.js +12 -0
  243. package/dist/core/session-write-reservation.js.map +1 -0
  244. package/dist/core/settings-manager.js +1 -1
  245. package/dist/core/settings-manager.js.map +1 -1
  246. package/dist/core/settings-shapes.js.map +1 -1
  247. package/dist/core/tools/bounded-realpath.d.ts +28 -0
  248. package/dist/core/tools/bounded-realpath.d.ts.map +1 -0
  249. package/dist/core/tools/bounded-realpath.js +53 -0
  250. package/dist/core/tools/bounded-realpath.js.map +1 -0
  251. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  252. package/dist/core/tools/file-mutation-queue.js +15 -13
  253. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  254. package/dist/core/tools/filesystem-policy.d.ts +7 -0
  255. package/dist/core/tools/filesystem-policy.d.ts.map +1 -1
  256. package/dist/core/tools/filesystem-policy.js +25 -15
  257. package/dist/core/tools/filesystem-policy.js.map +1 -1
  258. package/dist/core/tools/read-classifiers.d.ts +17 -0
  259. package/dist/core/tools/read-classifiers.d.ts.map +1 -0
  260. package/dist/core/tools/read-classifiers.js +26 -0
  261. package/dist/core/tools/read-classifiers.js.map +1 -0
  262. package/dist/core/tools/read.d.ts +5 -1
  263. package/dist/core/tools/read.d.ts.map +1 -1
  264. package/dist/core/tools/read.js +21 -1
  265. package/dist/core/tools/read.js.map +1 -1
  266. package/dist/core/trust-manager.d.ts.map +1 -1
  267. package/dist/core/trust-manager.js +13 -2
  268. package/dist/core/trust-manager.js.map +1 -1
  269. package/dist/index.d.ts +1 -0
  270. package/dist/index.d.ts.map +1 -1
  271. package/dist/index.js +1 -0
  272. package/dist/index.js.map +1 -1
  273. package/dist/main.d.ts +14 -0
  274. package/dist/main.d.ts.map +1 -1
  275. package/dist/main.js +166 -147
  276. package/dist/main.js.map +1 -1
  277. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  278. package/dist/modes/interactive/interactive-mode.js +4 -0
  279. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  280. package/dist/modes/interactive/tips/catalog/memory-tips.d.ts.map +1 -1
  281. package/dist/modes/interactive/tips/catalog/memory-tips.js +6 -0
  282. package/dist/modes/interactive/tips/catalog/memory-tips.js.map +1 -1
  283. package/dist/modes/interactive/tips/catalog/subagent-tips.d.ts.map +1 -1
  284. package/dist/modes/interactive/tips/catalog/subagent-tips.js +6 -0
  285. package/dist/modes/interactive/tips/catalog/subagent-tips.js.map +1 -1
  286. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  287. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  288. package/dist/modes/rpc/connection-handler.js +1 -1
  289. package/dist/modes/rpc/connection-handler.js.map +1 -1
  290. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  291. package/dist/modes/rpc/host-lifecycle.js +31 -5
  292. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  293. package/dist/modes/rpc/host-watchdog.d.ts +11 -0
  294. package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
  295. package/dist/modes/rpc/host-watchdog.js +16 -2
  296. package/dist/modes/rpc/host-watchdog.js.map +1 -1
  297. package/dist/modes/rpc/multi-session-host.d.ts +2 -0
  298. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  299. package/dist/modes/rpc/multi-session-host.js +72 -24
  300. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  301. package/dist/modes/rpc/session-binding.d.ts.map +1 -1
  302. package/dist/modes/rpc/session-binding.js +3 -0
  303. package/dist/modes/rpc/session-binding.js.map +1 -1
  304. package/dist/modes/rpc/session-command-router.d.ts +1 -1
  305. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  306. package/dist/modes/rpc/session-command-router.js +57 -25
  307. package/dist/modes/rpc/session-command-router.js.map +1 -1
  308. package/dist/modes/rpc/session-event-writer.d.ts +23 -1
  309. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  310. package/dist/modes/rpc/session-event-writer.js +108 -1
  311. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  312. package/dist/modes/rpc/session-registry.d.ts +4 -2
  313. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  314. package/dist/modes/rpc/session-registry.js +1 -1
  315. package/dist/modes/rpc/session-registry.js.map +1 -1
  316. package/dist/modes/rpc/session-worker-client.d.ts +47 -0
  317. package/dist/modes/rpc/session-worker-client.d.ts.map +1 -0
  318. package/dist/modes/rpc/session-worker-client.js +226 -0
  319. package/dist/modes/rpc/session-worker-client.js.map +1 -0
  320. package/dist/modes/rpc/session-worker-protocol.d.ts +103 -0
  321. package/dist/modes/rpc/session-worker-protocol.d.ts.map +1 -0
  322. package/dist/modes/rpc/session-worker-protocol.js +12 -0
  323. package/dist/modes/rpc/session-worker-protocol.js.map +1 -0
  324. package/dist/modes/rpc/session-worker-requests.d.ts +24 -0
  325. package/dist/modes/rpc/session-worker-requests.d.ts.map +1 -0
  326. package/dist/modes/rpc/session-worker-requests.js +71 -0
  327. package/dist/modes/rpc/session-worker-requests.js.map +1 -0
  328. package/dist/modes/rpc/session-worker.d.ts +2 -0
  329. package/dist/modes/rpc/session-worker.d.ts.map +1 -0
  330. package/dist/modes/rpc/session-worker.js +229 -0
  331. package/dist/modes/rpc/session-worker.js.map +1 -0
  332. package/dist/modes/rpc/socket-ownership.d.ts +46 -0
  333. package/dist/modes/rpc/socket-ownership.d.ts.map +1 -0
  334. package/dist/modes/rpc/socket-ownership.js +178 -0
  335. package/dist/modes/rpc/socket-ownership.js.map +1 -0
  336. package/dist/modes/rpc/worker-session-registry.d.ts +37 -0
  337. package/dist/modes/rpc/worker-session-registry.d.ts.map +1 -0
  338. package/dist/modes/rpc/worker-session-registry.js +207 -0
  339. package/dist/modes/rpc/worker-session-registry.js.map +1 -0
  340. package/dist/utils/fs-watch.d.ts +17 -0
  341. package/dist/utils/fs-watch.d.ts.map +1 -1
  342. package/dist/utils/fs-watch.js +38 -10
  343. package/dist/utils/fs-watch.js.map +1 -1
  344. package/dist/utils/paths.d.ts +33 -0
  345. package/dist/utils/paths.d.ts.map +1 -1
  346. package/dist/utils/paths.js +109 -3
  347. package/dist/utils/paths.js.map +1 -1
  348. package/docs/development.md +3 -2
  349. package/docs/providers.md +5 -1
  350. package/docs/rpc.md +70 -9
  351. package/docs/settings.md +2 -0
  352. package/docs/skills.md +1 -1
  353. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +55 -0
  354. package/node_modules/@code-yeongyu/senpi-codemode/README.md +14 -1
  355. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  356. package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/protocol.ts +1 -0
  357. package/node_modules/@code-yeongyu/senpi-codemode/src/extension/runtime-factory.ts +3 -0
  358. package/node_modules/@code-yeongyu/senpi-codemode/src/extension/session-manager.ts +7 -0
  359. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/AGENTS.md +7 -0
  360. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/jl/kernel.ts +4 -0
  361. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-contract.ts +3 -0
  362. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-core.js +29 -0
  363. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +10 -6
  364. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-shell-capture.d.ts +16 -0
  365. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-shell-capture.js +44 -8
  366. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-startup.ts +1 -0
  367. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel-contract.ts +3 -0
  368. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/transport.ts +9 -1
  369. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/rb/kernel.ts +4 -0
  370. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/session-env.ts +56 -0
  371. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-contract.ts +3 -0
  372. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-kernel.ts +9 -1
  373. package/node_modules/@code-yeongyu/senpi-codemode/src/output/output-meta.ts +26 -2
  374. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +17 -24
  375. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/image.ts +12 -3
  376. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
  377. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +2 -2
  378. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js.map +1 -1
  379. package/node_modules/@earendil-works/pi-agent-core/dist/assistant-terminal-state.d.ts +7 -0
  380. package/node_modules/@earendil-works/pi-agent-core/dist/assistant-terminal-state.d.ts.map +1 -1
  381. package/node_modules/@earendil-works/pi-agent-core/dist/assistant-terminal-state.js +19 -0
  382. package/node_modules/@earendil-works/pi-agent-core/dist/assistant-terminal-state.js.map +1 -1
  383. package/node_modules/@earendil-works/pi-agent-core/dist/empty-assistant-recovery.d.ts.map +1 -1
  384. package/node_modules/@earendil-works/pi-agent-core/dist/empty-assistant-recovery.js +24 -16
  385. package/node_modules/@earendil-works/pi-agent-core/dist/empty-assistant-recovery.js.map +1 -1
  386. package/node_modules/@earendil-works/pi-agent-core/dist/index.d.ts +1 -1
  387. package/node_modules/@earendil-works/pi-agent-core/dist/index.d.ts.map +1 -1
  388. package/node_modules/@earendil-works/pi-agent-core/dist/index.js +1 -1
  389. package/node_modules/@earendil-works/pi-agent-core/dist/index.js.map +1 -1
  390. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  391. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
  392. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +70 -183
  393. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
  394. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-references.d.ts +3 -0
  395. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-references.d.ts.map +1 -0
  396. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-references.js +260 -0
  397. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-references.js.map +1 -0
  398. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.d.ts.map +1 -1
  399. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +1 -0
  400. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
  401. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-edit.d.ts +4 -0
  402. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-edit.d.ts.map +1 -0
  403. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-edit.js +11 -0
  404. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-edit.js.map +1 -0
  405. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-params.d.ts +25 -0
  406. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-params.d.ts.map +1 -0
  407. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-params.js +58 -0
  408. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images-params.js.map +1 -0
  409. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images.d.ts +3 -6
  410. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images.d.ts.map +1 -1
  411. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images.js +15 -33
  412. package/node_modules/@earendil-works/pi-ai/dist/api/openai-images.js.map +1 -1
  413. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
  414. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +1 -0
  415. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
  416. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic-callback-listener.d.ts +40 -0
  417. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic-callback-listener.d.ts.map +1 -0
  418. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic-callback-listener.js +138 -0
  419. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic-callback-listener.js.map +1 -0
  420. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.d.ts +2 -3
  421. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.d.ts.map +1 -1
  422. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.js +42 -139
  423. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/anthropic.js.map +1 -1
  424. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/authorization-input.d.ts +6 -0
  425. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/authorization-input.d.ts.map +1 -0
  426. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/authorization-input.js +29 -0
  427. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/authorization-input.js.map +1 -0
  428. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/error-details.d.ts +3 -0
  429. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/error-details.d.ts.map +1 -0
  430. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/error-details.js +20 -0
  431. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/error-details.js.map +1 -0
  432. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +61 -1
  433. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  434. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +61 -1
  435. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  436. package/node_modules/@earendil-works/pi-ai/dist/images.d.ts +1 -0
  437. package/node_modules/@earendil-works/pi-ai/dist/images.d.ts.map +1 -1
  438. package/node_modules/@earendil-works/pi-ai/dist/images.js +1 -0
  439. package/node_modules/@earendil-works/pi-ai/dist/images.js.map +1 -1
  440. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  441. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  442. package/node_modules/@earendil-works/pi-ai/dist/providers/data/azure-openai-responses.json +1 -1
  443. package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  444. package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  445. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  446. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  447. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  448. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  449. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  450. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  451. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  452. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/recovery-stream-terminal.d.ts.map +1 -1
  453. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/recovery-stream-terminal.js +16 -1
  454. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/recovery-stream-terminal.js.map +1 -1
  455. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +7 -0
  456. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  457. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  458. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
  459. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
  460. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +14 -3
  461. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
  462. package/node_modules/@earendil-works/pi-ai/dist/utils/server-fallback-receipt.d.ts +2 -1
  463. package/node_modules/@earendil-works/pi-ai/dist/utils/server-fallback-receipt.d.ts.map +1 -1
  464. package/node_modules/@earendil-works/pi-ai/dist/utils/server-fallback-receipt.js +16 -0
  465. package/node_modules/@earendil-works/pi-ai/dist/utils/server-fallback-receipt.js.map +1 -1
  466. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  467. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  468. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  469. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  470. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"model-usability-budget.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/model-usability-budget.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,qBAAqB,EAAyB,MAAM,uBAAuB,CAAC;AAE/F,OAAO,EAAE,sBAA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AAmB,wBAAwB,UAAU,CAAC,uBAAuB,sBAAsB,UAAU,CAAC,qBAAqB,mBAAmB,UAAU,CAAC,kBAAkB,KAAK,UAAU,CAAC,mBAAmB,GAAG,CAAC;QACnX,MAAM,OAAO,GACZ,UAAU,CAAC,SAAS,KAAK,QAAQ;YAChC,CAAC,CAAC,UAAU,UAAU,CAAC,KAAK,0CAA0C,UAAU,CAAC,aAAa,cAAc,UAAU,CAAC,eAAe,wBAAwB,UAAU,CAAC,cAAc,oCAAoC,UAAU,CAAC,iBAAiB,KAAK,SAAS,IAAI;YACzQ,CAAC,CAAC,UAAU,CAAC,SAAS,KAAK,QAAQ;gBAClC,CAAC,CAAC,UAAU,UAAU,CAAC,KAAK,0CAA0C,UAAU,CAAC,aAAa,cAAc,UAAU,CAAC,eAAe,wBAAwB,UAAU,CAAC,cAAc,oCAAoC,UAAU,CAAC,iBAAiB,KAAK,SAAS,qEAAqE;gBAC1U,CAAC,CAAC,UAAU,UAAU,CAAC,KAAK,kCAAkC,UAAU,CAAC,aAAa,cAAc,UAAU,CAAC,eAAe,wBAAwB,UAAU,CAAC,cAAc,mBAAmB,SAAS,IAAI,CAAC;QACnN,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;QACxC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC9B,CAAC;CACD","sourcesContent":["import { type Api, estimateContextTokens, type Model, type Tool } from \"@earendil-works/pi-ai\";\nimport type { CompactionPreparation } from \"../../../compaction/index.ts\";\nimport { getPromptContextWindow } from \"./extension-wiring.ts\";\nimport { resolveCompactionGeometry } from \"./orchestration.ts\";\n\ninterface ModelSafetyMarginProfile {\n\treadonly id: string;\n\treadonly tokens: number;\n\treadonly providers?: readonly string[];\n\treadonly familyMarkers?: readonly string[];\n}\n\n/** Measured conversation runway by shipped prompt family, rounded up to a 4K token boundary. */\nconst MODEL_SAFETY_MARGIN_PROFILES: readonly ModelSafetyMarginProfile[] = [\n\t{ id: \"anthropic\", tokens: 16_384, providers: [\"anthropic\"], familyMarkers: [\"claude\"] },\n\t{ id: \"openai-reasoning\", tokens: 16_384, providers: [\"openai\"], familyMarkers: [\"gpt-5\", \"o1\", \"o3\", \"o4\"] },\n\t{ id: \"google\", tokens: 12_288, providers: [\"google\"], familyMarkers: [\"gemini\"] },\n\t{ id: \"deepseek\", tokens: 12_288, providers: [\"deepseek\"], familyMarkers: [\"deepseek\"] },\n\t{ id: \"default\", tokens: 8_192 },\n];\n\nexport type ModelUsabilityAdmission = \"start\" | \"resume\" | \"switch\";\n\nexport interface ModelUsabilityBudgetProjection {\n\treadonly model: string;\n\treadonly contextWindow: number;\n\treadonly liveContextTokens: number;\n\treadonly systemPromptTokens: number;\n\treadonly activeToolSchemaTokens: number;\n\treadonly outputReserveTokens: number;\n\treadonly compactionReserveTokens: number;\n\treadonly speculationLeadTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly safetyMarginProfile: string;\n\treadonly requiredTokens: number;\n\treadonly shortfallTokens: number;\n\treadonly usable: boolean;\n\treadonly admission: ModelUsabilityAdmission;\n}\n\nexport interface ModelUsabilityBudgetInput<TApi extends Api> {\n\treadonly model: Model<TApi>;\n\treadonly systemPrompt: string;\n\treadonly tools: readonly Tool[];\n\treadonly liveContextTokens?: number;\n\treadonly compaction: CompactionPreparation[\"settings\"];\n\t/** Defaults to true. Resume/startup must pass false so speculation can run after admit. */\n\treadonly includeSpeculationLead?: boolean;\n\treadonly admission?: ModelUsabilityAdmission;\n}\n\nfunction matchesFamilyMarker(modelId: string, marker: string): boolean {\n\tconst escapedMarker = marker.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\treturn new RegExp(`(?:^|[/.:_-])${escapedMarker}(?=$|[^a-z0-9])`).test(modelId.toLowerCase());\n}\n\nfunction resolveSafetyMarginProfile<TApi extends Api>(model: Model<TApi>): ModelSafetyMarginProfile {\n\treturn (\n\t\tMODEL_SAFETY_MARGIN_PROFILES.find(\n\t\t\t(profile) =>\n\t\t\t\tprofile.id !== \"default\" &&\n\t\t\t\t(profile.providers?.includes(model.provider) === true ||\n\t\t\t\t\tprofile.familyMarkers?.some((marker) => matchesFamilyMarker(model.id, marker)) === true),\n\t\t) ?? MODEL_SAFETY_MARGIN_PROFILES[MODEL_SAFETY_MARGIN_PROFILES.length - 1]\n\t);\n}\n\nexport function projectModelUsabilityBudget<TApi extends Api>(\n\tinput: ModelUsabilityBudgetInput<TApi>,\n): ModelUsabilityBudgetProjection {\n\tconst liveContextTokens = input.liveContextTokens ?? 0;\n\tconst systemPromptTokens = estimateContextTokens({\n\t\tsystemPrompt: input.systemPrompt,\n\t\tmessages: [],\n\t\ttools: [],\n\t}).tokens;\n\tconst promptAndToolsTokens = estimateContextTokens({\n\t\tsystemPrompt: input.systemPrompt,\n\t\tmessages: [],\n\t\ttools: [...input.tools],\n\t}).tokens;\n\tconst activeToolSchemaTokens = promptAndToolsTokens - systemPromptTokens;\n\tconst outputReserveTokens =\n\t\tinput.model.contextWindow - getPromptContextWindow(input.model.contextWindow, input.model.maxTokens);\n\tconst geometry = resolveCompactionGeometry({ contextWindow: input.model.contextWindow, settings: input.compaction });\n\tconst compactionReserveTokens = input.compaction.enabled ? geometry.reserveTokens : 0;\n\tconst includeSpeculationLead = input.includeSpeculationLead !== false;\n\tconst speculationLeadTokens =\n\t\tincludeSpeculationLead && input.compaction.enabled && input.compaction.speculativeEnabled !== false\n\t\t\t? geometry.leadTokens\n\t\t\t: 0;\n\tconst safetyMargin = resolveSafetyMarginProfile(input.model);\n\tconst requiredTokens =\n\t\tliveContextTokens +\n\t\tsystemPromptTokens +\n\t\tactiveToolSchemaTokens +\n\t\toutputReserveTokens +\n\t\tcompactionReserveTokens +\n\t\tspeculationLeadTokens +\n\t\tsafetyMargin.tokens;\n\tconst shortfallTokens = Math.max(0, requiredTokens - input.model.contextWindow);\n\tconst admission = input.admission ?? (liveContextTokens > 0 ? \"switch\" : \"start\");\n\n\treturn {\n\t\tmodel: `${input.model.provider}/${input.model.id}`,\n\t\tcontextWindow: input.model.contextWindow,\n\t\tliveContextTokens,\n\t\tsystemPromptTokens,\n\t\tactiveToolSchemaTokens,\n\t\toutputReserveTokens,\n\t\tcompactionReserveTokens,\n\t\tspeculationLeadTokens,\n\t\tsafetyMarginTokens: safetyMargin.tokens,\n\t\tsafetyMarginProfile: safetyMargin.id,\n\t\trequiredTokens,\n\t\tshortfallTokens,\n\t\tusable: shortfallTokens === 0,\n\t\tadmission,\n\t};\n}\n\nexport class ModelUsabilityBudgetError extends Error {\n\treadonly projection: ModelUsabilityBudgetProjection;\n\n\tconstructor(projection: ModelUsabilityBudgetProjection) {\n\t\tconst breakdown = `system prompt ${projection.systemPromptTokens}, active tool schemas ${projection.activeToolSchemaTokens}, output reserve ${projection.outputReserveTokens}, compaction reserve ${projection.compactionReserveTokens}, speculation lead ${projection.speculationLeadTokens}, safety margin ${projection.safetyMarginTokens} [${projection.safetyMarginProfile}]`;\n\t\tconst message =\n\t\t\tprojection.admission === \"resume\"\n\t\t\t\t? `Model \"${projection.model}\" cannot resume: target context window ${projection.contextWindow} tokens is ${projection.shortfallTokens} tokens short of the ${projection.requiredTokens}-token requirement (live context ${projection.liveContextTokens}, ${breakdown}).`\n\t\t\t\t: projection.admission === \"switch\"\n\t\t\t\t\t? `Model \"${projection.model}\" cannot switch: target context window ${projection.contextWindow} tokens is ${projection.shortfallTokens} tokens short of the ${projection.requiredTokens}-token requirement (live context ${projection.liveContextTokens}, ${breakdown}). Compact the session, then revalidate and retry the model switch.`\n\t\t\t\t\t: `Model \"${projection.model}\" cannot start: context window ${projection.contextWindow} tokens is ${projection.shortfallTokens} tokens short of the ${projection.requiredTokens}-token minimum (${breakdown}).`;\n\t\tsuper(message);\n\t\tthis.name = \"ModelUsabilityBudgetError\";\n\t\tthis.projection = projection;\n\t}\n}\n"]}
1
+ {"version":3,"file":"model-usability-budget.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/model-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AmB,UAAU,CAAC,kBAAkB,KAAK,UAAU,CAAC,mBAAmB,GAAG,CAAC;QACnX,MAAM,OAAO,GACZ,UAAU,CAAC,SAAS,KAAK,QAAQ;YAChC,CAAC,CAAC,UAAU,UAAU,CAAC,KAAK,0CAA0C,UAAU,CAAC,aAAa,cAAc,UAAU,CAAC,eAAe,wBAAwB,UAAU,CAAC,cAAc,oCAAoC,UAAU,CAAC,iBAAiB,KAAK,SAAS,IAAI;YACzQ,CAAC,CAAC,UAAU,CAAC,SAAS,KAAK,QAAQ;gBAClC,CAAC,CAAC,UAAU,UAAU,CAAC,KAAK,0CAA0C,UAAU,CAAC,aAAa,cAAc,UAAU,CAAC,eAAe,wBAAwB,UAAU,CAAC,cAAc,oCAAoC,UAAU,CAAC,iBAAiB,KAAK,SAAS,qEAAqE;gBAC1U,CAAC,CAAC,UAAU,UAAU,CAAC,KAAK,kCAAkC,UAAU,CAAC,aAAa,cAAc,UAAU,CAAC,eAAe,wBAAwB,UAAU,CAAC,cAAc,mBAAmB,SAAS,IAAI,CAAC;QACnN,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;QACxC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC9B,CAAC;CACD","sourcesContent":["import { type Api, estimateContextTokens, type Model, type Tool } from \"@earendil-works/pi-ai\";\nimport { type CompactionPreparation, DEFAULT_COMPACTION_SETTINGS } from \"../../../compaction/index.ts\";\nimport { getPromptContextWindow } from \"./extension-wiring.ts\";\nimport { resolveCompactionGeometry } from \"./orchestration.ts\";\nimport { baseThresholdRatioForWindow, computeEffectiveKeepRecentTokens } from \"./policy.ts\";\n\ninterface ModelSafetyMarginProfile {\n\treadonly id: string;\n\treadonly tokens: number;\n\treadonly providers?: readonly string[];\n\treadonly familyMarkers?: readonly string[];\n}\n\n/** Measured conversation runway by shipped prompt family, rounded up to a 4K token boundary. */\nconst MODEL_SAFETY_MARGIN_PROFILES: readonly ModelSafetyMarginProfile[] = [\n\t{ id: \"anthropic\", tokens: 16_384, providers: [\"anthropic\"], familyMarkers: [\"claude\"] },\n\t{ id: \"openai-reasoning\", tokens: 16_384, providers: [\"openai\"], familyMarkers: [\"gpt-5\", \"o1\", \"o3\", \"o4\"] },\n\t{ id: \"google\", tokens: 12_288, providers: [\"google\"], familyMarkers: [\"gemini\"] },\n\t{ id: \"deepseek\", tokens: 12_288, providers: [\"deepseek\"], familyMarkers: [\"deepseek\"] },\n\t{ id: \"default\", tokens: 8_192 },\n];\n\nexport type ModelUsabilityAdmission = \"start\" | \"resume\" | \"switch\";\n\nexport interface ModelUsabilityBudgetProjection {\n\treadonly model: string;\n\treadonly contextWindow: number;\n\treadonly liveContextTokens: number;\n\treadonly systemPromptTokens: number;\n\treadonly activeToolSchemaTokens: number;\n\treadonly outputReserveTokens: number;\n\treadonly compactionReserveTokens: number;\n\treadonly speculationLeadTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly safetyMarginProfile: string;\n\treadonly requiredTokens: number;\n\treadonly shortfallTokens: number;\n\treadonly usable: boolean;\n\treadonly admission: ModelUsabilityAdmission;\n}\n\nexport interface ModelUsabilityBudgetInput<TApi extends Api> {\n\treadonly model: Model<TApi>;\n\treadonly systemPrompt: string;\n\treadonly tools: readonly Tool[];\n\treadonly liveContextTokens?: number;\n\treadonly compaction: CompactionPreparation[\"settings\"];\n\t/** Defaults to true. Resume/startup must pass false so speculation can run after admit. */\n\treadonly includeSpeculationLead?: boolean;\n\treadonly admission?: ModelUsabilityAdmission;\n}\n\nfunction matchesFamilyMarker(modelId: string, marker: string): boolean {\n\tconst escapedMarker = marker.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\treturn new RegExp(`(?:^|[/.:_-])${escapedMarker}(?=$|[^a-z0-9])`).test(modelId.toLowerCase());\n}\n\nfunction resolveSafetyMarginProfile<TApi extends Api>(model: Model<TApi>): ModelSafetyMarginProfile {\n\treturn (\n\t\tMODEL_SAFETY_MARGIN_PROFILES.find(\n\t\t\t(profile) =>\n\t\t\t\tprofile.id !== \"default\" &&\n\t\t\t\t(profile.providers?.includes(model.provider) === true ||\n\t\t\t\t\tprofile.familyMarkers?.some((marker) => matchesFamilyMarker(model.id, marker)) === true),\n\t\t) ?? MODEL_SAFETY_MARGIN_PROFILES[MODEL_SAFETY_MARGIN_PROFILES.length - 1]\n\t);\n}\n\nexport function projectModelUsabilityBudget<TApi extends Api>(\n\tinput: ModelUsabilityBudgetInput<TApi>,\n): ModelUsabilityBudgetProjection {\n\tconst liveContextTokens = input.liveContextTokens ?? 0;\n\tconst systemPromptTokens = estimateContextTokens({\n\t\tsystemPrompt: input.systemPrompt,\n\t\tmessages: [],\n\t\ttools: [],\n\t}).tokens;\n\tconst promptAndToolsTokens = estimateContextTokens({\n\t\tsystemPrompt: input.systemPrompt,\n\t\tmessages: [],\n\t\ttools: [...input.tools],\n\t}).tokens;\n\tconst activeToolSchemaTokens = promptAndToolsTokens - systemPromptTokens;\n\tconst outputReserveTokens =\n\t\tinput.model.contextWindow - getPromptContextWindow(input.model.contextWindow, input.model.maxTokens);\n\tconst geometry = resolveCompactionGeometry({ contextWindow: input.model.contextWindow, settings: input.compaction });\n\tconst compactionReserveTokens = input.compaction.enabled ? geometry.reserveTokens : 0;\n\tconst includeSpeculationLead = input.includeSpeculationLead !== false;\n\tconst speculationLeadTokens =\n\t\tincludeSpeculationLead && input.compaction.enabled && input.compaction.speculativeEnabled !== false\n\t\t\t? geometry.leadTokens\n\t\t\t: 0;\n\tconst safetyMargin = resolveSafetyMarginProfile(input.model);\n\tconst baseRequiredTokens =\n\t\tsystemPromptTokens +\n\t\tactiveToolSchemaTokens +\n\t\toutputReserveTokens +\n\t\tcompactionReserveTokens +\n\t\tspeculationLeadTokens +\n\t\tsafetyMargin.tokens;\n\tconst uncompactedRequiredTokens = liveContextTokens + baseRequiredTokens;\n\tconst admission = input.admission ?? (liveContextTokens > 0 ? \"switch\" : \"start\");\n\n\tlet requiredTokens = uncompactedRequiredTokens;\n\tlet shortfallTokens = Math.max(0, requiredTokens - input.model.contextWindow);\n\tlet usable = shortfallTokens === 0;\n\n\tif (!usable && admission === \"resume\" && input.compaction.enabled && !includeSpeculationLead) {\n\t\tconst compactionRequiredTokens =\n\t\t\tliveContextTokens +\n\t\t\tsystemPromptTokens +\n\t\t\tactiveToolSchemaTokens +\n\t\t\tcompactionReserveTokens +\n\t\t\tsafetyMargin.tokens;\n\t\tconst keepRecentSetting = input.compaction.keepRecentTokens ?? DEFAULT_COMPACTION_SETTINGS.keepRecentTokens;\n\t\tconst effectiveKeepRecentTokens = computeEffectiveKeepRecentTokens(\n\t\t\tkeepRecentSetting,\n\t\t\tinput.model.contextWindow,\n\t\t\tbaseThresholdRatioForWindow(input.model.contextWindow),\n\t\t);\n\t\tconst postCompactionRequiredTokens = effectiveKeepRecentTokens + baseRequiredTokens;\n\n\t\tif (\n\t\t\tcompactionRequiredTokens <= input.model.contextWindow &&\n\t\t\tpostCompactionRequiredTokens <= input.model.contextWindow\n\t\t) {\n\t\t\trequiredTokens = Math.max(compactionRequiredTokens, postCompactionRequiredTokens);\n\t\t\tshortfallTokens = 0;\n\t\t\tusable = true;\n\t\t}\n\t}\n\n\treturn {\n\t\tmodel: `${input.model.provider}/${input.model.id}`,\n\t\tcontextWindow: input.model.contextWindow,\n\t\tliveContextTokens,\n\t\tsystemPromptTokens,\n\t\tactiveToolSchemaTokens,\n\t\toutputReserveTokens,\n\t\tcompactionReserveTokens,\n\t\tspeculationLeadTokens,\n\t\tsafetyMarginTokens: safetyMargin.tokens,\n\t\tsafetyMarginProfile: safetyMargin.id,\n\t\trequiredTokens,\n\t\tshortfallTokens,\n\t\tusable: shortfallTokens === 0,\n\t\tadmission,\n\t};\n}\n\nexport class ModelUsabilityBudgetError extends Error {\n\treadonly projection: ModelUsabilityBudgetProjection;\n\n\tconstructor(projection: ModelUsabilityBudgetProjection) {\n\t\tconst breakdown = `system prompt ${projection.systemPromptTokens}, active tool schemas ${projection.activeToolSchemaTokens}, output reserve ${projection.outputReserveTokens}, compaction reserve ${projection.compactionReserveTokens}, speculation lead ${projection.speculationLeadTokens}, safety margin ${projection.safetyMarginTokens} [${projection.safetyMarginProfile}]`;\n\t\tconst message =\n\t\t\tprojection.admission === \"resume\"\n\t\t\t\t? `Model \"${projection.model}\" cannot resume: target context window ${projection.contextWindow} tokens is ${projection.shortfallTokens} tokens short of the ${projection.requiredTokens}-token requirement (live context ${projection.liveContextTokens}, ${breakdown}).`\n\t\t\t\t: projection.admission === \"switch\"\n\t\t\t\t\t? `Model \"${projection.model}\" cannot switch: target context window ${projection.contextWindow} tokens is ${projection.shortfallTokens} tokens short of the ${projection.requiredTokens}-token requirement (live context ${projection.liveContextTokens}, ${breakdown}). Compact the session, then revalidate and retry the model switch.`\n\t\t\t\t\t: `Model \"${projection.model}\" cannot start: context window ${projection.contextWindow} tokens is ${projection.shortfallTokens} tokens short of the ${projection.requiredTokens}-token minimum (${breakdown}).`;\n\t\tsuper(message);\n\t\tthis.name = \"ModelUsabilityBudgetError\";\n\t\tthis.projection = projection;\n\t}\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { ModelUsabilityBudgetProjection } from "./model-usability-budget.ts";
2
+ export interface ResumeCompactionRequirement {
3
+ readonly projection: ModelUsabilityBudgetProjection;
4
+ readonly notice: string;
5
+ }
6
+ export declare function createResumeCompactionRequirement(projection: ModelUsabilityBudgetProjection): ResumeCompactionRequirement;
7
+ //# sourceMappingURL=resume-admission.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resume-admission.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/resume-admission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAElF,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,CAAC,UAAU,EAAE,8BAA8B,CAAC;IACpD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACxB;AAED,wBAAgB,iCAAiC,CAChD,UAAU,EAAE,8BAA8B,GACxC,2BAA2B,CAK7B"}
@@ -0,0 +1,7 @@
1
+ export function createResumeCompactionRequirement(projection) {
2
+ return {
3
+ projection,
4
+ notice: `Context exceeds the model budget by ${projection.shortfallTokens} tokens; compacting before the first prompt.`,
5
+ };
6
+ }
7
+ //# sourceMappingURL=resume-admission.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resume-admission.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/resume-admission.ts"],"names":[],"mappings":"AAOA,MAAM,UAAU,iCAAiC,CAChD,UAA0C;IAE1C,OAAO;QACN,UAAU;QACV,MAAM,EAAE,uCAAuC,UAAU,CAAC,eAAe,8CAA8C;KACvH,CAAC;AACH,CAAC","sourcesContent":["import type { ModelUsabilityBudgetProjection } from \"./model-usability-budget.ts\";\n\nexport interface ResumeCompactionRequirement {\n\treadonly projection: ModelUsabilityBudgetProjection;\n\treadonly notice: string;\n}\n\nexport function createResumeCompactionRequirement(\n\tprojection: ModelUsabilityBudgetProjection,\n): ResumeCompactionRequirement {\n\treturn {\n\t\tprojection,\n\t\tnotice: `Context exceeds the model budget by ${projection.shortfallTokens} tokens; compacting before the first prompt.`,\n\t};\n}\n"]}
@@ -8,6 +8,8 @@ export declare function isAssistantMessage(message: Message): message is Assista
8
8
  export declare function generateSummaryMessage(options: {
9
9
  context: SpeculativeCompactionContext;
10
10
  forbidToolCalls?: boolean;
11
+ /** Resolved per-attempt duration budget; falls back to the size-adaptive default. */
12
+ maxDurationMs?: number;
11
13
  messages: AgentMessage[];
12
14
  onProgress?: CompactionProgressCallback;
13
15
  prompt: ReturnType<typeof buildPrompt>;
@@ -1 +1 @@
1
- {"version":3,"file":"speculative-summary.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative-summary.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EACN,KAAK,gBAAgB,EAGrB,KAAK,OAAO,EAEZ,KAAK,eAAe,EAIpB,MAAM,uBAAuB,CAAC;AAQ/B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,KAAK,EAAE,4BAA4B,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AAKpG,KAAK,0BAA0B,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AAqC1D,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CASvD;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,gBAAgB,CAEhF;AAkBD,wBAAsB,sBAAsB,CAAC,OAAO,EAAE;IACrD,OAAO,EAAE,4BAA4B,CAAC;IACtC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,0BAA0B,CAAC;IACxC,MAAM,EAAE,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC;IACvC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,QAAQ,EAAE,6BAA6B,CAAC;IACxC,IAAI,EAAE;QACL,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,eAAe,CAAC;QAC1B,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACpC,CAAC;CACF,GAAG,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CA+D/B"}
1
+ {"version":3,"file":"speculative-summary.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative-summary.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EACN,KAAK,gBAAgB,EAGrB,KAAK,OAAO,EAEZ,KAAK,eAAe,EAIpB,MAAM,uBAAuB,CAAC;AAS/B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,KAAK,EAAE,4BAA4B,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AAKpG,KAAK,0BAA0B,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AAqC1D,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CASvD;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,gBAAgB,CAEhF;AAkBD,wBAAsB,sBAAsB,CAAC,OAAO,EAAE;IACrD,OAAO,EAAE,4BAA4B,CAAC;IACtC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,qFAAqF;IACrF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,0BAA0B,CAAC;IACxC,MAAM,EAAE,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC;IACvC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,QAAQ,EAAE,6BAA6B,CAAC;IACxC,IAAI,EAAE;QACL,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,eAAe,CAAC;QAC1B,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACpC,CAAC;CACF,GAAG,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAkE/B"}
@@ -1,6 +1,7 @@
1
1
  import { sanitizeAnthropicToolPairs as sanitizeAnthropicPayload, } from "@earendil-works/pi-ai";
2
2
  import { stream } from "@earendil-works/pi-ai/compat";
3
- import { consumeStreamWithIdleTimeout, DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS, DEFAULT_SUMMARIZATION_MAX_DURATION_MS, } from "../../../compaction/stream-watchdog.js";
3
+ import { estimateTokens } from "../../../compaction/compaction.js";
4
+ import { consumeStreamWithIdleTimeout, DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS, summarizationMaxDurationMs, } from "../../../compaction/stream-watchdog.js";
4
5
  import { convertToLlm } from "../../../messages.js";
5
6
  import { repairOrphanedToolResults } from "./repair-tool-pairs.js";
6
7
  import { normalizeSummarizationTurnOrder } from "./summarization-turn-order.js";
@@ -89,6 +90,8 @@ export async function generateSummaryMessage(options) {
89
90
  timestamp: Date.now(),
90
91
  },
91
92
  ];
93
+ const maxDurationMs = options.maxDurationMs ??
94
+ summarizationMaxDurationMs(requestMessages.reduce((total, message) => total + estimateTokens(message), 0));
92
95
  const providerRequest = await options.context.prepareProviderRequest?.(requestMessages);
93
96
  const requestContext = {
94
97
  systemPrompt: options.snapshot.systemPrompt ?? options.prompt.system,
@@ -113,7 +116,7 @@ export async function generateSummaryMessage(options) {
113
116
  });
114
117
  await consumeStreamWithIdleTimeout(responseStream, {
115
118
  idleTimeoutMs: DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,
116
- maxDurationMs: DEFAULT_SUMMARIZATION_MAX_DURATION_MS,
119
+ maxDurationMs,
117
120
  abort: () => requestController.abort(),
118
121
  signal: options.signal,
119
122
  onEvent: (event) => {
@@ -1 +1 @@
1
- {"version":3,"file":"speculative-summary.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative-summary.ts"],"names":[],"mappings":"AACA,OAAO,EAQN,0BAA0B,IAAI,wBAAwB,GAEtD,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AACtD,OAAO,EACN,4BAA4B,EAC5B,qCAAqC,EACrC,qCAAqC,GACrC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAEnE,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,MAAM,sBAAsB,GAAG,MAA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AAC,KAAK,CAAC,CAAC;gBACnC,CAAC;YACF,CAAC;SACD,CAAC,CAAC;QACH,OAAO,MAAM,cAAc,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;YAAS,CAAC;QACV,IAAI,OAAO,CAAC,MAAM;YAAE,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;AACF,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\ttype Message,\n\ttype Model,\n\ttype ProviderHeaders,\n\ttype StreamOptions,\n\tsanitizeAnthropicToolPairs as sanitizeAnthropicPayload,\n\ttype TextContent,\n} from \"@earendil-works/pi-ai\";\nimport { stream } from \"@earendil-works/pi-ai/compat\";\nimport {\n\tconsumeStreamWithIdleTimeout,\n\tDEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,\n\tDEFAULT_SUMMARIZATION_MAX_DURATION_MS,\n} from \"../../../compaction/stream-watchdog.ts\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport type { buildPrompt } from \"./prompts.ts\";\nimport { repairOrphanedToolResults } from \"./repair-tool-pairs.ts\";\nimport type { SpeculativeCompactionContext, SpeculativeCompactionSnapshot } from \"./speculative.ts\";\nimport { normalizeSummarizationTurnOrder } from \"./summarization-turn-order.ts\";\n\nconst SUMMARY_TOKEN_HEADROOM = 32_768;\nconst SUMMARY_CONTEXT_WINDOW_RESERVE_RATIO = 0.5;\ntype CompactionProgressCallback = (delta: string) => void;\n\nfunction summaryMaxTokens(model: Model<any>, contextWindow: number): number {\n\tconst headroom = model.maxTokens > 0 ? Math.min(SUMMARY_TOKEN_HEADROOM, model.maxTokens) : SUMMARY_TOKEN_HEADROOM;\n\tif (contextWindow > 0) {\n\t\treturn Math.min(headroom, Math.floor(contextWindow * SUMMARY_CONTEXT_WINDOW_RESERVE_RATIO));\n\t}\n\treturn headroom;\n}\n\n/**\n * Reasoning override for summarization requests. Compaction must be fast: a\n * summarization request that inherits the provider's default reasoning mode\n * burns its latency (and output budget) on invisible thinking before emitting\n * the summary. Disable or minimize reasoning per wire family; adapters ignore\n * options their provider does not support. Mirrors how OpenAI Codex keeps its\n * compaction turn cheap.\n */\nfunction summarizationReasoningOptions(model: Model<any>): Record<string, unknown> {\n\tif (!model.reasoning) return {};\n\tif (model.api === \"anthropic-messages\") return { thinkingEnabled: false };\n\tconst reasoningEffort = ([\"low\", \"medium\", \"high\"] as const).find(\n\t\t(level) => model.thinkingLevelMap?.[level] !== null,\n\t);\n\tif (!reasoningEffort) return {};\n\tswitch (model.api) {\n\t\tcase \"openai-responses\":\n\t\tcase \"openai-codex-responses\":\n\t\tcase \"azure-openai-responses\":\n\t\t\treturn { reasoningEffort, reasoningSummary: null };\n\t\tcase \"openai-completions\":\n\t\t\treturn { reasoningEffort };\n\t\tdefault:\n\t\t\treturn {};\n\t}\n}\n\nexport function getSummaryText(message: Message): string {\n\tconst content = Array.isArray(message.content)\n\t\t? message.content\n\t\t: [{ type: \"text\" as const, text: message.content }];\n\treturn content\n\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n}\n\nexport function isAssistantMessage(message: Message): message is AssistantMessage {\n\treturn message.role === \"assistant\" && \"stopReason\" in message;\n}\n\n/**\n * Providers registered through `pi.registerProvider()` (claude-sdk-oauth, Kiro, any\n * extension provider) exist only in Senpi's ModelRuntime, never in compat's builtin\n * api-registry, which rejects their api id outright. Dispatch through the runtime\n * whenever it is reachable and keep compat for contexts constructed without a registry.\n */\nfunction summarizationStream(\n\tcontext: SpeculativeCompactionContext,\n\tmodel: Model<any>,\n\trequestContext: Context,\n\toptions: StreamOptions & Record<string, unknown>,\n): AssistantMessageEventStream {\n\tconst runtime = context.modelRegistry?.modelRuntime;\n\treturn runtime ? runtime.stream(model, requestContext, options) : stream(model, requestContext, options);\n}\n\nexport async function generateSummaryMessage(options: {\n\tcontext: SpeculativeCompactionContext;\n\tforbidToolCalls?: boolean;\n\tmessages: AgentMessage[];\n\tonProgress?: CompactionProgressCallback;\n\tprompt: ReturnType<typeof buildPrompt>;\n\tsignal?: AbortSignal;\n\tsnapshot: SpeculativeCompactionSnapshot;\n\tauth: {\n\t\tapiKey?: string;\n\t\theaders?: ProviderHeaders;\n\t\textraBody?: Record<string, unknown>;\n\t};\n}): Promise<Message | undefined> {\n\t// Send the conversation as native LLM messages with the summarization\n\t// instruction as a trailing user message, mirroring normal agent traffic.\n\t// A single serialized `<conversation>` text dump of a large session is\n\t// deterministically refused by Anthropic's anti-distillation classifier\n\t// (\"reverse engineering or duplicating model outputs\"), while the same\n\t// content as native blocks with the agent's system prompt and tools passes.\n\t// Request-local controller: the idle watchdog must be able to tear down a\n\t// stalled summarization request without aborting the caller's own signal.\n\tconst requestController = new AbortController();\n\tconst onCallerAbort = () => requestController.abort(options.signal?.reason);\n\tif (options.signal) {\n\t\tif (options.signal.aborted) onCallerAbort();\n\t\telse options.signal.addEventListener(\"abort\", onCallerAbort, { once: true });\n\t}\n\ttry {\n\t\tconst requestMessages: AgentMessage[] = [\n\t\t\t...options.messages,\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{ type: \"text\", text: options.prompt.user }],\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t},\n\t\t];\n\t\tconst providerRequest = await options.context.prepareProviderRequest?.(requestMessages);\n\t\tconst requestContext = {\n\t\t\tsystemPrompt: options.snapshot.systemPrompt ?? options.prompt.system,\n\t\t\tmessages: repairOrphanedToolResults(\n\t\t\t\tnormalizeSummarizationTurnOrder(convertToLlm(providerRequest?.messages ?? requestMessages)),\n\t\t\t),\n\t\t\t...(options.snapshot.tools && options.snapshot.tools.length > 0 ? { tools: options.snapshot.tools } : {}),\n\t\t};\n\t\tconst headers = providerRequest\n\t\t\t? await providerRequest.transformHeaders(options.auth.headers ?? {})\n\t\t\t: options.auth.headers;\n\t\tconst responseStream = summarizationStream(options.context, options.snapshot.model, requestContext, {\n\t\t\tapiKey: options.auth.apiKey,\n\t\t\theaders,\n\t\t\textraBody: options.auth.extraBody,\n\t\t\tonPayload: async (payload, model) => {\n\t\t\t\tconst sanitized = model.api === \"anthropic-messages\" ? sanitizeAnthropicPayload(payload) : payload;\n\t\t\t\treturn providerRequest ? await providerRequest.transformPayload(sanitized) : sanitized;\n\t\t\t},\n\t\t\tmaxTokens: summaryMaxTokens(options.snapshot.model, options.snapshot.contextWindow),\n\t\t\tsignal: requestController.signal,\n\t\t\t...summarizationReasoningOptions(options.snapshot.model),\n\t\t\t...(options.forbidToolCalls ? { toolChoice: \"none\" as const } : {}),\n\t\t});\n\t\tawait consumeStreamWithIdleTimeout(responseStream, {\n\t\t\tidleTimeoutMs: DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,\n\t\t\tmaxDurationMs: DEFAULT_SUMMARIZATION_MAX_DURATION_MS,\n\t\t\tabort: () => requestController.abort(),\n\t\t\tsignal: options.signal,\n\t\t\tonEvent: (event) => {\n\t\t\t\tif (event.type === \"text_delta\" && event.delta) {\n\t\t\t\t\toptions.onProgress?.(event.delta);\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\treturn await responseStream.result();\n\t} finally {\n\t\tif (options.signal) options.signal.removeEventListener(\"abort\", onCallerAbort);\n\t}\n}\n"]}
1
+ {"version":3,"file":"speculative-summary.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative-summary.ts"],"names":[],"mappings":"AACA,OAAO,EAQN,0BAA0B,IAAI,wBAAwB,GAEtD,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACnE,OAAO,EACN,4BAA4B,EAC5B,qCAAqC,EACrC,0BAA0B,GAC1B,MAAM,wCAAwC,CAAC;AAChD,OAAO,E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SACnE,CAAC,CAAC;QACH,MAAM,4BAA4B,CAAC,cAAc,EAAE;YAClD,aAAa,EAAE,qCAAqC;YACpD,aAAa;YACb,KAAK,EAAE,GAAG,EAAE,CAAC,iBAAiB,CAAC,KAAK,EAAE;YACtC,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;gBAClB,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;oBAChD,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACnC,CAAC;YACF,CAAC;SACD,CAAC,CAAC;QACH,OAAO,MAAM,cAAc,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;YAAS,CAAC;QACV,IAAI,OAAO,CAAC,MAAM;YAAE,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;AACF,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\ttype Message,\n\ttype Model,\n\ttype ProviderHeaders,\n\ttype StreamOptions,\n\tsanitizeAnthropicToolPairs as sanitizeAnthropicPayload,\n\ttype TextContent,\n} from \"@earendil-works/pi-ai\";\nimport { stream } from \"@earendil-works/pi-ai/compat\";\nimport { estimateTokens } from \"../../../compaction/compaction.ts\";\nimport {\n\tconsumeStreamWithIdleTimeout,\n\tDEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,\n\tsummarizationMaxDurationMs,\n} from \"../../../compaction/stream-watchdog.ts\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport type { buildPrompt } from \"./prompts.ts\";\nimport { repairOrphanedToolResults } from \"./repair-tool-pairs.ts\";\nimport type { SpeculativeCompactionContext, SpeculativeCompactionSnapshot } from \"./speculative.ts\";\nimport { normalizeSummarizationTurnOrder } from \"./summarization-turn-order.ts\";\n\nconst SUMMARY_TOKEN_HEADROOM = 32_768;\nconst SUMMARY_CONTEXT_WINDOW_RESERVE_RATIO = 0.5;\ntype CompactionProgressCallback = (delta: string) => void;\n\nfunction summaryMaxTokens(model: Model<any>, contextWindow: number): number {\n\tconst headroom = model.maxTokens > 0 ? Math.min(SUMMARY_TOKEN_HEADROOM, model.maxTokens) : SUMMARY_TOKEN_HEADROOM;\n\tif (contextWindow > 0) {\n\t\treturn Math.min(headroom, Math.floor(contextWindow * SUMMARY_CONTEXT_WINDOW_RESERVE_RATIO));\n\t}\n\treturn headroom;\n}\n\n/**\n * Reasoning override for summarization requests. Compaction must be fast: a\n * summarization request that inherits the provider's default reasoning mode\n * burns its latency (and output budget) on invisible thinking before emitting\n * the summary. Disable or minimize reasoning per wire family; adapters ignore\n * options their provider does not support. Mirrors how OpenAI Codex keeps its\n * compaction turn cheap.\n */\nfunction summarizationReasoningOptions(model: Model<any>): Record<string, unknown> {\n\tif (!model.reasoning) return {};\n\tif (model.api === \"anthropic-messages\") return { thinkingEnabled: false };\n\tconst reasoningEffort = ([\"low\", \"medium\", \"high\"] as const).find(\n\t\t(level) => model.thinkingLevelMap?.[level] !== null,\n\t);\n\tif (!reasoningEffort) return {};\n\tswitch (model.api) {\n\t\tcase \"openai-responses\":\n\t\tcase \"openai-codex-responses\":\n\t\tcase \"azure-openai-responses\":\n\t\t\treturn { reasoningEffort, reasoningSummary: null };\n\t\tcase \"openai-completions\":\n\t\t\treturn { reasoningEffort };\n\t\tdefault:\n\t\t\treturn {};\n\t}\n}\n\nexport function getSummaryText(message: Message): string {\n\tconst content = Array.isArray(message.content)\n\t\t? message.content\n\t\t: [{ type: \"text\" as const, text: message.content }];\n\treturn content\n\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n}\n\nexport function isAssistantMessage(message: Message): message is AssistantMessage {\n\treturn message.role === \"assistant\" && \"stopReason\" in message;\n}\n\n/**\n * Providers registered through `pi.registerProvider()` (claude-sdk-oauth, Kiro, any\n * extension provider) exist only in Senpi's ModelRuntime, never in compat's builtin\n * api-registry, which rejects their api id outright. Dispatch through the runtime\n * whenever it is reachable and keep compat for contexts constructed without a registry.\n */\nfunction summarizationStream(\n\tcontext: SpeculativeCompactionContext,\n\tmodel: Model<any>,\n\trequestContext: Context,\n\toptions: StreamOptions & Record<string, unknown>,\n): AssistantMessageEventStream {\n\tconst runtime = context.modelRegistry?.modelRuntime;\n\treturn runtime ? runtime.stream(model, requestContext, options) : stream(model, requestContext, options);\n}\n\nexport async function generateSummaryMessage(options: {\n\tcontext: SpeculativeCompactionContext;\n\tforbidToolCalls?: boolean;\n\t/** Resolved per-attempt duration budget; falls back to the size-adaptive default. */\n\tmaxDurationMs?: number;\n\tmessages: AgentMessage[];\n\tonProgress?: CompactionProgressCallback;\n\tprompt: ReturnType<typeof buildPrompt>;\n\tsignal?: AbortSignal;\n\tsnapshot: SpeculativeCompactionSnapshot;\n\tauth: {\n\t\tapiKey?: string;\n\t\theaders?: ProviderHeaders;\n\t\textraBody?: Record<string, unknown>;\n\t};\n}): Promise<Message | undefined> {\n\t// Send the conversation as native LLM messages with the summarization\n\t// instruction as a trailing user message, mirroring normal agent traffic.\n\t// A single serialized `<conversation>` text dump of a large session is\n\t// deterministically refused by Anthropic's anti-distillation classifier\n\t// (\"reverse engineering or duplicating model outputs\"), while the same\n\t// content as native blocks with the agent's system prompt and tools passes.\n\t// Request-local controller: the idle watchdog must be able to tear down a\n\t// stalled summarization request without aborting the caller's own signal.\n\tconst requestController = new AbortController();\n\tconst onCallerAbort = () => requestController.abort(options.signal?.reason);\n\tif (options.signal) {\n\t\tif (options.signal.aborted) onCallerAbort();\n\t\telse options.signal.addEventListener(\"abort\", onCallerAbort, { once: true });\n\t}\n\ttry {\n\t\tconst requestMessages: AgentMessage[] = [\n\t\t\t...options.messages,\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{ type: \"text\", text: options.prompt.user }],\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t},\n\t\t];\n\t\tconst maxDurationMs =\n\t\t\toptions.maxDurationMs ??\n\t\t\tsummarizationMaxDurationMs(requestMessages.reduce((total, message) => total + estimateTokens(message), 0));\n\t\tconst providerRequest = await options.context.prepareProviderRequest?.(requestMessages);\n\t\tconst requestContext = {\n\t\t\tsystemPrompt: options.snapshot.systemPrompt ?? options.prompt.system,\n\t\t\tmessages: repairOrphanedToolResults(\n\t\t\t\tnormalizeSummarizationTurnOrder(convertToLlm(providerRequest?.messages ?? requestMessages)),\n\t\t\t),\n\t\t\t...(options.snapshot.tools && options.snapshot.tools.length > 0 ? { tools: options.snapshot.tools } : {}),\n\t\t};\n\t\tconst headers = providerRequest\n\t\t\t? await providerRequest.transformHeaders(options.auth.headers ?? {})\n\t\t\t: options.auth.headers;\n\t\tconst responseStream = summarizationStream(options.context, options.snapshot.model, requestContext, {\n\t\t\tapiKey: options.auth.apiKey,\n\t\t\theaders,\n\t\t\textraBody: options.auth.extraBody,\n\t\t\tonPayload: async (payload, model) => {\n\t\t\t\tconst sanitized = model.api === \"anthropic-messages\" ? sanitizeAnthropicPayload(payload) : payload;\n\t\t\t\treturn providerRequest ? await providerRequest.transformPayload(sanitized) : sanitized;\n\t\t\t},\n\t\t\tmaxTokens: summaryMaxTokens(options.snapshot.model, options.snapshot.contextWindow),\n\t\t\tsignal: requestController.signal,\n\t\t\t...summarizationReasoningOptions(options.snapshot.model),\n\t\t\t...(options.forbidToolCalls ? { toolChoice: \"none\" as const } : {}),\n\t\t});\n\t\tawait consumeStreamWithIdleTimeout(responseStream, {\n\t\t\tidleTimeoutMs: DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,\n\t\t\tmaxDurationMs,\n\t\t\tabort: () => requestController.abort(),\n\t\t\tsignal: options.signal,\n\t\t\tonEvent: (event) => {\n\t\t\t\tif (event.type === \"text_delta\" && event.delta) {\n\t\t\t\t\toptions.onProgress?.(event.delta);\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\treturn await responseStream.result();\n\t} finally {\n\t\tif (options.signal) options.signal.removeEventListener(\"abort\", onCallerAbort);\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"speculative.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAON,KAAK,KAAK,EAEV,KAAK,IAAI,EACT,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EAIrB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAGN,KAAK,kBAAkB,EACvB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,YAAY,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAUtG,OAAO,EAAe,KAAK,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAO/E,OAAO,EACN,yBAAyB,EACzB,KAAK,mBAAmB,EACxB,uBAAuB,EACvB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAW9B,KAAK,0BAA0B,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AAE1D,MAAM,WAAW,4BAA4B;IAC5C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IAC9B,cAAc,EAAE,sBAAsB,CAAC;IACvC,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,eAAe,IAAI,YAAY,GAAG,SAAS,CAAC;IAC5C,qBAAqB,CAAC,IAAI,qBAAqB,CAAC,UAAU,CAAC,CAAC;IAC5D,kBAAkB,I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AAC,CA2BtC;AAED,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,GAAG,SAAS,EACnD,oBAAoB,EAAE,MAAM,MAAM,EAClC,QAAQ,EAAE,MAAM,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,GACnD,OAAO,CAAC,2BAA2B,CAAC,CAKtC"}
1
+ {"version":3,"file":"speculative.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAON,KAAK,KAAK,EAEV,KAAK,IAAI,EACT,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EAKrB,MAAM,8BAA8B,CAAC;AAMtC,OAAO,EAGN,KAAK,kBAAkB,EACvB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,YAAY,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAUtG,OAAO,EAAe,KAAK,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAO/E,OAAO,EACN,yBAAyB,EACzB,KAAK,mBAAmB,EACxB,uBAAuB,EACvB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAW9B,KAAK,0BAA0B,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AAE1D,MAAM,WAAW,4BAA4B;IAC5C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IAC9B,cAAc,EAAE,sBAAsB,CAAC;IACvC,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,eAAe,IAAI,YAAY,GAAG,SAAS,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AAE,gBAAgB,GAAG,SAAS,EACxC,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,2BAA2B,CAAC,CA2BtC;AAED,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,GAAG,SAAS,EACnD,oBAAoB,EAAE,MAAM,MAAM,EAClC,QAAQ,EAAE,MAAM,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,GACnD,OAAO,CAAC,2BAA2B,CAAC,CAKtC"}
@@ -1,6 +1,6 @@
1
1
  import { hasCredentialHeaders, isContextOverflow, isRetryableAssistantError, isRetryableErrorMessage, retryTransientCall, } from "@earendil-works/pi-ai";
2
- import { DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, prepareCompaction, } from "../../../compaction/index.js";
3
- import { StreamDurationBudgetError, StreamIdleTimeoutError } from "../../../compaction/stream-watchdog.js";
2
+ import { DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, estimateTokens, prepareCompaction, } from "../../../compaction/index.js";
3
+ import { StreamDurationBudgetError, StreamIdleTimeoutError, summarizationMaxDurationMs, } from "../../../compaction/stream-watchdog.js";
4
4
  import { createWarmAnchorSnapshot, isWarmSummaryAnchorValid, } from "../../../compaction/warm-anchor.js";
5
5
  import { convertToLlm } from "../../../messages.js";
6
6
  import { pruneToolResults } from "./emergency-prune.js";
@@ -161,6 +161,11 @@ export async function runExtensionCompaction(context, snapshot, signal, onProgre
161
161
  // inheritable so the next blocking route degrades on it instead of paying
162
162
  // for a second request.
163
163
  const retryEligible = snapshot.origin === "core-route" || snapshot.origin === "blocking";
164
+ // The attempt budget and the retry gate share one input-size-scaled number,
165
+ // so a large session gets both a proportional attempt deadline and room to
166
+ // retry transient failures without the 120s-era retry budget disqualifying
167
+ // every slow attempt (#1068).
168
+ const attemptBudgetMs = summarizationMaxDurationMs(messages.reduce((total, message) => total + estimateTokens(message), 0), snapshot.preparation.settings.summarizationMaxDurationMs);
164
169
  try {
165
170
  // The provider `error` stop is raised INSIDE the retried producer so a
166
171
  // transient summarization failure spends the shared retry budget. The
@@ -170,6 +175,7 @@ export async function runExtensionCompaction(context, snapshot, signal, onProgre
170
175
  const attempt = await generateSummaryMessage({
171
176
  context,
172
177
  forbidToolCalls: toolUseRetrySpent,
178
+ maxDurationMs: attemptBudgetMs,
173
179
  messages: currentMessages,
174
180
  onProgress,
175
181
  prompt,
@@ -190,7 +196,7 @@ export async function runExtensionCompaction(context, snapshot, signal, onProgre
190
196
  }
191
197
  return attempt;
192
198
  }, (error) => retryEligible &&
193
- allowSummarizationRetry(Date.now() - retryStartedMs) &&
199
+ allowSummarizationRetry(Date.now() - retryStartedMs, attemptBudgetMs) &&
194
200
  isRetryableSummaryAttempt(error), DEFAULT_SUMMARIZATION_RETRY_POLICY, signal);
195
201
  }
196
202
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"speculative.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,oBAAoB,EACpB,iBAAiB,EACjB,yBAAyB,EACzB,uBAAuB,EAGvB,kBAAkB,GAElB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGN,2BAA2B,EAC3B,qBAAqB,EACrB,iBAAiB,GACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAC3G,OAAO,EACN,wBAAwB,EACxB,wBAAwB,GAExB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAIpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EACN,kBAAkB,EAClB,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,wCAAwC,GACxC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAA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"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\thasCredentialHeaders,\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\tisRetryableErrorMessage,\n\ttype Message,\n\ttype Model,\n\tretryTransientCall,\n\ttype Tool,\n} from \"@earendil-works/pi-ai\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\tprepareCompaction,\n} from \"../../../compaction/index.ts\";\nimport { StreamDurationBudgetError, StreamIdleTimeoutError } from \"../../../compaction/stream-watchdog.ts\";\nimport {\n\tcreateWarmAnchorSnapshot,\n\tisWarmSummaryAnchorValid,\n\ttype WarmAnchorSnapshot,\n} from \"../../../compaction/warm-anchor.ts\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport type { ModelRegistry } from \"../../../model-registry.ts\";\nimport type { ReadonlySessionManager } from \"../../../session-manager.ts\";\nimport type { ApplyCompactionResult, ContextUsage, ProviderRequestPreparation } from \"../../types.ts\";\nimport { pruneToolResults } from \"./emergency-prune.ts\";\nimport {\n\tallowOverflowRetry,\n\tboundSummarizationInput,\n\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\tSummarizationOverflowExhaustedError,\n\tshrinkSummarizationInputForOverflowRetry,\n} from \"./overflow-retry.ts\";\nimport { computeEffectiveKeepRecentTokens, computeEffectiveThreshold } from \"./policy.ts\";\nimport { buildPrompt, type MergedCompactionPromptVariant } from \"./prompts.ts\";\nimport { generateSummaryMessage, getSummaryText, isAssistantMessage } from \"./speculative-summary.ts\";\n\nimport { allowSummarizationRetry, DEFAULT_SUMMARIZATION_RETRY_POLICY } from \"./summarization-retry.ts\";\n\nimport { extractTaskIntent, resolveInheritedTaskIntent } from \"./task-intent.ts\";\n\nexport {\n\tcreateEmergencyPruneLatch,\n\ttype EmergencyPruneLatch,\n\thardLimitEmergencyPrune,\n\ttruncateContextMessages,\n} from \"./emergency-prune.ts\";\n\nimport { computeStructuralYield } from \"./yield.ts\";\n\nconst DEFAULT_CONTEXT_WINDOW = 200_000;\n// Hysteresis: the emergency prune engages at EMERGENCY_CONTEXT_TARGET_RATIO but only\n// releases once the context falls below this lower ratio. A single threshold makes a\n// session parked near the limit alternate between the pruned and un-pruned history on\n// consecutive requests; because pruning rewrites old tool results, every alternation\n// invalidates the provider prompt-cache prefix and re-bills the whole conversation.\nconst SUMMARY_SCHEMA = \"senpi.compaction.summary.v1\";\ntype CompactionProgressCallback = (delta: string) => void;\n\nexport interface SpeculativeCompactionContext {\n\tmodel: Model<any> | undefined;\n\tsessionManager: ReadonlySessionManager;\n\tmodelRegistry?: ModelRegistry;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetCompactionSettings?(): CompactionPreparation[\"settings\"];\n\tgetMessageRevision(): number;\n\tgetSystemPrompt?(): string;\n\tprepareProviderRequest?(messages: AgentMessage[]): Promise<ProviderRequestPreparation>;\n\tisIdle?(): boolean;\n\tapplyCompaction(\n\t\tprecomputed: CompactionResult,\n\t\toptions: {\n\t\t\treason: \"extension\";\n\t\t\texpectedRevision?: number;\n\t\t\texpectedWarmAnchor?: WarmAnchorSnapshot;\n\t\t\tsignal?: AbortSignal;\n\t\t},\n\t): Promise<ApplyCompactionResult>;\n}\n\nexport interface SpeculativeCompactionSnapshot {\n\tgeneration: number;\n\texpectedRevision: number;\n\tmodel: Model<any>;\n\tcontextWindow: number;\n\tpreparation: CompactionPreparation;\n\tbranchEntries?: ReturnType<ReadonlySessionManager[\"getBranch\"]>;\n\tpromptVariant: MergedCompactionPromptVariant;\n\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\tcustomInstructions?: string;\n\t/** Agent system prompt; used to make the summarization request look like normal agent traffic. */\n\tsystemPrompt?: string;\n\t/** Agent tool definitions; forwarded so the request shape matches normal agent traffic. */\n\ttools?: Tool[];\n}\n\nexport type SpeculativeCompactionResult = ApplyCompactionResult | { applied: false; reason: \"unavailable\" | \"failed\" };\n\nfunction approxTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\n/**\n * Summary-generation failure with a user-facing diagnosis. Distinct from a\n * user abort (which resolves `undefined`): callers surface `message` on the\n * manual route and degrade to \"unavailable\" on automatic routes.\n */\n/**\n * Provider `error` stop during summarization, carrying the metadata-aware\n * transient classification from the full assistant message. A refusal whose\n * text happens to look retryable must still surface loudly; the message\n * string alone cannot encode that.\n */\nexport type SummaryRequestFailureKind = \"upstream-stream-truncated\";\n\nexport class SummaryRequestError extends Error {\n\treadonly transient: boolean;\n\treadonly failureKind?: SummaryRequestFailureKind;\n\n\tconstructor(message: string, transient: boolean, failureKind?: SummaryRequestFailureKind) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryRequestError\";\n\t\tthis.transient = transient;\n\t\tthis.failureKind = failureKind;\n\t}\n}\n\nconst UPSTREAM_STREAM_TRUNCATED_PATTERN = /(?:^|[^A-Za-z0-9_])upstream_stream_truncated(?:[^A-Za-z0-9_]|$)/;\n\n/**\n * Only failures with no cheaper recovery earn another billed request.\n *\n * Every class that `classifyRequiredCompactionFallbackFailure` recognizes\n * (watchdog timeouts, `upstream-stream-truncated`, overflow exhaustion,\n * empty-summary generation failures) already\n * has a deterministic zero-LLM recovery, and context overflow is answered by\n * shrinking the input in the surrounding loop - replaying those would pay for a\n * summarization the fallback can rebuild for free. The classes checked here are\n * mirrored from that classifier rather than imported, because\n * `deterministic-fallback.ts` imports this module.\n */\nfunction isRetryableSummaryAttempt(error: unknown): boolean {\n\tif (error instanceof StreamDurationBudgetError || error instanceof StreamIdleTimeoutError) return false;\n\tif (error instanceof SummarizationOverflowExhaustedError) return false;\n\tif (error instanceof SummaryGenerationError) return false;\n\tif (error instanceof SummaryRequestError) return error.failureKind === undefined && error.transient;\n\tif (error instanceof Error) return isRetryableErrorMessage(error.message);\n\treturn false;\n}\n\nfunction summaryRequestFailureKind(response: AssistantMessage): SummaryRequestFailureKind | undefined {\n\tif (response.stopDetails?.type === \"refusal\" || response.stopDetails?.type === \"sensitive\") return undefined;\n\treturn UPSTREAM_STREAM_TRUNCATED_PATTERN.test(response.errorMessage ?? \"\") ? \"upstream-stream-truncated\" : undefined;\n}\n\nexport class SummaryGenerationError extends Error {\n\treadonly kind: \"auth\" | \"empty-summary\";\n\n\tconstructor(kind: \"auth\" | \"empty-summary\", message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryGenerationError\";\n\t\tthis.kind = kind;\n\t}\n}\n\n/**\n * Output budget for one summarization request. Adaptive-thinking models emit\n * reasoning tokens before the summary text, so the legacy flat 8192 cap could\n * be consumed entirely by thinking, ending the stream with zero text blocks.\n * Grant generous headroom, clamped to what the model can actually emit and to\n * half the context window: providers that enforce input + output <= window\n * would otherwise reject the request for models advertising contextWindow ==\n * maxTokens (every summarization request also carries conversation input).\n */\n\nexport function getPromptVariant(options: {\n\treason: string;\n\tpreparation: { previousSummary?: string; isSplitTurn: boolean };\n}): MergedCompactionPromptVariant {\n\tif (options.reason === \"branch\") return \"branch\";\n\tif (options.preparation.previousSummary) return \"update\";\n\tif (options.preparation.isSplitTurn) return \"turn_prefix\";\n\treturn \"default\";\n}\n\nexport function createSpeculativeCompactionSnapshot(\n\tcontext: SpeculativeCompactionContext,\n\toptions: {\n\t\tcustomInstructions?: string;\n\t\tgeneration: number;\n\t\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\t\ttools?: Tool[];\n\t},\n): SpeculativeCompactionSnapshot | undefined {\n\tconst model = context.model;\n\tif (!model) return undefined;\n\n\tconst expectedRevision = context.getMessageRevision();\n\tconst branchEntries = context.sessionManager.getBranch();\n\tconst contextWindow = context.getContextUsage()?.contextWindow ?? model.contextWindow ?? DEFAULT_CONTEXT_WINDOW;\n\tconst settings = context.getCompactionSettings?.() ?? DEFAULT_COMPACTION_SETTINGS;\n\tconst thresholdRatio = computeEffectiveThreshold(contextWindow);\n\tconst preparation = prepareCompaction(branchEntries, {\n\t\t...settings,\n\t\tkeepRecentTokens: computeEffectiveKeepRecentTokens(settings.keepRecentTokens, contextWindow, thresholdRatio),\n\t});\n\tif (!preparation) return undefined;\n\n\treturn {\n\t\t...options,\n\t\texpectedRevision,\n\t\tmodel,\n\t\tcontextWindow,\n\t\tpreparation,\n\t\tbranchEntries,\n\t\tpromptVariant: getPromptVariant({ reason: \"extension\", preparation }),\n\t\tsystemPrompt: context.getSystemPrompt?.(),\n\t};\n}\n\n/**\n * Generate a compaction summary for the snapshot. Resolves `undefined` only\n * when the request was aborted (caller signal or an aborted stream); every\n * other failure throws — {@link SummaryGenerationError} for diagnosable\n * generation failures, the raw provider error otherwise. Abort is checked\n * before and after credential resolution so a cancelled request never\n * misreports as an auth failure.\n */\nexport async function runExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot,\n\tsignal?: AbortSignal,\n\tonProgress?: CompactionProgressCallback,\n): Promise<CompactionResult | undefined> {\n\tif (signal?.aborted) return undefined;\n\tconst auth = await context.modelRegistry?.getApiKeyAndHeaders(snapshot.model);\n\tif (signal?.aborted) return undefined;\n\t// A provider is authenticated for summarization by either a resolved key or a\n\t// credential request header: `headers`-authenticated providers (models.json and\n\t// extension providers alike) never resolve an apiKey, yet their normal agent\n\t// turns are fully authenticated.\n\tif (!auth?.ok || !(auth.apiKey || hasCredentialHeaders(auth.headers))) {\n\t\tconst detail =\n\t\t\tauth && !auth.ok ? auth.error : `no credentials resolved for provider \"${snapshot.model.provider}\"`;\n\t\tthrow new SummaryGenerationError(\"auth\", `summarization credentials unavailable: ${detail}`);\n\t}\n\tconst requestSnapshot = auth.baseUrl\n\t\t? { ...snapshot, model: { ...snapshot.model, baseUrl: auth.baseUrl } }\n\t\t: snapshot;\n\n\tconst prompt = buildPrompt({\n\t\tvariant: requestSnapshot.promptVariant,\n\t\tpreviousSummary: requestSnapshot.preparation.previousSummary,\n\t\ttaskIntent: resolveInheritedTaskIntent(requestSnapshot.branchEntries ?? []),\n\t\tcustomInstructions: requestSnapshot.customInstructions,\n\t});\n\tconst promptTokens = approxTokens(prompt.user);\n\tlet messages = boundSummarizationInput(\n\t\tpruneToolResults(\n\t\t\t[...requestSnapshot.preparation.messagesToSummarize, ...requestSnapshot.preparation.turnPrefixMessages],\n\t\t\trequestSnapshot.contextWindow,\n\t\t\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\t\t),\n\t\trequestSnapshot.contextWindow,\n\t\tpromptTokens,\n\t);\n\tconst overflowRetryStartMs = Date.now();\n\tlet overflowAttempts = 0;\n\tconst summarizationToolsOffered = (requestSnapshot.tools?.length ?? 0) > 0;\n\tlet toolUseRetrySpent = false;\n\n\twhile (true) {\n\t\tif (signal?.aborted) return undefined;\n\t\tlet response: Message | undefined;\n\t\tconst currentMessages = messages;\n\t\tconst retryStartedMs = Date.now();\n\t\t// Only the routes that block the user's turn retry here. The speculative\n\t\t// warm-up owns its own bounded retry (`idle-retry.ts`) with idle/breaker\n\t\t// guards re-evaluated between attempts, and a failed warm job must stay\n\t\t// inheritable so the next blocking route degrades on it instead of paying\n\t\t// for a second request.\n\t\tconst retryEligible = snapshot.origin === \"core-route\" || snapshot.origin === \"blocking\";\n\t\ttry {\n\t\t\t// The provider `error` stop is raised INSIDE the retried producer so a\n\t\t\t// transient summarization failure spends the shared retry budget. The\n\t\t\t// surrounding loop keeps overflow shrinking and abort handling, which\n\t\t\t// must never be answered by replaying the same request.\n\t\t\tresponse = await retryTransientCall(\n\t\t\t\tasync () => {\n\t\t\t\t\tconst attempt = await generateSummaryMessage({\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\tforbidToolCalls: toolUseRetrySpent,\n\t\t\t\t\t\tmessages: currentMessages,\n\t\t\t\t\t\tonProgress,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tsnapshot: requestSnapshot,\n\t\t\t\t\t\tauth: {\n\t\t\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\t\t\theaders: auth.headers,\n\t\t\t\t\t\t\textraBody: auth.extraBody,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\tattempt &&\n\t\t\t\t\t\tisAssistantMessage(attempt) &&\n\t\t\t\t\t\tattempt.stopReason === \"error\" &&\n\t\t\t\t\t\t!isContextOverflow(attempt, snapshot.contextWindow)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst failureKind = summaryRequestFailureKind(attempt);\n\t\t\t\t\t\tthrow new SummaryRequestError(\n\t\t\t\t\t\t\tattempt.errorMessage || \"Compaction summary request failed\",\n\t\t\t\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(attempt),\n\t\t\t\t\t\t\tfailureKind,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn attempt;\n\t\t\t\t},\n\t\t\t\t(error) =>\n\t\t\t\t\tretryEligible &&\n\t\t\t\t\tallowSummarizationRetry(Date.now() - retryStartedMs) &&\n\t\t\t\t\tisRetryableSummaryAttempt(error),\n\t\t\t\tDEFAULT_SUMMARIZATION_RETRY_POLICY,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) return undefined;\n\t\t\tthrow error;\n\t\t}\n\t\tif (!response) return undefined;\n\n\t\tif (isAssistantMessage(response) && isContextOverflow(response, snapshot.contextWindow)) {\n\t\t\toverflowAttempts++;\n\t\t\tconst elapsedMs = Date.now() - overflowRetryStartMs;\n\t\t\tconst retryMessages = allowOverflowRetry(overflowAttempts, elapsedMs)\n\t\t\t\t? shrinkSummarizationInputForOverflowRetry(messages, snapshot.contextWindow, promptTokens)\n\t\t\t\t: undefined;\n\t\t\tif (!retryMessages) {\n\t\t\t\tthrow new SummarizationOverflowExhaustedError(overflowAttempts, elapsedMs);\n\t\t\t}\n\t\t\tmessages = retryMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"aborted\") {\n\t\t\t// A partial summary from an aborted stream must never be applied.\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"error\") {\n\t\t\t// Surface the real provider failure instead of silently degrading\n\t\t\t// into a generic \"Compaction cancelled\". Preserve the structured\n\t\t\t// truncation class here so downstream recovery never trusts arbitrary\n\t\t\t// thrown error text as authorization for destructive context reduction.\n\t\t\tconst failureKind = summaryRequestFailureKind(response);\n\t\t\tthrow new SummaryRequestError(\n\t\t\t\tresponse.errorMessage || \"Compaction summary request failed\",\n\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(response),\n\t\t\t\tfailureKind,\n\t\t\t);\n\t\t}\n\n\t\tconst summary = getSummaryText(response);\n\t\tif (!summary) {\n\t\t\tconst stopReason = isAssistantMessage(response) ? response.stopReason : \"unknown\";\n\t\t\t// A summarizer can hijack the forwarded agent tools and answer with a\n\t\t\t// bare tool call (observed on openai-codex gpt-5.6-sol, 2026-08-31),\n\t\t\t// which used to surface as a terminal empty-summary failure. Spend one\n\t\t\t// retry with tool calling forbidden; the tools stay in the request\n\t\t\t// because Anthropic rejects tool_use history without the tools param.\n\t\t\tif (stopReason === \"toolUse\" && summarizationToolsOffered && !toolUseRetrySpent) {\n\t\t\t\ttoolUseRetrySpent = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new SummaryGenerationError(\n\t\t\t\t\"empty-summary\",\n\t\t\t\t`summarization response contained no text (stopReason: ${stopReason})`,\n\t\t\t);\n\t\t}\n\n\t\t// Informational only: the core rejects an applied compaction that would\n\t\t// still overflow (_wouldCompactionOverflow). Rejecting here based on the\n\t\t// size of the *discarded* input made large sessions uncompactable.\n\t\tconst tokenEstimate = estimateContextTokens(convertToLlm(messages)).tokens + approxTokens(summary);\n\t\tconst parsedSummary = extractTaskIntent(summary);\n\t\tconst taskIntent = parsedSummary.taskIntent ?? resolveInheritedTaskIntent(snapshot.branchEntries ?? []);\n\n\t\treturn {\n\t\t\tsummary: parsedSummary.summaryText,\n\t\t\tfirstKeptEntryId: snapshot.preparation.firstKeptEntryId,\n\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\tdetails: {\n\t\t\t\tschema: SUMMARY_SCHEMA,\n\t\t\t\tpromptVariant: snapshot.promptVariant,\n\t\t\t\ttokenEstimate,\n\t\t\t\tstructuralYield: computeStructuralYield({\n\t\t\t\t\tpreviousSummary: snapshot.preparation.previousSummary ?? \"\",\n\t\t\t\t\tmessagesToSummarize: snapshot.preparation.messagesToSummarize,\n\t\t\t\t\tturnPrefixMessages: snapshot.preparation.turnPrefixMessages,\n\t\t\t\t\tsummary: parsedSummary.summaryText,\n\t\t\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\t\t}),\n\t\t\t\t...(snapshot.origin ? { origin: snapshot.origin } : {}),\n\t\t\t\t...(taskIntent ? { taskIntent } : {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function applyGeneratedCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tcompaction: CompactionResult | undefined,\n\tsignal?: AbortSignal,\n): Promise<SpeculativeCompactionResult> {\n\tconst provider = context.model?.provider;\n\tif ((provider === \"cursor\" || provider === \"cursor-cli-oauth\") && context.isIdle && !context.isIdle()) {\n\t\treturn { applied: false, reason: \"rejected\" };\n\t}\n\tif (!snapshot || !compaction) return { applied: false, reason: \"unavailable\" };\n\n\tif (snapshot.generation !== getCurrentGeneration()) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\tconst revisionUnchanged = snapshot.expectedRevision === context.getMessageRevision();\n\tconst warmAnchor = createWarmAnchorSnapshot(snapshot.preparation.firstKeptEntryId, snapshot.branchEntries ?? []);\n\tif (\n\t\t!revisionUnchanged &&\n\t\t(!warmAnchor || !isWarmSummaryAnchorValid(warmAnchor, context.sessionManager.getBranch()))\n\t) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\treturn await context.applyCompaction(compaction, {\n\t\treason: \"extension\",\n\t\t...(revisionUnchanged || !warmAnchor\n\t\t\t? { expectedRevision: snapshot.expectedRevision }\n\t\t\t: { expectedWarmAnchor: warmAnchor }),\n\t\tsignal,\n\t});\n}\n\nexport async function applySpeculativeCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tgenerate: () => Promise<CompactionResult | undefined>,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot) return { applied: false, reason: \"unavailable\" };\n\n\tconst compaction = await generate();\n\treturn await applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction);\n}\n"]}
1
+ {"version":3,"file":"speculative.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,oBAAoB,EACpB,iBAAiB,EACjB,yBAAyB,EACzB,uBAAuB,EAGvB,kBAAkB,GAElB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGN,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,EACd,iBAAiB,GACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,yBAAyB,EACzB,sBAAsB,EACtB,0BAA0B,GAC1B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACN,wBAAwB,EACxB,wBAAwB,GAExB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAIpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EACN,kBAAkB,EAClB,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,wCAAwC,GACxC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAsC,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,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,aAAa,EAAE,CAAC;IAEhE,MAAM,UAAU,GAAG,MAAM,QAAQ,EAAE,CAAC;IACpC,OAAO,MAAM,wBAAwB,CAAC,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,UAAU,CAAC,CAAC;AAC5F,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\thasCredentialHeaders,\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\tisRetryableErrorMessage,\n\ttype Message,\n\ttype Model,\n\tretryTransientCall,\n\ttype Tool,\n} from \"@earendil-works/pi-ai\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\testimateTokens,\n\tprepareCompaction,\n} from \"../../../compaction/index.ts\";\nimport {\n\tStreamDurationBudgetError,\n\tStreamIdleTimeoutError,\n\tsummarizationMaxDurationMs,\n} from \"../../../compaction/stream-watchdog.ts\";\nimport {\n\tcreateWarmAnchorSnapshot,\n\tisWarmSummaryAnchorValid,\n\ttype WarmAnchorSnapshot,\n} from \"../../../compaction/warm-anchor.ts\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport type { ModelRegistry } from \"../../../model-registry.ts\";\nimport type { ReadonlySessionManager } from \"../../../session-manager.ts\";\nimport type { ApplyCompactionResult, ContextUsage, ProviderRequestPreparation } from \"../../types.ts\";\nimport { pruneToolResults } from \"./emergency-prune.ts\";\nimport {\n\tallowOverflowRetry,\n\tboundSummarizationInput,\n\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\tSummarizationOverflowExhaustedError,\n\tshrinkSummarizationInputForOverflowRetry,\n} from \"./overflow-retry.ts\";\nimport { computeEffectiveKeepRecentTokens, computeEffectiveThreshold } from \"./policy.ts\";\nimport { buildPrompt, type MergedCompactionPromptVariant } from \"./prompts.ts\";\nimport { generateSummaryMessage, getSummaryText, isAssistantMessage } from \"./speculative-summary.ts\";\n\nimport { allowSummarizationRetry, DEFAULT_SUMMARIZATION_RETRY_POLICY } from \"./summarization-retry.ts\";\n\nimport { extractTaskIntent, resolveInheritedTaskIntent } from \"./task-intent.ts\";\n\nexport {\n\tcreateEmergencyPruneLatch,\n\ttype EmergencyPruneLatch,\n\thardLimitEmergencyPrune,\n\ttruncateContextMessages,\n} from \"./emergency-prune.ts\";\n\nimport { computeStructuralYield } from \"./yield.ts\";\n\nconst DEFAULT_CONTEXT_WINDOW = 200_000;\n// Hysteresis: the emergency prune engages at EMERGENCY_CONTEXT_TARGET_RATIO but only\n// releases once the context falls below this lower ratio. A single threshold makes a\n// session parked near the limit alternate between the pruned and un-pruned history on\n// consecutive requests; because pruning rewrites old tool results, every alternation\n// invalidates the provider prompt-cache prefix and re-bills the whole conversation.\nconst SUMMARY_SCHEMA = \"senpi.compaction.summary.v1\";\ntype CompactionProgressCallback = (delta: string) => void;\n\nexport interface SpeculativeCompactionContext {\n\tmodel: Model<any> | undefined;\n\tsessionManager: ReadonlySessionManager;\n\tmodelRegistry?: ModelRegistry;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetCompactionSettings?(): CompactionPreparation[\"settings\"];\n\tgetMessageRevision(): number;\n\tgetSystemPrompt?(): string;\n\tprepareProviderRequest?(messages: AgentMessage[]): Promise<ProviderRequestPreparation>;\n\tisIdle?(): boolean;\n\tapplyCompaction(\n\t\tprecomputed: CompactionResult,\n\t\toptions: {\n\t\t\treason: \"extension\";\n\t\t\texpectedRevision?: number;\n\t\t\texpectedWarmAnchor?: WarmAnchorSnapshot;\n\t\t\tsignal?: AbortSignal;\n\t\t},\n\t): Promise<ApplyCompactionResult>;\n}\n\nexport interface SpeculativeCompactionSnapshot {\n\tgeneration: number;\n\texpectedRevision: number;\n\tmodel: Model<any>;\n\tcontextWindow: number;\n\tpreparation: CompactionPreparation;\n\tbranchEntries?: ReturnType<ReadonlySessionManager[\"getBranch\"]>;\n\tpromptVariant: MergedCompactionPromptVariant;\n\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\tcustomInstructions?: string;\n\t/** Agent system prompt; used to make the summarization request look like normal agent traffic. */\n\tsystemPrompt?: string;\n\t/** Agent tool definitions; forwarded so the request shape matches normal agent traffic. */\n\ttools?: Tool[];\n}\n\nexport type SpeculativeCompactionResult = ApplyCompactionResult | { applied: false; reason: \"unavailable\" | \"failed\" };\n\nfunction approxTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\n/**\n * Summary-generation failure with a user-facing diagnosis. Distinct from a\n * user abort (which resolves `undefined`): callers surface `message` on the\n * manual route and degrade to \"unavailable\" on automatic routes.\n */\n/**\n * Provider `error` stop during summarization, carrying the metadata-aware\n * transient classification from the full assistant message. A refusal whose\n * text happens to look retryable must still surface loudly; the message\n * string alone cannot encode that.\n */\nexport type SummaryRequestFailureKind = \"upstream-stream-truncated\";\n\nexport class SummaryRequestError extends Error {\n\treadonly transient: boolean;\n\treadonly failureKind?: SummaryRequestFailureKind;\n\n\tconstructor(message: string, transient: boolean, failureKind?: SummaryRequestFailureKind) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryRequestError\";\n\t\tthis.transient = transient;\n\t\tthis.failureKind = failureKind;\n\t}\n}\n\nconst UPSTREAM_STREAM_TRUNCATED_PATTERN = /(?:^|[^A-Za-z0-9_])upstream_stream_truncated(?:[^A-Za-z0-9_]|$)/;\n\n/**\n * Only failures with no cheaper recovery earn another billed request.\n *\n * Every class that `classifyRequiredCompactionFallbackFailure` recognizes\n * (watchdog timeouts, `upstream-stream-truncated`, overflow exhaustion,\n * empty-summary generation failures) already\n * has a deterministic zero-LLM recovery, and context overflow is answered by\n * shrinking the input in the surrounding loop - replaying those would pay for a\n * summarization the fallback can rebuild for free. The classes checked here are\n * mirrored from that classifier rather than imported, because\n * `deterministic-fallback.ts` imports this module.\n */\nfunction isRetryableSummaryAttempt(error: unknown): boolean {\n\tif (error instanceof StreamDurationBudgetError || error instanceof StreamIdleTimeoutError) return false;\n\tif (error instanceof SummarizationOverflowExhaustedError) return false;\n\tif (error instanceof SummaryGenerationError) return false;\n\tif (error instanceof SummaryRequestError) return error.failureKind === undefined && error.transient;\n\tif (error instanceof Error) return isRetryableErrorMessage(error.message);\n\treturn false;\n}\n\nfunction summaryRequestFailureKind(response: AssistantMessage): SummaryRequestFailureKind | undefined {\n\tif (response.stopDetails?.type === \"refusal\" || response.stopDetails?.type === \"sensitive\") return undefined;\n\treturn UPSTREAM_STREAM_TRUNCATED_PATTERN.test(response.errorMessage ?? \"\") ? \"upstream-stream-truncated\" : undefined;\n}\n\nexport class SummaryGenerationError extends Error {\n\treadonly kind: \"auth\" | \"empty-summary\";\n\n\tconstructor(kind: \"auth\" | \"empty-summary\", message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryGenerationError\";\n\t\tthis.kind = kind;\n\t}\n}\n\n/**\n * Output budget for one summarization request. Adaptive-thinking models emit\n * reasoning tokens before the summary text, so the legacy flat 8192 cap could\n * be consumed entirely by thinking, ending the stream with zero text blocks.\n * Grant generous headroom, clamped to what the model can actually emit and to\n * half the context window: providers that enforce input + output <= window\n * would otherwise reject the request for models advertising contextWindow ==\n * maxTokens (every summarization request also carries conversation input).\n */\n\nexport function getPromptVariant(options: {\n\treason: string;\n\tpreparation: { previousSummary?: string; isSplitTurn: boolean };\n}): MergedCompactionPromptVariant {\n\tif (options.reason === \"branch\") return \"branch\";\n\tif (options.preparation.previousSummary) return \"update\";\n\tif (options.preparation.isSplitTurn) return \"turn_prefix\";\n\treturn \"default\";\n}\n\nexport function createSpeculativeCompactionSnapshot(\n\tcontext: SpeculativeCompactionContext,\n\toptions: {\n\t\tcustomInstructions?: string;\n\t\tgeneration: number;\n\t\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\t\ttools?: Tool[];\n\t},\n): SpeculativeCompactionSnapshot | undefined {\n\tconst model = context.model;\n\tif (!model) return undefined;\n\n\tconst expectedRevision = context.getMessageRevision();\n\tconst branchEntries = context.sessionManager.getBranch();\n\tconst contextWindow = context.getContextUsage()?.contextWindow ?? model.contextWindow ?? DEFAULT_CONTEXT_WINDOW;\n\tconst settings = context.getCompactionSettings?.() ?? DEFAULT_COMPACTION_SETTINGS;\n\tconst thresholdRatio = computeEffectiveThreshold(contextWindow);\n\tconst preparation = prepareCompaction(branchEntries, {\n\t\t...settings,\n\t\tkeepRecentTokens: computeEffectiveKeepRecentTokens(settings.keepRecentTokens, contextWindow, thresholdRatio),\n\t});\n\tif (!preparation) return undefined;\n\n\treturn {\n\t\t...options,\n\t\texpectedRevision,\n\t\tmodel,\n\t\tcontextWindow,\n\t\tpreparation,\n\t\tbranchEntries,\n\t\tpromptVariant: getPromptVariant({ reason: \"extension\", preparation }),\n\t\tsystemPrompt: context.getSystemPrompt?.(),\n\t};\n}\n\n/**\n * Generate a compaction summary for the snapshot. Resolves `undefined` only\n * when the request was aborted (caller signal or an aborted stream); every\n * other failure throws — {@link SummaryGenerationError} for diagnosable\n * generation failures, the raw provider error otherwise. Abort is checked\n * before and after credential resolution so a cancelled request never\n * misreports as an auth failure.\n */\nexport async function runExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot,\n\tsignal?: AbortSignal,\n\tonProgress?: CompactionProgressCallback,\n): Promise<CompactionResult | undefined> {\n\tif (signal?.aborted) return undefined;\n\tconst auth = await context.modelRegistry?.getApiKeyAndHeaders(snapshot.model);\n\tif (signal?.aborted) return undefined;\n\t// A provider is authenticated for summarization by either a resolved key or a\n\t// credential request header: `headers`-authenticated providers (models.json and\n\t// extension providers alike) never resolve an apiKey, yet their normal agent\n\t// turns are fully authenticated.\n\tif (!auth?.ok || !(auth.apiKey || hasCredentialHeaders(auth.headers))) {\n\t\tconst detail =\n\t\t\tauth && !auth.ok ? auth.error : `no credentials resolved for provider \"${snapshot.model.provider}\"`;\n\t\tthrow new SummaryGenerationError(\"auth\", `summarization credentials unavailable: ${detail}`);\n\t}\n\tconst requestSnapshot = auth.baseUrl\n\t\t? { ...snapshot, model: { ...snapshot.model, baseUrl: auth.baseUrl } }\n\t\t: snapshot;\n\n\tconst prompt = buildPrompt({\n\t\tvariant: requestSnapshot.promptVariant,\n\t\tpreviousSummary: requestSnapshot.preparation.previousSummary,\n\t\ttaskIntent: resolveInheritedTaskIntent(requestSnapshot.branchEntries ?? []),\n\t\tcustomInstructions: requestSnapshot.customInstructions,\n\t});\n\tconst promptTokens = approxTokens(prompt.user);\n\tlet messages = boundSummarizationInput(\n\t\tpruneToolResults(\n\t\t\t[...requestSnapshot.preparation.messagesToSummarize, ...requestSnapshot.preparation.turnPrefixMessages],\n\t\t\trequestSnapshot.contextWindow,\n\t\t\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\t\t),\n\t\trequestSnapshot.contextWindow,\n\t\tpromptTokens,\n\t);\n\tconst overflowRetryStartMs = Date.now();\n\tlet overflowAttempts = 0;\n\tconst summarizationToolsOffered = (requestSnapshot.tools?.length ?? 0) > 0;\n\tlet toolUseRetrySpent = false;\n\n\twhile (true) {\n\t\tif (signal?.aborted) return undefined;\n\t\tlet response: Message | undefined;\n\t\tconst currentMessages = messages;\n\t\tconst retryStartedMs = Date.now();\n\t\t// Only the routes that block the user's turn retry here. The speculative\n\t\t// warm-up owns its own bounded retry (`idle-retry.ts`) with idle/breaker\n\t\t// guards re-evaluated between attempts, and a failed warm job must stay\n\t\t// inheritable so the next blocking route degrades on it instead of paying\n\t\t// for a second request.\n\t\tconst retryEligible = snapshot.origin === \"core-route\" || snapshot.origin === \"blocking\";\n\t\t// The attempt budget and the retry gate share one input-size-scaled number,\n\t\t// so a large session gets both a proportional attempt deadline and room to\n\t\t// retry transient failures without the 120s-era retry budget disqualifying\n\t\t// every slow attempt (#1068).\n\t\tconst attemptBudgetMs = summarizationMaxDurationMs(\n\t\t\tmessages.reduce((total, message) => total + estimateTokens(message), 0),\n\t\t\tsnapshot.preparation.settings.summarizationMaxDurationMs,\n\t\t);\n\t\ttry {\n\t\t\t// The provider `error` stop is raised INSIDE the retried producer so a\n\t\t\t// transient summarization failure spends the shared retry budget. The\n\t\t\t// surrounding loop keeps overflow shrinking and abort handling, which\n\t\t\t// must never be answered by replaying the same request.\n\t\t\tresponse = await retryTransientCall(\n\t\t\t\tasync () => {\n\t\t\t\t\tconst attempt = await generateSummaryMessage({\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\tforbidToolCalls: toolUseRetrySpent,\n\t\t\t\t\t\tmaxDurationMs: attemptBudgetMs,\n\t\t\t\t\t\tmessages: currentMessages,\n\t\t\t\t\t\tonProgress,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tsnapshot: requestSnapshot,\n\t\t\t\t\t\tauth: {\n\t\t\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\t\t\theaders: auth.headers,\n\t\t\t\t\t\t\textraBody: auth.extraBody,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\tattempt &&\n\t\t\t\t\t\tisAssistantMessage(attempt) &&\n\t\t\t\t\t\tattempt.stopReason === \"error\" &&\n\t\t\t\t\t\t!isContextOverflow(attempt, snapshot.contextWindow)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst failureKind = summaryRequestFailureKind(attempt);\n\t\t\t\t\t\tthrow new SummaryRequestError(\n\t\t\t\t\t\t\tattempt.errorMessage || \"Compaction summary request failed\",\n\t\t\t\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(attempt),\n\t\t\t\t\t\t\tfailureKind,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn attempt;\n\t\t\t\t},\n\t\t\t\t(error) =>\n\t\t\t\t\tretryEligible &&\n\t\t\t\t\tallowSummarizationRetry(Date.now() - retryStartedMs, attemptBudgetMs) &&\n\t\t\t\t\tisRetryableSummaryAttempt(error),\n\t\t\t\tDEFAULT_SUMMARIZATION_RETRY_POLICY,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) return undefined;\n\t\t\tthrow error;\n\t\t}\n\t\tif (!response) return undefined;\n\n\t\tif (isAssistantMessage(response) && isContextOverflow(response, snapshot.contextWindow)) {\n\t\t\toverflowAttempts++;\n\t\t\tconst elapsedMs = Date.now() - overflowRetryStartMs;\n\t\t\tconst retryMessages = allowOverflowRetry(overflowAttempts, elapsedMs)\n\t\t\t\t? shrinkSummarizationInputForOverflowRetry(messages, snapshot.contextWindow, promptTokens)\n\t\t\t\t: undefined;\n\t\t\tif (!retryMessages) {\n\t\t\t\tthrow new SummarizationOverflowExhaustedError(overflowAttempts, elapsedMs);\n\t\t\t}\n\t\t\tmessages = retryMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"aborted\") {\n\t\t\t// A partial summary from an aborted stream must never be applied.\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"error\") {\n\t\t\t// Surface the real provider failure instead of silently degrading\n\t\t\t// into a generic \"Compaction cancelled\". Preserve the structured\n\t\t\t// truncation class here so downstream recovery never trusts arbitrary\n\t\t\t// thrown error text as authorization for destructive context reduction.\n\t\t\tconst failureKind = summaryRequestFailureKind(response);\n\t\t\tthrow new SummaryRequestError(\n\t\t\t\tresponse.errorMessage || \"Compaction summary request failed\",\n\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(response),\n\t\t\t\tfailureKind,\n\t\t\t);\n\t\t}\n\n\t\tconst summary = getSummaryText(response);\n\t\tif (!summary) {\n\t\t\tconst stopReason = isAssistantMessage(response) ? response.stopReason : \"unknown\";\n\t\t\t// A summarizer can hijack the forwarded agent tools and answer with a\n\t\t\t// bare tool call (observed on openai-codex gpt-5.6-sol, 2026-08-31),\n\t\t\t// which used to surface as a terminal empty-summary failure. Spend one\n\t\t\t// retry with tool calling forbidden; the tools stay in the request\n\t\t\t// because Anthropic rejects tool_use history without the tools param.\n\t\t\tif (stopReason === \"toolUse\" && summarizationToolsOffered && !toolUseRetrySpent) {\n\t\t\t\ttoolUseRetrySpent = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new SummaryGenerationError(\n\t\t\t\t\"empty-summary\",\n\t\t\t\t`summarization response contained no text (stopReason: ${stopReason})`,\n\t\t\t);\n\t\t}\n\n\t\t// Informational only: the core rejects an applied compaction that would\n\t\t// still overflow (_wouldCompactionOverflow). Rejecting here based on the\n\t\t// size of the *discarded* input made large sessions uncompactable.\n\t\tconst tokenEstimate = estimateContextTokens(convertToLlm(messages)).tokens + approxTokens(summary);\n\t\tconst parsedSummary = extractTaskIntent(summary);\n\t\tconst taskIntent = parsedSummary.taskIntent ?? resolveInheritedTaskIntent(snapshot.branchEntries ?? []);\n\n\t\treturn {\n\t\t\tsummary: parsedSummary.summaryText,\n\t\t\tfirstKeptEntryId: snapshot.preparation.firstKeptEntryId,\n\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\tdetails: {\n\t\t\t\tschema: SUMMARY_SCHEMA,\n\t\t\t\tpromptVariant: snapshot.promptVariant,\n\t\t\t\ttokenEstimate,\n\t\t\t\tstructuralYield: computeStructuralYield({\n\t\t\t\t\tpreviousSummary: snapshot.preparation.previousSummary ?? \"\",\n\t\t\t\t\tmessagesToSummarize: snapshot.preparation.messagesToSummarize,\n\t\t\t\t\tturnPrefixMessages: snapshot.preparation.turnPrefixMessages,\n\t\t\t\t\tsummary: parsedSummary.summaryText,\n\t\t\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\t\t}),\n\t\t\t\t...(snapshot.origin ? { origin: snapshot.origin } : {}),\n\t\t\t\t...(taskIntent ? { taskIntent } : {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function applyGeneratedCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tcompaction: CompactionResult | undefined,\n\tsignal?: AbortSignal,\n): Promise<SpeculativeCompactionResult> {\n\tconst provider = context.model?.provider;\n\tif ((provider === \"cursor\" || provider === \"cursor-cli-oauth\") && context.isIdle && !context.isIdle()) {\n\t\treturn { applied: false, reason: \"rejected\" };\n\t}\n\tif (!snapshot || !compaction) return { applied: false, reason: \"unavailable\" };\n\n\tif (snapshot.generation !== getCurrentGeneration()) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\tconst revisionUnchanged = snapshot.expectedRevision === context.getMessageRevision();\n\tconst warmAnchor = createWarmAnchorSnapshot(snapshot.preparation.firstKeptEntryId, snapshot.branchEntries ?? []);\n\tif (\n\t\t!revisionUnchanged &&\n\t\t(!warmAnchor || !isWarmSummaryAnchorValid(warmAnchor, context.sessionManager.getBranch()))\n\t) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\treturn await context.applyCompaction(compaction, {\n\t\treason: \"extension\",\n\t\t...(revisionUnchanged || !warmAnchor\n\t\t\t? { expectedRevision: snapshot.expectedRevision }\n\t\t\t: { expectedWarmAnchor: warmAnchor }),\n\t\tsignal,\n\t});\n}\n\nexport async function applySpeculativeCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tgenerate: () => Promise<CompactionResult | undefined>,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot) return { applied: false, reason: \"unavailable\" };\n\n\tconst compaction = await generate();\n\treturn await applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction);\n}\n"]}
@@ -16,12 +16,18 @@
16
16
  import type { RetryPolicy } from "@earendil-works/pi-ai";
17
17
  export declare const MAX_SUMMARIZATION_ATTEMPT_RETRIES = 3;
18
18
  /**
19
- * Total wall-clock all retried attempts of one summarization may consume.
20
- * Half of a single attempt's 120s budget: room for several fast upstream
19
+ * Total wall-clock all retried attempts of one summarization may consume:
20
+ * half of a single attempt's budget. Room for several fast upstream
21
21
  * rejections, never room to add another full deadline to the turn.
22
22
  */
23
- export declare const SUMMARIZATION_RETRY_TOTAL_BUDGET_MS = 60000;
23
+ export declare function summarizationRetryTotalBudgetMs(attemptBudgetMs: number): number;
24
24
  /** Faster first retry than the provider default: this route blocks the turn. */
25
25
  export declare const DEFAULT_SUMMARIZATION_RETRY_POLICY: RetryPolicy;
26
- export declare function allowSummarizationRetry(elapsedMs: number): boolean;
26
+ /**
27
+ * Whether a retry may start given the wall clock already spent on the current
28
+ * attempt set. The total budget tracks the attempt budget: a large session
29
+ * whose single attempt legitimately spans minutes keeps proportional room to
30
+ * retry, while the invariant "never another full deadline" still holds.
31
+ */
32
+ export declare function allowSummarizationRetry(elapsedMs: number, attemptBudgetMs?: number): boolean;
27
33
  //# sourceMappingURL=summarization-retry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"summarization-retry.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/summarization-retry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEzD,eAAO,MAAM,iCAAiC,IAAI,CAAC;AAEnD;;;;GAIG;AACH,eAAO,MAAM,mCAAmC,QAAS,CAAC;AAE1D,gFAAgF;AAChF,eAAO,MAAM,kCAAkC,EAAE,WAIhD,CAAC;AAEF,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAElE"}
1
+ {"version":3,"file":"summarization-retry.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/summarization-retry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAGzD,eAAO,MAAM,iCAAiC,IAAI,CAAC;AAEnD;;;;GAIG;AACH,wBAAgB,+BAA+B,CAAC,eAAe,EAAE,MAAM,GAAG,MAAM,CAE/E;AAED,gFAAgF;AAChF,eAAO,MAAM,kCAAkC,EAAE,WAIhD,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACtC,SAAS,EAAE,MAAM,EACjB,eAAe,GAAE,MAA8C,GAC7D,OAAO,CAET"}
@@ -1,17 +1,26 @@
1
+ import { DEFAULT_SUMMARIZATION_MAX_DURATION_MS } from "../../../compaction/stream-watchdog.js";
1
2
  export const MAX_SUMMARIZATION_ATTEMPT_RETRIES = 3;
2
3
  /**
3
- * Total wall-clock all retried attempts of one summarization may consume.
4
- * Half of a single attempt's 120s budget: room for several fast upstream
4
+ * Total wall-clock all retried attempts of one summarization may consume:
5
+ * half of a single attempt's budget. Room for several fast upstream
5
6
  * rejections, never room to add another full deadline to the turn.
6
7
  */
7
- export const SUMMARIZATION_RETRY_TOTAL_BUDGET_MS = 60_000;
8
+ export function summarizationRetryTotalBudgetMs(attemptBudgetMs) {
9
+ return attemptBudgetMs / 2;
10
+ }
8
11
  /** Faster first retry than the provider default: this route blocks the turn. */
9
12
  export const DEFAULT_SUMMARIZATION_RETRY_POLICY = {
10
13
  enabled: true,
11
14
  maxRetries: MAX_SUMMARIZATION_ATTEMPT_RETRIES,
12
15
  baseDelayMs: 1_000,
13
16
  };
14
- export function allowSummarizationRetry(elapsedMs) {
15
- return elapsedMs < SUMMARIZATION_RETRY_TOTAL_BUDGET_MS;
17
+ /**
18
+ * Whether a retry may start given the wall clock already spent on the current
19
+ * attempt set. The total budget tracks the attempt budget: a large session
20
+ * whose single attempt legitimately spans minutes keeps proportional room to
21
+ * retry, while the invariant "never another full deadline" still holds.
22
+ */
23
+ export function allowSummarizationRetry(elapsedMs, attemptBudgetMs = DEFAULT_SUMMARIZATION_MAX_DURATION_MS) {
24
+ return elapsedMs < summarizationRetryTotalBudgetMs(attemptBudgetMs);
16
25
  }
17
26
  //# sourceMappingURL=summarization-retry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"summarization-retry.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/summarization-retry.ts"],"names":[],"mappings":"AAiBA,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAC,CAAC;AAEnD;;;;GAIG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAE1D,gFAAgF;AAChF,MAAM,CAAC,MAAM,kCAAkC,GAAgB;IAC9D,OAAO,EAAE,IAAI;IACb,UAAU,EAAE,iCAAiC;IAC7C,WAAW,EAAE,KAAK;CAClB,CAAC;AAEF,MAAM,UAAU,uBAAuB,CAAC,SAAiB;IACxD,OAAO,SAAS,GAAG,mCAAmC,CAAC;AACxD,CAAC","sourcesContent":["/**\n * Bounded retry policy for one extension-route summarization request.\n *\n * The core `compact()` route retries summarization through\n * `completeSummarization` (`core/compaction/compaction.ts`) with\n * `SettingsManager.getRetrySettings()`; the extension route had no retry, so a\n * transient 5xx ended the compaction on attempt one (observed 2026-08-12:\n * `500 Worker exceeded memory limit.`, `willRetry:false`, 28ms round trip).\n *\n * Retries are bounded by ELAPSED TIME as well as attempts. One attempt may hold\n * the session for `DEFAULT_SUMMARIZATION_MAX_DURATION_MS` (120s), so replaying a\n * slow failure would stack deadlines back to back - the freeze the wall-clock\n * budget exists to prevent. A fast upstream rejection leaves budget and is\n * retried; a failure that already burned the budget degrades as before.\n */\nimport type { RetryPolicy } from \"@earendil-works/pi-ai\";\n\nexport const MAX_SUMMARIZATION_ATTEMPT_RETRIES = 3;\n\n/**\n * Total wall-clock all retried attempts of one summarization may consume.\n * Half of a single attempt's 120s budget: room for several fast upstream\n * rejections, never room to add another full deadline to the turn.\n */\nexport const SUMMARIZATION_RETRY_TOTAL_BUDGET_MS = 60_000;\n\n/** Faster first retry than the provider default: this route blocks the turn. */\nexport const DEFAULT_SUMMARIZATION_RETRY_POLICY: RetryPolicy = {\n\tenabled: true,\n\tmaxRetries: MAX_SUMMARIZATION_ATTEMPT_RETRIES,\n\tbaseDelayMs: 1_000,\n};\n\nexport function allowSummarizationRetry(elapsedMs: number): boolean {\n\treturn elapsedMs < SUMMARIZATION_RETRY_TOTAL_BUDGET_MS;\n}\n"]}
1
+ {"version":3,"file":"summarization-retry.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/summarization-retry.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,qCAAqC,EAAE,MAAM,wCAAwC,CAAC;AAE/F,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAC,CAAC;AAEnD;;;;GAIG;AACH,MAAM,UAAU,+BAA+B,CAAC,eAAuB;IACtE,OAAO,eAAe,GAAG,CAAC,CAAC;AAC5B,CAAC;AAED,gFAAgF;AAChF,MAAM,CAAC,MAAM,kCAAkC,GAAgB;IAC9D,OAAO,EAAE,IAAI;IACb,UAAU,EAAE,iCAAiC;IAC7C,WAAW,EAAE,KAAK;CAClB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CACtC,SAAiB,EACjB,kBAA0B,qCAAqC;IAE/D,OAAO,SAAS,GAAG,+BAA+B,CAAC,eAAe,CAAC,CAAC;AACrE,CAAC","sourcesContent":["/**\n * Bounded retry policy for one extension-route summarization request.\n *\n * The core `compact()` route retries summarization through\n * `completeSummarization` (`core/compaction/compaction.ts`) with\n * `SettingsManager.getRetrySettings()`; the extension route had no retry, so a\n * transient 5xx ended the compaction on attempt one (observed 2026-08-12:\n * `500 Worker exceeded memory limit.`, `willRetry:false`, 28ms round trip).\n *\n * Retries are bounded by ELAPSED TIME as well as attempts. One attempt may hold\n * the session for `DEFAULT_SUMMARIZATION_MAX_DURATION_MS` (120s), so replaying a\n * slow failure would stack deadlines back to back - the freeze the wall-clock\n * budget exists to prevent. A fast upstream rejection leaves budget and is\n * retried; a failure that already burned the budget degrades as before.\n */\nimport type { RetryPolicy } from \"@earendil-works/pi-ai\";\nimport { DEFAULT_SUMMARIZATION_MAX_DURATION_MS } from \"../../../compaction/stream-watchdog.ts\";\n\nexport const MAX_SUMMARIZATION_ATTEMPT_RETRIES = 3;\n\n/**\n * Total wall-clock all retried attempts of one summarization may consume:\n * half of a single attempt's budget. Room for several fast upstream\n * rejections, never room to add another full deadline to the turn.\n */\nexport function summarizationRetryTotalBudgetMs(attemptBudgetMs: number): number {\n\treturn attemptBudgetMs / 2;\n}\n\n/** Faster first retry than the provider default: this route blocks the turn. */\nexport const DEFAULT_SUMMARIZATION_RETRY_POLICY: RetryPolicy = {\n\tenabled: true,\n\tmaxRetries: MAX_SUMMARIZATION_ATTEMPT_RETRIES,\n\tbaseDelayMs: 1_000,\n};\n\n/**\n * Whether a retry may start given the wall clock already spent on the current\n * attempt set. The total budget tracks the attempt budget: a large session\n * whose single attempt legitimately spans minutes keeps proportional room to\n * retry, while the invariant \"never another full deadline\" still holds.\n */\nexport function allowSummarizationRetry(\n\telapsedMs: number,\n\tattemptBudgetMs: number = DEFAULT_SUMMARIZATION_MAX_DURATION_MS,\n): boolean {\n\treturn elapsedMs < summarizationRetryTotalBudgetMs(attemptBudgetMs);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-end-continuation.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/agent-end-continuation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AAE9E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,UAAU,mBAAmB;IAC5B,QAAQ,CAAC,GAAG,EAAE,gBAAgB,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;CAC3B;AAED,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,mBAAmB,GAC1B,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAoBtB"}
1
+ {"version":3,"file":"agent-end-continuation.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/agent-end-continuation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEtE,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AAE9E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,UAAU,mBAAmB;IAC5B,QAAQ,CAAC,GAAG,EAAE,gBAAgB,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;CAC3B;AAED,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,mBAAmB,GAC1B,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CA8BtB"}
@@ -1,3 +1,4 @@
1
+ import { isMalformedToolUseTurn } from "./continuation.js";
1
2
  import { didTerminalProviderErrorEndTurn } from "./terminal-provider-error.js";
2
3
  export async function continueGoalAfterAgentEnd(monitor, options) {
3
4
  if (options.event.aborted === true && options.event.abortSource === "system") {
@@ -9,6 +10,16 @@ export async function continueGoalAfterAgentEnd(monitor, options) {
9
10
  willRetry: options.event.willRetry === true,
10
11
  });
11
12
  }
13
+ const lastAssistant = [...options.event.messages].reverse().find((message) => message.role === "assistant");
14
+ if (lastAssistant?.role === "assistant" && isMalformedToolUseTurn(lastAssistant)) {
15
+ return monitor.afterProviderFailure({
16
+ ctx: options.ctx,
17
+ event: options.event,
18
+ goal: options.goal,
19
+ messages: options.event.messages,
20
+ willRetry: options.event.willRetry === true,
21
+ });
22
+ }
12
23
  if (didTerminalProviderErrorEndTurn(options.event)) {
13
24
  return monitor.afterProviderFailure({
14
25
  ctx: options.ctx,
@@ -1 +1 @@
1
- {"version":3,"file":"agent-end-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/agent-end-continuation.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAS/E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAqC,EACrC,OAA4B;IAE5B,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAC9E,OAAO,OAAO,CAAC,gBAAgB,CAAC;YAC/B,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,QAAQ,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ;YAChC,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS,KAAK,IAAI;SAC3C,CAAC,CAAC;IACJ,CAAC;IACD,IAAI,+BAA+B,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACpD,OAAO,OAAO,CAAC,oBAAoB,CAAC;YACnC,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,QAAQ,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ;YAChC,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS,KAAK,IAAI;SAC3C,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC1G,CAAC","sourcesContent":["import type { AgentEndEvent, ExtensionContext } from \"../../types.ts\";\nimport type { MonitorAwareGoalContinuation } from \"./monitor-continuation.ts\";\nimport { didTerminalProviderErrorEndTurn } from \"./terminal-provider-error.ts\";\nimport type { Goal } from \"./types.ts\";\n\ninterface GoalAgentEndOptions {\n\treadonly ctx: ExtensionContext;\n\treadonly event: AgentEndEvent;\n\treadonly goal: Goal | null;\n}\n\nexport async function continueGoalAfterAgentEnd(\n\tmonitor: MonitorAwareGoalContinuation,\n\toptions: GoalAgentEndOptions,\n): Promise<Goal | null> {\n\tif (options.event.aborted === true && options.event.abortSource === \"system\") {\n\t\treturn monitor.afterSystemAbort({\n\t\t\tctx: options.ctx,\n\t\t\tevent: options.event,\n\t\t\tgoal: options.goal,\n\t\t\tmessages: options.event.messages,\n\t\t\twillRetry: options.event.willRetry === true,\n\t\t});\n\t}\n\tif (didTerminalProviderErrorEndTurn(options.event)) {\n\t\treturn monitor.afterProviderFailure({\n\t\t\tctx: options.ctx,\n\t\t\tevent: options.event,\n\t\t\tgoal: options.goal,\n\t\t\tmessages: options.event.messages,\n\t\t\twillRetry: options.event.willRetry === true,\n\t\t});\n\t}\n\treturn monitor.afterAgentEnd({ ctx: options.ctx, goal: options.goal, messages: options.event.messages });\n}\n"]}
1
+ {"version":3,"file":"agent-end-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/agent-end-continuation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAE3D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAS/E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAqC,EACrC,OAA4B;IAE5B,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAC9E,OAAO,OAAO,CAAC,gBAAgB,CAAC;YAC/B,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,QAAQ,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ;YAChC,SAAS,EAAE,OAAO,CAAC,K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ation.ts\";\nimport type { MonitorAwareGoalContinuation } from \"./monitor-continuation.ts\";\nimport { didTerminalProviderErrorEndTurn } from \"./terminal-provider-error.ts\";\nimport type { Goal } from \"./types.ts\";\n\ninterface GoalAgentEndOptions {\n\treadonly ctx: ExtensionContext;\n\treadonly event: AgentEndEvent;\n\treadonly goal: Goal | null;\n}\n\nexport async function continueGoalAfterAgentEnd(\n\tmonitor: MonitorAwareGoalContinuation,\n\toptions: GoalAgentEndOptions,\n): Promise<Goal | null> {\n\tif (options.event.aborted === true && options.event.abortSource === \"system\") {\n\t\treturn monitor.afterSystemAbort({\n\t\t\tctx: options.ctx,\n\t\t\tevent: options.event,\n\t\t\tgoal: options.goal,\n\t\t\tmessages: options.event.messages,\n\t\t\twillRetry: options.event.willRetry === true,\n\t\t});\n\t}\n\tconst lastAssistant = [...options.event.messages].reverse().find((message) => message.role === \"assistant\");\n\tif (lastAssistant?.role === \"assistant\" && isMalformedToolUseTurn(lastAssistant)) {\n\t\treturn monitor.afterProviderFailure({\n\t\t\tctx: options.ctx,\n\t\t\tevent: options.event,\n\t\t\tgoal: options.goal,\n\t\t\tmessages: options.event.messages,\n\t\t\twillRetry: options.event.willRetry === true,\n\t\t});\n\t}\n\tif (didTerminalProviderErrorEndTurn(options.event)) {\n\t\treturn monitor.afterProviderFailure({\n\t\t\tctx: options.ctx,\n\t\t\tevent: options.event,\n\t\t\tgoal: options.goal,\n\t\t\tmessages: options.event.messages,\n\t\t\twillRetry: options.event.willRetry === true,\n\t\t});\n\t}\n\treturn monitor.afterAgentEnd({ ctx: options.ctx, goal: options.goal, messages: options.event.messages });\n}\n"]}
@@ -29,13 +29,15 @@ function validIteration(value) {
29
29
  function whyLine(data) {
30
30
  switch (data.phase) {
31
31
  case "scheduled": {
32
- const expected = `Continuation expected ${formatExpectedWake(data.dueAtMs, data.delayMs)}`;
32
+ // The wait is not a cache-warm timer: it lets the live wake sources
33
+ // deliver, and the timed wake is only the stall backstop.
34
+ const backstop = `Stall backstop ${formatExpectedWake(data.dueAtMs, data.delayMs)}`;
33
35
  if (data.cache?.ttlSeconds === undefined) {
34
- return `${expected} - the monitor wakes the goal the moment decisive output lands.`;
36
+ return `${backstop} - the goal resumes as soon as a wake source delivers.`;
35
37
  }
36
38
  return data.delayMs < data.cache.ttlSeconds * 1000
37
- ? `${expected} - the timed wake stays inside the ${formatCacheTtl(data.cache.ttlSeconds)} prompt-cache TTL.`
38
- : `${expected} - the prompt-cache TTL may elapse before the timed wake.`;
39
+ ? `${backstop} - the goal resumes as soon as a wake source delivers, inside the ${formatCacheTtl(data.cache.ttlSeconds)} prompt-cache TTL.`
40
+ : `${backstop} - the goal resumes as soon as a wake source delivers; the ${formatCacheTtl(data.cache.ttlSeconds)} prompt-cache TTL may elapse first.`;
39
41
  }
40
42
  case "resumed":
41
43
  return "Woke on schedule to keep pursuing the goal.";