@code-yeongyu/senpi 2026.9.5 → 2026.9.7-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 (307) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/dist/core/agent-session.d.ts +60 -5
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +262 -78
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/compaction/compaction.d.ts +6 -2
  7. package/dist/core/compaction/compaction.d.ts.map +1 -1
  8. package/dist/core/compaction/compaction.js +6 -1
  9. package/dist/core/compaction/compaction.js.map +1 -1
  10. package/dist/core/compaction/stuck-overflow.d.ts +11 -0
  11. package/dist/core/compaction/stuck-overflow.d.ts.map +1 -0
  12. package/dist/core/compaction/stuck-overflow.js +17 -0
  13. package/dist/core/compaction/stuck-overflow.js.map +1 -0
  14. package/dist/core/extensions/builtin/cache-keepalive/index.d.ts.map +1 -1
  15. package/dist/core/extensions/builtin/cache-keepalive/index.js +3 -21
  16. package/dist/core/extensions/builtin/cache-keepalive/index.js.map +1 -1
  17. package/dist/core/extensions/builtin/claude-sdk-oauth/prompt-bridge.d.ts.map +1 -1
  18. package/dist/core/extensions/builtin/claude-sdk-oauth/prompt-bridge.js +2 -0
  19. package/dist/core/extensions/builtin/claude-sdk-oauth/prompt-bridge.js.map +1 -1
  20. package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.d.ts.map +1 -1
  21. package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js +36 -19
  22. package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js.map +1 -1
  23. package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.d.ts.map +1 -1
  24. package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.js +21 -10
  25. package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.js.map +1 -1
  26. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts +4 -17
  27. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts.map +1 -1
  28. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js +23 -33
  29. package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js.map +1 -1
  30. package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-pump.d.ts.map +1 -1
  31. package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-pump.js +15 -2
  32. package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-pump.js.map +1 -1
  33. package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.d.ts.map +1 -1
  34. package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js +1 -0
  35. package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js.map +1 -1
  36. package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.d.ts.map +1 -1
  37. package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js +5 -3
  38. package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js.map +1 -1
  39. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.d.ts.map +1 -1
  40. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.js +8 -3
  41. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.js.map +1 -1
  42. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.d.ts +1 -1
  43. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.d.ts.map +1 -1
  44. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.js +2 -3
  45. package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.js.map +1 -1
  46. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.d.ts +6 -5
  47. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.d.ts.map +1 -1
  48. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.js +6 -5
  49. package/dist/core/extensions/builtin/claude-sdk-oauth/tools.js.map +1 -1
  50. package/dist/core/extensions/builtin/compaction/circuit-breaker.d.ts +8 -0
  51. package/dist/core/extensions/builtin/compaction/circuit-breaker.d.ts.map +1 -1
  52. package/dist/core/extensions/builtin/compaction/circuit-breaker.js +8 -0
  53. package/dist/core/extensions/builtin/compaction/circuit-breaker.js.map +1 -1
  54. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +4 -0
  55. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
  56. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +40 -20
  57. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
  58. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.d.ts +18 -0
  59. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.d.ts.map +1 -0
  60. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.js +20 -0
  61. package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.js.map +1 -0
  62. package/dist/core/extensions/builtin/compaction/index.js +2 -2
  63. package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
  64. package/dist/core/extensions/builtin/compaction/lane-policy.d.ts +12 -0
  65. package/dist/core/extensions/builtin/compaction/lane-policy.d.ts.map +1 -1
  66. package/dist/core/extensions/builtin/compaction/lane-policy.js +47 -18
  67. package/dist/core/extensions/builtin/compaction/lane-policy.js.map +1 -1
  68. package/dist/core/extensions/builtin/compaction/openai-remote-convert.d.ts.map +1 -1
  69. package/dist/core/extensions/builtin/compaction/openai-remote-convert.js +2 -0
  70. package/dist/core/extensions/builtin/compaction/openai-remote-convert.js.map +1 -1
  71. package/dist/core/extensions/builtin/compaction/retained-message-safety.d.ts.map +1 -1
  72. package/dist/core/extensions/builtin/compaction/retained-message-safety.js +14 -1
  73. package/dist/core/extensions/builtin/compaction/retained-message-safety.js.map +1 -1
  74. package/dist/core/extensions/builtin/goal/cache-warm-renderer.js +6 -4
  75. package/dist/core/extensions/builtin/goal/cache-warm-renderer.js.map +1 -1
  76. package/dist/core/extensions/builtin/goal/cache-warm.d.ts +19 -1
  77. package/dist/core/extensions/builtin/goal/cache-warm.d.ts.map +1 -1
  78. package/dist/core/extensions/builtin/goal/cache-warm.js +23 -10
  79. package/dist/core/extensions/builtin/goal/cache-warm.js.map +1 -1
  80. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts +1 -0
  81. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts.map +1 -1
  82. package/dist/core/extensions/builtin/goal/continuation-recovery.js +2 -0
  83. package/dist/core/extensions/builtin/goal/continuation-recovery.js.map +1 -1
  84. package/dist/core/extensions/builtin/goal/continuation.d.ts +3 -1
  85. package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
  86. package/dist/core/extensions/builtin/goal/continuation.js +4 -0
  87. package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
  88. package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts +3 -0
  89. package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts.map +1 -1
  90. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +14 -3
  91. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js.map +1 -1
  92. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts +1 -1
  93. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  94. package/dist/core/extensions/builtin/goal/monitor-continuation.js +7 -3
  95. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  96. package/dist/core/extensions/builtin/hooks/plugin-manifest.js +2 -2
  97. package/dist/core/extensions/builtin/hooks/plugin-manifest.js.map +1 -1
  98. package/dist/core/extensions/builtin/hooks/safety.js +2 -2
  99. package/dist/core/extensions/builtin/hooks/safety.js.map +1 -1
  100. package/dist/core/extensions/builtin/permission-system/external-dir.d.ts.map +1 -1
  101. package/dist/core/extensions/builtin/permission-system/external-dir.js +5 -22
  102. package/dist/core/extensions/builtin/permission-system/external-dir.js.map +1 -1
  103. package/dist/core/extensions/builtin/permission-system/parsers.d.ts.map +1 -1
  104. package/dist/core/extensions/builtin/permission-system/parsers.js +5 -7
  105. package/dist/core/extensions/builtin/permission-system/parsers.js.map +1 -1
  106. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts +2 -2
  107. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts.map +1 -1
  108. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +8 -2
  109. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js.map +1 -1
  110. package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts.map +1 -1
  111. package/dist/core/extensions/builtin/terminal/monitor-registry.js +14 -7
  112. package/dist/core/extensions/builtin/terminal/monitor-registry.js.map +1 -1
  113. package/dist/core/messages.d.ts +7 -0
  114. package/dist/core/messages.d.ts.map +1 -1
  115. package/dist/core/messages.js +2 -0
  116. package/dist/core/messages.js.map +1 -1
  117. package/dist/core/package-identity.d.ts +12 -0
  118. package/dist/core/package-identity.d.ts.map +1 -0
  119. package/dist/core/package-identity.js +57 -0
  120. package/dist/core/package-identity.js.map +1 -0
  121. package/dist/core/resource-loader.d.ts +0 -2
  122. package/dist/core/resource-loader.d.ts.map +1 -1
  123. package/dist/core/resource-loader.js +8 -60
  124. package/dist/core/resource-loader.js.map +1 -1
  125. package/dist/core/retry-fallback/controller.d.ts.map +1 -1
  126. package/dist/core/retry-fallback/controller.js +5 -4
  127. package/dist/core/retry-fallback/controller.js.map +1 -1
  128. package/dist/core/sdk.d.ts.map +1 -1
  129. package/dist/core/sdk.js +5 -0
  130. package/dist/core/sdk.js.map +1 -1
  131. package/dist/core/session-manager.d.ts +12 -1
  132. package/dist/core/session-manager.d.ts.map +1 -1
  133. package/dist/core/session-manager.js +29 -3
  134. package/dist/core/session-manager.js.map +1 -1
  135. package/dist/core/settings-manager.d.ts +6 -2
  136. package/dist/core/settings-manager.d.ts.map +1 -1
  137. package/dist/core/settings-manager.js +4 -1
  138. package/dist/core/settings-manager.js.map +1 -1
  139. package/dist/core/tools/bounded-realpath.d.ts +28 -0
  140. package/dist/core/tools/bounded-realpath.d.ts.map +1 -0
  141. package/dist/core/tools/bounded-realpath.js +53 -0
  142. package/dist/core/tools/bounded-realpath.js.map +1 -0
  143. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  144. package/dist/core/tools/file-mutation-queue.js +15 -13
  145. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  146. package/dist/core/tools/filesystem-policy.d.ts +7 -0
  147. package/dist/core/tools/filesystem-policy.d.ts.map +1 -1
  148. package/dist/core/tools/filesystem-policy.js +25 -15
  149. package/dist/core/tools/filesystem-policy.js.map +1 -1
  150. package/dist/core/trust-manager.d.ts.map +1 -1
  151. package/dist/core/trust-manager.js +13 -2
  152. package/dist/core/trust-manager.js.map +1 -1
  153. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  154. package/dist/modes/interactive/interactive-mode.js +5 -1
  155. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  156. package/dist/modes/interactive/tips/catalog/memory-tips.d.ts.map +1 -1
  157. package/dist/modes/interactive/tips/catalog/memory-tips.js +6 -0
  158. package/dist/modes/interactive/tips/catalog/memory-tips.js.map +1 -1
  159. package/dist/modes/interactive/tips/catalog/subagent-tips.d.ts.map +1 -1
  160. package/dist/modes/interactive/tips/catalog/subagent-tips.js +6 -0
  161. package/dist/modes/interactive/tips/catalog/subagent-tips.js.map +1 -1
  162. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  163. package/dist/modes/rpc/host-lifecycle.js +31 -5
  164. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  165. package/dist/modes/rpc/host-watchdog.d.ts +11 -0
  166. package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
  167. package/dist/modes/rpc/host-watchdog.js +16 -2
  168. package/dist/modes/rpc/host-watchdog.js.map +1 -1
  169. package/dist/modes/rpc/multi-session-host.d.ts +3 -7
  170. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  171. package/dist/modes/rpc/multi-session-host.js +57 -29
  172. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  173. package/dist/modes/rpc/rpc-types.d.ts +1 -2
  174. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  175. package/dist/modes/rpc/rpc-types.js +0 -1
  176. package/dist/modes/rpc/rpc-types.js.map +1 -1
  177. package/dist/modes/rpc/session-registry.d.ts +1 -4
  178. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  179. package/dist/modes/rpc/session-registry.js +0 -15
  180. package/dist/modes/rpc/session-registry.js.map +1 -1
  181. package/dist/modes/rpc/socket-ownership.d.ts +46 -0
  182. package/dist/modes/rpc/socket-ownership.d.ts.map +1 -0
  183. package/dist/modes/rpc/socket-ownership.js +178 -0
  184. package/dist/modes/rpc/socket-ownership.js.map +1 -0
  185. package/dist/utils/fs-watch.d.ts +17 -0
  186. package/dist/utils/fs-watch.d.ts.map +1 -1
  187. package/dist/utils/fs-watch.js +38 -10
  188. package/dist/utils/fs-watch.js.map +1 -1
  189. package/dist/utils/paths.d.ts +33 -0
  190. package/dist/utils/paths.d.ts.map +1 -1
  191. package/dist/utils/paths.js +109 -3
  192. package/dist/utils/paths.js.map +1 -1
  193. package/docs/compaction-guide.md +2 -2
  194. package/docs/compaction.md +2 -2
  195. package/docs/development.md +3 -2
  196. package/docs/providers.md +1 -1
  197. package/docs/rpc.md +6 -7
  198. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +74 -0
  199. package/node_modules/@code-yeongyu/senpi-codemode/README.md +34 -5
  200. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  201. package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/protocol.ts +1 -0
  202. package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/reserved.ts +2 -0
  203. package/node_modules/@code-yeongyu/senpi-codemode/src/extension/runtime-factory.ts +3 -0
  204. package/node_modules/@code-yeongyu/senpi-codemode/src/extension/session-manager.ts +7 -0
  205. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/AGENTS.md +7 -0
  206. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/jl/kernel.ts +6 -2
  207. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +73 -129
  208. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/inline-worker.ts +2 -2
  209. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/interrupt-bounds.ts +66 -0
  210. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-contract.ts +3 -0
  211. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/run-queue.ts +18 -3
  212. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-core.js +59 -0
  213. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +10 -6
  214. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-runtime.js +16 -0
  215. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-shell-capture.d.ts +25 -0
  216. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-shell-capture.js +70 -8
  217. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-slot.ts +106 -0
  218. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-startup.ts +70 -0
  219. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel-contract.ts +3 -0
  220. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/transport.ts +11 -3
  221. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/rb/kernel.ts +6 -2
  222. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/session-env.ts +56 -0
  223. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/runtime-asset.ts +40 -14
  224. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-contract.ts +3 -0
  225. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-kernel.ts +9 -1
  226. package/node_modules/@code-yeongyu/senpi-codemode/src/output/output-meta.ts +26 -2
  227. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +10 -5
  228. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-execution.ts +9 -11
  229. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-contract.ts +45 -0
  230. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +43 -71
  231. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-notification.ts +4 -5
  232. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-snapshot.ts +2 -0
  233. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-status.ts +30 -0
  234. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +1 -0
  235. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-notification-queue.ts +2 -2
  236. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/image.ts +12 -3
  237. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/interrupt-note.ts +29 -15
  238. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/types.ts +2 -0
  239. package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts.map +1 -1
  240. package/node_modules/@earendil-works/pi-agent-core/dist/agent.js +3 -1
  241. package/node_modules/@earendil-works/pi-agent-core/dist/agent.js.map +1 -1
  242. package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.d.ts.map +1 -1
  243. package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +17 -0
  244. package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js.map +1 -1
  245. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
  246. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +1 -0
  247. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js.map +1 -1
  248. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.d.ts.map +1 -1
  249. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +1 -0
  250. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js.map +1 -1
  251. package/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.d.ts.map +1 -1
  252. package/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +6 -0
  253. package/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js.map +1 -1
  254. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.d.ts +2 -1
  255. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.d.ts.map +1 -1
  256. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +5 -1
  257. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js.map +1 -1
  258. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.d.ts.map +1 -1
  259. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +1 -0
  260. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js.map +1 -1
  261. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.d.ts +7 -1
  262. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.d.ts.map +1 -1
  263. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js.map +1 -1
  264. package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +2 -0
  265. package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts.map +1 -1
  266. package/node_modules/@earendil-works/pi-agent-core/dist/types.js.map +1 -1
  267. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  268. package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +2 -0
  269. package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js.map +1 -1
  270. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.d.ts.map +1 -1
  271. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +15 -0
  272. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js.map +1 -1
  273. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +4 -4
  274. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  275. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  276. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  277. package/node_modules/@earendil-works/pi-ai/dist/providers/data/azure-openai-responses.json +1 -1
  278. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cerebras.json +1 -1
  279. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  280. package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  281. package/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai-cn.json +1 -1
  282. package/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai.json +1 -1
  283. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  284. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  285. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  286. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  287. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  288. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  289. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  290. package/node_modules/@earendil-works/pi-ai/dist/providers/faux.d.ts.map +1 -1
  291. package/node_modules/@earendil-works/pi-ai/dist/providers/faux.js +2 -0
  292. package/node_modules/@earendil-works/pi-ai/dist/providers/faux.js.map +1 -1
  293. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +8 -1
  294. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  295. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  296. package/node_modules/@earendil-works/pi-ai/dist/utils/estimate.d.ts.map +1 -1
  297. package/node_modules/@earendil-works/pi-ai/dist/utils/estimate.js +2 -0
  298. package/node_modules/@earendil-works/pi-ai/dist/utils/estimate.js.map +1 -1
  299. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
  300. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
  301. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +14 -3
  302. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
  303. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  304. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  305. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  306. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  307. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"openai-remote-convert.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/openai-remote-convert.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAqB,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC/F,OAAO,EACN,gCAAgC,EAChC,QAAQ,GAMR,MAAM,2BAA2B,CAAC;AAUnC,OAAO,EACN,gCAAgC,EAChC,6BAA6B,EAC7B,kCAAkC,EAClC,QAAQ,EACR,0BAA0B,EAC1B,kCAAkC,EAClC,+BAA+B,GAC/B,MAAM,2BAA2B,CAAC;AAEnC,SAAS,eAAe,CAAC,KAAyB;IACjD,IAAI,CAAC,KAAK,EAAE,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9C,IAAI,CAAC;QACJ,MAAM,MAAM,GAA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AC;YACrD,KAAK,CAAC,IAAI,CAAC,GAAG,iBAAiB,CAAC,OAAO,EAAE,YAAY,EAAE,KAAK,CAAC,CAAC,CAAC;YAC/D,YAAY,EAAE,CAAC;QAChB,CAAC;QACD,eAAe,GAAG,EAAE,CAAC;IACtB,CAAC,CAAC;IACF,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YACjC,MAAM,OAAO,GAAG,gCAAgC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,IAAI,OAAO,EAAE,CAAC;gBACb,KAAK,EAAE,CAAC;gBACR,KAAK,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;gBACxC,SAAS;YACV,CAAC;QACF,CAAC;QACD,eAAe,CAAC,IAAI,CAAC,GAAG,6BAA6B,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/D,CAAC;IACD,KAAK,EAAE,CAAC;IACR,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"@earendil-works/pi-ai\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport { type SessionEntry, sessionEntryToContextMessages } from \"../../../session-manager.ts\";\nimport {\n\tgetOpenAiRemoteCompactionDetails,\n\tisRecord,\n\ttype OpenAiAssistantMessageItem,\n\ttype OpenAiFunctionCallItem,\n\ttype OpenAiInputContent,\n\ttype OpenAiProviderNativeItem,\n\ttype OpenAiRemoteInputItem,\n} from \"./openai-remote-schema.ts\";\n\nexport type {\n\tOpenAiCompactBody,\n\tOpenAiContextCompactionItem,\n\tOpenAiContextCompactionTriggerItem,\n\tOpenAiRemoteCompactionDetails,\n\tOpenAiRemoteInputItem,\n\tOpenAiRemoteTransport,\n} from \"./openai-remote-schema.ts\";\nexport {\n\tgetOpenAiRemoteCompactionDetails,\n\tisOpenAiContextCompactionItem,\n\tisOpenAiRemoteCompactionOutputItem,\n\tisRecord,\n\tisRetainedRemoteOutputItem,\n\tisRetainedResponsesStreamInputItem,\n\tOPENAI_REMOTE_COMPACTION_SCHEMA,\n} from \"./openai-remote-schema.ts\";\n\nfunction parseJsonRecord(value: string | undefined): Record<string, unknown> | undefined {\n\tif (!value?.startsWith(\"{\")) return undefined;\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\treturn isRecord(parsed) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: \"commentary\" | \"final_answer\" } | undefined {\n\tif (!signature) return undefined;\n\tconst parsed = parseJsonRecord(signature);\n\tif (parsed?.v === 1 && typeof parsed.id === \"string\") {\n\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t}\n\t\treturn { id: parsed.id };\n\t}\n\treturn { id: signature };\n}\n\nfunction convertUserContent(content: string | (TextContent | ImageContent)[]): OpenAiInputContent[] {\n\tif (typeof content === \"string\") return [{ type: \"input_text\", text: content }];\n\treturn content.map((block): OpenAiInputContent => {\n\t\tif (block.type === \"text\") return { type: \"input_text\", text: block.text };\n\t\treturn {\n\t\t\ttype: \"input_image\",\n\t\t\tdetail: \"auto\",\n\t\t\timage_url: `data:${block.mimeType};base64,${block.data}`,\n\t\t};\n\t});\n}\n\nexport function providerNativeItem(raw: unknown): OpenAiProviderNativeItem | undefined {\n\tif (!isRecord(raw) || typeof raw.type !== \"string\") return undefined;\n\treturn { ...raw, type: raw.type };\n}\n\nfunction convertThinking(block: { thinkingSignature?: string }): OpenAiProviderNativeItem | undefined {\n\tconst parsed = parseJsonRecord(block.thinkingSignature);\n\tif (parsed?.type !== \"reasoning\") return undefined;\n\treturn { ...parsed, type: \"reasoning\" };\n}\n\nfunction convertTextBlock(block: TextContent, messageIndex: number): OpenAiAssistantMessageItem {\n\tconst signature = parseTextSignature(block.textSignature);\n\tconst item = {\n\t\ttype: \"message\",\n\t\trole: \"assistant\",\n\t\tstatus: \"completed\",\n\t\tid: signature?.id ?? `msg_${messageIndex}`,\n\t\tcontent: [{ type: \"output_text\", text: block.text, annotations: [] }],\n\t\t...(signature?.phase ? { phase: signature.phase } : {}),\n\t} satisfies OpenAiAssistantMessageItem;\n\treturn item;\n}\n\nfunction convertToolCall(block: ToolCall): OpenAiFunctionCallItem {\n\tconst [callId = block.id, itemId] = block.id.split(\"|\");\n\treturn {\n\t\ttype: \"function_call\",\n\t\t// The Responses API rejects item ids not beginning with \"fc\"; custom tool\n\t\t// calls carry the \"<call_id>|custom\" sentinel, not a server-issued id.\n\t\t...(itemId?.startsWith(\"fc\") ? { id: itemId } : {}),\n\t\tcall_id: callId,\n\t\tname: block.name,\n\t\targuments: JSON.stringify(block.arguments ?? {}),\n\t};\n}\n\n/**\n * Convert any assistant message — OpenAI Responses-native or foreign — into\n * replayable input items. Native text/reasoning/tool-call items are preserved\n * verbatim; blocks that have no OpenAI Responses representation (foreign\n * thinking, unknown provider-native payloads) are skipped, mirroring what the\n * provider would have received for that message in a normal turn.\n */\nfunction convertAssistantMessage(message: AssistantMessage, messageIndex: number): OpenAiRemoteInputItem[] {\n\tconst items: OpenAiRemoteInputItem[] = [];\n\tfor (const block of message.content) {\n\t\tswitch (block.type) {\n\t\t\tcase \"text\":\n\t\t\t\titems.push(convertTextBlock(block, messageIndex));\n\t\t\t\tbreak;\n\t\t\tcase \"thinking\": {\n\t\t\t\tconst reasoning = convertThinking(block);\n\t\t\t\tif (reasoning) items.push(reasoning);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolCall\":\n\t\t\t\titems.push(convertToolCall(block));\n\t\t\t\tbreak;\n\t\t\tcase \"providerNative\": {\n\t\t\t\tconst item = providerNativeItem(block.raw);\n\t\t\t\tif (item) items.push(item);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn items;\n}\n\n/**\n * Convert a tool result into a function_call_output item, mirroring the\n * Responses API payload builder: image results stay structured for\n * image-capable models and degrade to a text placeholder otherwise.\n */\nfunction convertToolResultMessage(message: ToolResultMessage, model: Model<Api>): OpenAiRemoteInputItem[] {\n\tconst [callId = message.toolCallId] = message.toolCallId.split(\"|\");\n\tconst text = message.content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tconst images = message.content.filter((block): block is ImageContent => block.type === \"image\");\n\tlet output: string | OpenAiInputContent[];\n\tif (images.length > 0 && model.input.includes(\"image\")) {\n\t\tconst parts: OpenAiInputContent[] = [];\n\t\tif (text.length > 0) parts.push({ type: \"input_text\", text });\n\t\tfor (const image of images) {\n\t\t\tparts.push({\n\t\t\t\ttype: \"input_image\",\n\t\t\t\tdetail: \"auto\",\n\t\t\t\timage_url: `data:${image.mimeType};base64,${image.data}`,\n\t\t\t});\n\t\t}\n\t\toutput = parts.length > 0 ? parts : \"(no tool output)\";\n\t} else {\n\t\toutput = text.length > 0 ? text : images.length > 0 ? \"(see attached image)\" : \"(no tool output)\";\n\t}\n\treturn [{ type: \"function_call_output\", call_id: callId, output }];\n}\n\nfunction convertLlmMessage(message: Message, messageIndex: number, model: Model<Api>): OpenAiRemoteInputItem[] {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn [{ role: \"user\", content: convertUserContent(message.content) }];\n\t\tcase \"assistant\":\n\t\t\treturn convertAssistantMessage(message, messageIndex);\n\t\tcase \"toolResult\":\n\t\t\treturn convertToolResultMessage(message, model);\n\t}\n}\n\n/**\n * Convert messages that are not yet persisted in the session branch (the\n * in-flight prompt) into input items, so payload replay can append them after\n * the branch-derived items.\n */\nexport function convertPendingMessages(messages: AgentMessage[], model: Model<Api>): OpenAiRemoteInputItem[] {\n\treturn convertToLlm(messages).flatMap((message, index) => convertLlmMessage(message, index, model));\n}\n\n/**\n * Convert session branch entries into OpenAI Responses input items.\n *\n * The route gate is provider capability (checked by the caller), not history\n * provenance: any entry the session can carry is converted through the same\n * pipeline the normal context path uses (`sessionEntryToContextMessages` +\n * `convertToLlm`), so foreign-provider messages, bash executions, branch\n * summaries, and prior local compactions degrade to their canonical text\n * form instead of disqualifying remote compaction. Prior OpenAI remote\n * compaction checkpoints splice their native `replacementInput` in order.\n */\nexport function convertBranchEntries(entries: SessionEntry[], model: Model<Api>): OpenAiRemoteInputItem[] {\n\tconst items: OpenAiRemoteInputItem[] = [];\n\tlet pendingMessages: AgentMessage[] = [];\n\tlet messageIndex = 0;\n\tconst flush = (): void => {\n\t\tfor (const message of convertToLlm(pendingMessages)) {\n\t\t\titems.push(...convertLlmMessage(message, messageIndex, model));\n\t\t\tmessageIndex++;\n\t\t}\n\t\tpendingMessages = [];\n\t};\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"compaction\") {\n\t\t\tconst details = getOpenAiRemoteCompactionDetails(entry.details);\n\t\t\tif (details) {\n\t\t\t\tflush();\n\t\t\t\titems.push(...details.replacementInput);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tpendingMessages.push(...sessionEntryToContextMessages(entry));\n\t}\n\tflush();\n\treturn items;\n}\n"]}
