@code-yeongyu/senpi 2026.8.26 → 2026.8.27

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 (231) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +3 -3
  3. package/dist/cli/args.d.ts +3 -1
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +14 -1
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/core/agent-session.d.ts.map +1 -1
  8. package/dist/core/agent-session.js +10 -1
  9. package/dist/core/agent-session.js.map +1 -1
  10. package/dist/core/bash-executor.d.ts.map +1 -1
  11. package/dist/core/bash-executor.js +67 -29
  12. package/dist/core/bash-executor.js.map +1 -1
  13. package/dist/core/credential-pool/classify.d.ts +42 -0
  14. package/dist/core/credential-pool/classify.d.ts.map +1 -0
  15. package/dist/core/credential-pool/classify.js +75 -0
  16. package/dist/core/credential-pool/classify.js.map +1 -0
  17. package/dist/core/credential-pool/env-slots.d.ts +22 -0
  18. package/dist/core/credential-pool/env-slots.d.ts.map +1 -0
  19. package/dist/core/credential-pool/env-slots.js +37 -0
  20. package/dist/core/credential-pool/env-slots.js.map +1 -0
  21. package/dist/core/credential-pool/failover.d.ts +54 -0
  22. package/dist/core/credential-pool/failover.d.ts.map +1 -0
  23. package/dist/core/credential-pool/failover.js +106 -0
  24. package/dist/core/credential-pool/failover.js.map +1 -0
  25. package/dist/core/credential-pool/rotation-stream.d.ts +43 -0
  26. package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -0
  27. package/dist/core/credential-pool/rotation-stream.js +96 -0
  28. package/dist/core/credential-pool/rotation-stream.js.map +1 -0
  29. package/dist/core/credential-pool/state-store.d.ts +89 -0
  30. package/dist/core/credential-pool/state-store.d.ts.map +1 -0
  31. package/dist/core/credential-pool/state-store.js +166 -0
  32. package/dist/core/credential-pool/state-store.js.map +1 -0
  33. package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
  34. package/dist/core/extensions/builtin/compaction/index.js +67 -0
  35. package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
  36. package/dist/core/extensions/builtin/compaction/log.d.ts +1 -1
  37. package/dist/core/extensions/builtin/compaction/log.d.ts.map +1 -1
  38. package/dist/core/extensions/builtin/compaction/log.js +1 -0
  39. package/dist/core/extensions/builtin/compaction/log.js.map +1 -1
  40. package/dist/core/extensions/builtin/config-reload/index.js +14 -22
  41. package/dist/core/extensions/builtin/config-reload/index.js.map +1 -1
  42. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts +1 -0
  43. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts.map +1 -1
  44. package/dist/core/extensions/builtin/goal/continuation-recovery.js +2 -0
  45. package/dist/core/extensions/builtin/goal/continuation-recovery.js.map +1 -1
  46. package/dist/core/extensions/builtin/goal/continuation.d.ts +8 -1
  47. package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
  48. package/dist/core/extensions/builtin/goal/continuation.js +15 -0
  49. package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
  50. package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js +2 -2
  51. package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js.map +1 -1
  52. package/dist/core/extensions/builtin/goal/format.d.ts +6 -1
  53. package/dist/core/extensions/builtin/goal/format.d.ts.map +1 -1
  54. package/dist/core/extensions/builtin/goal/format.js +6 -0
  55. package/dist/core/extensions/builtin/goal/format.js.map +1 -1
  56. package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts.map +1 -1
  57. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +5 -2
  58. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js.map +1 -1
  59. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  60. package/dist/core/extensions/builtin/goal/monitor-continuation.js +31 -7
  61. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  62. package/dist/core/extensions/builtin/goal/persistence.js +2 -0
  63. package/dist/core/extensions/builtin/goal/persistence.js.map +1 -1
  64. package/dist/core/extensions/builtin/goal/renderers.d.ts +14 -0
  65. package/dist/core/extensions/builtin/goal/renderers.d.ts.map +1 -0
  66. package/dist/core/extensions/builtin/goal/renderers.js +153 -0
  67. package/dist/core/extensions/builtin/goal/renderers.js.map +1 -0
  68. package/dist/core/extensions/builtin/goal/store.d.ts +6 -2
  69. package/dist/core/extensions/builtin/goal/store.d.ts.map +1 -1
  70. package/dist/core/extensions/builtin/goal/store.js +8 -2
  71. package/dist/core/extensions/builtin/goal/store.js.map +1 -1
  72. package/dist/core/extensions/builtin/goal/tool-registration.d.ts.map +1 -1
  73. package/dist/core/extensions/builtin/goal/tool-registration.js +16 -6
  74. package/dist/core/extensions/builtin/goal/tool-registration.js.map +1 -1
  75. package/dist/core/extensions/builtin/goal/types.d.ts +1 -0
  76. package/dist/core/extensions/builtin/goal/types.d.ts.map +1 -1
  77. package/dist/core/extensions/builtin/goal/types.js.map +1 -1
  78. package/dist/core/extensions/builtin/todotools/index.js +1 -1
  79. package/dist/core/extensions/builtin/todotools/index.js.map +1 -1
  80. package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts +1 -1
  81. package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts.map +1 -1
  82. package/dist/core/extensions/builtin/todotools/native-todo-mirror.js +1 -1
  83. package/dist/core/extensions/builtin/todotools/native-todo-mirror.js.map +1 -1
  84. package/dist/core/hidden-stdout-log.d.ts +10 -0
  85. package/dist/core/hidden-stdout-log.d.ts.map +1 -1
  86. package/dist/core/hidden-stdout-log.js +36 -5
  87. package/dist/core/hidden-stdout-log.js.map +1 -1
  88. package/dist/core/model-config-schema.d.ts +85 -12
  89. package/dist/core/model-config-schema.d.ts.map +1 -1
  90. package/dist/core/model-config-schema.js +25 -0
  91. package/dist/core/model-config-schema.js.map +1 -1
  92. package/dist/core/model-runtime.d.ts +34 -1
  93. package/dist/core/model-runtime.d.ts.map +1 -1
  94. package/dist/core/model-runtime.js +98 -5
  95. package/dist/core/model-runtime.js.map +1 -1
  96. package/dist/core/tools/output-accumulator.d.ts +2 -0
  97. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  98. package/dist/core/tools/output-accumulator.js +32 -7
  99. package/dist/core/tools/output-accumulator.js.map +1 -1
  100. package/dist/index.d.ts +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/index.js.map +1 -1
  104. package/dist/main.d.ts.map +1 -1
  105. package/dist/main.js +26 -2
  106. package/dist/main.js.map +1 -1
  107. package/dist/modes/index.d.ts +1 -0
  108. package/dist/modes/index.d.ts.map +1 -1
  109. package/dist/modes/index.js +1 -0
  110. package/dist/modes/index.js.map +1 -1
  111. package/dist/modes/interactive/components/tool-execution-fallback.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/tool-execution-fallback.js +82 -1
  113. package/dist/modes/interactive/components/tool-execution-fallback.js.map +1 -1
  114. package/dist/modes/interactive/interactive-host-runtime.d.ts +29 -0
  115. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -0
  116. package/dist/modes/interactive/interactive-host-runtime.js +244 -0
  117. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -0
  118. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  119. package/dist/modes/interactive/interactive-mode.js +46 -8
  120. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  121. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  122. package/dist/modes/rpc/connection-handler.js +7 -1
  123. package/dist/modes/rpc/connection-handler.js.map +1 -1
  124. package/dist/modes/rpc/host-ensure.d.ts +41 -0
  125. package/dist/modes/rpc/host-ensure.d.ts.map +1 -0
  126. package/dist/modes/rpc/host-ensure.js +245 -0
  127. package/dist/modes/rpc/host-ensure.js.map +1 -0
  128. package/dist/modes/rpc/host-lifecycle.d.ts +57 -0
  129. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -0
  130. package/dist/modes/rpc/host-lifecycle.js +491 -0
  131. package/dist/modes/rpc/host-lifecycle.js.map +1 -0
  132. package/dist/modes/rpc/host-watchdog.d.ts +33 -0
  133. package/dist/modes/rpc/host-watchdog.d.ts.map +1 -0
  134. package/dist/modes/rpc/host-watchdog.js +142 -0
  135. package/dist/modes/rpc/host-watchdog.js.map +1 -0
  136. package/dist/modes/rpc/multi-session-host.d.ts +7 -1
  137. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  138. package/dist/modes/rpc/multi-session-host.js +206 -32
  139. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  140. package/dist/modes/rpc/rpc-client.d.ts +25 -0
  141. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  142. package/dist/modes/rpc/rpc-client.js +83 -10
  143. package/dist/modes/rpc/rpc-client.js.map +1 -1
  144. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  145. package/dist/modes/rpc/rpc-mode.js +1 -1
  146. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  147. package/dist/modes/rpc/rpc-types.d.ts +2 -1
  148. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  149. package/dist/modes/rpc/rpc-types.js.map +1 -1
  150. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  151. package/dist/modes/rpc/session-command-router.js +12 -2
  152. package/dist/modes/rpc/session-command-router.js.map +1 -1
  153. package/dist/modes/rpc/session-event-writer.d.ts +13 -2
  154. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  155. package/dist/modes/rpc/session-event-writer.js +65 -25
  156. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  157. package/docs/rpc.md +53 -1
  158. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +30 -0
  159. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  160. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +711 -1
  161. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +10 -10
  162. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +9 -3
  163. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +6 -1
  164. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  165. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts +1 -1
  166. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts.map +1 -1
  167. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js +46 -14
  168. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js.map +1 -1
  169. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts +11 -0
  170. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts.map +1 -1
  171. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js +30 -16
  172. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
  173. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts +16 -0
  174. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts.map +1 -0
  175. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js +75 -0
  176. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js.map +1 -0
  177. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts +45 -0
  178. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts.map +1 -0
  179. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js +81 -0
  180. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js.map +1 -0
  181. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts +31 -0
  182. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts.map +1 -0
  183. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js +65 -0
  184. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js.map +1 -0
  185. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts +12 -0
  186. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts.map +1 -1
  187. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js +37 -0
  188. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js.map +1 -1
  189. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts +6 -0
  190. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts.map +1 -1
  191. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js +32 -6
  192. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js.map +1 -1
  193. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts +6 -0
  194. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  195. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +6 -1
  196. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  197. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +75 -0
  198. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  199. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +75 -0
  200. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  201. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  202. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  203. package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  204. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  205. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  206. package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  207. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  208. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  209. package/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  210. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  211. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  212. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  213. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  214. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  215. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  216. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  217. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  218. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
  219. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +4 -0
  220. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
  221. package/node_modules/@earendil-works/pi-ai/package.json +5 -5
  222. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  223. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  224. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +5 -0
  225. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
  226. package/node_modules/@earendil-works/pi-tui/dist/terminal.js +90 -1
  227. package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
  228. package/node_modules/@earendil-works/pi-tui/dist/tui.js +1 -1
  229. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  230. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  231. package/package.json +7 -7
@@ -51,6 +51,12 @@ export function formatGoalForTool(goal) {
51
51
  lines.push(`Completed at: ${new Date(goal.completedAt * 1000).toISOString()}`);
52
52
  return lines.join("\n");
53
53
  }
54
+ export function goalToolRenderDetails(goal, notice) {
55
+ return {
56
+ goal: goal === null ? null : goalToolSnapshot(goal),
57
+ ...(notice === undefined ? {} : { notice }),
58
+ };
59
+ }
54
60
  export function goalToolResponse(goal) {
55
61
  return { goal: goal === null ? null : goalToolSnapshot(goal) };
56
62
  }
@@ -1 +1 @@
1
- {"version":3,"file":"format.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/format.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,wBAAwB,CAAC,KAAa;IACrD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/C,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,OAAO,GAAG,CAAC;IAEvC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;IACzC,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,OAAO,GAAG,CAAC;IAEvC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;IACvC,MAAM,gBAAgB,GAAG,OAAO,GAAG,EAAE,CAAC;IACtC,IAAI,KAAK,IAAI,EAAE,EAAE,CAAC;QACjB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC,CAAC;QACpC,MAAM,cAAc,GAAG,KAAK,GAAG,EAAE,CAAC;QAClC,OAAO,GAAG,IAAI,KAAK,cAAc,KAAK,gBAAgB,GAAG,CAAC;IAC3D,CAAC;IAED,IAAI,gBAAgB,KAAK,CAAC;QAAE,OAAO,GAAG,KAAK,GAAG,CAAC;IAC/C,OAAO,GAAG,KAAK,KAAK,gBAAgB,GAAG,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAChD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,C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,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;AAChE,CAAC","sourcesContent":["import type { Goal, GoalStatus, GoalToolResponse, GoalToolSnapshot } from \"./types.ts\";\n\nexport function formatGoalElapsedSeconds(value: number): string {\n\tconst seconds = Math.max(0, Math.trunc(value));\n\tif (seconds < 60) return `${seconds}s`;\n\n\tconst minutes = Math.trunc(seconds / 60);\n\tif (minutes < 60) return `${minutes}m`;\n\n\tconst hours = Math.trunc(minutes / 60);\n\tconst remainingMinutes = minutes % 60;\n\tif (hours >= 24) {\n\t\tconst days = Math.trunc(hours / 24);\n\t\tconst remainingHours = hours % 24;\n\t\treturn `${days}d ${remainingHours}h ${remainingMinutes}m`;\n\t}\n\n\tif (remainingMinutes === 0) return `${hours}h`;\n\treturn `${hours}h ${remainingMinutes}m`;\n}\n\nexport function formatTokensCompact(value: number): string {\n\tconst abs = Math.abs(value);\n\tif (abs >= 1_000_000) return `${formatOneDecimal(value / 1_000_000)}M`;\n\tif (abs >= 1_000) return `${formatOneDecimal(value / 1_000)}K`;\n\treturn `${Math.trunc(value)}`;\n}\n\nexport function goalStatusLabel(status: GoalStatus): string {\n\tswitch (status) {\n\t\tcase \"active\":\n\t\t\treturn \"active\";\n\t\tcase \"paused\":\n\t\t\treturn \"paused\";\n\t\tcase \"blocked\":\n\t\t\treturn \"blocked\";\n\t\tcase \"complete\":\n\t\t\treturn \"complete\";\n\t}\n}\n\nexport function formatGoalForTool(goal: Goal | null): string {\n\tif (!goal) return \"No active goal is set.\";\n\tconst lines = [\n\t\t`Objective: ${goal.objective}`,\n\t\t`Status: ${goalStatusLabel(goal.status)}`,\n\t\t`Time used: ${formatGoalElapsedSeconds(goal.timeUsedSeconds)}`,\n\t\t`Tokens used: ${formatTokensCompact(goal.tokensUsed)}`,\n\t];\n\tif (goal.blockedReason) lines.push(`Blocked reason: ${goal.blockedReason}`);\n\tif (goal.completedAt) lines.push(`Completed at: ${new Date(goal.completedAt * 1000).toISOString()}`);\n\treturn lines.join(\"\\n\");\n}\n\nexport function goalToolResponse(goal: Goal | null): GoalToolResponse {\n\treturn { goal: goal === null ? null : goalToolSnapshot(goal) };\n}\n\nexport function formatGoalToolResponse(goal: Goal | null, notice?: string): string {\n\tconst response = JSON.stringify(goalToolResponse(goal), null, 2);\n\treturn notice === undefined ? response : `${response}\\n${notice}`;\n}\n\nfunction goalToolSnapshot(goal: Goal): GoalToolSnapshot {\n\treturn {\n\t\tthreadId: goal.threadId,\n\t\tobjective: goal.objective,\n\t\tstatus: goal.status,\n\t\ttokensUsed: goal.tokensUsed,\n\t\ttimeUsedSeconds: goal.timeUsedSeconds,\n\t\tcreatedAt: goal.createdAt,\n\t\tupdatedAt: goal.updatedAt,\n\t\t...(goal.blockedReason === undefined ? {} : { blockedReason: goal.blockedReason }),\n\t\t...(goal.blockedAt === undefined ? {} : { blockedAt: goal.blockedAt }),\n\t};\n}\n\nfunction formatOneDecimal(value: number): string {\n\tconst rounded = value.toFixed(1);\n\treturn rounded.endsWith(\".0\") ? rounded.slice(0, -2) : rounded;\n}\n"]}
1
+ {"version":3,"file":"format.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/format.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,wBAAwB,CAAC,KAAa;IACrD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/C,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,OAAO,GAAG,CAAC;IAEvC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;IACzC,IAAI,OAAO,GAAG,EAAE;QAAE,OAAO,GAAG,OAAO,GAAG,CAAC;IAEvC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;IACvC,MAAM,gBAAgB,G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AAC;AAED,SAAS,gBAAgB,CAAC,IAAU;IACnC,OAAO;QACN,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,GAAG,CAAC,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC;QAClF,GAAG,CAAC,IAAI,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;KACtE,CAAC;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACtC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IACjC,OAAO,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;AAChE,CAAC","sourcesContent":["import type { Goal, GoalStatus, GoalToolResponse, GoalToolSnapshot } from \"./types.ts\";\n\nexport function formatGoalElapsedSeconds(value: number): string {\n\tconst seconds = Math.max(0, Math.trunc(value));\n\tif (seconds < 60) return `${seconds}s`;\n\n\tconst minutes = Math.trunc(seconds / 60);\n\tif (minutes < 60) return `${minutes}m`;\n\n\tconst hours = Math.trunc(minutes / 60);\n\tconst remainingMinutes = minutes % 60;\n\tif (hours >= 24) {\n\t\tconst days = Math.trunc(hours / 24);\n\t\tconst remainingHours = hours % 24;\n\t\treturn `${days}d ${remainingHours}h ${remainingMinutes}m`;\n\t}\n\n\tif (remainingMinutes === 0) return `${hours}h`;\n\treturn `${hours}h ${remainingMinutes}m`;\n}\n\nexport function formatTokensCompact(value: number): string {\n\tconst abs = Math.abs(value);\n\tif (abs >= 1_000_000) return `${formatOneDecimal(value / 1_000_000)}M`;\n\tif (abs >= 1_000) return `${formatOneDecimal(value / 1_000)}K`;\n\treturn `${Math.trunc(value)}`;\n}\n\nexport function goalStatusLabel(status: GoalStatus): string {\n\tswitch (status) {\n\t\tcase \"active\":\n\t\t\treturn \"active\";\n\t\tcase \"paused\":\n\t\t\treturn \"paused\";\n\t\tcase \"blocked\":\n\t\t\treturn \"blocked\";\n\t\tcase \"complete\":\n\t\t\treturn \"complete\";\n\t}\n}\n\nexport function formatGoalForTool(goal: Goal | null): string {\n\tif (!goal) return \"No active goal is set.\";\n\tconst lines = [\n\t\t`Objective: ${goal.objective}`,\n\t\t`Status: ${goalStatusLabel(goal.status)}`,\n\t\t`Time used: ${formatGoalElapsedSeconds(goal.timeUsedSeconds)}`,\n\t\t`Tokens used: ${formatTokensCompact(goal.tokensUsed)}`,\n\t];\n\tif (goal.blockedReason) lines.push(`Blocked reason: ${goal.blockedReason}`);\n\tif (goal.completedAt) lines.push(`Completed at: ${new Date(goal.completedAt * 1000).toISOString()}`);\n\treturn lines.join(\"\\n\");\n}\n\nexport type GoalToolRenderDetails = {\n\tgoal: GoalToolSnapshot | null;\n\tnotice?: string;\n};\n\nexport function goalToolRenderDetails(goal: Goal | null, notice?: string): GoalToolRenderDetails {\n\treturn {\n\t\tgoal: goal === null ? null : goalToolSnapshot(goal),\n\t\t...(notice === undefined ? {} : { notice }),\n\t};\n}\n\nexport function goalToolResponse(goal: Goal | null): GoalToolResponse {\n\treturn { goal: goal === null ? null : goalToolSnapshot(goal) };\n}\n\nexport function formatGoalToolResponse(goal: Goal | null, notice?: string): string {\n\tconst response = JSON.stringify(goalToolResponse(goal), null, 2);\n\treturn notice === undefined ? response : `${response}\\n${notice}`;\n}\n\nfunction goalToolSnapshot(goal: Goal): GoalToolSnapshot {\n\treturn {\n\t\tthreadId: goal.threadId,\n\t\tobjective: goal.objective,\n\t\tstatus: goal.status,\n\t\ttokensUsed: goal.tokensUsed,\n\t\ttimeUsedSeconds: goal.timeUsedSeconds,\n\t\tcreatedAt: goal.createdAt,\n\t\tupdatedAt: goal.updatedAt,\n\t\t...(goal.blockedReason === undefined ? {} : { blockedReason: goal.blockedReason }),\n\t\t...(goal.blockedAt === undefined ? {} : { blockedAt: goal.blockedAt }),\n\t};\n}\n\nfunction formatOneDecimal(value: number): string {\n\tconst rounded = value.toFixed(1);\n\treturn rounded.endsWith(\".0\") ? rounded.slice(0, -2) : rounded;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"lifecycle-helpers.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAErE,OAAO,EAGN,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAE5B,MAAM,mBAAmB,CAAC;AAW3B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,KAAK,iCAAiC,GAAG,OAAO,CAAC,uBAAuB,EAAE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAEhG,KAAK,+BAA+B,GAAG;IACtC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;IACpD,QAAQ,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,iCAAiC,KAAK,MAAM,CAAC;IACzE,QAAQ,CAAC,uBAAuB,EAAE,MAAM,IAAI,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,+BAA+B,GAAG;IAC7C,QAAQ,CAAC,mBAAmB,EAAE,OAAO,CAAC;IACtC,QAAQ,CAAC,uBAAuB,EAAE,MAAM,IAAI,CAAC;CAC7C,CAAC;AAQF;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACpC,GAAG,EAAE,gBAAgB,EACrB,kBAAkB,EAAE,MAAM,EAC1B,IAAI,EAAE,IAAI,GAAG,IAAI,GACf,IAAI,IAAI,IAAI,CASd;AAED,sFAAsF;AACtF,wBAAsB,6BAA6B,CAClD,EAAE,EAAE,YAAY,EAChB,GAAG,EAAE,gBAAgB,EACrB,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,+BAA+B,GACtC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAgBtB;AAED,mHAAmH;AACnH,wBAAsB,qBAAqB,CAC1C,EAAE,EAAE,YAAY,EAChB,GAAG,EAAE,gBAAgB,EACrB,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,+BAA+B,GACtC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAuBtB;AAED,wBAAgB,qCAAqC,CACpD,GAAG,EAAE,gBAAgB,EACrB,IAAI,EAAE,IAAI,EACV,iBAAiB,EAAE,MAAM,GACvB,MAAM,CAKR;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAM3E;AA0DD,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAK7E"}
1
+ {"version":3,"file":"lifecycle-helpers.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAErE,OAAO,EAGN,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAE5B,MAAM,mBAAmB,CAAC;AAY3B,OAAO,KA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AE,GAAG,MAAM,CAM3E;AA6DD,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAK7E"}
@@ -1,7 +1,7 @@
1
1
  import { GOAL_CONTINUATION_MESSAGE_TYPE } from "../../../messages.js";
2
2
  import { getLatestPhasesFromBranchEntries } from "../todotools/state.js";
3
3
  import { buildGoalContinuationSignature, evaluateGoalContinuation, hashAssistantText, } from "./continuation.js";
4
- import { CONTINUATION_CAP_BLOCKED_REASON, continuationCapRecoveryHint, LENGTH_EXHAUSTED_BLOCKED_REASON, REPETITION_BLOCKED_REASON, } from "./continuation-recovery.js";
4
+ import { CONTINUATION_CAP_BLOCKED_REASON, continuationCapRecoveryHint, LENGTH_EXHAUSTED_BLOCKED_REASON, REPETITION_BLOCKED_REASON, UNATTENDED_CONTINUATION_BLOCKED_REASON, } from "./continuation-recovery.js";
5
5
  import { buildContinuationPrompt } from "./prompt.js";
6
6
  import { recordContinuationDelivered, updateGoal } from "./store.js";
7
7
  import { goalStoreRef } from "./store-ref.js";
@@ -33,7 +33,7 @@ export async function admitAndQueueGoalContinuation(pi, ctx, goal, options) {
33
33
  if (options.input.currentSignature === undefined) {
34
34
  throw new Error("Cannot queue a goal continuation without a progress signature");
35
35
  }
36
- const recordedGoal = await recordContinuationDelivered(goalStoreRef(ctx.sessionManager, ctx.cwd), options.input.currentSignature, goal.id);
36
+ const recordedGoal = await recordContinuationDelivered(goalStoreRef(ctx.sessionManager, ctx.cwd), options.input.currentSignature, goal.id, { countUnattended: options.input.path !== "monitorDelayed" });
37
37
  if (recordedGoal === null)
38
38
  return null;
39
39
  options.markContinuationPending();
@@ -100,6 +100,7 @@ async function handleDeniedContinuation(pi, ctx, goal, input, reason) {
100
100
  goalId: goal.id,
101
101
  reason,
102
102
  count: input.consecutiveContinuations,
103
+ unattendedContinuations: goal.unattendedContinuations ?? 0,
103
104
  });
104
105
  return blocked;
105
106
  }
@@ -107,6 +108,8 @@ function blockedReasonForContinuationGuard(reason) {
107
108
  switch (reason) {
108
109
  case "cap":
109
110
  return CONTINUATION_CAP_BLOCKED_REASON;
111
+ case "unattended":
112
+ return UNATTENDED_CONTINUATION_BLOCKED_REASON;
110
113
  case "repetition":
111
114
  return REPETITION_BLOCKED_REASON;
112
115
  case "length-exhausted":
@@ -1 +1 @@
1
- {"version":3,"file":"lifecycle-helpers.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAGtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EACN,8BAA8B,EAC9B,wBAAwB,EAGxB,iBAAiB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACN,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,yBAAyB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAgBtD;;;GAGG;AACH,MAAM,gCAAgC,GAA8B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;AAE1F;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CACpC,GAAqB,EACrB,kBAA0B,EAC1B,IAAiB;IAEjB,OAAO,CACN,kBAAkB,KAAK,QAAQ;QAC/B,IAAI,KAAK,IAAI;QACb,gCAAgC,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC;QACtD,GAAG,CAAC,KAAK;QACT,GAAG,CAAC,MAAM,EAAE;QACZ,CAAC,GAAG,CAAC,kBAAkB,EAAE,CACzB,CAAC;AACH,CAAC;AAED,s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,SAAS,CAAC,CAAC;IACpF,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,iCAAiC,EAAE;QAClD,MAAM,EAAE,IAAI,CAAC,EAAE;QACf,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,wBAAwB;KACrC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,SAAS,iCAAiC,CACzC,MAAoE;IAEpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,KAAK;YACT,OAAO,+BAA+B,CAAC;QACxC,KAAK,YAAY;YAChB,OAAO,yBAAyB,CAAC;QAClC,KAAK,kBAAkB;YACtB,OAAO,+BAA+B,CAAC;QACxC,KAAK,cAAc,CAAC;QACpB,KAAK,eAAe,CAAC;QACrB,KAAK,OAAO;YACX,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,EAAgB,EAAE,OAAe;IACtE,EAAE,CAAC,WAAW,CACb,EAAE,UAAU,EAAE,8BAA8B,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,EACvE,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,CAC5C,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { GOAL_CONTINUATION_MESSAGE_TYPE } from \"../../../messages.ts\";\nimport type { SessionEntry } from \"../../../session-manager.ts\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport { getLatestPhasesFromBranchEntries } from \"../todotools/state.ts\";\nimport {\n\tbuildGoalContinuationSignature,\n\tevaluateGoalContinuation,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationVerdict,\n\thashAssistantText,\n} from \"./continuation.ts\";\nimport {\n\tCONTINUATION_CAP_BLOCKED_REASON,\n\tcontinuationCapRecoveryHint,\n\tLENGTH_EXHAUSTED_BLOCKED_REASON,\n\tREPETITION_BLOCKED_REASON,\n} from \"./continuation-recovery.ts\";\nimport { buildContinuationPrompt } from \"./prompt.ts\";\nimport { recordContinuationDelivered, updateGoal } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { openTodoTaskContents } from \"./todo-gate.ts\";\nimport type { Goal } from \"./types.ts\";\n\ntype ContinuingGoalContinuationVerdict = Extract<GoalContinuationVerdict, { kind: \"continue\" }>;\n\ntype GoalContinuationDeliveryOptions = {\n\treadonly input: Omit<GoalContinuationInput, \"goal\">;\n\treadonly content: (verdict: ContinuingGoalContinuationVerdict) => string;\n\treadonly markContinuationPending: () => void;\n};\n\nexport type SessionStartContinuationOptions = {\n\treadonly continuationPending: boolean;\n\treadonly markContinuationPending: () => void;\n};\n\n/**\n * Statuses that leave a goal stopped without finishing it. A restart is the only\n * moment the user can act on them, so both earn the resume prompt.\n */\nconst STOPPED_UNFINISHED_GOAL_STATUSES: readonly Goal[\"status\"][] = [\"paused\", \"blocked\"];\n\n/**\n * Mirrors codex `maybe_prompt_resume_paused_goal_after_resume`\n * (codex-rs/tui/src/app/thread_goal_actions.rs), which prompts on resume for every\n * stopped-but-unfinished status. senpi is budget-free, so codex's `UsageLimited`\n * has no counterpart here and the stopped set is `paused | blocked`.\n */\nexport function isResumeOfStoppedGoal(\n\tctx: ExtensionContext,\n\tsessionStartReason: string,\n\tgoal: Goal | null,\n): goal is Goal {\n\treturn (\n\t\tsessionStartReason === \"resume\" &&\n\t\tgoal !== null &&\n\t\tSTOPPED_UNFINISHED_GOAL_STATUSES.includes(goal.status) &&\n\t\tctx.hasUI &&\n\t\tctx.isIdle() &&\n\t\t!ctx.hasPendingMessages()\n\t);\n}\n\n/** Evaluates and delivers a continuation only after all guardrail checks admit it. */\nexport async function admitAndQueueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: GoalContinuationDeliveryOptions,\n): Promise<Goal | null> {\n\tconst verdict = evaluateGoalContinuation({ goal, ...options.input });\n\tif (verdict.kind === \"deny\") return handleDeniedContinuation(pi, ctx, goal, options.input, verdict.reason);\n\n\tif (options.input.currentSignature === undefined) {\n\t\tthrow new Error(\"Cannot queue a goal continuation without a progress signature\");\n\t}\n\tconst recordedGoal = await recordContinuationDelivered(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\toptions.input.currentSignature,\n\t\tgoal.id,\n\t);\n\tif (recordedGoal === null) return null;\n\toptions.markContinuationPending();\n\tqueueHiddenGoalPrompt(pi, options.content(verdict));\n\treturn recordedGoal;\n}\n\n/** Routes startup and resume continuations through the same verdict and delivery accounting as agent-end paths. */\nexport async function queueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: SessionStartContinuationOptions,\n): Promise<Goal | null> {\n\tconst signature = buildCurrentGoalContinuationSignature(\n\t\tctx,\n\t\tgoal,\n\t\tlastAssistantTextFromEntries(ctx.sessionManager.getBranch()),\n\t);\n\treturn admitAndQueueGoalContinuation(pi, ctx, goal, {\n\t\tinput: {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath: \"sessionStart\",\n\t\t\tlastStopReason: undefined,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: signature,\n\t\t\tconsecutiveLengthRecoveries: 0,\n\t\t\trecentNormalizedOutputHashes: [],\n\t\t\ttoollessContinuationStreak: 0,\n\t\t\tcontinuationPending: options.continuationPending,\n\t\t},\n\t\tcontent: () => buildContinuationPrompt(goal),\n\t\tmarkContinuationPending: options.markContinuationPending,\n\t});\n}\n\nexport function buildCurrentGoalContinuationSignature(\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tlastAssistantText: string,\n): string {\n\tconst entries = ctx.sessionManager.getBranch();\n\tconst openTodos = openTodoTaskContents(entries).length;\n\tconst totalTodos = getLatestPhasesFromBranchEntries(entries).reduce((count, phase) => count + phase.tasks.length, 0);\n\treturn buildGoalContinuationSignature(goal, openTodos, totalTodos, hashAssistantText(lastAssistantText));\n}\n\nexport function lastAssistantText(messages: readonly AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"assistant\") return textContent(message);\n\t}\n\treturn \"\";\n}\n\nfunction lastAssistantTextFromEntries(entries: readonly SessionEntry[]): string {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"message\" && entry.message.role === \"assistant\") return textContent(entry.message);\n\t}\n\treturn \"\";\n}\n\nfunction textContent(message: Extract<AgentMessage, { role: \"assistant\" }>): string {\n\treturn message.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n}\n\nasync function handleDeniedContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tinput: Omit<GoalContinuationInput, \"goal\">,\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): Promise<Goal> {\n\tconst blockedReason = blockedReasonForContinuationGuard(reason);\n\tif (blockedReason === undefined) return goal;\n\n\tconst blocked = await updateGoal(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\t{ status: \"blocked\", reason: blockedReason },\n\t\t\"model\",\n\t);\n\tif (ctx.hasUI) ctx.ui.notify(continuationCapRecoveryHint(blockedReason), \"warning\");\n\tpi.events?.emit(\"goal_continuation_guard_tripped\", {\n\t\tgoalId: goal.id,\n\t\treason,\n\t\tcount: input.consecutiveContinuations,\n\t});\n\treturn blocked;\n}\n\nfunction blockedReasonForContinuationGuard(\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): string | undefined {\n\tswitch (reason) {\n\t\tcase \"cap\":\n\t\t\treturn CONTINUATION_CAP_BLOCKED_REASON;\n\t\tcase \"repetition\":\n\t\t\treturn REPETITION_BLOCKED_REASON;\n\t\tcase \"length-exhausted\":\n\t\t\treturn LENGTH_EXHAUSTED_BLOCKED_REASON;\n\t\tcase \"not-eligible\":\n\t\tcase \"single-flight\":\n\t\tcase \"stale\":\n\t\t\treturn undefined;\n\t}\n}\n\nexport function queueHiddenGoalPrompt(pi: ExtensionAPI, content: string): void {\n\tpi.sendMessage(\n\t\t{ customType: GOAL_CONTINUATION_MESSAGE_TYPE, content, display: false },\n\t\t{ triggerTurn: true, deliverAs: \"followUp\" },\n\t);\n}\n"]}
1
+ {"version":3,"file":"lifecycle-helpers.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAGtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EACN,8BAA8B,EAC9B,wBAAwB,EAGxB,iBAAiB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACN,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,yBAAyB,EACzB,sCAAsC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAgBtD;;;GAGG;AACH,MAAM,gCAAgC,GAA8B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;AAE1F;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CACpC,GAAqB,EACrB,kBAA0B,EAC1B,IAAiB;IAEjB,OAAO,CACN,kBAAkB,KAAK,QAAQ;QAC/B,IAAI,KAAK,IAAI;QACb,gCAAgC,CAAC,QAAQ,CAAC,IAAI,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AE,GAAG,CAAC,GAAG,CAAC,EACzC,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,EAC5C,OAAO,CACP,CAAC;IACF,IAAI,GAAG,CAAC,KAAK;QAAE,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,2BAA2B,CAAC,aAAa,CAAC,EAAE,SAAS,CAAC,CAAC;IACpF,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,iCAAiC,EAAE;QAClD,MAAM,EAAE,IAAI,CAAC,EAAE;QACf,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,wBAAwB;QACrC,uBAAuB,EAAE,IAAI,CAAC,uBAAuB,IAAI,CAAC;KAC1D,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,SAAS,iCAAiC,CACzC,MAAoE;IAEpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,KAAK;YACT,OAAO,+BAA+B,CAAC;QACxC,KAAK,YAAY;YAChB,OAAO,sCAAsC,CAAC;QAC/C,KAAK,YAAY;YAChB,OAAO,yBAAyB,CAAC;QAClC,KAAK,kBAAkB;YACtB,OAAO,+BAA+B,CAAC;QACxC,KAAK,cAAc,CAAC;QACpB,KAAK,eAAe,CAAC;QACrB,KAAK,OAAO;YACX,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,EAAgB,EAAE,OAAe;IACtE,EAAE,CAAC,WAAW,CACb,EAAE,UAAU,EAAE,8BAA8B,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,EACvE,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,CAC5C,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { GOAL_CONTINUATION_MESSAGE_TYPE } from \"../../../messages.ts\";\nimport type { SessionEntry } from \"../../../session-manager.ts\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport { getLatestPhasesFromBranchEntries } from \"../todotools/state.ts\";\nimport {\n\tbuildGoalContinuationSignature,\n\tevaluateGoalContinuation,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationVerdict,\n\thashAssistantText,\n} from \"./continuation.ts\";\nimport {\n\tCONTINUATION_CAP_BLOCKED_REASON,\n\tcontinuationCapRecoveryHint,\n\tLENGTH_EXHAUSTED_BLOCKED_REASON,\n\tREPETITION_BLOCKED_REASON,\n\tUNATTENDED_CONTINUATION_BLOCKED_REASON,\n} from \"./continuation-recovery.ts\";\nimport { buildContinuationPrompt } from \"./prompt.ts\";\nimport { recordContinuationDelivered, updateGoal } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { openTodoTaskContents } from \"./todo-gate.ts\";\nimport type { Goal } from \"./types.ts\";\n\ntype ContinuingGoalContinuationVerdict = Extract<GoalContinuationVerdict, { kind: \"continue\" }>;\n\ntype GoalContinuationDeliveryOptions = {\n\treadonly input: Omit<GoalContinuationInput, \"goal\">;\n\treadonly content: (verdict: ContinuingGoalContinuationVerdict) => string;\n\treadonly markContinuationPending: () => void;\n};\n\nexport type SessionStartContinuationOptions = {\n\treadonly continuationPending: boolean;\n\treadonly markContinuationPending: () => void;\n};\n\n/**\n * Statuses that leave a goal stopped without finishing it. A restart is the only\n * moment the user can act on them, so both earn the resume prompt.\n */\nconst STOPPED_UNFINISHED_GOAL_STATUSES: readonly Goal[\"status\"][] = [\"paused\", \"blocked\"];\n\n/**\n * Mirrors codex `maybe_prompt_resume_paused_goal_after_resume`\n * (codex-rs/tui/src/app/thread_goal_actions.rs), which prompts on resume for every\n * stopped-but-unfinished status. senpi is budget-free, so codex's `UsageLimited`\n * has no counterpart here and the stopped set is `paused | blocked`.\n */\nexport function isResumeOfStoppedGoal(\n\tctx: ExtensionContext,\n\tsessionStartReason: string,\n\tgoal: Goal | null,\n): goal is Goal {\n\treturn (\n\t\tsessionStartReason === \"resume\" &&\n\t\tgoal !== null &&\n\t\tSTOPPED_UNFINISHED_GOAL_STATUSES.includes(goal.status) &&\n\t\tctx.hasUI &&\n\t\tctx.isIdle() &&\n\t\t!ctx.hasPendingMessages()\n\t);\n}\n\n/** Evaluates and delivers a continuation only after all guardrail checks admit it. */\nexport async function admitAndQueueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: GoalContinuationDeliveryOptions,\n): Promise<Goal | null> {\n\tconst verdict = evaluateGoalContinuation({ goal, ...options.input });\n\tif (verdict.kind === \"deny\") return handleDeniedContinuation(pi, ctx, goal, options.input, verdict.reason);\n\n\tif (options.input.currentSignature === undefined) {\n\t\tthrow new Error(\"Cannot queue a goal continuation without a progress signature\");\n\t}\n\tconst recordedGoal = await recordContinuationDelivered(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\toptions.input.currentSignature,\n\t\tgoal.id,\n\t\t{ countUnattended: options.input.path !== \"monitorDelayed\" },\n\t);\n\tif (recordedGoal === null) return null;\n\toptions.markContinuationPending();\n\tqueueHiddenGoalPrompt(pi, options.content(verdict));\n\treturn recordedGoal;\n}\n\n/** Routes startup and resume continuations through the same verdict and delivery accounting as agent-end paths. */\nexport async function queueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: SessionStartContinuationOptions,\n): Promise<Goal | null> {\n\tconst signature = buildCurrentGoalContinuationSignature(\n\t\tctx,\n\t\tgoal,\n\t\tlastAssistantTextFromEntries(ctx.sessionManager.getBranch()),\n\t);\n\treturn admitAndQueueGoalContinuation(pi, ctx, goal, {\n\t\tinput: {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath: \"sessionStart\",\n\t\t\tlastStopReason: undefined,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: signature,\n\t\t\tconsecutiveLengthRecoveries: 0,\n\t\t\trecentNormalizedOutputHashes: [],\n\t\t\ttoollessContinuationStreak: 0,\n\t\t\tcontinuationPending: options.continuationPending,\n\t\t},\n\t\tcontent: () => buildContinuationPrompt(goal),\n\t\tmarkContinuationPending: options.markContinuationPending,\n\t});\n}\n\nexport function buildCurrentGoalContinuationSignature(\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tlastAssistantText: string,\n): string {\n\tconst entries = ctx.sessionManager.getBranch();\n\tconst openTodos = openTodoTaskContents(entries).length;\n\tconst totalTodos = getLatestPhasesFromBranchEntries(entries).reduce((count, phase) => count + phase.tasks.length, 0);\n\treturn buildGoalContinuationSignature(goal, openTodos, totalTodos, hashAssistantText(lastAssistantText));\n}\n\nexport function lastAssistantText(messages: readonly AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"assistant\") return textContent(message);\n\t}\n\treturn \"\";\n}\n\nfunction lastAssistantTextFromEntries(entries: readonly SessionEntry[]): string {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"message\" && entry.message.role === \"assistant\") return textContent(entry.message);\n\t}\n\treturn \"\";\n}\n\nfunction textContent(message: Extract<AgentMessage, { role: \"assistant\" }>): string {\n\treturn message.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n}\n\nasync function handleDeniedContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tinput: Omit<GoalContinuationInput, \"goal\">,\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): Promise<Goal> {\n\tconst blockedReason = blockedReasonForContinuationGuard(reason);\n\tif (blockedReason === undefined) return goal;\n\n\tconst blocked = await updateGoal(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\t{ status: \"blocked\", reason: blockedReason },\n\t\t\"model\",\n\t);\n\tif (ctx.hasUI) ctx.ui.notify(continuationCapRecoveryHint(blockedReason), \"warning\");\n\tpi.events?.emit(\"goal_continuation_guard_tripped\", {\n\t\tgoalId: goal.id,\n\t\treason,\n\t\tcount: input.consecutiveContinuations,\n\t\tunattendedContinuations: goal.unattendedContinuations ?? 0,\n\t});\n\treturn blocked;\n}\n\nfunction blockedReasonForContinuationGuard(\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): string | undefined {\n\tswitch (reason) {\n\t\tcase \"cap\":\n\t\t\treturn CONTINUATION_CAP_BLOCKED_REASON;\n\t\tcase \"unattended\":\n\t\t\treturn UNATTENDED_CONTINUATION_BLOCKED_REASON;\n\t\tcase \"repetition\":\n\t\t\treturn REPETITION_BLOCKED_REASON;\n\t\tcase \"length-exhausted\":\n\t\t\treturn LENGTH_EXHAUSTED_BLOCKED_REASON;\n\t\tcase \"not-eligible\":\n\t\tcase \"single-flight\":\n\t\tcase \"stale\":\n\t\t\treturn undefined;\n\t}\n}\n\nexport function queueHiddenGoalPrompt(pi: ExtensionAPI, content: string): void {\n\tpi.sendMessage(\n\t\t{ customType: GOAL_CONTINUATION_MESSAGE_TYPE, content, display: false },\n\t\t{ triggerTurn: true, deliverAs: \"followUp\" },\n\t);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"monitor-continuation.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAarE,OAAO,EAAE,2CAA2C,EAAE,MAAM,iBAAiB,CAAC;AAkB9E,OAAO,KAAK,EACX,eAAe,EAIf,uBAAuB,EAEvB,kBAAkB,EAClB,MAAM,iCAAiC,CAAC;AAKzC,OAAO,KAAK,EAAE,IAAI,EAAsB,MAAM,YAAY,CAAC;AAC3D,OAAO,KAAK,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MtC,mGAAmG;IACnG,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAwBtC,6FAA6F;IAC7F,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAG,IAAI;IAc5D,sEAAsE;IACtE,cAAc,IAAI,IAAI;IAOtB,mGAAmG;IACnG,uBAAuB,IAAI,IAAI;IAI/B,OAAO,IAAI,IAAI;CAkWf"}
@@ -5,6 +5,7 @@ import { continuationTurnUsedTools, evaluateGoalContinuation, GOAL_USER_GRACE_DE
5
5
  import { lastAssistantMessage } from "./last-assistant-message.js";
6
6
  import { admitAndQueueGoalContinuation, buildCurrentGoalContinuationSignature, lastAssistantText, } from "./lifecycle-helpers.js";
7
7
  import { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from "./prompt.js";
8
+ import { isStaleExtensionContextError } from "./stale-context.js";
8
9
  import { resetContinuationStreak } from "./store.js";
9
10
  import { goalStoreRef } from "./store-ref.js";
10
11
  import { collectAssistantUsage } from "./turn-usage.js";
@@ -100,7 +101,8 @@ export class MonitorAwareGoalContinuation {
100
101
  return goal;
101
102
  case "cap":
102
103
  case "repetition":
103
- case "length-exhausted": {
104
+ case "length-exhausted":
105
+ case "unattended": {
104
106
  const admission = await this.#admitAndQueue(options.ctx, goal, "immediate", options.messages);
105
107
  return admission.goal;
106
108
  }
@@ -300,10 +302,28 @@ export class MonitorAwareGoalContinuation {
300
302
  }
301
303
  this.#armTimer(kind, delayMs, delayMs);
302
304
  }
305
+ /**
306
+ * `hasUI` is an `assertActive()`-guarded getter, so a ctx retired by session
307
+ * replacement or reload THROWS instead of reporting false. Optional chaining
308
+ * only guards an undefined ctx (what `dispose()` leaves behind), never a stale
309
+ * object left by a replacement that never disposed this monitor. Callers reach
310
+ * this from timer and event callbacks where a throw is fatal, so a retired ctx
311
+ * reports "no UI" and any other failure keeps its current behavior.
312
+ */
313
+ #ctxHasUI(ctx = this.#ctx) {
314
+ try {
315
+ return ctx?.hasUI === true;
316
+ }
317
+ catch (error) {
318
+ if (isStaleExtensionContextError(error))
319
+ return false;
320
+ throw error;
321
+ }
322
+ }
303
323
  #armTimer(kind, delayMs, totalMs, drainFire = false) {
304
324
  this.#scheduledDueAtMs = Date.now() + delayMs;
305
325
  const ctx = this.#ctx;
306
- if (ctx?.hasUI) {
326
+ if (ctx !== undefined && this.#ctxHasUI(ctx)) {
307
327
  this.#waitTicker?.sync(ctx, {
308
328
  kind,
309
329
  remainingMs: delayMs,
@@ -313,10 +333,14 @@ export class MonitorAwareGoalContinuation {
313
333
  }
314
334
  this.#timer = setTimeout(() => {
315
335
  void this.#continueIfEligible(kind, drainFire).catch((error) => {
316
- if (this.#ctx?.hasUI) {
317
- const message = error instanceof Error ? error.message : String(error);
318
- this.#ctx.ui.notify(`Goal continuation delivery failed: ${message}`, "error");
319
- }
336
+ // Runs from a bare setTimeout: anything thrown here escapes as an
337
+ // uncaughtException and kills the session. A retired ctx cannot be
338
+ // notified, and its own staleness is the expected cause of this
339
+ // rejection after a session replacement, so drop it quietly.
340
+ if (isStaleExtensionContextError(error) || !this.#ctxHasUI())
341
+ return;
342
+ const message = error instanceof Error ? error.message : String(error);
343
+ this.#ctx?.ui.notify(`Goal continuation delivery failed: ${message}`, "error");
320
344
  });
321
345
  }, delayMs);
322
346
  }
@@ -420,7 +444,7 @@ export class MonitorAwareGoalContinuation {
420
444
  consecutiveContinuations: this.#toollessContinuationStreak,
421
445
  toolless: true,
422
446
  });
423
- if (ctx.hasUI) {
447
+ if (this.#ctxHasUI(ctx)) {
424
448
  const context = liveSources.length > 0 ? `while ${liveSources.join(", ")} channels stayed active` : "without tool use";
425
449
  ctx.ui.notify(`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`, "info");
426
450
  }
@@ -1 +1 @@
1
- {"version":3,"file":"monitor-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AAEA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,CAAC;IAED,gCAAgC;QAC/B,IAAI,CAAC,2BAA2B,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;IACnC,CAAC;IAED,YAAY;QACX,MAAM,IAAI,GAAG,IAAI,CAAC,0BAA0B,CAAC;QAC7C,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,4BAA4B,GAAG,SAAS,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,0BAA0B,GAAG,SAAS,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport { GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS } from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tProviderRecoveryOptions,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\nexport const GOAL_CONTINUATION_SCHEDULED_EVENT = \"goal_continuation_scheduled\";\nexport const GOAL_CONTINUATION_RESUMED_EVENT = \"goal_continuation_resumed\";\nexport const GOAL_CONTINUATION_TIMER_STATE_EVENT = \"goal_continuation_timer_state\";\nexport const GOAL_MONITOR_STALL_EVENT = \"goal_monitor_continuation_stall\";\n\nexport class MonitorAwareGoalContinuation {\n\treadonly #pi: ExtensionAPI;\n\treadonly #isContinuationPending: () => boolean;\n\treadonly #markContinuationPending: () => void;\n\treadonly #waitTicker: GoalWaitTicker | undefined;\n\t#wakeSources = new Map<string, number>();\n\t#hasStarted = false;\n\t#ctx: ExtensionContext | undefined;\n\t#goal: Goal | null = null;\n\t#timer: ReturnType<typeof setTimeout> | undefined;\n\t#scheduledContinuationKind: DelayedContinuationKind | undefined;\n\t#channelStateUnsubscribers: Array<() => void> = [];\n\t#lastAgentEndMessages: readonly AgentMessage[] = [];\n\t#consecutiveLengthRecoveries = new Map<string, number>();\n\t#recentNormalizedOutputHashes: string[] = [];\n\t#toollessContinuationStreak = 0;\n\t#toollessStreakGoalId: string | null = null;\n\t#endedTurnWasUserInitiated = false;\n\t#lastTurnUsage: TokenUsageSnapshot | undefined;\n\t#scheduledAtMs: number | undefined;\n\t#scheduledDueAtMs: number | undefined;\n\t#scheduledCache: GoalCacheWarmMetrics | undefined;\n\t#scheduledDelayMs: number | undefined;\n\t#cacheWarmIteration = 0;\n\t#scheduledCacheWarmIteration: number | undefined;\n\t#heldTimer:\n\t\t| { kind: DelayedContinuationKind; remainingMs: number; heldAtMs: number; totalMs: number; drainFire: boolean }\n\t\t| undefined;\n\t#directInputHolds = new Set<string>();\n\t#pendingSystemRecovery: SystemAbortOptions | undefined;\n\t#pendingProviderRecovery: ProviderRecoveryOptions | undefined;\n\n\tconstructor(\n\t\tpi: ExtensionAPI,\n\t\tisContinuationPending: () => boolean = () => false,\n\t\tmarkContinuationPending: () => void = () => {},\n\t\twaitTicker?: GoalWaitTicker,\n\t) {\n\t\tthis.#pi = pi;\n\t\tthis.#isContinuationPending = isContinuationPending;\n\t\tthis.#markContinuationPending = markContinuationPending;\n\t\tthis.#waitTicker = waitTicker;\n\t\tthis.#subscribeToChannelState();\n\t}\n\n\tstart(ctx: ExtensionContext): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#ctx = ctx;\n\t\tif (this.#hasStarted) this.#wakeSources.clear();\n\t\telse this.#hasStarted = true;\n\t\tthis.#goal = null;\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\tasync afterAgentEnd(options: AgentEndOptions): Promise<Goal | null> {\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tthis.#resetLengthRecoveryAfterCleanStop(options.goal, options.messages);\n\t\tconst turnUsedTools = continuationTurnUsedTools(options.messages);\n\t\tthis.#recordAssistantOutput(options.messages, turnUsedTools);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tthis.#recordToollessContinuationTurn(options.goal, turnUsedTools);\n\t\tconst immediateInput = this.#buildVerdictInput(options.ctx, options.goal, \"immediate\", options.messages);\n\t\tconst goal =\n\t\t\t!this.#endedTurnWasUserInitiated && (turnUsedTools || hasGoalContinuationProgress(immediateInput))\n\t\t\t\t? ((await resetContinuationStreak(goalStoreRef(options.ctx.sessionManager, options.ctx.cwd))) ??\n\t\t\t\t\toptions.goal)\n\t\t\t\t: options.goal;\n\t\tthis.#goal = goal;\n\t\tconst immediateVerdict = evaluateGoalContinuation({\n\t\t\tgoal,\n\t\t\t...this.#buildVerdictInput(options.ctx, goal, \"immediate\", options.messages),\n\t\t});\n\t\tif (this.#endedTurnWasUserInitiated) {\n\t\t\tthis.#endedTurnWasUserInitiated = false;\n\t\t\tthis.#cancelTimer();\n\t\t\tif (immediateVerdict.kind === \"continue\") {\n\t\t\t\tthis.#schedule(goal, \"userGrace\");\n\t\t\t\treturn goal;\n\t\t\t}\n\t\t\tswitch (immediateVerdict.reason) {\n\t\t\t\tcase \"not-eligible\":\n\t\t\t\tcase \"single-flight\":\n\t\t\t\tcase \"stale\":\n\t\t\t\t\treturn goal;\n\t\t\t\tcase \"cap\":\n\t\t\t\tcase \"repetition\":\n\t\t\t\tcase \"length-exhausted\": {\n\t\t\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\t\t\treturn admission.goal;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (immediateVerdict.kind === \"deny\" && immediateVerdict.reason === \"not-eligible\") return goal;\n\n\t\tif (this.#activeWakeSourceCount() === 0) {\n\t\t\tthis.#cancelTimer();\n\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\treturn admission.goal;\n\t\t}\n\t\tthis.#schedule(goal, \"monitor\");\n\t\treturn goal;\n\t}\n\n\tasync afterSystemAbort(options: SystemAbortOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (options.willRetry) return options.goal;\n\t\tif (this.#activeWakeSourceCount() > 0) this.#schedule(options.goal, \"monitor\");\n\t\telse if (lastAssistantMessage(options.messages)?.stopReason === \"error\") {\n\t\t\tthis.#pendingSystemRecovery = options;\n\t\t}\n\t\treturn options.goal;\n\t}\n\n\tasync afterProviderFailure(options: ProviderRecoveryOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (!options.willRetry) this.#pendingProviderRecovery = options;\n\t\treturn options.goal;\n\t}\n\n\tasync afterAgentSettled(): Promise<Goal | null | undefined> {\n\t\tconst pendingSystem = this.#pendingSystemRecovery;\n\t\tconst pendingProvider = this.#pendingProviderRecovery;\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tif (pendingSystem !== undefined && pendingSystem.goal !== null && pendingSystem.event.abortSource !== \"user\") {\n\t\t\treturn (\n\t\t\t\tawait this.#admitAndQueue(pendingSystem.ctx, pendingSystem.goal, \"systemRecovery\", pendingSystem.messages)\n\t\t\t).goal;\n\t\t}\n\t\tif (\n\t\t\tpendingProvider === undefined ||\n\t\t\tpendingProvider.goal === null ||\n\t\t\tpendingProvider.event.abortSource === \"user\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn (\n\t\t\tawait this.#admitAndQueue(\n\t\t\t\tpendingProvider.ctx,\n\t\t\t\tpendingProvider.goal,\n\t\t\t\t\"providerRecovery\",\n\t\t\t\tpendingProvider.messages,\n\t\t\t)\n\t\t).goal;\n\t}\n\n\tsyncGoal(goal: Goal | null): void {\n\t\tif (goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#goal = goal;\n\t\tif (goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t}\n\t}\n\n\t/** Live resumption channels known to this generation (e.g. terminal snapshots replayed on reload). */\n\thasActiveWakeSources(): boolean {\n\t\treturn this.#activeWakeSourceCount() > 0;\n\t}\n\n\t/**\n\t * Re-arms the monitor-delayed backstop a reload tore down with the retired\n\t * generation, so a later wake-source drain can still deliver the goal\n\t * continuation. No-op unless the goal is active, a wake source is live, and\n\t * no continuation is already scheduled.\n\t */\n\trearmMonitorBackstop(goal: Goal): void {\n\t\tif (goal.status !== \"active\" || this.#activeWakeSourceCount() === 0) return;\n\t\tthis.#goal = goal;\n\t\tthis.#schedule(goal, \"monitor\");\n\t}\n\n\t/** Temporarily prevents a scheduled continuation from racing unresolved direct-input admission. */\n\tholdDirectInput(inputId: string): void {\n\t\tif (this.#directInputHolds.has(inputId)) return;\n\t\tthis.#directInputHolds.add(inputId);\n\t\tif (\n\t\t\tthis.#directInputHolds.size !== 1 ||\n\t\t\tthis.#timer === undefined ||\n\t\t\tthis.#scheduledContinuationKind === undefined\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst heldAtMs = Date.now();\n\t\tthis.#heldTimer = {\n\t\t\tkind: this.#scheduledContinuationKind,\n\t\t\tremainingMs: Math.max(0, (this.#scheduledDueAtMs ?? heldAtMs) - heldAtMs),\n\t\t\theldAtMs,\n\t\t\ttotalMs: this.#scheduledDelayMs ?? GOAL_USER_GRACE_DELAY_MS,\n\t\t\tdrainFire: false,\n\t\t};\n\t\tclearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t}\n\n\t/** Resolves one admission hold without allowing overlapping inputs to consume each other. */\n\tresolveDirectInput(inputId: string, accepted: boolean): void {\n\t\tif (!this.#directInputHolds.delete(inputId)) return;\n\t\tif (accepted) {\n\t\t\tthis.#heldTimer = undefined;\n\t\t\tthis.noteUserPrompt();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#directInputHolds.size > 0 || this.#heldTimer === undefined) return;\n\t\tconst held = this.#heldTimer;\n\t\tthis.#heldTimer = undefined;\n\t\tconst elapsedWhileHeldMs = Math.max(0, Date.now() - held.heldAtMs);\n\t\tthis.#armTimer(held.kind, Math.max(0, held.remainingMs - elapsedWhileHeldMs), held.totalMs, held.drainFire);\n\t}\n\n\t/** An accepted real user prompt starts a grace-governed user turn. */\n\tnoteUserPrompt(): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#endedTurnWasUserInitiated = true;\n\t\tthis.#resetContinuationState();\n\t}\n\n\t/** A hidden continuation or system recovery has started, so the next end is not user-initiated. */\n\tnoteContinuationStarted(): void {\n\t\tthis.#endedTurnWasUserInitiated = false;\n\t}\n\n\tdispose(): void {\n\t\tthis.#cancelTimer();\n\t\tfor (const unsubscribe of this.#channelStateUnsubscribers) unsubscribe();\n\t\tthis.#channelStateUnsubscribers = [];\n\t\tthis.#ctx = undefined;\n\t\tthis.#goal = null;\n\t\tthis.#wakeSources.clear();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? resolveGoalMonitorContinuationDelayMs(\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheSafeWaitSeconds?.(),\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.(),\n\t\t\t\t\t)\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tthis.#cacheWarmIteration += 1;\n\t\t\tthis.#scheduledCacheWarmIteration = this.#cacheWarmIteration;\n\t\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\t\tconst cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);\n\t\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\t\tthis.#scheduledCache = cache;\n\t\t\tthis.#scheduledAtMs = Date.now();\n\t\t\tconst scheduleData = createGoalCacheWarmScheduleData({\n\t\t\t\tgoalId: goal.id,\n\t\t\t\tdelayMs,\n\t\t\t\tscheduledAtMs: this.#scheduledAtMs,\n\t\t\t\titeration,\n\t\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\t\twakeSources,\n\t\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t\t});\n\t\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);\n\t\t\tthis.#appendWarmupEntry({\n\t\t\t\tphase: \"scheduled\",\n\t\t\t\t...scheduleData,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#scheduledAtMs = undefined;\n\t\t\tthis.#scheduledCache = undefined;\n\t\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\t}\n\t\tthis.#scheduledContinuationKind = kind;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind });\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = { kind, remainingMs: delayMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false };\n\t\t\treturn;\n\t\t}\n\t\tthis.#armTimer(kind, delayMs, delayMs);\n\t}\n\n\t#armTimer(kind: DelayedContinuationKind, delayMs: number, totalMs: number, drainFire = false): void {\n\t\tthis.#scheduledDueAtMs = Date.now() + delayMs;\n\t\tconst ctx = this.#ctx;\n\t\tif (ctx?.hasUI) {\n\t\t\tthis.#waitTicker?.sync(ctx, {\n\t\t\t\tkind,\n\t\t\t\tremainingMs: delayMs,\n\t\t\t\ttotalMs,\n\t\t\t\tchannelCounts: this.#wakeSourceSnapshot(),\n\t\t\t});\n\t\t}\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tvoid this.#continueIfEligible(kind, drainFire).catch((error: unknown) => {\n\t\t\t\tif (this.#ctx?.hasUI) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis.#ctx.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t\t}\n\t\t\t});\n\t\t}, delayMs);\n\t}\n\n\tasync #continueIfEligible(kind: DelayedContinuationKind, drainFire = false): Promise<void> {\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t\tconst delayMs =\n\t\t\tthis.#scheduledDelayMs ??\n\t\t\t(kind === \"monitor\" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : GOAL_USER_GRACE_DELAY_MS);\n\t\tconst waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs);\n\t\tconst cache = this.#scheduledCache;\n\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tconst ctx = this.#ctx;\n\t\tconst goal = this.#goal;\n\t\tif (ctx === undefined || goal?.status !== \"active\" || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\tif (kind === \"monitor\" && this.#activeWakeSourceCount() === 0 && !drainFire) return;\n\t\tconst admission = await this.#admitAndQueue(\n\t\t\tctx,\n\t\t\tgoal,\n\t\t\tkind === \"monitor\" ? \"monitorDelayed\" : \"userGrace\",\n\t\t\tthis.#lastAgentEndMessages,\n\t\t);\n\t\tif (kind !== \"monitor\" || !admission.admitted || iteration === undefined) return;\n\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_RESUMED_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\tcache,\n\t\t});\n\t\tthis.#appendWarmupEntry({\n\t\t\tphase: \"resumed\",\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t});\n\t\tif (drainFire || admission.goal.status !== \"active\") this.#resetCacheWarmIteration();\n\t}\n\n\tasync #admitAndQueue(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Promise<GoalContinuationAdmission> {\n\t\tconst input = this.#buildVerdictInput(ctx, goal, path, messages);\n\t\tconst verdict = evaluateGoalContinuation({ goal, ...input });\n\t\tconst admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, {\n\t\t\tinput,\n\t\t\tcontent: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict),\n\t\t\tmarkContinuationPending: this.#markContinuationPending,\n\t\t});\n\t\tif (admittedGoal === null) {\n\t\t\tthis.#goal = null;\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn { goal, admitted: false };\n\t\t}\n\t\tif (verdict.kind === \"continue\" && input.lastStopReason === \"length\") {\n\t\t\tthis.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1);\n\t\t}\n\t\tthis.#goal = admittedGoal;\n\t\tif (admittedGoal.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t}\n\t\treturn { goal: admittedGoal, admitted: verdict.kind === \"continue\" };\n\t}\n\n\t#appendWarmupEntry(data: LiveGoalCacheWarmupEntryData): void {\n\t\tthis.#pi.appendEntry?.<GoalCacheWarmupEntryData>(GOAL_CACHE_WARMUP_ENTRY_TYPE, data);\n\t}\n\n\t#buildVerdictInput(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Omit<GoalContinuationInput, \"goal\"> {\n\t\tconst lastAssistant = lastAssistantMessage(messages);\n\t\treturn {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath,\n\t\t\tlastStopReason: lastAssistant?.stopReason,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (ctx.hasUI) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),\n\t\t\t\tonContinuationHold: (source, active) => {\n\t\t\t\t\tconst inputId = `external:${source}`;\n\t\t\t\t\tif (active) this.holdDirectInput(inputId);\n\t\t\t\t\telse this.resolveDirectInput(inputId, false);\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tthis.#wakeSources.set(source, activeCount);\n\t\tconst nextTotal = this.#activeWakeSourceCount();\n\t\tif (previousTotal > 0 && nextTotal === 0) {\n\t\t\tif (this.#scheduledContinuationKind === \"monitor\") this.#armDrainFire();\n\t\t\telse this.#resetCacheWarmIteration();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#scheduledContinuationKind === \"monitor\") {\n\t\t\tthis.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot());\n\t\t}\n\t}\n\n\t#armDrainFire(): void {\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = {\n\t\t\t\tkind: \"monitor\",\n\t\t\t\tremainingMs: 1_000,\n\t\t\t\theldAtMs: Date.now(),\n\t\t\t\ttotalMs: 1_000,\n\t\t\t\tdrainFire: true,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t\tthis.#armTimer(\"monitor\", 1_000, 1_000, true);\n\t}\n\n\t#activeWakeSourceCount(): number {\n\t\tlet total = 0;\n\t\tfor (const count of this.#wakeSources.values()) total += count;\n\t\treturn total;\n\t}\n\n\t#wakeSourceSnapshot(): ResumptionChannelCounts {\n\t\treturn Object.fromEntries([...this.#wakeSources.entries()].sort(([left], [right]) => left.localeCompare(right)));\n\t}\n\n\t#liveWakeSources(): string[] {\n\t\treturn [...this.#wakeSources.entries()]\n\t\t\t.filter(([, count]) => count > 0)\n\t\t\t.map(([source]) => source)\n\t\t\t.sort();\n\t}\n\n\t#resetContinuationState(): void {\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#consecutiveLengthRecoveries.clear();\n\t\tthis.#recentNormalizedOutputHashes = [];\n\t\tthis.#resetToollessContinuationStreak();\n\t\tthis.#resetCacheWarmIteration();\n\t}\n\n\t#resetCacheWarmIteration(): void {\n\t\tthis.#cacheWarmIteration = 0;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t}\n\n\t#resetToollessContinuationStreak(): void {\n\t\tthis.#toollessContinuationStreak = 0;\n\t\tthis.#toollessStreakGoalId = null;\n\t}\n\n\t#cancelTimer(): void {\n\t\tconst kind = this.#scheduledContinuationKind;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tthis.#heldTimer = undefined;\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tif (kind !== undefined) this.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t}\n}\n"]}
1
+ {"version":3,"file":"monitor-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,2CAA2C,EAI3C,qCAAqC,GACrC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EAAE,2CAA2C,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EAGxB,2BAA2B,EAC3B,iBAAiB,EACjB,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EACN,6BAA6B,EAC7B,qCAAqC,EACrC,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAUhC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAC;AAC3G,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAIxD,MAAM,CAAC,MAAM,iCAAiC,GAAG,6BAA6B,CAAC;AAC/E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CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,4BAA4B,GAAG,SAAS,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,0BAA0B,GAAG,SAAS,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport { GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS } from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tProviderRecoveryOptions,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { isStaleExtensionContextError } from \"./stale-context.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\nexport const GOAL_CONTINUATION_SCHEDULED_EVENT = \"goal_continuation_scheduled\";\nexport const GOAL_CONTINUATION_RESUMED_EVENT = \"goal_continuation_resumed\";\nexport const GOAL_CONTINUATION_TIMER_STATE_EVENT = \"goal_continuation_timer_state\";\nexport const GOAL_MONITOR_STALL_EVENT = \"goal_monitor_continuation_stall\";\n\nexport class MonitorAwareGoalContinuation {\n\treadonly #pi: ExtensionAPI;\n\treadonly #isContinuationPending: () => boolean;\n\treadonly #markContinuationPending: () => void;\n\treadonly #waitTicker: GoalWaitTicker | undefined;\n\t#wakeSources = new Map<string, number>();\n\t#hasStarted = false;\n\t#ctx: ExtensionContext | undefined;\n\t#goal: Goal | null = null;\n\t#timer: ReturnType<typeof setTimeout> | undefined;\n\t#scheduledContinuationKind: DelayedContinuationKind | undefined;\n\t#channelStateUnsubscribers: Array<() => void> = [];\n\t#lastAgentEndMessages: readonly AgentMessage[] = [];\n\t#consecutiveLengthRecoveries = new Map<string, number>();\n\t#recentNormalizedOutputHashes: string[] = [];\n\t#toollessContinuationStreak = 0;\n\t#toollessStreakGoalId: string | null = null;\n\t#endedTurnWasUserInitiated = false;\n\t#lastTurnUsage: TokenUsageSnapshot | undefined;\n\t#scheduledAtMs: number | undefined;\n\t#scheduledDueAtMs: number | undefined;\n\t#scheduledCache: GoalCacheWarmMetrics | undefined;\n\t#scheduledDelayMs: number | undefined;\n\t#cacheWarmIteration = 0;\n\t#scheduledCacheWarmIteration: number | undefined;\n\t#heldTimer:\n\t\t| { kind: DelayedContinuationKind; remainingMs: number; heldAtMs: number; totalMs: number; drainFire: boolean }\n\t\t| undefined;\n\t#directInputHolds = new Set<string>();\n\t#pendingSystemRecovery: SystemAbortOptions | undefined;\n\t#pendingProviderRecovery: ProviderRecoveryOptions | undefined;\n\n\tconstructor(\n\t\tpi: ExtensionAPI,\n\t\tisContinuationPending: () => boolean = () => false,\n\t\tmarkContinuationPending: () => void = () => {},\n\t\twaitTicker?: GoalWaitTicker,\n\t) {\n\t\tthis.#pi = pi;\n\t\tthis.#isContinuationPending = isContinuationPending;\n\t\tthis.#markContinuationPending = markContinuationPending;\n\t\tthis.#waitTicker = waitTicker;\n\t\tthis.#subscribeToChannelState();\n\t}\n\n\tstart(ctx: ExtensionContext): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#ctx = ctx;\n\t\tif (this.#hasStarted) this.#wakeSources.clear();\n\t\telse this.#hasStarted = true;\n\t\tthis.#goal = null;\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\tasync afterAgentEnd(options: AgentEndOptions): Promise<Goal | null> {\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tthis.#resetLengthRecoveryAfterCleanStop(options.goal, options.messages);\n\t\tconst turnUsedTools = continuationTurnUsedTools(options.messages);\n\t\tthis.#recordAssistantOutput(options.messages, turnUsedTools);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tthis.#recordToollessContinuationTurn(options.goal, turnUsedTools);\n\t\tconst immediateInput = this.#buildVerdictInput(options.ctx, options.goal, \"immediate\", options.messages);\n\t\tconst goal =\n\t\t\t!this.#endedTurnWasUserInitiated && (turnUsedTools || hasGoalContinuationProgress(immediateInput))\n\t\t\t\t? ((await resetContinuationStreak(goalStoreRef(options.ctx.sessionManager, options.ctx.cwd))) ??\n\t\t\t\t\toptions.goal)\n\t\t\t\t: options.goal;\n\t\tthis.#goal = goal;\n\t\tconst immediateVerdict = evaluateGoalContinuation({\n\t\t\tgoal,\n\t\t\t...this.#buildVerdictInput(options.ctx, goal, \"immediate\", options.messages),\n\t\t});\n\t\tif (this.#endedTurnWasUserInitiated) {\n\t\t\tthis.#endedTurnWasUserInitiated = false;\n\t\t\tthis.#cancelTimer();\n\t\t\tif (immediateVerdict.kind === \"continue\") {\n\t\t\t\tthis.#schedule(goal, \"userGrace\");\n\t\t\t\treturn goal;\n\t\t\t}\n\t\t\tswitch (immediateVerdict.reason) {\n\t\t\t\tcase \"not-eligible\":\n\t\t\t\tcase \"single-flight\":\n\t\t\t\tcase \"stale\":\n\t\t\t\t\treturn goal;\n\t\t\t\tcase \"cap\":\n\t\t\t\tcase \"repetition\":\n\t\t\t\tcase \"length-exhausted\":\n\t\t\t\tcase \"unattended\": {\n\t\t\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\t\t\treturn admission.goal;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (immediateVerdict.kind === \"deny\" && immediateVerdict.reason === \"not-eligible\") return goal;\n\n\t\tif (this.#activeWakeSourceCount() === 0) {\n\t\t\tthis.#cancelTimer();\n\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\treturn admission.goal;\n\t\t}\n\t\tthis.#schedule(goal, \"monitor\");\n\t\treturn goal;\n\t}\n\n\tasync afterSystemAbort(options: SystemAbortOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (options.willRetry) return options.goal;\n\t\tif (this.#activeWakeSourceCount() > 0) this.#schedule(options.goal, \"monitor\");\n\t\telse if (lastAssistantMessage(options.messages)?.stopReason === \"error\") {\n\t\t\tthis.#pendingSystemRecovery = options;\n\t\t}\n\t\treturn options.goal;\n\t}\n\n\tasync afterProviderFailure(options: ProviderRecoveryOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (!options.willRetry) this.#pendingProviderRecovery = options;\n\t\treturn options.goal;\n\t}\n\n\tasync afterAgentSettled(): Promise<Goal | null | undefined> {\n\t\tconst pendingSystem = this.#pendingSystemRecovery;\n\t\tconst pendingProvider = this.#pendingProviderRecovery;\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tif (pendingSystem !== undefined && pendingSystem.goal !== null && pendingSystem.event.abortSource !== \"user\") {\n\t\t\treturn (\n\t\t\t\tawait this.#admitAndQueue(pendingSystem.ctx, pendingSystem.goal, \"systemRecovery\", pendingSystem.messages)\n\t\t\t).goal;\n\t\t}\n\t\tif (\n\t\t\tpendingProvider === undefined ||\n\t\t\tpendingProvider.goal === null ||\n\t\t\tpendingProvider.event.abortSource === \"user\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn (\n\t\t\tawait this.#admitAndQueue(\n\t\t\t\tpendingProvider.ctx,\n\t\t\t\tpendingProvider.goal,\n\t\t\t\t\"providerRecovery\",\n\t\t\t\tpendingProvider.messages,\n\t\t\t)\n\t\t).goal;\n\t}\n\n\tsyncGoal(goal: Goal | null): void {\n\t\tif (goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#goal = goal;\n\t\tif (goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t}\n\t}\n\n\t/** Live resumption channels known to this generation (e.g. terminal snapshots replayed on reload). */\n\thasActiveWakeSources(): boolean {\n\t\treturn this.#activeWakeSourceCount() > 0;\n\t}\n\n\t/**\n\t * Re-arms the monitor-delayed backstop a reload tore down with the retired\n\t * generation, so a later wake-source drain can still deliver the goal\n\t * continuation. No-op unless the goal is active, a wake source is live, and\n\t * no continuation is already scheduled.\n\t */\n\trearmMonitorBackstop(goal: Goal): void {\n\t\tif (goal.status !== \"active\" || this.#activeWakeSourceCount() === 0) return;\n\t\tthis.#goal = goal;\n\t\tthis.#schedule(goal, \"monitor\");\n\t}\n\n\t/** Temporarily prevents a scheduled continuation from racing unresolved direct-input admission. */\n\tholdDirectInput(inputId: string): void {\n\t\tif (this.#directInputHolds.has(inputId)) return;\n\t\tthis.#directInputHolds.add(inputId);\n\t\tif (\n\t\t\tthis.#directInputHolds.size !== 1 ||\n\t\t\tthis.#timer === undefined ||\n\t\t\tthis.#scheduledContinuationKind === undefined\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst heldAtMs = Date.now();\n\t\tthis.#heldTimer = {\n\t\t\tkind: this.#scheduledContinuationKind,\n\t\t\tremainingMs: Math.max(0, (this.#scheduledDueAtMs ?? heldAtMs) - heldAtMs),\n\t\t\theldAtMs,\n\t\t\ttotalMs: this.#scheduledDelayMs ?? GOAL_USER_GRACE_DELAY_MS,\n\t\t\tdrainFire: false,\n\t\t};\n\t\tclearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t}\n\n\t/** Resolves one admission hold without allowing overlapping inputs to consume each other. */\n\tresolveDirectInput(inputId: string, accepted: boolean): void {\n\t\tif (!this.#directInputHolds.delete(inputId)) return;\n\t\tif (accepted) {\n\t\t\tthis.#heldTimer = undefined;\n\t\t\tthis.noteUserPrompt();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#directInputHolds.size > 0 || this.#heldTimer === undefined) return;\n\t\tconst held = this.#heldTimer;\n\t\tthis.#heldTimer = undefined;\n\t\tconst elapsedWhileHeldMs = Math.max(0, Date.now() - held.heldAtMs);\n\t\tthis.#armTimer(held.kind, Math.max(0, held.remainingMs - elapsedWhileHeldMs), held.totalMs, held.drainFire);\n\t}\n\n\t/** An accepted real user prompt starts a grace-governed user turn. */\n\tnoteUserPrompt(): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#endedTurnWasUserInitiated = true;\n\t\tthis.#resetContinuationState();\n\t}\n\n\t/** A hidden continuation or system recovery has started, so the next end is not user-initiated. */\n\tnoteContinuationStarted(): void {\n\t\tthis.#endedTurnWasUserInitiated = false;\n\t}\n\n\tdispose(): void {\n\t\tthis.#cancelTimer();\n\t\tfor (const unsubscribe of this.#channelStateUnsubscribers) unsubscribe();\n\t\tthis.#channelStateUnsubscribers = [];\n\t\tthis.#ctx = undefined;\n\t\tthis.#goal = null;\n\t\tthis.#wakeSources.clear();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? resolveGoalMonitorContinuationDelayMs(\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheSafeWaitSeconds?.(),\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.(),\n\t\t\t\t\t)\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tthis.#cacheWarmIteration += 1;\n\t\t\tthis.#scheduledCacheWarmIteration = this.#cacheWarmIteration;\n\t\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\t\tconst cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);\n\t\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\t\tthis.#scheduledCache = cache;\n\t\t\tthis.#scheduledAtMs = Date.now();\n\t\t\tconst scheduleData = createGoalCacheWarmScheduleData({\n\t\t\t\tgoalId: goal.id,\n\t\t\t\tdelayMs,\n\t\t\t\tscheduledAtMs: this.#scheduledAtMs,\n\t\t\t\titeration,\n\t\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\t\twakeSources,\n\t\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t\t});\n\t\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);\n\t\t\tthis.#appendWarmupEntry({\n\t\t\t\tphase: \"scheduled\",\n\t\t\t\t...scheduleData,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#scheduledAtMs = undefined;\n\t\t\tthis.#scheduledCache = undefined;\n\t\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\t}\n\t\tthis.#scheduledContinuationKind = kind;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind });\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = { kind, remainingMs: delayMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false };\n\t\t\treturn;\n\t\t}\n\t\tthis.#armTimer(kind, delayMs, delayMs);\n\t}\n\n\t/**\n\t * `hasUI` is an `assertActive()`-guarded getter, so a ctx retired by session\n\t * replacement or reload THROWS instead of reporting false. Optional chaining\n\t * only guards an undefined ctx (what `dispose()` leaves behind), never a stale\n\t * object left by a replacement that never disposed this monitor. Callers reach\n\t * this from timer and event callbacks where a throw is fatal, so a retired ctx\n\t * reports \"no UI\" and any other failure keeps its current behavior.\n\t */\n\t#ctxHasUI(ctx: ExtensionContext | undefined = this.#ctx): boolean {\n\t\ttry {\n\t\t\treturn ctx?.hasUI === true;\n\t\t} catch (error) {\n\t\t\tif (isStaleExtensionContextError(error)) return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t#armTimer(kind: DelayedContinuationKind, delayMs: number, totalMs: number, drainFire = false): void {\n\t\tthis.#scheduledDueAtMs = Date.now() + delayMs;\n\t\tconst ctx = this.#ctx;\n\t\tif (ctx !== undefined && this.#ctxHasUI(ctx)) {\n\t\t\tthis.#waitTicker?.sync(ctx, {\n\t\t\t\tkind,\n\t\t\t\tremainingMs: delayMs,\n\t\t\t\ttotalMs,\n\t\t\t\tchannelCounts: this.#wakeSourceSnapshot(),\n\t\t\t});\n\t\t}\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tvoid this.#continueIfEligible(kind, drainFire).catch((error: unknown) => {\n\t\t\t\t// Runs from a bare setTimeout: anything thrown here escapes as an\n\t\t\t\t// uncaughtException and kills the session. A retired ctx cannot be\n\t\t\t\t// notified, and its own staleness is the expected cause of this\n\t\t\t\t// rejection after a session replacement, so drop it quietly.\n\t\t\t\tif (isStaleExtensionContextError(error) || !this.#ctxHasUI()) return;\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tthis.#ctx?.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t});\n\t\t}, delayMs);\n\t}\n\n\tasync #continueIfEligible(kind: DelayedContinuationKind, drainFire = false): Promise<void> {\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t\tconst delayMs =\n\t\t\tthis.#scheduledDelayMs ??\n\t\t\t(kind === \"monitor\" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : GOAL_USER_GRACE_DELAY_MS);\n\t\tconst waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs);\n\t\tconst cache = this.#scheduledCache;\n\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tconst ctx = this.#ctx;\n\t\tconst goal = this.#goal;\n\t\tif (ctx === undefined || goal?.status !== \"active\" || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\tif (kind === \"monitor\" && this.#activeWakeSourceCount() === 0 && !drainFire) return;\n\t\tconst admission = await this.#admitAndQueue(\n\t\t\tctx,\n\t\t\tgoal,\n\t\t\tkind === \"monitor\" ? \"monitorDelayed\" : \"userGrace\",\n\t\t\tthis.#lastAgentEndMessages,\n\t\t);\n\t\tif (kind !== \"monitor\" || !admission.admitted || iteration === undefined) return;\n\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_RESUMED_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\tcache,\n\t\t});\n\t\tthis.#appendWarmupEntry({\n\t\t\tphase: \"resumed\",\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t});\n\t\tif (drainFire || admission.goal.status !== \"active\") this.#resetCacheWarmIteration();\n\t}\n\n\tasync #admitAndQueue(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Promise<GoalContinuationAdmission> {\n\t\tconst input = this.#buildVerdictInput(ctx, goal, path, messages);\n\t\tconst verdict = evaluateGoalContinuation({ goal, ...input });\n\t\tconst admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, {\n\t\t\tinput,\n\t\t\tcontent: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict),\n\t\t\tmarkContinuationPending: this.#markContinuationPending,\n\t\t});\n\t\tif (admittedGoal === null) {\n\t\t\tthis.#goal = null;\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn { goal, admitted: false };\n\t\t}\n\t\tif (verdict.kind === \"continue\" && input.lastStopReason === \"length\") {\n\t\t\tthis.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1);\n\t\t}\n\t\tthis.#goal = admittedGoal;\n\t\tif (admittedGoal.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t}\n\t\treturn { goal: admittedGoal, admitted: verdict.kind === \"continue\" };\n\t}\n\n\t#appendWarmupEntry(data: LiveGoalCacheWarmupEntryData): void {\n\t\tthis.#pi.appendEntry?.<GoalCacheWarmupEntryData>(GOAL_CACHE_WARMUP_ENTRY_TYPE, data);\n\t}\n\n\t#buildVerdictInput(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Omit<GoalContinuationInput, \"goal\"> {\n\t\tconst lastAssistant = lastAssistantMessage(messages);\n\t\treturn {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath,\n\t\t\tlastStopReason: lastAssistant?.stopReason,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (this.#ctxHasUI(ctx)) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),\n\t\t\t\tonContinuationHold: (source, active) => {\n\t\t\t\t\tconst inputId = `external:${source}`;\n\t\t\t\t\tif (active) this.holdDirectInput(inputId);\n\t\t\t\t\telse this.resolveDirectInput(inputId, false);\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tthis.#wakeSources.set(source, activeCount);\n\t\tconst nextTotal = this.#activeWakeSourceCount();\n\t\tif (previousTotal > 0 && nextTotal === 0) {\n\t\t\tif (this.#scheduledContinuationKind === \"monitor\") this.#armDrainFire();\n\t\t\telse this.#resetCacheWarmIteration();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#scheduledContinuationKind === \"monitor\") {\n\t\t\tthis.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot());\n\t\t}\n\t}\n\n\t#armDrainFire(): void {\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = {\n\t\t\t\tkind: \"monitor\",\n\t\t\t\tremainingMs: 1_000,\n\t\t\t\theldAtMs: Date.now(),\n\t\t\t\ttotalMs: 1_000,\n\t\t\t\tdrainFire: true,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t\tthis.#armTimer(\"monitor\", 1_000, 1_000, true);\n\t}\n\n\t#activeWakeSourceCount(): number {\n\t\tlet total = 0;\n\t\tfor (const count of this.#wakeSources.values()) total += count;\n\t\treturn total;\n\t}\n\n\t#wakeSourceSnapshot(): ResumptionChannelCounts {\n\t\treturn Object.fromEntries([...this.#wakeSources.entries()].sort(([left], [right]) => left.localeCompare(right)));\n\t}\n\n\t#liveWakeSources(): string[] {\n\t\treturn [...this.#wakeSources.entries()]\n\t\t\t.filter(([, count]) => count > 0)\n\t\t\t.map(([source]) => source)\n\t\t\t.sort();\n\t}\n\n\t#resetContinuationState(): void {\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#consecutiveLengthRecoveries.clear();\n\t\tthis.#recentNormalizedOutputHashes = [];\n\t\tthis.#resetToollessContinuationStreak();\n\t\tthis.#resetCacheWarmIteration();\n\t}\n\n\t#resetCacheWarmIteration(): void {\n\t\tthis.#cacheWarmIteration = 0;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t}\n\n\t#resetToollessContinuationStreak(): void {\n\t\tthis.#toollessContinuationStreak = 0;\n\t\tthis.#toollessStreakGoalId = null;\n\t}\n\n\t#cancelTimer(): void {\n\t\tconst kind = this.#scheduledContinuationKind;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tthis.#heldTimer = undefined;\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tif (kind !== undefined) this.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t}\n}\n"]}
@@ -310,6 +310,8 @@ function sanitizeContinuationState(goal) {
310
310
  const next = { ...goal };
311
311
  if (!isNonNegativeSafeInteger(next.consecutiveContinuations))
312
312
  delete next.consecutiveContinuations;
313
+ if (!isNonNegativeSafeInteger(next.unattendedContinuations))
314
+ delete next.unattendedContinuations;
313
315
  if (typeof next.lastContinuationSignature !== "string")
314
316
  delete next.lastContinuationSignature;
315
317
  return next;
@@ -1 +1 @@
1
- {"version":3,"file":"persistence.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE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ir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, sep } from \"node:path\";\nimport { InvalidGoalStoreError, UnsupportedGoalStoreVersionError } from \"./errors.ts\";\nimport type { Goal, GoalFile, GoalStatus, GoalStoreRef } from \"./types.ts\";\nimport { isRecord } from \"./types.ts\";\nimport { isGoalStatus, isNonNegativeSafeInteger } from \"./validation.ts\";\n\nconst STORE_VERSION = 1;\nconst CURRENT_STORE_DIRECTORY = \"goal\";\nconst LEGACY_STORE_DIRECTORY = \"pi-goal\";\nconst LEGACY_BUDGET_LIMITED_STATUSES = [\"budgetLimited\", \"budget_limited\"];\n\nexport function encodedThreadId(ref: GoalStoreRef): string {\n\treturn encodeURIComponent(ref.threadId);\n}\n\nexport function goalFilePath(ref: GoalStoreRef): string {\n\treturn join(ref.baseDir, `${encodedThreadId(ref)}.json`);\n}\n\nexport async function readGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\treturn parseGoalFile(await readFile(goalFilePath(ref), \"utf8\")).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error)) return null;\n\t\tthrow error;\n\t}\n}\n\n/**\n * Imports legacy standalone `pi-goal` state into the current budget-free store.\n *\n * The current store always wins and legacy normalization is confined to this path.\n * Invalid, unsupported, or malformed legacy files are best-effort dead-data imports:\n * they remain untouched and do not block the live current store. Unexpected filesystem\n * failures still propagate.\n *\n * Session-backed stores use their stable thread id. No-session stores enumerate the\n * cwd-keyed legacy bucket because each ephemeral run receives a new thread id, and they\n * inspect both the redirected Senpi-root sibling and the standalone pi agent root.\n * Multiple valid live candidates are reported as a conflict rather than guessed.\n *\n * Returns the imported goal, or null when nothing was migrated.\n */\nexport async function migrateLegacyGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\tawait readFile(goalFilePath(ref), \"utf8\");\n\t\treturn null;\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t}\n\n\tconst legacyCandidates = await readLegacyGoalCandidates(ref);\n\tif (legacyCandidates.length > 1) {\n\t\tthrow new Error(\n\t\t\t`multiple legacy goals found for no-session store: ${legacyCandidates.map(({ path }) => path).join(\", \")}`,\n\t\t);\n\t}\n\tconst candidate = legacyCandidates[0];\n\tif (candidate === undefined) return null;\n\tconst published = await publishMigratedGoalFile(ref, candidate.goal);\n\tawait retireLegacyGoalFile(candidate.path);\n\treturn published ? candidate.goal : null;\n}\n\ninterface LegacyGoalCandidate {\n\tpath: string;\n\tgoal: Goal;\n}\n\nasync function readLegacyGoalCandidates(ref: GoalStoreRef): Promise<LegacyGoalCandidate[]> {\n\tconst legacyBaseDir = legacyBaseDirFor(ref.baseDir);\n\tif (legacyBaseDir === undefined) return [];\n\tconst cwdKey = noSessionCwdKey(ref.baseDir);\n\tif (cwdKey === undefined) {\n\t\tconst candidate = await readLegacyGoalCandidate(goalFilePath({ ...ref, baseDir: legacyBaseDir }));\n\t\treturn candidate === null ? [] : [candidate];\n\t}\n\n\tconst standaloneAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), \".pi\", \"agent\");\n\tconst baseDirs = new Set([\n\t\tlegacyBaseDir,\n\t\tjoin(standaloneAgentDir, \"extensions\", LEGACY_STORE_DIRECTORY, \"no-session\", cwdKey),\n\t]);\n\tconst candidatePaths: string[] = [];\n\tfor (const baseDir of baseDirs) {\n\t\tlet entries: Dirent<string>[];\n\t\ttry {\n\t\t\tentries = await readdir(baseDir, { withFileTypes: true });\n\t\t} catch (error) {\n\t\t\tif (isMissingFile(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".json\")) candidatePaths.push(join(baseDir, entry.name));\n\t\t}\n\t}\n\n\tconst candidates: LegacyGoalCandidate[] = [];\n\tfor (const path of candidatePaths.sort()) {\n\t\tconst candidate = await readLegacyGoalCandidate(path);\n\t\tif (candidate !== null) candidates.push(candidate);\n\t}\n\treturn candidates;\n}\n\nasync function readLegacyGoalCandidate(path: string): Promise<LegacyGoalCandidate | null> {\n\tlet goal: Goal | null;\n\ttry {\n\t\tgoal = parseGoalFile(await readFile(path, \"utf8\"), { legacy: true }).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error) || isIgnoredLegacyStoreError(error)) return null;\n\t\tthrow error;\n\t}\n\tif (goal === null) {\n\t\tawait retireLegacyGoalFile(path);\n\t\treturn null;\n\t}\n\treturn { path, goal };\n}\n\nasync function retireLegacyGoalFile(path: string): Promise<void> {\n\ttry {\n\t\tawait rename(path, `${path}.migrated`);\n\t} catch {\n\t\t// Retirement is best-effort: a preserved legacy file must never fail live migration.\n\t}\n}\n\nfunction isIgnoredLegacyStoreError(error: unknown): boolean {\n\treturn (\n\t\terror instanceof InvalidGoalStoreError ||\n\t\terror instanceof UnsupportedGoalStoreVersionError ||\n\t\terror instanceof SyntaxError\n\t);\n}\n\n/**\n * Maps a current goal-store directory to its legacy `pi-goal` counterpart by replacing\n * the `goal` path segment itself.\n *\n * Both store layouts must map correctly:\n * <sessionDir>/extensions/goal -> <sessionDir>/extensions/pi-goal\n * <agentDir>/extensions/goal/no-session/<cwdKey>\n * -> <agentDir>/extensions/pi-goal/no-session/<cwdKey>\n *\n * Swapping `dirname(baseDir)` only works for the first layout; in the no-session\n * fallback it points inside the current store tree, which both misses real legacy\n * state and can import an unrelated nested directory.\n */\nfunction legacyBaseDirFor(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1) return undefined;\n\tsegments[goalIndex] = LEGACY_STORE_DIRECTORY;\n\treturn segments.join(sep);\n}\n\nfunction noSessionCwdKey(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1 || segments[goalIndex + 1] !== \"no-session\") return undefined;\n\treturn segments[goalIndex + 2];\n}\n\nfunction pathSegments(path: string): string[] {\n\treturn path.split(/[\\\\/]/);\n}\n\nexport async function writeGoalFile(ref: GoalStoreRef, goal: Goal | null): Promise<void> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tawait writeGoalFileAtomic(filePath, `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`);\n}\n\nasync function writeGoalFileAtomic(filePath: string, contents: string): Promise<void> {\n\tconst tempPath = join(dirname(filePath), `.goal-${randomUUID()}.tmp`);\n\ttry {\n\t\tawait writeFile(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait rm(tempPath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, cleanupError],\n\t\t\t\t\"goal store write failed and its temporary file could not be removed\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function publishMigratedGoalFile(ref: GoalStoreRef, goal: Goal): Promise<boolean> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tconst contents = `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`;\n\ttry {\n\t\tawait writeFile(filePath, contents, { encoding: \"utf8\", mode: 0o600, flag: \"wx\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (isFileSystemError(error, \"EEXIST\")) return false;\n\t\tthrow error;\n\t}\n}\n\nfunction parseGoalFile(raw: string, { legacy = false }: { legacy?: boolean } = {}): GoalFile {\n\tconst parsed = parseGoalFileJson(raw);\n\tif (!isRecord(parsed)) throw new InvalidGoalStoreError(\"goal store must be a JSON object\");\n\tif (parsed.version !== STORE_VERSION) throw new UnsupportedGoalStoreVersionError(\"unsupported goal store version\");\n\tconst goal = legacy ? normalizeLegacyGoal(parsed.goal) : parsed.goal;\n\tif (goal !== null && !isGoal(goal)) throw new InvalidGoalStoreError(\"goal store contains an invalid goal\");\n\treturn { version: STORE_VERSION, goal: goal === null ? null : sanitizeContinuationState(goal) };\n}\n\nfunction parseGoalFileJson(raw: string): unknown {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (error) {\n\t\tif (!(error instanceof SyntaxError)) throw error;\n\t\tconst recovered = recoverGoalFileWithStaleClosingBraces(raw);\n\t\tif (recovered === undefined) throw error;\n\t\ttry {\n\t\t\tparsed = JSON.parse(recovered);\n\t\t} catch {\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn parsed;\n}\n\n/**\n * Drops legacy budget enforcement: `tokenBudget` is a budgeting input in `pi-goal`, and\n * `budgetLimited` is a status this fork removed, so a budget-limited legacy goal resumes\n * as `active`. This runs only on the legacy import path.\n */\nfunction normalizeLegacyGoal(value: unknown): unknown {\n\tif (!isRecord(value)) return value;\n\tconst normalized = { ...value };\n\tdelete normalized.tokenBudget;\n\tif (typeof normalized.status === \"string\" && LEGACY_BUDGET_LIMITED_STATUSES.includes(normalized.status)) {\n\t\tnormalized.status = \"active\";\n\t}\n\treturn normalized;\n}\n\nfunction recoverGoalFileWithStaleClosingBraces(raw: string): string | undefined {\n\tlet rootStart = 0;\n\twhile (rootStart < raw.length && /[\\t\\n\\r ]/.test(raw[rootStart] ?? \"\")) rootStart += 1;\n\tif (raw[rootStart] !== \"{\") return undefined;\n\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = rootStart; index < raw.length; index += 1) {\n\t\tconst character = raw[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') inString = true;\n\t\telse if (character === \"{\" || character === \"[\") depth += 1;\n\t\telse if (character === \"}\" || character === \"]\") {\n\t\t\tdepth -= 1;\n\t\t\tif (depth < 0) return undefined;\n\t\t\tif (depth === 0) {\n\t\t\t\tlet hasStaleClosingBrace = false;\n\t\t\t\tfor (let suffixIndex = index + 1; suffixIndex < raw.length; suffixIndex += 1) {\n\t\t\t\t\tconst suffix = raw[suffixIndex];\n\t\t\t\t\tif (suffix === \"}\") hasStaleClosingBrace = true;\n\t\t\t\t\telse if (suffix !== \" \" && suffix !== \"\\t\" && suffix !== \"\\n\" && suffix !== \"\\r\") return undefined;\n\t\t\t\t}\n\t\t\t\treturn hasStaleClosingBrace ? raw.slice(0, index + 1) : undefined;\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isGoal(value: unknown): value is Goal {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.threadId === \"string\" &&\n\t\ttypeof value.objective === \"string\" &&\n\t\tisGoalStatus(value.status) &&\n\t\t(value.tokenBudget === undefined || isNonNegativeSafeInteger(value.tokenBudget)) &&\n\t\thasValidBlockedFields(value, value.status) &&\n\t\tisNonNegativeSafeInteger(value.tokensUsed) &&\n\t\tisNonNegativeSafeInteger(value.timeUsedSeconds) &&\n\t\tisNonNegativeSafeInteger(value.createdAt) &&\n\t\tisNonNegativeSafeInteger(value.updatedAt) &&\n\t\t(value.lastStartedAt === undefined || isNonNegativeSafeInteger(value.lastStartedAt)) &&\n\t\t(value.completedAt === undefined || isNonNegativeSafeInteger(value.completedAt))\n\t);\n}\n\nfunction hasValidBlockedFields(value: Record<string, unknown>, status: GoalStatus): boolean {\n\tif (status === \"blocked\") {\n\t\treturn (\n\t\t\ttypeof value.blockedReason === \"string\" &&\n\t\t\tvalue.blockedReason.trim().length > 0 &&\n\t\t\tisNonNegativeSafeInteger(value.blockedAt)\n\t\t);\n\t}\n\treturn value.blockedReason === undefined && value.blockedAt === undefined;\n}\n\nfunction sanitizeContinuationState(goal: Goal): Goal {\n\tconst next: Goal = { ...goal };\n\tif (!isNonNegativeSafeInteger(next.consecutiveContinuations)) delete next.consecutiveContinuations;\n\tif (typeof next.lastContinuationSignature !== \"string\") delete next.lastContinuationSignature;\n\treturn next;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn isFileSystemError(error, \"ENOENT\");\n}\n\nfunction isFileSystemError(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}
1
+ {"version":3,"file":"persistence.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAEtF,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEzE,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,uBAAuB,GAAG,MAAM,CAAC;AACvC,MAAM,sBAAsB,GAAG,SAAS,CAAC;AACzC,MAAM,8BAA8B,GAAG,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAE3E,MAAM,UAAU,eAAe,CAAC,GAAiB;IAChD,OAAO,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAiB;IAC7C,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC1D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,GAAiB;IACnD,IAAI,CAA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CAAC,wBAAwB,CAAC,IAAI,CAAC,wBAAwB,CAAC;QAAE,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACnG,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,uBAAuB,CAAC;QAAE,OAAO,IAAI,CAAC,uBAAuB,CAAC;IACjG,IAAI,OAAO,IAAI,CAAC,yBAAyB,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,yBAAyB,CAAC;IAC9F,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,IAAY;IACtD,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACzE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Dirent } from \"node:fs\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, sep } from \"node:path\";\nimport { InvalidGoalStoreError, UnsupportedGoalStoreVersionError } from \"./errors.ts\";\nimport type { Goal, GoalFile, GoalStatus, GoalStoreRef } from \"./types.ts\";\nimport { isRecord } from \"./types.ts\";\nimport { isGoalStatus, isNonNegativeSafeInteger } from \"./validation.ts\";\n\nconst STORE_VERSION = 1;\nconst CURRENT_STORE_DIRECTORY = \"goal\";\nconst LEGACY_STORE_DIRECTORY = \"pi-goal\";\nconst LEGACY_BUDGET_LIMITED_STATUSES = [\"budgetLimited\", \"budget_limited\"];\n\nexport function encodedThreadId(ref: GoalStoreRef): string {\n\treturn encodeURIComponent(ref.threadId);\n}\n\nexport function goalFilePath(ref: GoalStoreRef): string {\n\treturn join(ref.baseDir, `${encodedThreadId(ref)}.json`);\n}\n\nexport async function readGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\treturn parseGoalFile(await readFile(goalFilePath(ref), \"utf8\")).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error)) return null;\n\t\tthrow error;\n\t}\n}\n\n/**\n * Imports legacy standalone `pi-goal` state into the current budget-free store.\n *\n * The current store always wins and legacy normalization is confined to this path.\n * Invalid, unsupported, or malformed legacy files are best-effort dead-data imports:\n * they remain untouched and do not block the live current store. Unexpected filesystem\n * failures still propagate.\n *\n * Session-backed stores use their stable thread id. No-session stores enumerate the\n * cwd-keyed legacy bucket because each ephemeral run receives a new thread id, and they\n * inspect both the redirected Senpi-root sibling and the standalone pi agent root.\n * Multiple valid live candidates are reported as a conflict rather than guessed.\n *\n * Returns the imported goal, or null when nothing was migrated.\n */\nexport async function migrateLegacyGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\tawait readFile(goalFilePath(ref), \"utf8\");\n\t\treturn null;\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t}\n\n\tconst legacyCandidates = await readLegacyGoalCandidates(ref);\n\tif (legacyCandidates.length > 1) {\n\t\tthrow new Error(\n\t\t\t`multiple legacy goals found for no-session store: ${legacyCandidates.map(({ path }) => path).join(\", \")}`,\n\t\t);\n\t}\n\tconst candidate = legacyCandidates[0];\n\tif (candidate === undefined) return null;\n\tconst published = await publishMigratedGoalFile(ref, candidate.goal);\n\tawait retireLegacyGoalFile(candidate.path);\n\treturn published ? candidate.goal : null;\n}\n\ninterface LegacyGoalCandidate {\n\tpath: string;\n\tgoal: Goal;\n}\n\nasync function readLegacyGoalCandidates(ref: GoalStoreRef): Promise<LegacyGoalCandidate[]> {\n\tconst legacyBaseDir = legacyBaseDirFor(ref.baseDir);\n\tif (legacyBaseDir === undefined) return [];\n\tconst cwdKey = noSessionCwdKey(ref.baseDir);\n\tif (cwdKey === undefined) {\n\t\tconst candidate = await readLegacyGoalCandidate(goalFilePath({ ...ref, baseDir: legacyBaseDir }));\n\t\treturn candidate === null ? [] : [candidate];\n\t}\n\n\tconst standaloneAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), \".pi\", \"agent\");\n\tconst baseDirs = new Set([\n\t\tlegacyBaseDir,\n\t\tjoin(standaloneAgentDir, \"extensions\", LEGACY_STORE_DIRECTORY, \"no-session\", cwdKey),\n\t]);\n\tconst candidatePaths: string[] = [];\n\tfor (const baseDir of baseDirs) {\n\t\tlet entries: Dirent<string>[];\n\t\ttry {\n\t\t\tentries = await readdir(baseDir, { withFileTypes: true });\n\t\t} catch (error) {\n\t\t\tif (isMissingFile(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".json\")) candidatePaths.push(join(baseDir, entry.name));\n\t\t}\n\t}\n\n\tconst candidates: LegacyGoalCandidate[] = [];\n\tfor (const path of candidatePaths.sort()) {\n\t\tconst candidate = await readLegacyGoalCandidate(path);\n\t\tif (candidate !== null) candidates.push(candidate);\n\t}\n\treturn candidates;\n}\n\nasync function readLegacyGoalCandidate(path: string): Promise<LegacyGoalCandidate | null> {\n\tlet goal: Goal | null;\n\ttry {\n\t\tgoal = parseGoalFile(await readFile(path, \"utf8\"), { legacy: true }).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error) || isIgnoredLegacyStoreError(error)) return null;\n\t\tthrow error;\n\t}\n\tif (goal === null) {\n\t\tawait retireLegacyGoalFile(path);\n\t\treturn null;\n\t}\n\treturn { path, goal };\n}\n\nasync function retireLegacyGoalFile(path: string): Promise<void> {\n\ttry {\n\t\tawait rename(path, `${path}.migrated`);\n\t} catch {\n\t\t// Retirement is best-effort: a preserved legacy file must never fail live migration.\n\t}\n}\n\nfunction isIgnoredLegacyStoreError(error: unknown): boolean {\n\treturn (\n\t\terror instanceof InvalidGoalStoreError ||\n\t\terror instanceof UnsupportedGoalStoreVersionError ||\n\t\terror instanceof SyntaxError\n\t);\n}\n\n/**\n * Maps a current goal-store directory to its legacy `pi-goal` counterpart by replacing\n * the `goal` path segment itself.\n *\n * Both store layouts must map correctly:\n * <sessionDir>/extensions/goal -> <sessionDir>/extensions/pi-goal\n * <agentDir>/extensions/goal/no-session/<cwdKey>\n * -> <agentDir>/extensions/pi-goal/no-session/<cwdKey>\n *\n * Swapping `dirname(baseDir)` only works for the first layout; in the no-session\n * fallback it points inside the current store tree, which both misses real legacy\n * state and can import an unrelated nested directory.\n */\nfunction legacyBaseDirFor(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1) return undefined;\n\tsegments[goalIndex] = LEGACY_STORE_DIRECTORY;\n\treturn segments.join(sep);\n}\n\nfunction noSessionCwdKey(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1 || segments[goalIndex + 1] !== \"no-session\") return undefined;\n\treturn segments[goalIndex + 2];\n}\n\nfunction pathSegments(path: string): string[] {\n\treturn path.split(/[\\\\/]/);\n}\n\nexport async function writeGoalFile(ref: GoalStoreRef, goal: Goal | null): Promise<void> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tawait writeGoalFileAtomic(filePath, `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`);\n}\n\nasync function writeGoalFileAtomic(filePath: string, contents: string): Promise<void> {\n\tconst tempPath = join(dirname(filePath), `.goal-${randomUUID()}.tmp`);\n\ttry {\n\t\tawait writeFile(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait rm(tempPath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, cleanupError],\n\t\t\t\t\"goal store write failed and its temporary file could not be removed\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function publishMigratedGoalFile(ref: GoalStoreRef, goal: Goal): Promise<boolean> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tconst contents = `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`;\n\ttry {\n\t\tawait writeFile(filePath, contents, { encoding: \"utf8\", mode: 0o600, flag: \"wx\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (isFileSystemError(error, \"EEXIST\")) return false;\n\t\tthrow error;\n\t}\n}\n\nfunction parseGoalFile(raw: string, { legacy = false }: { legacy?: boolean } = {}): GoalFile {\n\tconst parsed = parseGoalFileJson(raw);\n\tif (!isRecord(parsed)) throw new InvalidGoalStoreError(\"goal store must be a JSON object\");\n\tif (parsed.version !== STORE_VERSION) throw new UnsupportedGoalStoreVersionError(\"unsupported goal store version\");\n\tconst goal = legacy ? normalizeLegacyGoal(parsed.goal) : parsed.goal;\n\tif (goal !== null && !isGoal(goal)) throw new InvalidGoalStoreError(\"goal store contains an invalid goal\");\n\treturn { version: STORE_VERSION, goal: goal === null ? null : sanitizeContinuationState(goal) };\n}\n\nfunction parseGoalFileJson(raw: string): unknown {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (error) {\n\t\tif (!(error instanceof SyntaxError)) throw error;\n\t\tconst recovered = recoverGoalFileWithStaleClosingBraces(raw);\n\t\tif (recovered === undefined) throw error;\n\t\ttry {\n\t\t\tparsed = JSON.parse(recovered);\n\t\t} catch {\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn parsed;\n}\n\n/**\n * Drops legacy budget enforcement: `tokenBudget` is a budgeting input in `pi-goal`, and\n * `budgetLimited` is a status this fork removed, so a budget-limited legacy goal resumes\n * as `active`. This runs only on the legacy import path.\n */\nfunction normalizeLegacyGoal(value: unknown): unknown {\n\tif (!isRecord(value)) return value;\n\tconst normalized = { ...value };\n\tdelete normalized.tokenBudget;\n\tif (typeof normalized.status === \"string\" && LEGACY_BUDGET_LIMITED_STATUSES.includes(normalized.status)) {\n\t\tnormalized.status = \"active\";\n\t}\n\treturn normalized;\n}\n\nfunction recoverGoalFileWithStaleClosingBraces(raw: string): string | undefined {\n\tlet rootStart = 0;\n\twhile (rootStart < raw.length && /[\\t\\n\\r ]/.test(raw[rootStart] ?? \"\")) rootStart += 1;\n\tif (raw[rootStart] !== \"{\") return undefined;\n\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = rootStart; index < raw.length; index += 1) {\n\t\tconst character = raw[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') inString = true;\n\t\telse if (character === \"{\" || character === \"[\") depth += 1;\n\t\telse if (character === \"}\" || character === \"]\") {\n\t\t\tdepth -= 1;\n\t\t\tif (depth < 0) return undefined;\n\t\t\tif (depth === 0) {\n\t\t\t\tlet hasStaleClosingBrace = false;\n\t\t\t\tfor (let suffixIndex = index + 1; suffixIndex < raw.length; suffixIndex += 1) {\n\t\t\t\t\tconst suffix = raw[suffixIndex];\n\t\t\t\t\tif (suffix === \"}\") hasStaleClosingBrace = true;\n\t\t\t\t\telse if (suffix !== \" \" && suffix !== \"\\t\" && suffix !== \"\\n\" && suffix !== \"\\r\") return undefined;\n\t\t\t\t}\n\t\t\t\treturn hasStaleClosingBrace ? raw.slice(0, index + 1) : undefined;\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isGoal(value: unknown): value is Goal {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.threadId === \"string\" &&\n\t\ttypeof value.objective === \"string\" &&\n\t\tisGoalStatus(value.status) &&\n\t\t(value.tokenBudget === undefined || isNonNegativeSafeInteger(value.tokenBudget)) &&\n\t\thasValidBlockedFields(value, value.status) &&\n\t\tisNonNegativeSafeInteger(value.tokensUsed) &&\n\t\tisNonNegativeSafeInteger(value.timeUsedSeconds) &&\n\t\tisNonNegativeSafeInteger(value.createdAt) &&\n\t\tisNonNegativeSafeInteger(value.updatedAt) &&\n\t\t(value.lastStartedAt === undefined || isNonNegativeSafeInteger(value.lastStartedAt)) &&\n\t\t(value.completedAt === undefined || isNonNegativeSafeInteger(value.completedAt))\n\t);\n}\n\nfunction hasValidBlockedFields(value: Record<string, unknown>, status: GoalStatus): boolean {\n\tif (status === \"blocked\") {\n\t\treturn (\n\t\t\ttypeof value.blockedReason === \"string\" &&\n\t\t\tvalue.blockedReason.trim().length > 0 &&\n\t\t\tisNonNegativeSafeInteger(value.blockedAt)\n\t\t);\n\t}\n\treturn value.blockedReason === undefined && value.blockedAt === undefined;\n}\n\nfunction sanitizeContinuationState(goal: Goal): Goal {\n\tconst next: Goal = { ...goal };\n\tif (!isNonNegativeSafeInteger(next.consecutiveContinuations)) delete next.consecutiveContinuations;\n\tif (!isNonNegativeSafeInteger(next.unattendedContinuations)) delete next.unattendedContinuations;\n\tif (typeof next.lastContinuationSignature !== \"string\") delete next.lastContinuationSignature;\n\treturn next;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn isFileSystemError(error, \"ENOENT\");\n}\n\nfunction isFileSystemError(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}