1
+ {"version":3,"file":"openai-remote-convert.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/openai-remote-convert.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAqB,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC/F,OAAO,EACN,gCAAgC,EAChC,QAAQ,GAMR,MAAM,2BAA2B,CAAC;AAUnC,OAAO,EACN,gCAAgC,EAChC,6BAA6B,EAC7B,kCAAkC,EAClC,QAAQ,EACR,0BAA0B,EAC1B,kCAAkC,EAClC,+BAA+B,GAC/B,MAAM,2BAA2B,CAAC;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AK,GAA4B,EAAE,CAAC;IAC1C,IAAI,eAAe,GAAmB,EAAE,CAAC;IACzC,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,MAAM,KAAK,GAAG,GAAS,EAAE;QACxB,KAAK,MAAM,OAAO,IAAI,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC;YACrD,KAAK,CAAC,IAAI,CAAC,GAAG,iBAAiB,CAAC,OAAO,EAAE,YAAY,EAAE,KAAK,CAAC,CAAC,CAAC;YAC/D,YAAY,EAAE,CAAC;QAChB,CAAC;QACD,eAAe,GAAG,EAAE,CAAC;IACtB,CAAC,CAAC;IACF,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YACjC,MAAM,OAAO,GAAG,gCAAgC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,IAAI,OAAO,EAAE,CAAC;gBACb,KAAK,EAAE,CAAC;gBACR,KAAK,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;gBACxC,SAAS;YACV,CAAC;QACF,CAAC;QACD,eAAe,CAAC,IAAI,CAAC,GAAG,6BAA6B,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/D,CAAC;IACD,KAAK,EAAE,CAAC;IACR,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"@earendil-works/pi-ai\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport { type SessionEntry, sessionEntryToContextMessages } from \"../../../session-manager.ts\";\nimport {\n\tgetOpenAiRemoteCompactionDetails,\n\tisRecord,\n\ttype OpenAiAssistantMessageItem,\n\ttype OpenAiFunctionCallItem,\n\ttype OpenAiInputContent,\n\ttype OpenAiProviderNativeItem,\n\ttype OpenAiRemoteInputItem,\n} from \"./openai-remote-schema.ts\";\n\nexport type {\n\tOpenAiCompactBody,\n\tOpenAiContextCompactionItem,\n\tOpenAiContextCompactionTriggerItem,\n\tOpenAiRemoteCompactionDetails,\n\tOpenAiRemoteInputItem,\n\tOpenAiRemoteTransport,\n} from \"./openai-remote-schema.ts\";\nexport {\n\tgetOpenAiRemoteCompactionDetails,\n\tisOpenAiContextCompactionItem,\n\tisOpenAiRemoteCompactionOutputItem,\n\tisRecord,\n\tisRetainedRemoteOutputItem,\n\tisRetainedResponsesStreamInputItem,\n\tOPENAI_REMOTE_COMPACTION_SCHEMA,\n} from \"./openai-remote-schema.ts\";\n\nfunction parseJsonRecord(value: string | undefined): Record<string, unknown> | undefined {\n\tif (!value?.startsWith(\"{\")) return undefined;\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\treturn isRecord(parsed) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: \"commentary\" | \"final_answer\" } | undefined {\n\tif (!signature) return undefined;\n\tconst parsed = parseJsonRecord(signature);\n\tif (parsed?.v === 1 && typeof parsed.id === \"string\") {\n\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t}\n\t\treturn { id: parsed.id };\n\t}\n\treturn { id: signature };\n}\n\nfunction convertUserContent(content: string | (TextContent | ImageContent)[]): OpenAiInputContent[] {\n\tif (typeof content === \"string\") return [{ type: \"input_text\", text: content }];\n\treturn content.map((block): OpenAiInputContent => {\n\t\tif (block.type === \"text\") return { type: \"input_text\", text: block.text };\n\t\treturn {\n\t\t\ttype: \"input_image\",\n\t\t\tdetail: \"auto\",\n\t\t\timage_url: `data:${block.mimeType};base64,${block.data}`,\n\t\t};\n\t});\n}\n\nexport function providerNativeItem(raw: unknown): OpenAiProviderNativeItem | undefined {\n\tif (!isRecord(raw) || typeof raw.type !== \"string\") return undefined;\n\treturn { ...raw, type: raw.type };\n}\n\nfunction convertThinking(block: { thinkingSignature?: string }): OpenAiProviderNativeItem | undefined {\n\tconst parsed = parseJsonRecord(block.thinkingSignature);\n\tif (parsed?.type !== \"reasoning\") return undefined;\n\treturn { ...parsed, type: \"reasoning\" };\n}\n\nfunction convertTextBlock(block: TextContent, messageIndex: number): OpenAiAssistantMessageItem {\n\tconst signature = parseTextSignature(block.textSignature);\n\tconst item = {\n\t\ttype: \"message\",\n\t\trole: \"assistant\",\n\t\tstatus: \"completed\",\n\t\tid: signature?.id ?? `msg_${messageIndex}`,\n\t\tcontent: [{ type: \"output_text\", text: block.text, annotations: [] }],\n\t\t...(signature?.phase ? { phase: signature.phase } : {}),\n\t} satisfies OpenAiAssistantMessageItem;\n\treturn item;\n}\n\nfunction convertToolCall(block: ToolCall): OpenAiFunctionCallItem {\n\tconst [callId = block.id, itemId] = block.id.split(\"|\");\n\treturn {\n\t\ttype: \"function_call\",\n\t\t// The Responses API rejects item ids not beginning with \"fc\"; custom tool\n\t\t// calls carry the \"<call_id>|custom\" sentinel, not a server-issued id.\n\t\t...(itemId?.startsWith(\"fc\") ? { id: itemId } : {}),\n\t\tcall_id: callId,\n\t\tname: block.name,\n\t\targuments: JSON.stringify(block.arguments ?? {}),\n\t};\n}\n\n/**\n * Convert any assistant message — OpenAI Responses-native or foreign — into\n * replayable input items. Native text/reasoning/tool-call items are preserved\n * verbatim; blocks that have no OpenAI Responses representation (foreign\n * thinking, unknown provider-native payloads) are skipped, mirroring what the\n * provider would have received for that message in a normal turn.\n */\nfunction convertAssistantMessage(message: AssistantMessage, messageIndex: number): OpenAiRemoteInputItem[] {\n\tconst items: OpenAiRemoteInputItem[] = [];\n\tfor (const block of message.content) {\n\t\tswitch (block.type) {\n\t\t\tcase \"text\":\n\t\t\t\titems.push(convertTextBlock(block, messageIndex));\n\t\t\t\tbreak;\n\t\t\tcase \"thinking\": {\n\t\t\t\tconst reasoning = convertThinking(block);\n\t\t\t\tif (reasoning) items.push(reasoning);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolCall\":\n\t\t\t\titems.push(convertToolCall(block));\n\t\t\t\tbreak;\n\t\t\tcase \"providerNative\": {\n\t\t\t\tconst item = providerNativeItem(block.raw);\n\t\t\t\tif (item) items.push(item);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn items;\n}\n\n/**\n * Convert a tool result into a function_call_output item, mirroring the\n * Responses API payload builder: image results stay structured for\n * image-capable models and degrade to a text placeholder otherwise.\n */\nfunction convertToolResultMessage(message: ToolResultMessage, model: Model<Api>): OpenAiRemoteInputItem[] {\n\tconst [callId = message.toolCallId] = message.toolCallId.split(\"|\");\n\tconst text = message.content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n\tconst images = message.content.filter((block): block is ImageContent => block.type === \"image\");\n\tlet output: string | OpenAiInputContent[];\n\tif (images.length > 0 && model.input.includes(\"image\")) {\n\t\tconst parts: OpenAiInputContent[] = [];\n\t\tif (text.length > 0) parts.push({ type: \"input_text\", text });\n\t\tfor (const image of images) {\n\t\t\tparts.push({\n\t\t\t\ttype: \"input_image\",\n\t\t\t\tdetail: \"auto\",\n\t\t\t\timage_url: `data:${image.mimeType};base64,${image.data}`,\n\t\t\t});\n\t\t}\n\t\toutput = parts.length > 0 ? parts : \"(no tool output)\";\n\t} else {\n\t\toutput = text.length > 0 ? text : images.length > 0 ? \"(see attached image)\" : \"(no tool output)\";\n\t}\n\treturn [{ type: \"function_call_output\", call_id: callId, output }];\n}\n\nfunction convertLlmMessage(message: Message, messageIndex: number, model: Model<Api>): OpenAiRemoteInputItem[] {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn [{ role: \"user\", content: convertUserContent(message.content) }];\n\t\tcase \"assistant\":\n\t\t\treturn convertAssistantMessage(message, messageIndex);\n\t\tcase \"toolResult\":\n\t\t\treturn convertToolResultMessage(message, model);\n\t\tcase \"configurationUpdate\":\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Convert messages that are not yet persisted in the session branch (the\n * in-flight prompt) into input items, so payload replay can append them after\n * the branch-derived items.\n */\nexport function convertPendingMessages(messages: AgentMessage[], model: Model<Api>): OpenAiRemoteInputItem[] {\n\treturn convertToLlm(messages).flatMap((message, index) => convertLlmMessage(message, index, model));\n}\n\n/**\n * Convert session branch entries into OpenAI Responses input items.\n *\n * The route gate is provider capability (checked by the caller), not history\n * provenance: any entry the session can carry is converted through the same\n * pipeline the normal context path uses (`sessionEntryToContextMessages` +\n * `convertToLlm`), so foreign-provider messages, bash executions, branch\n * summaries, and prior local compactions degrade to their canonical text\n * form instead of disqualifying remote compaction. Prior OpenAI remote\n * compaction checkpoints splice their native `replacementInput` in order.\n */\nexport function convertBranchEntries(entries: SessionEntry[], model: Model<Api>): OpenAiRemoteInputItem[] {\n\tconst items: OpenAiRemoteInputItem[] = [];\n\tlet pendingMessages: AgentMessage[] = [];\n\tlet messageIndex = 0;\n\tconst flush = (): void => {\n\t\tfor (const message of convertToLlm(pendingMessages)) {\n\t\t\titems.push(...convertLlmMessage(message, messageIndex, model));\n\t\t\tmessageIndex++;\n\t\t}\n\t\tpendingMessages = [];\n\t};\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"compaction\") {\n\t\t\tconst details = getOpenAiRemoteCompactionDetails(entry.details);\n\t\t\tif (details) {\n\t\t\t\tflush();\n\t\t\t\titems.push(...details.replacementInput);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tpendingMessages.push(...sessionEntryToContextMessages(entry));\n\t}\n\tflush();\n\treturn items;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"retained-message-safety.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/retained-message-safety.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAgJlE,yGAAyG;AACzG,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,CAmD1E"}
1
+ {"version":3,"file":"retained-message-safety.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/retained-message-safety.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAmKlE,yGAAyG;AACzG,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,CAmD1E"}
@@ -11,6 +11,19 @@ function hasTextOnlyContent(content, allowString) {
11
11
  return false;
12
12
  return content.every((block) => isRecord(block) && block.type === "text" && typeof block.text === "string");
13
13
  }
14
+ function isWellFormedImageBlock(block) {
15
+ return (block.type === "image" &&
16
+ typeof block.mimeType === "string" &&
17
+ block.mimeType.startsWith("image/") &&
18
+ typeof block.data === "string" &&
19
+ block.data.length > 0);
20
+ }
21
+ function hasSafeToolResultContent(content) {
22
+ if (!Array.isArray(content))
23
+ return false;
24
+ return content.every((block) => isRecord(block) &&
25
+ ((block.type === "text" && typeof block.text === "string") || isWellFormedImageBlock(block)));
26
+ }
14
27
  function isUsage(value) {
15
28
  if (!isRecord(value) || !isRecord(value.cost))
16
29
  return false;
@@ -117,7 +130,7 @@ function hasSafeToolResultEnvelope(message) {
117
130
  message.toolCallId.length > 0 &&
118
131
  typeof message.toolName === "string" &&
119
132
  message.toolName.length > 0 &&
120
- hasTextOnlyContent(message.content, false) &&
133
+ hasSafeToolResultContent(message.content) &&
121
134
  typeof message.isError === "boolean" &&
122
135
  isFiniteNumber(message.timestamp) &&
123
136
  (message.usage === undefined || isUsage(message.usage)) &&
@@ -1 +1 @@
1
- {"version":3,"file":"retained-message-safety.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/retained-message-safety.ts"],"names":[],"mappings":"AAEA,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IA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cAAc,KAAK,QAAQ,CAAC;oBAChF,CAAC,KAAK,CAAC,kBAAkB,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,kBAAkB,KAAK,SAAS,CAAC;oBACzF,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,CAAC,EAC/B,CAAC;oBACF,OAAO,IAAI,CAAC;gBACb,CAAC;gBACD,MAAM;YACP,KAAK,mBAAmB;gBACvB,IACC,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ;oBACjC,CAAC,cAAc,CAAC,KAAK,CAAC,YAAY,CAAC;oBACnC,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,CAAC,EAC/B,CAAC;oBACF,OAAO,IAAI,CAAC;gBACb,CAAC;gBACD,MAAM;YACP;gBACC,OAAO,IAAI,CAAC;QACd,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction hasTextOnlyContent(content: unknown, allowString: boolean): boolean {\n\tif (typeof content === \"string\") return allowString;\n\tif (!Array.isArray(content)) return false;\n\treturn content.every((block) => isRecord(block) && block.type === \"text\" && typeof block.text === \"string\");\n}\n\nfunction isUsage(value: unknown): boolean {\n\tif (!isRecord(value) || !isRecord(value.cost)) return false;\n\tfor (const field of [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"totalTokens\"] as const) {\n\t\tif (!isFiniteNumber(value[field])) return false;\n\t}\n\tfor (const field of [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"total\"] as const) {\n\t\tif (!isFiniteNumber(value.cost[field])) return false;\n\t}\n\treturn (\n\t\t(value.cacheWrite1h === undefined || isFiniteNumber(value.cacheWrite1h)) &&\n\t\t(value.reasoning === undefined || isFiniteNumber(value.reasoning))\n\t);\n}\n\nconst base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;\n\n/** Validate an opaque provider signature without exposing or logging content. */\nfunction isValidOpaqueSignature(sig: unknown): sig is string {\n\treturn typeof sig === \"string\" && sig.length > 0 && sig.length <= 65_536;\n}\n\n/** Gemini signatures are base64; other providers use bounded opaque strings. */\nfunction isValidProviderSignature(sig: unknown, providerIsGoogle: boolean): sig is string {\n\tif (!isValidOpaqueSignature(sig)) return false;\n\treturn !providerIsGoogle || (sig.length % 4 === 0 && base64SignaturePattern.test(sig));\n}\n\nfunction hasSafeAssistantContent(content: unknown, providerIsGoogle: boolean): boolean {\n\tif (!Array.isArray(content)) return false;\n\tfor (const block of content) {\n\t\tif (!isRecord(block) || typeof block.type !== \"string\") return false;\n\t\tswitch (block.type) {\n\t\t\tcase \"text\":\n\t\t\t\tif (typeof block.text !== \"string\") return false;\n\t\t\t\tif (block.textSignature !== undefined && !isValidProviderSignature(block.textSignature, providerIsGoogle)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"thinking\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof block.thinking !== \"string\" ||\n\t\t\t\t\t(block.startedAt !== undefined && !isFiniteNumber(block.startedAt)) ||\n\t\t\t\t\t(block.endedAt !== undefined && !isFiniteNumber(block.endedAt)) ||\n\t\t\t\t\t(block.redacted !== undefined && typeof block.redacted !== \"boolean\")\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t// Redacted thinking requires a bounded opaque signature for replay.\n\t\t\t\tif (\n\t\t\t\t\t(block.thinkingSignature !== undefined &&\n\t\t\t\t\t\t!isValidProviderSignature(block.thinkingSignature, providerIsGoogle)) ||\n\t\t\t\t\t(block.redacted === true && !isValidOpaqueSignature(block.thinkingSignature))\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"toolCall\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof block.id !== \"string\" ||\n\t\t\t\t\ttypeof block.name !== \"string\" ||\n\t\t\t\t\t!isRecord(block.arguments) ||\n\t\t\t\t\t(block.incomplete !== undefined && block.incomplete !== true) ||\n\t\t\t\t\t(block.errorMessage !== undefined && typeof block.errorMessage !== \"string\")\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tblock.thoughtSignature !== undefined &&\n\t\t\t\t\t!isValidProviderSignature(block.thoughtSignature, providerIsGoogle)\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction hasSafeAssistantEnvelope(message: Record<string, unknown>): boolean {\n\tconst provider = typeof message.provider === \"string\" ? message.provider : \"\";\n\tconst providerIsGoogle = provider === \"google\" || provider === \"google-vertex\";\n\tconst stopReason = message.stopReason;\n\tconst stopDetails = message.stopDetails;\n\tconst safeStopDetails =\n\t\tstopDetails === undefined ||\n\t\t(isRecord(stopDetails) &&\n\t\t\t(stopDetails.type === \"sensitive\" ||\n\t\t\t\t(stopDetails.type === \"refusal\" &&\n\t\t\t\t\t(stopDetails.explanation === undefined || typeof stopDetails.explanation === \"string\"))));\n\treturn (\n\t\ttypeof message.api === \"string\" &&\n\t\ttypeof message.provider === \"string\" &&\n\t\ttypeof message.model === \"string\" &&\n\t\tisUsage(message.usage) &&\n\t\t(stopReason === \"pending\" ||\n\t\t\tstopReason === \"stop\" ||\n\t\t\tstopReason === \"length\" ||\n\t\t\tstopReason === \"toolUse\" ||\n\t\t\tstopReason === \"error\" ||\n\t\t\tstopReason === \"aborted\") &&\n\t\tsafeStopDetails &&\n\t\tisFiniteNumber(message.timestamp) &&\n\t\t(message.responseModel === undefined || typeof message.responseModel === \"string\") &&\n\t\t(message.responseId === undefined || typeof message.responseId === \"string\") &&\n\t\t(message.diagnostics === undefined || Array.isArray(message.diagnostics)) &&\n\t\t(message.errorMessage === undefined || typeof message.errorMessage === \"string\") &&\n\t\t(message.rawStopReason === undefined || typeof message.rawStopReason === \"string\") &&\n\t\thasSafeAssistantContent(message.content, providerIsGoogle)\n\t);\n}\n\nfunction hasSafeToolResultEnvelope(message: Record<string, unknown>): boolean {\n\treturn (\n\t\ttypeof message.toolCallId === \"string\" &&\n\t\tmessage.toolCallId.length > 0 &&\n\t\ttypeof message.toolName === \"string\" &&\n\t\tmessage.toolName.length > 0 &&\n\t\thasTextOnlyContent(message.content, false) &&\n\t\ttypeof message.isError === \"boolean\" &&\n\t\tisFiniteNumber(message.timestamp) &&\n\t\t(message.usage === undefined || isUsage(message.usage)) &&\n\t\t(message.addedToolNames === undefined ||\n\t\t\t(Array.isArray(message.addedToolNames) && message.addedToolNames.every((name) => typeof name === \"string\")))\n\t);\n}\n\n/** Reject any retained message that cannot be safely replayed through normalized provider conversion. */\nexport function hasUnsafeRetainedContent(messages: AgentMessage[]): boolean {\n\tfor (const value of messages as unknown[]) {\n\t\tif (!isRecord(value) || typeof value.role !== \"string\") return true;\n\t\tswitch (value.role) {\n\t\t\tcase \"user\":\n\t\t\t\tif (!isFiniteNumber(value.timestamp) || !hasTextOnlyContent(value.content, true)) return true;\n\t\t\t\tbreak;\n\t\t\tcase \"assistant\":\n\t\t\t\tif (!hasSafeAssistantEnvelope(value)) return true;\n\t\t\t\tbreak;\n\t\t\tcase \"toolResult\":\n\t\t\t\tif (!hasSafeToolResultEnvelope(value)) return true;\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof value.customType !== \"string\" ||\n\t\t\t\t\ttypeof value.display !== \"boolean\" ||\n\t\t\t\t\t!isFiniteNumber(value.timestamp) ||\n\t\t\t\t\t!hasTextOnlyContent(value.content, true)\n\t\t\t\t) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"bashExecution\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof value.command !== \"string\" ||\n\t\t\t\t\ttypeof value.output !== \"string\" ||\n\t\t\t\t\t(value.exitCode !== undefined && !isFiniteNumber(value.exitCode)) ||\n\t\t\t\t\ttypeof value.cancelled !== \"boolean\" ||\n\t\t\t\t\ttypeof value.truncated !== \"boolean\" ||\n\t\t\t\t\t(value.fullOutputPath !== undefined && typeof value.fullOutputPath !== \"string\") ||\n\t\t\t\t\t(value.excludeFromContext !== undefined && typeof value.excludeFromContext !== \"boolean\") ||\n\t\t\t\t\t!isFiniteNumber(value.timestamp)\n\t\t\t\t) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"compactionSummary\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof value.summary !== \"string\" ||\n\t\t\t\t\t!isFiniteNumber(value.tokensBefore) ||\n\t\t\t\t\t!isFiniteNumber(value.timestamp)\n\t\t\t\t) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n"]}
1
+ {"version":3,"file":"retained-message-safety.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/retained-message-safety.ts"],"names":[],"mappings":"AAEA,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,cAAc,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,kBAAkB,CAAC,OAAgB,EAAE,WAAoB;IACjE,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,WAAW,CAAC;IACpD,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O,KAAK,QAAQ;oBACjC,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ;oBAChC,CAAC,KAAK,CAAC,QAAQ,KAAK,SAAS,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;oBACjE,OAAO,KAAK,CAAC,SAAS,KAAK,SAAS;oBACpC,OAAO,KAAK,CAAC,SAAS,KAAK,SAAS;oBACpC,CAAC,KAAK,CAAC,cAAc,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,cAAc,KAAK,QAAQ,CAAC;oBAChF,CAAC,KAAK,CAAC,kBAAkB,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,kBAAkB,KAAK,SAAS,CAAC;oBACzF,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,CAAC,EAC/B,CAAC;oBACF,OAAO,IAAI,CAAC;gBACb,CAAC;gBACD,MAAM;YACP,KAAK,mBAAmB;gBACvB,IACC,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ;oBACjC,CAAC,cAAc,CAAC,KAAK,CAAC,YAAY,CAAC;oBACnC,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,CAAC,EAC/B,CAAC;oBACF,OAAO,IAAI,CAAC;gBACb,CAAC;gBACD,MAAM;YACP;gBACC,OAAO,IAAI,CAAC;QACd,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction hasTextOnlyContent(content: unknown, allowString: boolean): boolean {\n\tif (typeof content === \"string\") return allowString;\n\tif (!Array.isArray(content)) return false;\n\treturn content.every((block) => isRecord(block) && block.type === \"text\" && typeof block.text === \"string\");\n}\n\nfunction isWellFormedImageBlock(block: Record<string, unknown>): boolean {\n\treturn (\n\t\tblock.type === \"image\" &&\n\t\ttypeof block.mimeType === \"string\" &&\n\t\tblock.mimeType.startsWith(\"image/\") &&\n\t\ttypeof block.data === \"string\" &&\n\t\tblock.data.length > 0\n\t);\n}\n\nfunction hasSafeToolResultContent(content: unknown): boolean {\n\tif (!Array.isArray(content)) return false;\n\treturn content.every(\n\t\t(block) =>\n\t\t\tisRecord(block) &&\n\t\t\t((block.type === \"text\" && typeof block.text === \"string\") || isWellFormedImageBlock(block)),\n\t);\n}\n\nfunction isUsage(value: unknown): boolean {\n\tif (!isRecord(value) || !isRecord(value.cost)) return false;\n\tfor (const field of [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"totalTokens\"] as const) {\n\t\tif (!isFiniteNumber(value[field])) return false;\n\t}\n\tfor (const field of [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"total\"] as const) {\n\t\tif (!isFiniteNumber(value.cost[field])) return false;\n\t}\n\treturn (\n\t\t(value.cacheWrite1h === undefined || isFiniteNumber(value.cacheWrite1h)) &&\n\t\t(value.reasoning === undefined || isFiniteNumber(value.reasoning))\n\t);\n}\n\nconst base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;\n\n/** Validate an opaque provider signature without exposing or logging content. */\nfunction isValidOpaqueSignature(sig: unknown): sig is string {\n\treturn typeof sig === \"string\" && sig.length > 0 && sig.length <= 65_536;\n}\n\n/** Gemini signatures are base64; other providers use bounded opaque strings. */\nfunction isValidProviderSignature(sig: unknown, providerIsGoogle: boolean): sig is string {\n\tif (!isValidOpaqueSignature(sig)) return false;\n\treturn !providerIsGoogle || (sig.length % 4 === 0 && base64SignaturePattern.test(sig));\n}\n\nfunction hasSafeAssistantContent(content: unknown, providerIsGoogle: boolean): boolean {\n\tif (!Array.isArray(content)) return false;\n\tfor (const block of content) {\n\t\tif (!isRecord(block) || typeof block.type !== \"string\") return false;\n\t\tswitch (block.type) {\n\t\t\tcase \"text\":\n\t\t\t\tif (typeof block.text !== \"string\") return false;\n\t\t\t\tif (block.textSignature !== undefined && !isValidProviderSignature(block.textSignature, providerIsGoogle)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"thinking\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof block.thinking !== \"string\" ||\n\t\t\t\t\t(block.startedAt !== undefined && !isFiniteNumber(block.startedAt)) ||\n\t\t\t\t\t(block.endedAt !== undefined && !isFiniteNumber(block.endedAt)) ||\n\t\t\t\t\t(block.redacted !== undefined && typeof block.redacted !== \"boolean\")\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t// Redacted thinking requires a bounded opaque signature for replay.\n\t\t\t\tif (\n\t\t\t\t\t(block.thinkingSignature !== undefined &&\n\t\t\t\t\t\t!isValidProviderSignature(block.thinkingSignature, providerIsGoogle)) ||\n\t\t\t\t\t(block.redacted === true && !isValidOpaqueSignature(block.thinkingSignature))\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"toolCall\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof block.id !== \"string\" ||\n\t\t\t\t\ttypeof block.name !== \"string\" ||\n\t\t\t\t\t!isRecord(block.arguments) ||\n\t\t\t\t\t(block.incomplete !== undefined && block.incomplete !== true) ||\n\t\t\t\t\t(block.errorMessage !== undefined && typeof block.errorMessage !== \"string\")\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tblock.thoughtSignature !== undefined &&\n\t\t\t\t\t!isValidProviderSignature(block.thoughtSignature, providerIsGoogle)\n\t\t\t\t) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction hasSafeAssistantEnvelope(message: Record<string, unknown>): boolean {\n\tconst provider = typeof message.provider === \"string\" ? message.provider : \"\";\n\tconst providerIsGoogle = provider === \"google\" || provider === \"google-vertex\";\n\tconst stopReason = message.stopReason;\n\tconst stopDetails = message.stopDetails;\n\tconst safeStopDetails =\n\t\tstopDetails === undefined ||\n\t\t(isRecord(stopDetails) &&\n\t\t\t(stopDetails.type === \"sensitive\" ||\n\t\t\t\t(stopDetails.type === \"refusal\" &&\n\t\t\t\t\t(stopDetails.explanation === undefined || typeof stopDetails.explanation === \"string\"))));\n\treturn (\n\t\ttypeof message.api === \"string\" &&\n\t\ttypeof message.provider === \"string\" &&\n\t\ttypeof message.model === \"string\" &&\n\t\tisUsage(message.usage) &&\n\t\t(stopReason === \"pending\" ||\n\t\t\tstopReason === \"stop\" ||\n\t\t\tstopReason === \"length\" ||\n\t\t\tstopReason === \"toolUse\" ||\n\t\t\tstopReason === \"error\" ||\n\t\t\tstopReason === \"aborted\") &&\n\t\tsafeStopDetails &&\n\t\tisFiniteNumber(message.timestamp) &&\n\t\t(message.responseModel === undefined || typeof message.responseModel === \"string\") &&\n\t\t(message.responseId === undefined || typeof message.responseId === \"string\") &&\n\t\t(message.diagnostics === undefined || Array.isArray(message.diagnostics)) &&\n\t\t(message.errorMessage === undefined || typeof message.errorMessage === \"string\") &&\n\t\t(message.rawStopReason === undefined || typeof message.rawStopReason === \"string\") &&\n\t\thasSafeAssistantContent(message.content, providerIsGoogle)\n\t);\n}\n\nfunction hasSafeToolResultEnvelope(message: Record<string, unknown>): boolean {\n\treturn (\n\t\ttypeof message.toolCallId === \"string\" &&\n\t\tmessage.toolCallId.length > 0 &&\n\t\ttypeof message.toolName === \"string\" &&\n\t\tmessage.toolName.length > 0 &&\n\t\thasSafeToolResultContent(message.content) &&\n\t\ttypeof message.isError === \"boolean\" &&\n\t\tisFiniteNumber(message.timestamp) &&\n\t\t(message.usage === undefined || isUsage(message.usage)) &&\n\t\t(message.addedToolNames === undefined ||\n\t\t\t(Array.isArray(message.addedToolNames) && message.addedToolNames.every((name) => typeof name === \"string\")))\n\t);\n}\n\n/** Reject any retained message that cannot be safely replayed through normalized provider conversion. */\nexport function hasUnsafeRetainedContent(messages: AgentMessage[]): boolean {\n\tfor (const value of messages as unknown[]) {\n\t\tif (!isRecord(value) || typeof value.role !== \"string\") return true;\n\t\tswitch (value.role) {\n\t\t\tcase \"user\":\n\t\t\t\tif (!isFiniteNumber(value.timestamp) || !hasTextOnlyContent(value.content, true)) return true;\n\t\t\t\tbreak;\n\t\t\tcase \"assistant\":\n\t\t\t\tif (!hasSafeAssistantEnvelope(value)) return true;\n\t\t\t\tbreak;\n\t\t\tcase \"toolResult\":\n\t\t\t\tif (!hasSafeToolResultEnvelope(value)) return true;\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof value.customType !== \"string\" ||\n\t\t\t\t\ttypeof value.display !== \"boolean\" ||\n\t\t\t\t\t!isFiniteNumber(value.timestamp) ||\n\t\t\t\t\t!hasTextOnlyContent(value.content, true)\n\t\t\t\t) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"bashExecution\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof value.command !== \"string\" ||\n\t\t\t\t\ttypeof value.output !== \"string\" ||\n\t\t\t\t\t(value.exitCode !== undefined && !isFiniteNumber(value.exitCode)) ||\n\t\t\t\t\ttypeof value.cancelled !== \"boolean\" ||\n\t\t\t\t\ttypeof value.truncated !== \"boolean\" ||\n\t\t\t\t\t(value.fullOutputPath !== undefined && typeof value.fullOutputPath !== \"string\") ||\n\t\t\t\t\t(value.excludeFromContext !== undefined && typeof value.excludeFromContext !== \"boolean\") ||\n\t\t\t\t\t!isFiniteNumber(value.timestamp)\n\t\t\t\t) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"compactionSummary\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof value.summary !== \"string\" ||\n\t\t\t\t\t!isFiniteNumber(value.tokensBefore) ||\n\t\t\t\t\t!isFiniteNumber(value.timestamp)\n\t\t\t\t) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\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.";
@@ -1 +1 @@
1
- {"version":3,"file":"cache-warm-renderer.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/cache-warm-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,EACN,cAAc,EACd,cAAc,EACd,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,GAEpB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,CAAC,MAAM,0BAA0B,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CacheTtl,\n\tformatSavedUsd,\n\tformatWakeDuration,\n\tformatWakeTimestamp,\n\tformatWarmTokenCount,\n\ttype GoalCacheWarmupEntryData,\n} from \"./cache-warm.ts\";\n\nexport const renderGoalCacheWarmupEntry: EntryRenderer<GoalCacheWarmupEntryData> = noticeEntryRenderer((entry) => {\n\tconst data = entry.data;\n\tif (data === undefined) return undefined;\n\tconst warm = warmLine(data);\n\treturn {\n\t\ttitle: titleLine(data),\n\t\twhy: whyLine(data),\n\t\textra: warm === undefined ? [] : [{ text: warm, tone: \"success\" }],\n\t\texpandedLine: expandedLine(data),\n\t};\n});\n\nfunction titleLine(data: GoalCacheWarmupEntryData): string {\n\tconst wakeSources =\n\t\tdata.activeMonitorCount === 1 ? \"1 wake source on duty\" : `${data.activeMonitorCount} wake sources on duty`;\n\tconst iteration = validIteration(data.iteration);\n\tconst iterationText = iteration === undefined ? \"\" : ` · iteration ${iteration}`;\n\tswitch (data.phase) {\n\t\tcase \"scheduled\":\n\t\t\treturn `⚡ Cache-warm wait${iterationText} · ${wakeSources}`;\n\t\tcase \"resumed\":\n\t\t\treturn `⚡ Cache-warm wake${iterationText} · ${formatExpectedWake(data.dueAtMs, data.waitedMs ?? data.delayMs)} · ${wakeSources}`;\n\t}\n}\n\nfunction validIteration(value: number | undefined): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction whyLine(data: GoalCacheWarmupEntryData): string {\n\tswitch (data.phase) {\n\t\tcase \"scheduled\": {\n\t\t\tconst expected = `Continuation expected ${formatExpectedWake(data.dueAtMs, data.delayMs)}`;\n\t\t\tif (data.cache?.ttlSeconds === undefined) {\n\t\t\t\treturn `${expected} - the monitor wakes the goal the moment decisive output lands.`;\n\t\t\t}\n\t\t\treturn data.delayMs < data.cache.ttlSeconds * 1000\n\t\t\t\t? `${expected} - the timed wake stays inside the ${formatCacheTtl(data.cache.ttlSeconds)} prompt-cache TTL.`\n\t\t\t\t: `${expected} - the prompt-cache TTL may elapse before the timed wake.`;\n\t\t}\n\t\tcase \"resumed\":\n\t\t\treturn \"Woke on schedule to keep pursuing the goal.\";\n\t}\n}\n\nfunction formatExpectedWake(dueAtMs: number | undefined, elapsedMs: number): string {\n\tif (dueAtMs === undefined || !Number.isFinite(dueAtMs)) return `waited ${formatWakeDuration(elapsedMs)}`;\n\treturn `ready ${formatWakeTimestamp(dueAtMs)} (${formatWakeDuration(elapsedMs)})`;\n}\n\nfunction expandedLine(data: GoalCacheWarmupEntryData): string {\n\tconst planned = `goal ${data.goalId} · planned delay ${formatWakeDuration(data.delayMs)}`;\n\tif (data.phase === \"scheduled\") return `${planned} · ${formatExpectedWake(data.dueAtMs, data.delayMs)}`;\n\treturn `${planned} · ${formatExpectedWake(data.dueAtMs, data.waitedMs ?? data.delayMs)}`;\n}\n\nfunction warmLine(data: GoalCacheWarmupEntryData): string | undefined {\n\tconst cache = data.cache;\n\tif (cache === undefined || cache.cachedTokens <= 0) return undefined;\n\tconst tokens = `~${formatWarmTokenCount(cache.cachedTokens)} tokens`;\n\tconst ttlMayHaveElapsed =\n\t\tcache.ttlSeconds !== undefined && (data.waitedMs ?? data.delayMs) >= cache.ttlSeconds * 1000;\n\tif (ttlMayHaveElapsed) {\n\t\treturn `${tokens} were cached after the prior turn · prompt-cache TTL may have elapsed before this wake`;\n\t}\n\tconst body = data.phase === \"scheduled\" ? `${tokens} kept warm` : `${tokens} stayed warm in the prompt cache`;\n\tconst saved =\n\t\tcache.estimatedSavedUsd !== undefined && cache.estimatedSavedUsd > 0\n\t\t\t? ` · est. ${formatSavedUsd(cache.estimatedSavedUsd)} saved vs a cold re-read`\n\t\t\t: \"\";\n\treturn `${body}${saved}`;\n}\n"]}
1
+ {"version":3,"file":"cache-warm-renderer.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/cache-warm-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,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KAAK,CAAC,iBAAiB,CAAC,0BAA0B;QAC9E,CAAC,CAAC,EAAE,CAAC;IACP,OAAO,GAAG,IAAI,GAAG,KAAK,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["import { noticeEntryRenderer } from \"../../notice/index.ts\";\nimport type { EntryRenderer } from \"../../types.ts\";\nimport {\n\tformatCacheTtl,\n\tformatSavedUsd,\n\tformatWakeDuration,\n\tformatWakeTimestamp,\n\tformatWarmTokenCount,\n\ttype GoalCacheWarmupEntryData,\n} from \"./cache-warm.ts\";\n\nexport const renderGoalCacheWarmupEntry: EntryRenderer<GoalCacheWarmupEntryData> = noticeEntryRenderer((entry) => {\n\tconst data = entry.data;\n\tif (data === undefined) return undefined;\n\tconst warm = warmLine(data);\n\treturn {\n\t\ttitle: titleLine(data),\n\t\twhy: whyLine(data),\n\t\textra: warm === undefined ? [] : [{ text: warm, tone: \"success\" }],\n\t\texpandedLine: expandedLine(data),\n\t};\n});\n\nfunction titleLine(data: GoalCacheWarmupEntryData): string {\n\tconst wakeSources =\n\t\tdata.activeMonitorCount === 1 ? \"1 wake source on duty\" : `${data.activeMonitorCount} wake sources on duty`;\n\tconst iteration = validIteration(data.iteration);\n\tconst iterationText = iteration === undefined ? \"\" : ` · iteration ${iteration}`;\n\tswitch (data.phase) {\n\t\tcase \"scheduled\":\n\t\t\treturn `⚡ Cache-warm wait${iterationText} · ${wakeSources}`;\n\t\tcase \"resumed\":\n\t\t\treturn `⚡ Cache-warm wake${iterationText} · ${formatExpectedWake(data.dueAtMs, data.waitedMs ?? data.delayMs)} · ${wakeSources}`;\n\t}\n}\n\nfunction validIteration(value: number | undefined): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction whyLine(data: GoalCacheWarmupEntryData): string {\n\tswitch (data.phase) {\n\t\tcase \"scheduled\": {\n\t\t\t// The wait is not a cache-warm timer: it lets the live wake sources\n\t\t\t// deliver, and the timed wake is only the stall backstop.\n\t\t\tconst backstop = `Stall backstop ${formatExpectedWake(data.dueAtMs, data.delayMs)}`;\n\t\t\tif (data.cache?.ttlSeconds === undefined) {\n\t\t\t\treturn `${backstop} - the goal resumes as soon as a wake source delivers.`;\n\t\t\t}\n\t\t\treturn data.delayMs < data.cache.ttlSeconds * 1000\n\t\t\t\t? `${backstop} - the goal resumes as soon as a wake source delivers, inside the ${formatCacheTtl(data.cache.ttlSeconds)} prompt-cache TTL.`\n\t\t\t\t: `${backstop} - the goal resumes as soon as a wake source delivers; the ${formatCacheTtl(data.cache.ttlSeconds)} prompt-cache TTL may elapse first.`;\n\t\t}\n\t\tcase \"resumed\":\n\t\t\treturn \"Woke on schedule to keep pursuing the goal.\";\n\t}\n}\n\nfunction formatExpectedWake(dueAtMs: number | undefined, elapsedMs: number): string {\n\tif (dueAtMs === undefined || !Number.isFinite(dueAtMs)) return `waited ${formatWakeDuration(elapsedMs)}`;\n\treturn `ready ${formatWakeTimestamp(dueAtMs)} (${formatWakeDuration(elapsedMs)})`;\n}\n\nfunction expandedLine(data: GoalCacheWarmupEntryData): string {\n\tconst planned = `goal ${data.goalId} · planned delay ${formatWakeDuration(data.delayMs)}`;\n\tif (data.phase === \"scheduled\") return `${planned} · ${formatExpectedWake(data.dueAtMs, data.delayMs)}`;\n\treturn `${planned} · ${formatExpectedWake(data.dueAtMs, data.waitedMs ?? data.delayMs)}`;\n}\n\nfunction warmLine(data: GoalCacheWarmupEntryData): string | undefined {\n\tconst cache = data.cache;\n\tif (cache === undefined || cache.cachedTokens <= 0) return undefined;\n\tconst tokens = `~${formatWarmTokenCount(cache.cachedTokens)} tokens`;\n\tconst ttlMayHaveElapsed =\n\t\tcache.ttlSeconds !== undefined && (data.waitedMs ?? data.delayMs) >= cache.ttlSeconds * 1000;\n\tif (ttlMayHaveElapsed) {\n\t\treturn `${tokens} were cached after the prior turn · prompt-cache TTL may have elapsed before this wake`;\n\t}\n\tconst body = data.phase === \"scheduled\" ? `${tokens} kept warm` : `${tokens} stayed warm in the prompt cache`;\n\tconst saved =\n\t\tcache.estimatedSavedUsd !== undefined && cache.estimatedSavedUsd > 0\n\t\t\t? ` · est. ${formatSavedUsd(cache.estimatedSavedUsd)} saved vs a cold re-read`\n\t\t\t: \"\";\n\treturn `${body}${saved}`;\n}\n"]}
@@ -2,8 +2,26 @@ import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import type { TokenUsageSnapshot } from "./types.ts";
3
3
  /** Custom session-entry type carrying the cache-warm continuation story. */
4
4
  export declare const GOAL_CACHE_WARMUP_ENTRY_TYPE = "goal-cache-warmup";
5
+ /**
6
+ * Accounting fallback for a monitor continuation whose scheduled delay is no
7
+ * longer known (a held timer restored across a reload). It is deliberately NOT
8
+ * the armed delay: while a wake source is live the monitor arms the stall
9
+ * backstop below, never a cache-safe-wait timer.
10
+ */
5
11
  export declare const GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS = 240000;
6
- export declare function resolveGoalMonitorContinuationDelayMs(cacheSafeWaitSeconds: number | undefined, goalBackstopMaxSeconds?: number): number;
12
+ /** Default `promptCache.goalBackstopMaxSeconds` (settings-manager.ts) expressed in ms. */
13
+ export declare const GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS = 3570000;
14
+ /**
15
+ * Delay of the goal-monitor stall backstop, in milliseconds.
16
+ *
17
+ * The backstop exists to break a stall, not to keep the prompt cache warm, so
18
+ * it deliberately ignores the prompt-cache safe wait: a live wake source means
19
+ * the goal resumes when that source delivers (the drain fire), not on a timer.
20
+ * Configured through `promptCache.goalBackstopMaxSeconds`; a missing,
21
+ * non-finite, or non-positive setting falls back to the 3570s default, and the
22
+ * result is clamped into [1s, 1h].
23
+ */
24
+ export declare function resolveGoalMonitorContinuationDelayMs(goalBackstopMaxSeconds: number | undefined): number;
7
25
  /** Cache context captured when a monitor-wait continuation is scheduled. */
8
26
  export interface GoalCacheWarmMetrics {
9
27
  /** Prompt-cache TTL of the active model in seconds, when known. */
@@ -1 +1 @@
1
- {"version":3,"file":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ED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAK3D;AAmCD,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAItD;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAIpD"}
@@ -1,21 +1,34 @@
1
1
  import { resolvePromptCacheTtlSeconds } from "@earendil-works/pi-ai";
2
2
  /** Custom session-entry type carrying the cache-warm continuation story. */
3
3
  export const GOAL_CACHE_WARMUP_ENTRY_TYPE = "goal-cache-warmup";
4
+ /**
5
+ * Accounting fallback for a monitor continuation whose scheduled delay is no
6
+ * longer known (a held timer restored across a reload). It is deliberately NOT
7
+ * the armed delay: while a wake source is live the monitor arms the stall
8
+ * backstop below, never a cache-safe-wait timer.
9
+ */
4
10
  export const GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS = 240_000;
11
+ /** Default `promptCache.goalBackstopMaxSeconds` (settings-manager.ts) expressed in ms. */
12
+ export const GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS = 3_570_000;
5
13
  const GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS = 1_000;
6
14
  const GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS = 3_600_000;
7
- export function resolveGoalMonitorContinuationDelayMs(cacheSafeWaitSeconds, goalBackstopMaxSeconds) {
8
- if (typeof cacheSafeWaitSeconds !== "number" ||
9
- !Number.isFinite(cacheSafeWaitSeconds) ||
10
- cacheSafeWaitSeconds <= 0) {
11
- return GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS;
12
- }
13
- const configuredCeilingMs = typeof goalBackstopMaxSeconds === "number" &&
15
+ /**
16
+ * Delay of the goal-monitor stall backstop, in milliseconds.
17
+ *
18
+ * The backstop exists to break a stall, not to keep the prompt cache warm, so
19
+ * it deliberately ignores the prompt-cache safe wait: a live wake source means
20
+ * the goal resumes when that source delivers (the drain fire), not on a timer.
21
+ * Configured through `promptCache.goalBackstopMaxSeconds`; a missing,
22
+ * non-finite, or non-positive setting falls back to the 3570s default, and the
23
+ * result is clamped into [1s, 1h].
24
+ */
25
+ export function resolveGoalMonitorContinuationDelayMs(goalBackstopMaxSeconds) {
26
+ const configuredMs = typeof goalBackstopMaxSeconds === "number" &&
14
27
  Number.isFinite(goalBackstopMaxSeconds) &&
15
28
  goalBackstopMaxSeconds > 0
16
- ? Math.min(goalBackstopMaxSeconds * 1000, GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS)
17
- : GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS;
18
- return Math.max(GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS, Math.min(cacheSafeWaitSeconds * 1000, configuredCeilingMs));
29
+ ? goalBackstopMaxSeconds * 1000
30
+ : GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS;
31
+ return Math.max(GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS, Math.min(configuredMs, GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS));
19
32
  }
20
33
  export function createGoalCacheWarmScheduleData(options) {
21
34
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"cache-warm.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/cache-warm.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAGrE,4EAA4E;AAC5E,MAAM,CAAC,MAAM,4BAA4B,GAAG,mBAAmB,CAAC;AAEhE,MAAM,CAAC,MAAM,2CAA2C,GAAG,OAAO,CAAC;AACnE,MAAM,sCAAsC,GAAG,KAAK,CAAC;AACrD,MAAM,yCAAyC,GAAG,SAAS,CAAC;AAE5D,MAAM,UAAU,qCAAqC,CACpD,oBAAwC,EACxC,sBAA+B;IAE/B,IACC,OAAO,oBAAoB,KAAK,QAAQ;QACxC,CAAC,MAAM,CAAC,QAAQ,CAAC,oBAAoB,CAAC;QACtC,oBAAoB,IAAI,CAAC,EACxB,CAAC;QACF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AI,KAAK,GAAG,MAAM;QAAE,OAAO,SAAS,CAAC;IACrC,IAAI,KAAK,GAAG,CAAC;QAAE,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;IAC7C,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACtC,OAAO,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAC1D,CAAC;AAED,SAAS,WAAW,CAAC,KAAyB;IAC7C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACjG,CAAC;AAED,SAAS,aAAa,CAAC,GAAsB;IAC5C,MAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAChD,IAAI,KAAK,KAAK,SAAS;YAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IAChD,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC","sourcesContent":["import type { Api, Model, ProviderEnv } from \"@earendil-works/pi-ai\";\nimport { resolvePromptCacheTtlSeconds } from \"@earendil-works/pi-ai\";\nimport type { TokenUsageSnapshot } from \"./types.ts\";\n\n/** Custom session-entry type carrying the cache-warm continuation story. */\nexport const GOAL_CACHE_WARMUP_ENTRY_TYPE = \"goal-cache-warmup\";\n\nexport const GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS = 240_000;\nconst GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS = 1_000;\nconst GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS = 3_600_000;\n\nexport function resolveGoalMonitorContinuationDelayMs(\n\tcacheSafeWaitSeconds: number | undefined,\n\tgoalBackstopMaxSeconds?: number,\n): number {\n\tif (\n\t\ttypeof cacheSafeWaitSeconds !== \"number\" ||\n\t\t!Number.isFinite(cacheSafeWaitSeconds) ||\n\t\tcacheSafeWaitSeconds <= 0\n\t) {\n\t\treturn GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS;\n\t}\n\tconst configuredCeilingMs =\n\t\ttypeof goalBackstopMaxSeconds === \"number\" &&\n\t\tNumber.isFinite(goalBackstopMaxSeconds) &&\n\t\tgoalBackstopMaxSeconds > 0\n\t\t\t? Math.min(goalBackstopMaxSeconds * 1000, GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS)\n\t\t\t: GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS;\n\treturn Math.max(GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS, Math.min(cacheSafeWaitSeconds * 1000, configuredCeilingMs));\n}\n\n/** Cache context captured when a monitor-wait continuation is scheduled. */\nexport interface GoalCacheWarmMetrics {\n\t/** Prompt-cache TTL of the active model in seconds, when known. */\n\treadonly ttlSeconds?: number;\n\t/** Tokens sitting warm in the provider prompt cache after the last turn. */\n\treadonly cachedTokens: number;\n\t/** Estimated USD saved by re-reading those tokens from cache instead of paying a cold input read. */\n\treadonly estimatedSavedUsd?: number;\n}\n\nexport type GoalCacheWarmupPhase = \"scheduled\" | \"resumed\";\n\n/**\n * Durable payload appended as a `goal-cache-warmup` custom entry and carried by\n * the `goal_continuation_scheduled` / `goal_continuation_resumed` pi-events, so\n * external consumers (for example omo-desktop-app) can render the story later.\n */\nexport interface GoalCacheWarmupEntryData {\n\treadonly phase: GoalCacheWarmupPhase;\n\treadonly goalId: string;\n\t/** Display ordinal within the current in-memory Goal/wake epoch; absent on legacy persisted entries. */\n\treadonly iteration?: number;\n\t/** Planned continuation delay in milliseconds. */\n\treadonly delayMs: number;\n\t/** Epoch milliseconds when the scheduled continuation is expected to resume. */\n\treadonly dueAtMs?: number;\n\t/** Actual wait in milliseconds; present on the `resumed` phase only. */\n\treadonly waitedMs?: number;\n\t/** Backward-compatible field containing the total active wake-source count. */\n\treadonly activeMonitorCount: number;\n\t/** Full source-keyed snapshot; absent on entries written before wake sources were generalized. */\n\treadonly wakeSources?: Readonly<Record<string, number>>;\n\treadonly cache?: GoalCacheWarmMetrics;\n}\n\n/** Live entries always carry an iteration; the ordinal is intentionally not persisted into Goal state. */\nexport type LiveGoalCacheWarmupEntryData = GoalCacheWarmupEntryData & { readonly iteration: number };\n\nexport type GoalCacheWarmScheduleData = Omit<LiveGoalCacheWarmupEntryData, \"phase\" | \"waitedMs\">;\n\nexport function createGoalCacheWarmScheduleData(options: {\n\treadonly goalId: string;\n\treadonly delayMs: number;\n\treadonly scheduledAtMs: number;\n\treadonly iteration: number;\n\treadonly activeMonitorCount: number;\n\treadonly wakeSources: Readonly<Record<string, number>>;\n\treadonly cache?: GoalCacheWarmMetrics;\n}): GoalCacheWarmScheduleData {\n\treturn {\n\t\tgoalId: options.goalId,\n\t\tdelayMs: options.delayMs,\n\t\tdueAtMs: options.scheduledAtMs + options.delayMs,\n\t\titeration: options.iteration,\n\t\tactiveMonitorCount: options.activeMonitorCount,\n\t\twakeSources: options.wakeSources,\n\t\t...(options.cache !== undefined ? { cache: options.cache } : {}),\n\t};\n}\n\nconst TOKENS_PER_PRICE_UNIT = 1_000_000;\n\nexport function estimateCacheWarmMetrics(\n\tmodel: Model<Api> | undefined,\n\tenv: NodeJS.ProcessEnv,\n\tlastTurnUsage: Pick<TokenUsageSnapshot, \"cacheRead\" | \"cacheWrite\"> | undefined,\n): GoalCacheWarmMetrics | undefined {\n\tconst cachedTokens = clampTokens(lastTurnUsage?.cacheRead) + clampTokens(lastTurnUsage?.cacheWrite);\n\tconst ttlSeconds = model === undefined ? undefined : resolvePromptCacheTtlSeconds(model, toProviderEnv(env));\n\tif (ttlSeconds === undefined && cachedTokens === 0) return undefined;\n\tconst estimatedSavedUsd =\n\t\tmodel !== undefined && cachedTokens > 0\n\t\t\t? (Math.max(0, model.cost.input - model.cost.cacheRead) * cachedTokens) / TOKENS_PER_PRICE_UNIT\n\t\t\t: undefined;\n\treturn {\n\t\tcachedTokens,\n\t\t...(ttlSeconds !== undefined ? { ttlSeconds } : {}),\n\t\t...(estimatedSavedUsd !== undefined ? { estimatedSavedUsd } : {}),\n\t};\n}\n\nexport function formatWarmTokenCount(tokens: number): string {\n\tif (tokens >= 1_000_000) return `${trimTrailingZero((tokens / 1_000_000).toFixed(1))}M`;\n\tif (tokens >= 1000) return `${trimTrailingZero((tokens / 1000).toFixed(1))}K`;\n\treturn String(Math.max(0, Math.trunc(tokens)));\n}\n\nexport function formatWakeDuration(ms: number): string {\n\tconst seconds = Math.round(ms / 1000);\n\tif (seconds < 60) return `${seconds}s`;\n\tconst minutes = Math.floor(seconds / 60);\n\tconst restSeconds = seconds % 60;\n\tif (minutes < 60) return restSeconds === 0 ? `${minutes}m` : `${minutes}m ${restSeconds}s`;\n\tconst hours = Math.floor(minutes / 60);\n\tconst restMinutes = minutes % 60;\n\treturn restMinutes === 0 ? `${hours}h` : `${hours}h ${restMinutes}m`;\n}\n\n/**\n * Wake timestamp shown in cache-warm notices. Rendered in the user's local\n * system timezone with its short zone label (for example `GMT+9`); falls back\n * to the legacy UTC shape when local timezone formatting is unavailable.\n */\nexport function formatWakeTimestamp(dueAtMs: number): string {\n\tconst date = new Date(dueAtMs);\n\tconst local = formatLocalWakeTimestamp(date);\n\tif (local !== undefined) return local;\n\treturn `${date.toISOString().slice(0, 16).replace(\"T\", \" \")} UTC`;\n}\n\nfunction formatLocalWakeTimestamp(date: Date): string | undefined {\n\ttry {\n\t\tconst parts = new Intl.DateTimeFormat(\"en-CA\", {\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"2-digit\",\n\t\t\tday: \"2-digit\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\thourCycle: \"h23\",\n\t\t\ttimeZoneName: \"short\",\n\t\t}).formatToParts(date);\n\t\tconst read = (type: string): string | undefined => parts.find((part) => part.type === type)?.value;\n\t\tconst year = read(\"year\");\n\t\tconst month = read(\"month\");\n\t\tconst day = read(\"day\");\n\t\tconst hour = read(\"hour\");\n\t\tconst minute = read(\"minute\");\n\t\tif (\n\t\t\tyear === undefined ||\n\t\t\tmonth === undefined ||\n\t\t\tday === undefined ||\n\t\t\thour === undefined ||\n\t\t\tminute === undefined\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst zone = read(\"timeZoneName\");\n\t\treturn `${year}-${month}-${day} ${hour}:${minute}${zone === undefined ? \"\" : ` ${zone}`}`;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function formatCacheTtl(seconds: number): string {\n\tif (seconds % 3600 === 0) return `${seconds / 3600}h`;\n\tif (seconds % 60 === 0) return `${seconds / 60}m`;\n\treturn `${seconds}s`;\n}\n\nexport function formatSavedUsd(value: number): string {\n\tif (value < 0.0005) return \"<$0.001\";\n\tif (value < 1) return `$${value.toFixed(3)}`;\n\treturn `$${value.toFixed(2)}`;\n}\n\nfunction trimTrailingZero(value: string): string {\n\treturn value.endsWith(\".0\") ? value.slice(0, -2) : value;\n}\n\nfunction clampTokens(value: number | undefined): number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;\n}\n\nfunction toProviderEnv(env: NodeJS.ProcessEnv): ProviderEnv {\n\tconst resolved: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (value !== undefined) resolved[key] = value;\n\t}\n\treturn resolved;\n}\n"]}
1
+ {"version":3,"file":"cache-warm.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/cache-warm.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,4BAA4B,E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":["import type { Api, Model, ProviderEnv } from \"@earendil-works/pi-ai\";\nimport { resolvePromptCacheTtlSeconds } from \"@earendil-works/pi-ai\";\nimport type { TokenUsageSnapshot } from \"./types.ts\";\n\n/** Custom session-entry type carrying the cache-warm continuation story. */\nexport const GOAL_CACHE_WARMUP_ENTRY_TYPE = \"goal-cache-warmup\";\n\n/**\n * Accounting fallback for a monitor continuation whose scheduled delay is no\n * longer known (a held timer restored across a reload). It is deliberately NOT\n * the armed delay: while a wake source is live the monitor arms the stall\n * backstop below, never a cache-safe-wait timer.\n */\nexport const GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS = 240_000;\n/** Default `promptCache.goalBackstopMaxSeconds` (settings-manager.ts) expressed in ms. */\nexport const GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS = 3_570_000;\nconst GOAL_MONITOR_CONTINUATION_MIN_DELAY_MS = 1_000;\nconst GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS = 3_600_000;\n\n/**\n * Delay of the goal-monitor stall backstop, in milliseconds.\n *\n * The backstop exists to break a stall, not to keep the prompt cache warm, so\n * it deliberately ignores the prompt-cache safe wait: a live wake source means\n * the goal resumes when that source delivers (the drain fire), not on a timer.\n * Configured through `promptCache.goalBackstopMaxSeconds`; a missing,\n * non-finite, or non-positive setting falls back to the 3570s default, and the\n * result is clamped into [1s, 1h].\n */\nexport function resolveGoalMonitorContinuationDelayMs(goalBackstopMaxSeconds: number | undefined): number {\n\tconst configuredMs =\n\t\ttypeof goalBackstopMaxSeconds === \"number\" &&\n\t\tNumber.isFinite(goalBackstopMaxSeconds) &&\n\t\tgoalBackstopMaxSeconds > 0\n\t\t\t? goalBackstopMaxSeconds * 1000\n\t\t\t: GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS;\n\treturn Math.max(\n\t\tGOAL_MONITOR_CONTINUATION_MIN_DELAY_MS,\n\t\tMath.min(configuredMs, GOAL_MONITOR_CONTINUATION_HARD_CEILING_MS),\n\t);\n}\n\n/** Cache context captured when a monitor-wait continuation is scheduled. */\nexport interface GoalCacheWarmMetrics {\n\t/** Prompt-cache TTL of the active model in seconds, when known. */\n\treadonly ttlSeconds?: number;\n\t/** Tokens sitting warm in the provider prompt cache after the last turn. */\n\treadonly cachedTokens: number;\n\t/** Estimated USD saved by re-reading those tokens from cache instead of paying a cold input read. */\n\treadonly estimatedSavedUsd?: number;\n}\n\nexport type GoalCacheWarmupPhase = \"scheduled\" | \"resumed\";\n\n/**\n * Durable payload appended as a `goal-cache-warmup` custom entry and carried by\n * the `goal_continuation_scheduled` / `goal_continuation_resumed` pi-events, so\n * external consumers (for example omo-desktop-app) can render the story later.\n */\nexport interface GoalCacheWarmupEntryData {\n\treadonly phase: GoalCacheWarmupPhase;\n\treadonly goalId: string;\n\t/** Display ordinal within the current in-memory Goal/wake epoch; absent on legacy persisted entries. */\n\treadonly iteration?: number;\n\t/** Planned continuation delay in milliseconds. */\n\treadonly delayMs: number;\n\t/** Epoch milliseconds when the scheduled continuation is expected to resume. */\n\treadonly dueAtMs?: number;\n\t/** Actual wait in milliseconds; present on the `resumed` phase only. */\n\treadonly waitedMs?: number;\n\t/** Backward-compatible field containing the total active wake-source count. */\n\treadonly activeMonitorCount: number;\n\t/** Full source-keyed snapshot; absent on entries written before wake sources were generalized. */\n\treadonly wakeSources?: Readonly<Record<string, number>>;\n\treadonly cache?: GoalCacheWarmMetrics;\n}\n\n/** Live entries always carry an iteration; the ordinal is intentionally not persisted into Goal state. */\nexport type LiveGoalCacheWarmupEntryData = GoalCacheWarmupEntryData & { readonly iteration: number };\n\nexport type GoalCacheWarmScheduleData = Omit<LiveGoalCacheWarmupEntryData, \"phase\" | \"waitedMs\">;\n\nexport function createGoalCacheWarmScheduleData(options: {\n\treadonly goalId: string;\n\treadonly delayMs: number;\n\treadonly scheduledAtMs: number;\n\treadonly iteration: number;\n\treadonly activeMonitorCount: number;\n\treadonly wakeSources: Readonly<Record<string, number>>;\n\treadonly cache?: GoalCacheWarmMetrics;\n}): GoalCacheWarmScheduleData {\n\treturn {\n\t\tgoalId: options.goalId,\n\t\tdelayMs: options.delayMs,\n\t\tdueAtMs: options.scheduledAtMs + options.delayMs,\n\t\titeration: options.iteration,\n\t\tactiveMonitorCount: options.activeMonitorCount,\n\t\twakeSources: options.wakeSources,\n\t\t...(options.cache !== undefined ? { cache: options.cache } : {}),\n\t};\n}\n\nconst TOKENS_PER_PRICE_UNIT = 1_000_000;\n\nexport function estimateCacheWarmMetrics(\n\tmodel: Model<Api> | undefined,\n\tenv: NodeJS.ProcessEnv,\n\tlastTurnUsage: Pick<TokenUsageSnapshot, \"cacheRead\" | \"cacheWrite\"> | undefined,\n): GoalCacheWarmMetrics | undefined {\n\tconst cachedTokens = clampTokens(lastTurnUsage?.cacheRead) + clampTokens(lastTurnUsage?.cacheWrite);\n\tconst ttlSeconds = model === undefined ? undefined : resolvePromptCacheTtlSeconds(model, toProviderEnv(env));\n\tif (ttlSeconds === undefined && cachedTokens === 0) return undefined;\n\tconst estimatedSavedUsd =\n\t\tmodel !== undefined && cachedTokens > 0\n\t\t\t? (Math.max(0, model.cost.input - model.cost.cacheRead) * cachedTokens) / TOKENS_PER_PRICE_UNIT\n\t\t\t: undefined;\n\treturn {\n\t\tcachedTokens,\n\t\t...(ttlSeconds !== undefined ? { ttlSeconds } : {}),\n\t\t...(estimatedSavedUsd !== undefined ? { estimatedSavedUsd } : {}),\n\t};\n}\n\nexport function formatWarmTokenCount(tokens: number): string {\n\tif (tokens >= 1_000_000) return `${trimTrailingZero((tokens / 1_000_000).toFixed(1))}M`;\n\tif (tokens >= 1000) return `${trimTrailingZero((tokens / 1000).toFixed(1))}K`;\n\treturn String(Math.max(0, Math.trunc(tokens)));\n}\n\nexport function formatWakeDuration(ms: number): string {\n\tconst seconds = Math.round(ms / 1000);\n\tif (seconds < 60) return `${seconds}s`;\n\tconst minutes = Math.floor(seconds / 60);\n\tconst restSeconds = seconds % 60;\n\tif (minutes < 60) return restSeconds === 0 ? `${minutes}m` : `${minutes}m ${restSeconds}s`;\n\tconst hours = Math.floor(minutes / 60);\n\tconst restMinutes = minutes % 60;\n\treturn restMinutes === 0 ? `${hours}h` : `${hours}h ${restMinutes}m`;\n}\n\n/**\n * Wake timestamp shown in cache-warm notices. Rendered in the user's local\n * system timezone with its short zone label (for example `GMT+9`); falls back\n * to the legacy UTC shape when local timezone formatting is unavailable.\n */\nexport function formatWakeTimestamp(dueAtMs: number): string {\n\tconst date = new Date(dueAtMs);\n\tconst local = formatLocalWakeTimestamp(date);\n\tif (local !== undefined) return local;\n\treturn `${date.toISOString().slice(0, 16).replace(\"T\", \" \")} UTC`;\n}\n\nfunction formatLocalWakeTimestamp(date: Date): string | undefined {\n\ttry {\n\t\tconst parts = new Intl.DateTimeFormat(\"en-CA\", {\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"2-digit\",\n\t\t\tday: \"2-digit\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\thourCycle: \"h23\",\n\t\t\ttimeZoneName: \"short\",\n\t\t}).formatToParts(date);\n\t\tconst read = (type: string): string | undefined => parts.find((part) => part.type === type)?.value;\n\t\tconst year = read(\"year\");\n\t\tconst month = read(\"month\");\n\t\tconst day = read(\"day\");\n\t\tconst hour = read(\"hour\");\n\t\tconst minute = read(\"minute\");\n\t\tif (\n\t\t\tyear === undefined ||\n\t\t\tmonth === undefined ||\n\t\t\tday === undefined ||\n\t\t\thour === undefined ||\n\t\t\tminute === undefined\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst zone = read(\"timeZoneName\");\n\t\treturn `${year}-${month}-${day} ${hour}:${minute}${zone === undefined ? \"\" : ` ${zone}`}`;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function formatCacheTtl(seconds: number): string {\n\tif (seconds % 3600 === 0) return `${seconds / 3600}h`;\n\tif (seconds % 60 === 0) return `${seconds / 60}m`;\n\treturn `${seconds}s`;\n}\n\nexport function formatSavedUsd(value: number): string {\n\tif (value < 0.0005) return \"<$0.001\";\n\tif (value < 1) return `$${value.toFixed(3)}`;\n\treturn `$${value.toFixed(2)}`;\n}\n\nfunction trimTrailingZero(value: string): string {\n\treturn value.endsWith(\".0\") ? value.slice(0, -2) : value;\n}\n\nfunction clampTokens(value: number | undefined): number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;\n}\n\nfunction toProviderEnv(env: NodeJS.ProcessEnv): ProviderEnv {\n\tconst resolved: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (value !== undefined) resolved[key] = value;\n\t}\n\treturn resolved;\n}\n"]}
@@ -3,6 +3,7 @@ export declare const REPETITION_BLOCKED_REASON = "repeated assistant output";
3
3
  export declare const LENGTH_EXHAUSTED_BLOCKED_REASON = "output truncation repeated";
4
4
  export declare const UNATTENDED_CONTINUATION_BLOCKED_REASON = "unattended continuation limit reached";
5
5
  export declare const PROVIDER_ERROR_BLOCKED_REASON = "provider error ended the turn (retries exhausted)";
6
+ export declare const CONTEXT_OVERFLOW_BLOCKED_REASON = "context overflow ended the turn (compaction did not recover)";
6
7
  export declare function isMechanicalContinuationBlock(blockedReason: string | undefined): boolean;
7
8
  export declare function continuationCapRecoveryHint(blockedReason: string): string;
8
9
  //# sourceMappingURL=continuation-recovery.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"continuation-recovery.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/continuation-recovery.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,+BAA+B,6BAA6B,CAAC;AAC1E,eAAO,MAAM,yBAAyB,8BAA8B,CAAC;AACrE,eAAO,MAAM,+BAA+B,+BAA+B,CAAC;AAC5E,eAAO,MAAM,sCAAsC,0CAA0C,CAAC;AAC9F,eAAO,MAAM,6BAA6B,sDAAsD,CAAC;AAiBjG,wBAAgB,6BAA6B,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAGxF;AAED,wBAAgB,2BAA2B,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAGzE"}
1
+ {"version":3,"file":"continuation-recovery.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/continuation-recovery.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,+BAA+B,6BAA6B,CAAC;AAC1E,eAAO,MAAM,yBAAyB,8BAA8B,CAAC;AACrE,eAAO,MAAM,+BAA+B,+BAA+B,CAAC;AAC5E,eAAO,MAAM,sCAAsC,0CAA0C,CAAC;AAC9F,eAAO,MAAM,6BAA6B,sDAAsD,CAAC;AACjG,eAAO,MAAM,+BAA+B,iEAAiE,CAAC;AAkB9G,wBAAgB,6BAA6B,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAGxF;AAED,wBAAgB,2BAA2B,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAGzE"}
@@ -3,6 +3,7 @@ export const REPETITION_BLOCKED_REASON = "repeated assistant output";
3
3
  export const LENGTH_EXHAUSTED_BLOCKED_REASON = "output truncation repeated";
4
4
  export const UNATTENDED_CONTINUATION_BLOCKED_REASON = "unattended continuation limit reached";
5
5
  export const PROVIDER_ERROR_BLOCKED_REASON = "provider error ended the turn (retries exhausted)";
6
+ export const CONTEXT_OVERFLOW_BLOCKED_REASON = "context overflow ended the turn (compaction did not recover)";
6
7
  // Mechanical blocks are stops the runtime imposed on itself, not decisions the
7
8
  // user or the model made. A terminal provider error belongs here: the provider
8
9
  // failing is infrastructure, and the user's next message is exactly the retry
@@ -14,6 +15,7 @@ const MECHANICAL_CONTINUATION_BLOCKS = [
14
15
  LENGTH_EXHAUSTED_BLOCKED_REASON,
15
16
  UNATTENDED_CONTINUATION_BLOCKED_REASON,
16
17
  PROVIDER_ERROR_BLOCKED_REASON,
18
+ CONTEXT_OVERFLOW_BLOCKED_REASON,
17
19
  ];
18
20
  const RESUME_GUIDANCE = "Send any message to resume.";
19
21
  export function isMechanicalContinuationBlock(blockedReason) {
@@ -1 +1 @@
1
- {"version":3,"file":"continuation-recovery.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/continuation-recovery.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,+BAA+B,GAAG,0BAA0B,CAAC;AAC1E,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AACrE,MAAM,CAAC,MAAM,+BAA+B,GAAG,4BAA4B,CAAC;AAC5E,MAAM,CAAC,MAAM,sCAAsC,GAAG,uCAAuC,CAAC;AAC9F,MAAM,CAAC,MAAM,6BAA6B,GAAG,mDAAmD,CAAC;AAEjG,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,4EAA4E;AAC5E,8BAA8B;AAC9B,MAAM,8BAA8B,GAAsB;IACzD,+BAA+B;IAC/B,yBAAyB;IACzB,+BAA+B;IAC/B,sCAAsC;IACtC,6BAA6B;CAC7B,CAAC;AAEF,MAAM,eAAe,GAAG,6BAA6B,CAAC;AAEtD,MAAM,UAAU,6BAA6B,CAAC,aAAiC;IAC9E,IAAI,aAAa,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAC9C,OAAO,8BAA8B,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;AAC/D,CAAC;AAED,MAAM,UAAU,2BAA2B,CAAC,aAAqB;IAChE,IAAI,CAAC,6BAA6B,CAAC,aAAa,CAAC;QAAE,OAAO,8BAA8B,aAAa,EAAE,CAAC;IACxG,OAAO,8BAA8B,aAAa,KAAK,eAAe,EAAE,CAAC;AAC1E,CAAC","sourcesContent":["export const CONTINUATION_CAP_BLOCKED_REASON = \"continuation cap reached\";\nexport const REPETITION_BLOCKED_REASON = \"repeated assistant output\";\nexport const LENGTH_EXHAUSTED_BLOCKED_REASON = \"output truncation repeated\";\nexport const UNATTENDED_CONTINUATION_BLOCKED_REASON = \"unattended continuation limit reached\";\nexport const PROVIDER_ERROR_BLOCKED_REASON = \"provider error ended the turn (retries exhausted)\";\n\n// Mechanical blocks are stops the runtime imposed on itself, not decisions the\n// user or the model made. A terminal provider error belongs here: the provider\n// failing is infrastructure, and the user's next message is exactly the retry\n// signal, so the goal resumes instead of stranding behind a block that only\n// `/goal resume` could clear.\nconst MECHANICAL_CONTINUATION_BLOCKS: readonly string[] = [\n\tCONTINUATION_CAP_BLOCKED_REASON,\n\tREPETITION_BLOCKED_REASON,\n\tLENGTH_EXHAUSTED_BLOCKED_REASON,\n\tUNATTENDED_CONTINUATION_BLOCKED_REASON,\n\tPROVIDER_ERROR_BLOCKED_REASON,\n];\n\nconst RESUME_GUIDANCE = \"Send any message to resume.\";\n\nexport function isMechanicalContinuationBlock(blockedReason: string | undefined): boolean {\n\tif (blockedReason === undefined) return false;\n\treturn MECHANICAL_CONTINUATION_BLOCKS.includes(blockedReason);\n}\n\nexport function continuationCapRecoveryHint(blockedReason: string): string {\n\tif (!isMechanicalContinuationBlock(blockedReason)) return `Goal continuation blocked: ${blockedReason}`;\n\treturn `Goal continuation blocked: ${blockedReason}. ${RESUME_GUIDANCE}`;\n}\n"]}
1
+ {"version":3,"file":"continuation-recovery.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/continuation-recovery.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,+BAA+B,GAAG,0BAA0B,CAAC;AAC1E,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AACrE,MAAM,CAAC,MAAM,+BAA+B,GAAG,4BAA4B,CAAC;AAC5E,MAAM,CAAC,MAAM,sCAAsC,GAAG,uCAAuC,CAAC;AAC9F,MAAM,CAAC,MAAM,6BAA6B,GAAG,mDAAmD,CAAC;AACjG,MAAM,CAAC,MAAM,+BAA+B,GAAG,8DAA8D,CAAC;AAE9G,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,4EAA4E;AAC5E,8BAA8B;AAC9B,MAAM,8BAA8B,GAAsB;IACzD,+BAA+B;IAC/B,yBAAyB;IACzB,+BAA+B;IAC/B,sCAAsC;IACtC,6BAA6B;IAC7B,+BAA+B;CAC/B,CAAC;AAEF,MAAM,eAAe,GAAG,6BAA6B,CAAC;AAEtD,MAAM,UAAU,6BAA6B,CAAC,aAAiC;IAC9E,IAAI,aAAa,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAC9C,OAAO,8BAA8B,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;AAC/D,CAAC;AAED,MAAM,UAAU,2BAA2B,CAAC,aAAqB;IAChE,IAAI,CAAC,6BAA6B,CAAC,aAAa,CAAC;QAAE,OAAO,8BAA8B,aAAa,EAAE,CAAC;IACxG,OAAO,8BAA8B,aAAa,KAAK,eAAe,EAAE,CAAC;AAC1E,CAAC","sourcesContent":["export const CONTINUATION_CAP_BLOCKED_REASON = \"continuation cap reached\";\nexport const REPETITION_BLOCKED_REASON = \"repeated assistant output\";\nexport const LENGTH_EXHAUSTED_BLOCKED_REASON = \"output truncation repeated\";\nexport const UNATTENDED_CONTINUATION_BLOCKED_REASON = \"unattended continuation limit reached\";\nexport const PROVIDER_ERROR_BLOCKED_REASON = \"provider error ended the turn (retries exhausted)\";\nexport const CONTEXT_OVERFLOW_BLOCKED_REASON = \"context overflow ended the turn (compaction did not recover)\";\n\n// Mechanical blocks are stops the runtime imposed on itself, not decisions the\n// user or the model made. A terminal provider error belongs here: the provider\n// failing is infrastructure, and the user's next message is exactly the retry\n// signal, so the goal resumes instead of stranding behind a block that only\n// `/goal resume` could clear.\nconst MECHANICAL_CONTINUATION_BLOCKS: readonly string[] = [\n\tCONTINUATION_CAP_BLOCKED_REASON,\n\tREPETITION_BLOCKED_REASON,\n\tLENGTH_EXHAUSTED_BLOCKED_REASON,\n\tUNATTENDED_CONTINUATION_BLOCKED_REASON,\n\tPROVIDER_ERROR_BLOCKED_REASON,\n\tCONTEXT_OVERFLOW_BLOCKED_REASON,\n];\n\nconst RESUME_GUIDANCE = \"Send any message to resume.\";\n\nexport function isMechanicalContinuationBlock(blockedReason: string | undefined): boolean {\n\tif (blockedReason === undefined) return false;\n\treturn MECHANICAL_CONTINUATION_BLOCKS.includes(blockedReason);\n}\n\nexport function continuationCapRecoveryHint(blockedReason: string): string {\n\tif (!isMechanicalContinuationBlock(blockedReason)) return `Goal continuation blocked: ${blockedReason}`;\n\treturn `Goal continuation blocked: ${blockedReason}. ${RESUME_GUIDANCE}`;\n}\n"]}
@@ -29,6 +29,8 @@ export type GoalContinuationInput = {
29
29
  readonly recentNormalizedOutputHashes: readonly string[];
30
30
  readonly toollessContinuationStreak: number;
31
31
  readonly continuationPending: boolean;
32
+ /** The last turn was rejected (or silently starved) by context size and recovery did not shrink it. */
33
+ readonly lastTurnStuckOnContextOverflow: boolean;
32
34
  };
33
35
  export type GoalContinuationVerdict = {
34
36
  kind: "continue";
@@ -36,7 +38,7 @@ export type GoalContinuationVerdict = {
36
38
  stallNotice: boolean;
37
39
  } | {
38
40
  kind: "deny";
39
- reason: "not-eligible" | "single-flight" | "cap" | "stale" | "repetition" | "length-exhausted" | "unattended";
41
+ reason: "not-eligible" | "single-flight" | "cap" | "stale" | "repetition" | "length-exhausted" | "unattended" | "context-overflow";
40
42
  };
41
43
  export declare function shouldQueueGoalContinuationWhenIdle(goal: Goal | null, isIdle: boolean, hasPendingMessages: boolean): goal is Goal;
42
44
  export declare function shouldQueueGoalContinuationAfterAgentEnd(goal: Goal | null, hasPendingMessages: boolean, messages: readonly AgentMessage[]): goal is Goal;
@@ -1 +1 @@
1
- {"version":3,"file":"continuation.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/continuation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,KAAK,qBAAqB,GAAG,OAAO,CAAC,YAAY,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,CAAC;AAG1E,eAAO,MAAM,q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KAAK,GAAG,OAAO,GAAG,YAAY,GAAG,kBAAkB,GAAG,YAAY,CAAC;CAC7G,CAAC;AAEL,wBAAgB,mCAAmC,CAClD,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,MAAM,EAAE,OAAO,EACf,kBAAkB,EAAE,OAAO,GACzB,IAAI,IAAI,IAAI,CAEd;AAED,wBAAgB,wCAAwC,CACvD,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,kBAAkB,EAAE,OAAO,EAC3B,QAAQ,EAAE,SAAS,YAAY,EAAE,GAC/B,IAAI,IAAI,IAAI,CAEd;AAmCD,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,qBAAqB,GAAG,uBAAuB,CAuB9F;AAED,yFAAyF;AACzF,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,uFAAuF;AACvF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQtD;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,CAC7C,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,EACtB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,qBAAqB,EAAE,MAAM,GAC3B,MAAM,CAER;AAED,wBAAgB,2BAA2B,CAC1C,KAAK,EAAE,IAAI,CAAC,qBAAqB,EAAE,2BAA2B,GAAG,kBAAkB,CAAC,GAClF,OAAO,CAMT;AAED,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,OAAO,CAKpF"}
1
+ {"version":3,"file":"continuation.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/continuation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,KAAK,qBAAqB,GAAG,OAAO,CAAC,YAAY,EAAE;I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AG,SAAS,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,GACtE;IACA,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EACH,cAAc,GACd,eAAe,GACf,KAAK,GACL,OAAO,GACP,YAAY,GACZ,kBAAkB,GAClB,YAAY,GACZ,kBAAkB,CAAC;CACrB,CAAC;AAEL,wBAAgB,mCAAmC,CAClD,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,MAAM,EAAE,OAAO,EACf,kBAAkB,EAAE,OAAO,GACzB,IAAI,IAAI,IAAI,CAEd;AAED,wBAAgB,wCAAwC,CACvD,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,kBAAkB,EAAE,OAAO,EAC3B,QAAQ,EAAE,SAAS,YAAY,EAAE,GAC/B,IAAI,IAAI,IAAI,CAEd;AAmCD,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,qBAAqB,GAAG,uBAAuB,CA2B9F;AAED,yFAAyF;AACzF,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,uFAAuF;AACvF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQtD;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,CAC7C,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,EACtB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,qBAAqB,EAAE,MAAM,GAC3B,MAAM,CAER;AAED,wBAAgB,2BAA2B,CAC1C,KAAK,EAAE,IAAI,CAAC,qBAAqB,EAAE,2BAA2B,GAAG,kBAAkB,CAAC,GAClF,OAAO,CAMT;AAED,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,OAAO,CAKpF"}
@@ -48,6 +48,10 @@ function isAbortedToolResult(message) {
48
48
  return message.content.some((content) => content.type === "text" && /\babort(?:ed)?\b/i.test(content.text));
49
49
  }
50
50
  export function evaluateGoalContinuation(input) {
51
+ // Re-sending an overflowed context fails identically on every path (#1422).
52
+ if (input.goal?.status === "active" && input.lastTurnStuckOnContextOverflow) {
53
+ return { kind: "deny", reason: "context-overflow" };
54
+ }
51
55
  if (!isEligibleForGoalContinuation(input))
52
56
  return { kind: "deny", reason: "not-eligible" };
53
57
  if (input.continuationPending)
@@ -1 +1 @@
1
- {"version":3,"file":"continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/continuation.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AACvC,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAC;AAC7C,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAC5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,GAAG,CAAC;AACtD,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAgC/C,MAAM,UAAU,mCAAmC,CAClD,IAAiB,EACjB,MAAe,EACf,kBAA2B;IAE3B,OAAO,IAAI,EAAE,MAAM,KAAK,QAAQ,IAAI,MAAM,IAAI,CAAC,kBAAkB,CAAC;AACnE,CAAC;AAED,MAAM,UAAU,wCAAwC,CACvD,IAAiB,EACjB,kBAA2B,EAC3B,QAAiC;IAEjC,OAAO,IAAI,EAAE,MAAM,KAAK,QAAQ,IAAI,CAAC,kBAAkB,IAAI,kBAAkB,CAAC,QAAQ,CAAC,CAAC;AACzF,CAAC;AAED,SAAS,kBAAkB,CAAC,QAAiC;IAC5D,MAAM,kBAAkB,GAAG,6BAA6B,CAAC,QAAQ,CAAC,CAAC;IACnE,IAAI,kBAAkB,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAEnD,MAAM,aAAa,GAAG,QAAQ,CAAC,kBAAkB,CAAC,CAAC;IACnD,IAAI,aAAa,EAAE,IAAI,KAAK,WAAW,IA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C,KAAK,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC;QACzF,MAAM,IAAI,CAAC,CAAC;IACb,CAAC;IACD,OAAO,MAAM,IAAI,2BAA2B,CAAC;AAC9C,CAAC;AAED,SAAS,qBAAqB,CAAC,KAA4B;IAC1D,OAAO,KAAK,CAAC,0BAA0B,IAAI,6BAA6B,CAAC;AAC1E,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Goal } from \"./types.ts\";\n\ntype AssistantAgentMessage = Extract<AgentMessage, { role: \"assistant\" }>;\ntype ToolResultAgentMessage = Extract<AgentMessage, { role: \"toolResult\" }>;\n\nexport const GOAL_CONTINUATION_CAP = 8;\nexport const GOAL_STALL_TOOLLESS_THRESHOLD = 3;\nexport const GOAL_REPETITION_HASH_STREAK = 3;\nexport const GOAL_LENGTH_RECOVERY_LIMIT = 1;\n/**\n * Hard budget of automatic continuations without accepted direct user input (#1139).\n * Progress and tool use never refill it: only direct input does. Stays above the\n * #447 distinct-progress pin (50) and an 8-hour monitor-backstop cadence\n * (~120 deliveries at 240s), below the observed 289-continuation incident run.\n */\nexport const GOAL_UNATTENDED_CONTINUATION_LIMIT = 150;\nexport const GOAL_USER_GRACE_DELAY_MS = 10_000;\n\nexport type GoalContinuationPath =\n\t| \"immediate\"\n\t| \"monitorDelayed\"\n\t| \"userGrace\"\n\t| \"sessionStart\"\n\t| \"systemRecovery\"\n\t| \"providerRecovery\";\n\nexport type GoalContinuationInput = {\n\treadonly goal: Goal | null;\n\treadonly isIdle: boolean;\n\treadonly hasPendingMessages: boolean;\n\treadonly path: GoalContinuationPath;\n\treadonly lastStopReason: AssistantAgentMessage[\"stopReason\"] | undefined;\n\treadonly consecutiveContinuations: number;\n\treadonly lastContinuationSignature: string | undefined;\n\treadonly currentSignature: string | undefined;\n\treadonly consecutiveLengthRecoveries: number;\n\treadonly recentNormalizedOutputHashes: readonly string[];\n\treadonly toollessContinuationStreak: number;\n\treadonly continuationPending: boolean;\n};\n\nexport type GoalContinuationVerdict =\n\t| { kind: \"continue\"; prompt: \"full\" | \"minimal\"; stallNotice: boolean }\n\t| {\n\t\t\tkind: \"deny\";\n\t\t\treason: \"not-eligible\" | \"single-flight\" | \"cap\" | \"stale\" | \"repetition\" | \"length-exhausted\" | \"unattended\";\n\t };\n\nexport function shouldQueueGoalContinuationWhenIdle(\n\tgoal: Goal | null,\n\tisIdle: boolean,\n\thasPendingMessages: boolean,\n): goal is Goal {\n\treturn goal?.status === \"active\" && isIdle && !hasPendingMessages;\n}\n\nexport function shouldQueueGoalContinuationAfterAgentEnd(\n\tgoal: Goal | null,\n\thasPendingMessages: boolean,\n\tmessages: readonly AgentMessage[],\n): goal is Goal {\n\treturn goal?.status === \"active\" && !hasPendingMessages && didAgentEndCleanly(messages);\n}\n\nfunction didAgentEndCleanly(messages: readonly AgentMessage[]): boolean {\n\tconst lastAssistantIndex = findLastAssistantMessageIndex(messages);\n\tif (lastAssistantIndex === undefined) return false;\n\n\tconst lastAssistant = messages[lastAssistantIndex];\n\tif (lastAssistant?.role !== \"assistant\" || !isContinuableStopReason(lastAssistant.stopReason)) return false;\n\n\tfor (let index = lastAssistantIndex + 1; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"toolResult\" && isAbortedToolResult(message)) return false;\n\t}\n\treturn true;\n}\n\nfunction findLastAssistantMessageIndex(messages: readonly AgentMessage[]): number | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"assistant\") {\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isContinuableStopReason(stopReason: AssistantAgentMessage[\"stopReason\"]): boolean {\n\treturn stopReason === \"stop\" || stopReason === \"length\";\n}\n\nfunction isAbortedToolResult(message: ToolResultAgentMessage): boolean {\n\tif (!message.isError) return false;\n\treturn message.content.some((content) => content.type === \"text\" && /\\babort(?:ed)?\\b/i.test(content.text));\n}\n\nexport function evaluateGoalContinuation(input: GoalContinuationInput): GoalContinuationVerdict {\n\tif (!isEligibleForGoalContinuation(input)) return { kind: \"deny\", reason: \"not-eligible\" };\n\tif (input.continuationPending) return { kind: \"deny\", reason: \"single-flight\" };\n\tif (hasRepeatedNormalizedOutputHash(input.recentNormalizedOutputHashes))\n\t\treturn { kind: \"deny\", reason: \"repetition\" };\n\tif (isUnattendedBudgetExhausted(input)) return { kind: \"deny\", reason: \"unattended\" };\n\tif (input.consecutiveContinuations >= GOAL_CONTINUATION_CAP) {\n\t\treturn { kind: \"deny\", reason: \"cap\" };\n\t}\n\tif (\n\t\t(input.path === \"immediate\" || input.path === \"userGrace\") &&\n\t\tinput.lastContinuationSignature !== undefined &&\n\t\tinput.lastContinuationSignature === input.currentSignature\n\t) {\n\t\treturn { kind: \"deny\", reason: \"stale\" };\n\t}\n\tif (input.lastStopReason === \"length\") {\n\t\tif (input.consecutiveLengthRecoveries >= GOAL_LENGTH_RECOVERY_LIMIT) {\n\t\t\treturn { kind: \"deny\", reason: \"length-exhausted\" };\n\t\t}\n\t\treturn { kind: \"continue\", prompt: \"minimal\", stallNotice: shouldShowStallNotice(input) };\n\t}\n\treturn { kind: \"continue\", prompt: \"full\", stallNotice: shouldShowStallNotice(input) };\n}\n\n/** Produces a stable, whitespace-insensitive representation for repetition detection. */\nexport function normalizeAssistantText(text: string): string {\n\treturn text.toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\n/** Hashes normalized assistant text with the deterministic 32-bit FNV-1a algorithm. */\nexport function hashAssistantText(text: string): string {\n\tconst normalized = normalizeAssistantText(text);\n\tlet hash = 0x811c9dc5;\n\tfor (let index = 0; index < normalized.length; index++) {\n\t\thash ^= normalized.charCodeAt(index);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Identifies the observable goal progress for stale-continuation admission.\n * Deliberately excludes goal.updatedAt because usage accounting updates it after every agent turn.\n */\nexport function buildGoalContinuationSignature(\n\tgoal: Pick<Goal, \"id\">,\n\topenTodos: number,\n\ttotalTodos: number,\n\tlastAssistantTextHash: string,\n): string {\n\treturn `${goal.id}:${openTodos}/${totalTodos}:${lastAssistantTextHash}`;\n}\n\nexport function hasGoalContinuationProgress(\n\tinput: Pick<GoalContinuationInput, \"lastContinuationSignature\" | \"currentSignature\">,\n): boolean {\n\treturn (\n\t\tinput.lastContinuationSignature !== undefined &&\n\t\tinput.currentSignature !== undefined &&\n\t\tinput.lastContinuationSignature !== input.currentSignature\n\t);\n}\n\nexport function continuationTurnUsedTools(messages: readonly AgentMessage[]): boolean {\n\treturn messages.some((message) => {\n\t\tif (message?.role === \"toolResult\") return true;\n\t\treturn message?.role === \"assistant\" && message.content.some((content) => content.type === \"toolCall\");\n\t});\n}\n\nfunction isEligibleForGoalContinuation(input: GoalContinuationInput): boolean {\n\tif (input.goal?.status !== \"active\" || input.hasPendingMessages) return false;\n\tif (input.path === \"systemRecovery\" || input.path === \"providerRecovery\") return true;\n\tif (input.path === \"immediate\") {\n\t\treturn input.lastStopReason !== undefined && isContinuableStopReason(input.lastStopReason);\n\t}\n\treturn input.isIdle;\n}\n\n/** Monitor-delayed deliveries are exempt: armed-wake waiting is by-design and rate-limited by the cache-aware timer. */\nfunction isUnattendedBudgetExhausted(input: GoalContinuationInput): boolean {\n\tif (input.path === \"monitorDelayed\") return false;\n\treturn (input.goal?.unattendedContinuations ?? 0) >= GOAL_UNATTENDED_CONTINUATION_LIMIT;\n}\n\nfunction hasRepeatedNormalizedOutputHash(hashes: readonly string[]): boolean {\n\tconst latestHash = hashes.at(-1);\n\tif (latestHash === undefined) return false;\n\n\tlet streak = 0;\n\tfor (let index = hashes.length - 1; index >= 0 && hashes[index] === latestHash; index--) {\n\t\tstreak += 1;\n\t}\n\treturn streak >= GOAL_REPETITION_HASH_STREAK;\n}\n\nfunction shouldShowStallNotice(input: GoalContinuationInput): boolean {\n\treturn input.toollessContinuationStreak >= GOAL_STALL_TOOLLES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AAK,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC;QACzF,MAAM,IAAI,CAAC,CAAC;IACb,CAAC;IACD,OAAO,MAAM,IAAI,2BAA2B,CAAC;AAC9C,CAAC;AAED,SAAS,qBAAqB,CAAC,KAA4B;IAC1D,OAAO,KAAK,CAAC,0BAA0B,IAAI,6BAA6B,CAAC;AAC1E,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Goal } from \"./types.ts\";\n\ntype AssistantAgentMessage = Extract<AgentMessage, { role: \"assistant\" }>;\ntype ToolResultAgentMessage = Extract<AgentMessage, { role: \"toolResult\" }>;\n\nexport const GOAL_CONTINUATION_CAP = 8;\nexport const GOAL_STALL_TOOLLESS_THRESHOLD = 3;\nexport const GOAL_REPETITION_HASH_STREAK = 3;\nexport const GOAL_LENGTH_RECOVERY_LIMIT = 1;\n/**\n * Hard budget of automatic continuations without accepted direct user input (#1139).\n * Progress and tool use never refill it: only direct input does. Stays above the\n * #447 distinct-progress pin (50) and an 8-hour monitor-backstop cadence\n * (~120 deliveries at 240s), below the observed 289-continuation incident run.\n */\nexport const GOAL_UNATTENDED_CONTINUATION_LIMIT = 150;\nexport const GOAL_USER_GRACE_DELAY_MS = 10_000;\n\nexport type GoalContinuationPath =\n\t| \"immediate\"\n\t| \"monitorDelayed\"\n\t| \"userGrace\"\n\t| \"sessionStart\"\n\t| \"systemRecovery\"\n\t| \"providerRecovery\";\n\nexport type GoalContinuationInput = {\n\treadonly goal: Goal | null;\n\treadonly isIdle: boolean;\n\treadonly hasPendingMessages: boolean;\n\treadonly path: GoalContinuationPath;\n\treadonly lastStopReason: AssistantAgentMessage[\"stopReason\"] | undefined;\n\treadonly consecutiveContinuations: number;\n\treadonly lastContinuationSignature: string | undefined;\n\treadonly currentSignature: string | undefined;\n\treadonly consecutiveLengthRecoveries: number;\n\treadonly recentNormalizedOutputHashes: readonly string[];\n\treadonly toollessContinuationStreak: number;\n\treadonly continuationPending: boolean;\n\t/** The last turn was rejected (or silently starved) by context size and recovery did not shrink it. */\n\treadonly lastTurnStuckOnContextOverflow: boolean;\n};\n\nexport type GoalContinuationVerdict =\n\t| { kind: \"continue\"; prompt: \"full\" | \"minimal\"; stallNotice: boolean }\n\t| {\n\t\t\tkind: \"deny\";\n\t\t\treason:\n\t\t\t\t| \"not-eligible\"\n\t\t\t\t| \"single-flight\"\n\t\t\t\t| \"cap\"\n\t\t\t\t| \"stale\"\n\t\t\t\t| \"repetition\"\n\t\t\t\t| \"length-exhausted\"\n\t\t\t\t| \"unattended\"\n\t\t\t\t| \"context-overflow\";\n\t };\n\nexport function shouldQueueGoalContinuationWhenIdle(\n\tgoal: Goal | null,\n\tisIdle: boolean,\n\thasPendingMessages: boolean,\n): goal is Goal {\n\treturn goal?.status === \"active\" && isIdle && !hasPendingMessages;\n}\n\nexport function shouldQueueGoalContinuationAfterAgentEnd(\n\tgoal: Goal | null,\n\thasPendingMessages: boolean,\n\tmessages: readonly AgentMessage[],\n): goal is Goal {\n\treturn goal?.status === \"active\" && !hasPendingMessages && didAgentEndCleanly(messages);\n}\n\nfunction didAgentEndCleanly(messages: readonly AgentMessage[]): boolean {\n\tconst lastAssistantIndex = findLastAssistantMessageIndex(messages);\n\tif (lastAssistantIndex === undefined) return false;\n\n\tconst lastAssistant = messages[lastAssistantIndex];\n\tif (lastAssistant?.role !== \"assistant\" || !isContinuableStopReason(lastAssistant.stopReason)) return false;\n\n\tfor (let index = lastAssistantIndex + 1; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"toolResult\" && isAbortedToolResult(message)) return false;\n\t}\n\treturn true;\n}\n\nfunction findLastAssistantMessageIndex(messages: readonly AgentMessage[]): number | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"assistant\") {\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isContinuableStopReason(stopReason: AssistantAgentMessage[\"stopReason\"]): boolean {\n\treturn stopReason === \"stop\" || stopReason === \"length\";\n}\n\nfunction isAbortedToolResult(message: ToolResultAgentMessage): boolean {\n\tif (!message.isError) return false;\n\treturn message.content.some((content) => content.type === \"text\" && /\\babort(?:ed)?\\b/i.test(content.text));\n}\n\nexport function evaluateGoalContinuation(input: GoalContinuationInput): GoalContinuationVerdict {\n\t// Re-sending an overflowed context fails identically on every path (#1422).\n\tif (input.goal?.status === \"active\" && input.lastTurnStuckOnContextOverflow) {\n\t\treturn { kind: \"deny\", reason: \"context-overflow\" };\n\t}\n\tif (!isEligibleForGoalContinuation(input)) return { kind: \"deny\", reason: \"not-eligible\" };\n\tif (input.continuationPending) return { kind: \"deny\", reason: \"single-flight\" };\n\tif (hasRepeatedNormalizedOutputHash(input.recentNormalizedOutputHashes))\n\t\treturn { kind: \"deny\", reason: \"repetition\" };\n\tif (isUnattendedBudgetExhausted(input)) return { kind: \"deny\", reason: \"unattended\" };\n\tif (input.consecutiveContinuations >= GOAL_CONTINUATION_CAP) {\n\t\treturn { kind: \"deny\", reason: \"cap\" };\n\t}\n\tif (\n\t\t(input.path === \"immediate\" || input.path === \"userGrace\") &&\n\t\tinput.lastContinuationSignature !== undefined &&\n\t\tinput.lastContinuationSignature === input.currentSignature\n\t) {\n\t\treturn { kind: \"deny\", reason: \"stale\" };\n\t}\n\tif (input.lastStopReason === \"length\") {\n\t\tif (input.consecutiveLengthRecoveries >= GOAL_LENGTH_RECOVERY_LIMIT) {\n\t\t\treturn { kind: \"deny\", reason: \"length-exhausted\" };\n\t\t}\n\t\treturn { kind: \"continue\", prompt: \"minimal\", stallNotice: shouldShowStallNotice(input) };\n\t}\n\treturn { kind: \"continue\", prompt: \"full\", stallNotice: shouldShowStallNotice(input) };\n}\n\n/** Produces a stable, whitespace-insensitive representation for repetition detection. */\nexport function normalizeAssistantText(text: string): string {\n\treturn text.toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\n/** Hashes normalized assistant text with the deterministic 32-bit FNV-1a algorithm. */\nexport function hashAssistantText(text: string): string {\n\tconst normalized = normalizeAssistantText(text);\n\tlet hash = 0x811c9dc5;\n\tfor (let index = 0; index < normalized.length; index++) {\n\t\thash ^= normalized.charCodeAt(index);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Identifies the observable goal progress for stale-continuation admission.\n * Deliberately excludes goal.updatedAt because usage accounting updates it after every agent turn.\n */\nexport function buildGoalContinuationSignature(\n\tgoal: Pick<Goal, \"id\">,\n\topenTodos: number,\n\ttotalTodos: number,\n\tlastAssistantTextHash: string,\n): string {\n\treturn `${goal.id}:${openTodos}/${totalTodos}:${lastAssistantTextHash}`;\n}\n\nexport function hasGoalContinuationProgress(\n\tinput: Pick<GoalContinuationInput, \"lastContinuationSignature\" | \"currentSignature\">,\n): boolean {\n\treturn (\n\t\tinput.lastContinuationSignature !== undefined &&\n\t\tinput.currentSignature !== undefined &&\n\t\tinput.lastContinuationSignature !== input.currentSignature\n\t);\n}\n\nexport function continuationTurnUsedTools(messages: readonly AgentMessage[]): boolean {\n\treturn messages.some((message) => {\n\t\tif (message?.role === \"toolResult\") return true;\n\t\treturn message?.role === \"assistant\" && message.content.some((content) => content.type === \"toolCall\");\n\t});\n}\n\nfunction isEligibleForGoalContinuation(input: GoalContinuationInput): boolean {\n\tif (input.goal?.status !== \"active\" || input.hasPendingMessages) return false;\n\tif (input.path === \"systemRecovery\" || input.path === \"providerRecovery\") return true;\n\tif (input.path === \"immediate\") {\n\t\treturn input.lastStopReason !== undefined && isContinuableStopReason(input.lastStopReason);\n\t}\n\treturn input.isIdle;\n}\n\n/** Monitor-delayed deliveries are exempt: armed-wake waiting is by-design and rate-limited by the cache-aware timer. */\nfunction isUnattendedBudgetExhausted(input: GoalContinuationInput): boolean {\n\tif (input.path === \"monitorDelayed\") return false;\n\treturn (input.goal?.unattendedContinuations ?? 0) >= GOAL_UNATTENDED_CONTINUATION_LIMIT;\n}\n\nfunction hasRepeatedNormalizedOutputHash(hashes: readonly string[]): boolean {\n\tconst latestHash = hashes.at(-1);\n\tif (latestHash === undefined) return false;\n\n\tlet streak = 0;\n\tfor (let index = hashes.length - 1; index >= 0 && hashes[index] === latestHash; index--) {\n\t\tstreak += 1;\n\t}\n\treturn streak >= GOAL_REPETITION_HASH_STREAK;\n}\n\nfunction shouldShowStallNotice(input: GoalContinuationInput): boolean {\n\treturn input.toollessContinuationStreak >= GOAL_STALL_TOOLLESS_THRESHOLD;\n}\n"]}
@@ -27,6 +27,9 @@ export declare function admitAndQueueGoalContinuation(pi: ExtensionAPI, ctx: Ext
27
27
  export declare function queueGoalContinuation(pi: ExtensionAPI, ctx: ExtensionContext, goal: Goal, options: SessionStartContinuationOptions): Promise<Goal | null>;
28
28
  export declare function buildCurrentGoalContinuationSignature(ctx: ExtensionContext, goal: Goal, lastAssistantText: string): string;
29
29
  export declare function lastAssistantText(messages: readonly AgentMessage[]): string;
30
+ export declare function isLastTurnStuckOnContextOverflow(ctx: ExtensionContext, lastAssistant: Extract<AgentMessage, {
31
+ role: "assistant";
32
+ }> | undefined): boolean;
30
33
  export declare function queueHiddenGoalPrompt(pi: ExtensionAPI, content: string): void;
31
34
  export {};
32
35
  //# sourceMappingURL=lifecycle-helpers.d.ts.map