@caupulican/pi-adaptative 0.92.0 → 0.93.0

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 (159) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/cli/args.d.ts +2 -0
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +24 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/core/agent-session-contracts.d.ts +1 -0
  7. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  8. package/dist/core/agent-session-contracts.js.map +1 -1
  9. package/dist/core/agent-session-services.d.ts +1 -0
  10. package/dist/core/agent-session-services.d.ts.map +1 -1
  11. package/dist/core/agent-session-services.js +1 -0
  12. package/dist/core/agent-session-services.js.map +1 -1
  13. package/dist/core/agent-session.d.ts +1 -6
  14. package/dist/core/agent-session.d.ts.map +1 -1
  15. package/dist/core/agent-session.js +15 -13
  16. package/dist/core/agent-session.js.map +1 -1
  17. package/dist/core/background-lane-controller.d.ts +2 -4
  18. package/dist/core/background-lane-controller.d.ts.map +1 -1
  19. package/dist/core/background-lane-controller.js +0 -1
  20. package/dist/core/background-lane-controller.js.map +1 -1
  21. package/dist/core/compaction-controller.d.ts.map +1 -1
  22. package/dist/core/compaction-controller.js +2 -1
  23. package/dist/core/compaction-controller.js.map +1 -1
  24. package/dist/core/context/context-composition.d.ts +1 -1
  25. package/dist/core/context/context-composition.d.ts.map +1 -1
  26. package/dist/core/context/context-composition.js +1 -1
  27. package/dist/core/context/context-composition.js.map +1 -1
  28. package/dist/core/default-tool-surface.d.ts +0 -10
  29. package/dist/core/default-tool-surface.d.ts.map +1 -1
  30. package/dist/core/default-tool-surface.js +3 -1
  31. package/dist/core/default-tool-surface.js.map +1 -1
  32. package/dist/core/extensions/bundled-virtual-modules.js +8 -0
  33. package/dist/core/extensions/bundled-virtual-modules.js.map +1 -1
  34. package/dist/core/extensions/runner.d.ts +1 -1
  35. package/dist/core/extensions/runner.d.ts.map +1 -1
  36. package/dist/core/extensions/runner.js +1 -1
  37. package/dist/core/extensions/runner.js.map +1 -1
  38. package/dist/core/extensions/virtual-modules.d.ts +4 -0
  39. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  40. package/dist/core/extensions/virtual-modules.js +4 -0
  41. package/dist/core/extensions/virtual-modules.js.map +1 -1
  42. package/dist/core/goal-loop-controller.d.ts +6 -2
  43. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  44. package/dist/core/goal-loop-controller.js +15 -4
  45. package/dist/core/goal-loop-controller.js.map +1 -1
  46. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  47. package/dist/core/goals/compact-goal-context.js +10 -14
  48. package/dist/core/goals/compact-goal-context.js.map +1 -1
  49. package/dist/core/goals/goal-auto-continue-controller.d.ts +0 -2
  50. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
  51. package/dist/core/goals/goal-auto-continue-controller.js +0 -2
  52. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  53. package/dist/core/goals/goal-session-controller.d.ts +7 -7
  54. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  55. package/dist/core/goals/goal-session-controller.js +27 -5
  56. package/dist/core/goals/goal-session-controller.js.map +1 -1
  57. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  58. package/dist/core/goals/goal-tool-core.js +7 -0
  59. package/dist/core/goals/goal-tool-core.js.map +1 -1
  60. package/dist/core/goals/goal-tool-names.d.ts +7 -0
  61. package/dist/core/goals/goal-tool-names.d.ts.map +1 -0
  62. package/dist/core/goals/goal-tool-names.js +8 -0
  63. package/dist/core/goals/goal-tool-names.js.map +1 -0
  64. package/dist/core/model-capability.d.ts +1 -1
  65. package/dist/core/model-capability.d.ts.map +1 -1
  66. package/dist/core/model-capability.js +3 -1
  67. package/dist/core/model-capability.js.map +1 -1
  68. package/dist/core/models/perf-profile.d.ts +2 -1
  69. package/dist/core/models/perf-profile.d.ts.map +1 -1
  70. package/dist/core/models/perf-profile.js +1 -1
  71. package/dist/core/models/perf-profile.js.map +1 -1
  72. package/dist/core/provider-request-context-controller.d.ts.map +1 -1
  73. package/dist/core/provider-request-context-controller.js +6 -5
  74. package/dist/core/provider-request-context-controller.js.map +1 -1
  75. package/dist/core/provider-request-runtime-controller.d.ts.map +1 -1
  76. package/dist/core/provider-request-runtime-controller.js +3 -2
  77. package/dist/core/provider-request-runtime-controller.js.map +1 -1
  78. package/dist/core/runtime-builder.d.ts.map +1 -1
  79. package/dist/core/runtime-builder.js +13 -4
  80. package/dist/core/runtime-builder.js.map +1 -1
  81. package/dist/core/sdk.d.ts +3 -1
  82. package/dist/core/sdk.d.ts.map +1 -1
  83. package/dist/core/sdk.js +3 -1
  84. package/dist/core/sdk.js.map +1 -1
  85. package/dist/core/session-analytics.d.ts +2 -2
  86. package/dist/core/session-analytics.d.ts.map +1 -1
  87. package/dist/core/session-analytics.js +3 -2
  88. package/dist/core/session-analytics.js.map +1 -1
  89. package/dist/core/session-manager-factory.d.ts +1 -1
  90. package/dist/core/session-manager-factory.d.ts.map +1 -1
  91. package/dist/core/session-manager-factory.js +1 -1
  92. package/dist/core/session-manager-factory.js.map +1 -1
  93. package/dist/core/session-role.d.ts.map +1 -1
  94. package/dist/core/session-role.js +2 -0
  95. package/dist/core/session-role.js.map +1 -1
  96. package/dist/core/session-tree-navigator.d.ts +2 -2
  97. package/dist/core/session-tree-navigator.d.ts.map +1 -1
  98. package/dist/core/session-tree-navigator.js +1 -1
  99. package/dist/core/session-tree-navigator.js.map +1 -1
  100. package/dist/core/skill-vault.d.ts +6 -7
  101. package/dist/core/skill-vault.d.ts.map +1 -1
  102. package/dist/core/skill-vault.js +12 -12
  103. package/dist/core/skill-vault.js.map +1 -1
  104. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  105. package/dist/core/tool-capability-policy.js +2 -1
  106. package/dist/core/tool-capability-policy.js.map +1 -1
  107. package/dist/core/tools/edit.d.ts +1 -1
  108. package/dist/core/tools/edit.d.ts.map +1 -1
  109. package/dist/core/tools/edit.js +1 -1
  110. package/dist/core/tools/edit.js.map +1 -1
  111. package/dist/core/tools/file-failure-recovery.d.ts +1 -1
  112. package/dist/core/tools/file-failure-recovery.d.ts.map +1 -1
  113. package/dist/core/tools/file-failure-recovery.js +1 -1
  114. package/dist/core/tools/file-failure-recovery.js.map +1 -1
  115. package/dist/core/tools/goal.d.ts +9 -2
  116. package/dist/core/tools/goal.d.ts.map +1 -1
  117. package/dist/core/tools/goal.js +64 -1
  118. package/dist/core/tools/goal.js.map +1 -1
  119. package/dist/core/tools/grep.d.ts +2 -2
  120. package/dist/core/tools/grep.d.ts.map +1 -1
  121. package/dist/core/tools/grep.js +1 -1
  122. package/dist/core/tools/grep.js.map +1 -1
  123. package/dist/core/tools/read.d.ts +2 -2
  124. package/dist/core/tools/read.d.ts.map +1 -1
  125. package/dist/core/tools/read.js +1 -1
  126. package/dist/core/tools/read.js.map +1 -1
  127. package/dist/core/tools/render-utils.d.ts +1 -0
  128. package/dist/core/tools/render-utils.d.ts.map +1 -1
  129. package/dist/core/tools/render-utils.js +11 -9
  130. package/dist/core/tools/render-utils.js.map +1 -1
  131. package/dist/core/tools/skill.js +2 -2
  132. package/dist/core/tools/skill.js.map +1 -1
  133. package/dist/core/tools/write.d.ts +1 -1
  134. package/dist/core/tools/write.d.ts.map +1 -1
  135. package/dist/core/tools/write.js +1 -1
  136. package/dist/core/tools/write.js.map +1 -1
  137. package/dist/index.d.ts +1 -1
  138. package/dist/index.d.ts.map +1 -1
  139. package/dist/index.js +1 -1
  140. package/dist/index.js.map +1 -1
  141. package/dist/main.d.ts.map +1 -1
  142. package/dist/main.js +2 -0
  143. package/dist/main.js.map +1 -1
  144. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  145. package/dist/modes/interactive/components/bash-execution.js +4 -33
  146. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  147. package/dist/modes/interactive/components/tool-execution.d.ts +3 -0
  148. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/tool-execution.js +63 -27
  150. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  151. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  152. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  153. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  154. package/examples/extensions/sandbox/package-lock.json +2 -2
  155. package/examples/extensions/sandbox/package.json +2 -2
  156. package/examples/extensions/with-deps/package-lock.json +2 -2
  157. package/examples/extensions/with-deps/package.json +1 -1
  158. package/npm-shrinkwrap.json +318 -332
  159. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"compact-goal-context.js","sourceRoot":"","sources":["../../../src/core/goals/compact-goal-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAGzE,OAAO,EAAE,qCAAqC,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAkB,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAExE,MAAM,CAAC,MAAM,+BAA+B,GAAG,qBAAqB,CAAC;AACrE,MAAM,+BAA+B,GAAG,sDAAsD,CAAC;AAE/F,SAAS,WAAW,CAAC,OAAqB;IACzC,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,EAAE,CAAC;IACvC,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC;IAChE,OAAO,OAAO,CAAC,OAAO;SACpB,MAAM,CAAC,CAAC,IAAI,EAAuB,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;SAC3D,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;SACxB,IAAI,CAAC,IAAI,CAAC,CAAC;AACd,CAAC;AAED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AAgB,GAAG,QAAQ,CAAC,IAAI,CACrC,CAAC,OAAO,EAAE,EAAE,CACX,CAAC,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,UAAU,KAAK,qCAAqC,CAAC;QAC3F,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,+BAA+B,CAAC,CACjE,CAAC;IACF,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;IAC9E,IAAI,CAAC,KAAK,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC;QAAE,OAAO,QAAQ,CAAC;IACpE,OAAO;QACN,GAAG,QAAQ;QACX,mBAAmB,CAClB,+BAA+B,EAC/B,wBAAwB,CAAC,KAAK,EAAE,gBAAgB,CAAC,EACjD,KAAK,EACL,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,IAAI,CAAC,EAAE,EACvD,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CACxB;KACD,CAAC;AACH,CAAC","sourcesContent":["import { createCustomMessage } from \"@caupulican/pi-agent-core/messages\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport type { TextContent } from \"@caupulican/pi-ai\";\nimport { GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE } from \"./goal-continuation-prompt.ts\";\nimport { projectGoalRecord } from \"./goal-record.ts\";\nimport { type GoalState, isGoalExecutionActive } from \"./goal-state.ts\";\n\nexport const ACTIVE_GOAL_CONTEXT_CUSTOM_TYPE = \"active_goal_context\";\nconst LEGACY_GOAL_CONTINUATION_PREFIX = \"Goal continuation context\\n=========================\";\n\nfunction messageText(message: AgentMessage): string {\n\tif (message.role !== \"user\") return \"\";\n\tif (typeof message.content === \"string\") return message.content;\n\treturn message.content\n\t\t.filter((part): part is TextContent => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\\n\");\n}\n\nfunction isGoalContextMessage(message: AgentMessage): boolean {\n\tif (message.role === \"custom\") {\n\t\treturn (\n\t\t\tmessage.customType === GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE ||\n\t\t\tmessage.customType === ACTIVE_GOAL_CONTEXT_CUSTOM_TYPE\n\t\t);\n\t}\n\treturn messageText(message).startsWith(LEGACY_GOAL_CONTINUATION_PREFIX);\n}\n\nexport function formatCompactGoalContext(state: GoalState, continuationTurn: boolean): string {\n\tconst record = projectGoalRecord(state);\n\tconst budgetText = record.tokenBudget === undefined ? \"unbounded\" : String(record.tokenBudget);\n\tconst remainingText = record.tokensRemaining === undefined ? \"unbounded\" : String(record.tokensRemaining);\n\tconst instruction = continuationTurn\n\t\t? \"Continue now: inspect authoritative state, make concrete progress toward full objective.\"\n\t\t: \"Goal persists; current user message steers this turn, never replaces objective.\";\n\tconst encodedRecord = JSON.stringify({\n\t\tobjective: record.objective,\n\t\ttokensUsed: record.tokensUsed,\n\t\ttokenBudget: budgetText,\n\t\ttokensRemaining: remainingText,\n\t})\n\t\t.replaceAll(\"<\", \"\\\\u003c\")\n\t\t.replaceAll(\">\", \"\\\\u003e\");\n\treturn [\n\t\t\"ACTIVE GOAL\",\n\t\tencodedRecord,\n\t\tinstruction,\n\t\t\"Use task_steps for decomposition, delegate for workers, tool/artifact results as evidence. Keep active unless completion is proven or same genuine blocker persists 3 goal turns.\",\n\t].join(\"\\n\");\n}\n\n/**\n * Replace every historical goal continuation payload with one current compact projection. The\n * projection exists only in the provider request returned from context assembly; it is never\n * appended to the transcript or session log.\n */\nexport function injectCompactGoalContext(messages: AgentMessage[], state: GoalState | undefined): AgentMessage[] {\n\tconst continuationTurn = messages.some(\n\t\t(message) =>\n\t\t\t(message.role === \"custom\" && message.customType === GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE) ||\n\t\t\tmessageText(message).startsWith(LEGACY_GOAL_CONTINUATION_PREFIX),\n\t);\n\tconst filtered = messages.filter((message) => !isGoalContextMessage(message));\n\tif (!state || !isGoalExecutionActive(state.status)) return filtered;\n\treturn [\n\t\t...filtered,\n\t\tcreateCustomMessage(\n\t\t\tACTIVE_GOAL_CONTEXT_CUSTOM_TYPE,\n\t\t\tformatCompactGoalContext(state, continuationTurn),\n\t\t\tfalse,\n\t\t\t{ goalId: state.goalId, revision: state.revision ?? 0 },\n\t\t\tnew Date().toISOString(),\n\t\t),\n\t];\n}\n"]}
1
+ {"version":3,"file":"compact-goal-context.js","sourceRoot":"","sources":["../../../src/core/goals/compact-goal-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAGzE,OAAO,EAAE,qCAAqC,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAkB,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAExE,MAAM,CAAC,MAAM,+BAA+B,GAAG,qBAAqB,CAAC;AACrE,MAAM,+BAA+B,GAAG,sDAAsD,CAAC;AAE/F,SAAS,WAAW,CAAC,OAAqB;IACzC,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,EAAE,CAAC;IACvC,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC;IAChE,OAAO,OAAO,CAAC,OAAO;SACpB,MAAM,CAAC,CAAC,IAAI,EAAuB,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;SAC3D,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;SACxB,IAAI,CAAC,IAAI,CAAC,CAAC;AACd,CAAC;AAED,SAAS,oBAAoB,CAAC,OAAqB;IAClD,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC/B,OAAO,CACN,OAAO,CAA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,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;IAC9E,IAAI,CAAC,KAAK,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC;QAAE,OAAO,QAAQ,CAAC;IACpE,OAAO;QACN,GAAG,QAAQ;QACX,mBAAmB,CAClB,+BAA+B,EAC/B,wBAAwB,CAAC,KAAK,EAAE,gBAAgB,CAAC,EACjD,KAAK,EACL,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,IAAI,CAAC,EAAE,EACvD,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CACxB;KACD,CAAC;AACH,CAAC","sourcesContent":["import { createCustomMessage } from \"@caupulican/pi-agent-core/messages\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport type { TextContent } from \"@caupulican/pi-ai\";\nimport { GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE } from \"./goal-continuation-prompt.ts\";\nimport { projectGoalRecord } from \"./goal-record.ts\";\nimport { type GoalState, isGoalExecutionActive } from \"./goal-state.ts\";\n\nexport const ACTIVE_GOAL_CONTEXT_CUSTOM_TYPE = \"active_goal_context\";\nconst LEGACY_GOAL_CONTINUATION_PREFIX = \"Goal continuation context\\n=========================\";\n\nfunction messageText(message: AgentMessage): string {\n\tif (message.role !== \"user\") return \"\";\n\tif (typeof message.content === \"string\") return message.content;\n\treturn message.content\n\t\t.filter((part): part is TextContent => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\\n\");\n}\n\nfunction isGoalContextMessage(message: AgentMessage): boolean {\n\tif (message.role === \"custom\") {\n\t\treturn (\n\t\t\tmessage.customType === GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE ||\n\t\t\tmessage.customType === ACTIVE_GOAL_CONTEXT_CUSTOM_TYPE\n\t\t);\n\t}\n\treturn messageText(message).startsWith(LEGACY_GOAL_CONTINUATION_PREFIX);\n}\n\nexport function formatCompactGoalContext(state: GoalState, continuationTurn: boolean): string {\n\tconst record = projectGoalRecord(state);\n\tconst instruction = continuationTurn\n\t\t? \"Continue now: pursue full objective.\"\n\t\t: \"current user message steers this turn.\";\n\tconst compactRecord =\n\t\trecord.tokenBudget === undefined\n\t\t\t? { untrustedObjective: record.objective }\n\t\t\t: { untrustedObjective: record.objective, tokenBudget: String(record.tokenBudget) };\n\tconst encodedRecord = JSON.stringify(compactRecord).replaceAll(\"<\", \"\\\\u003c\").replaceAll(\">\", \"\\\\u003e\");\n\treturn [\n\t\t\"ACTIVE GOAL — HOST-OWNED CONTINUATION\",\n\t\tencodedRecord,\n\t\tinstruction,\n\t\t\"get_goal; task_steps for decomposition.\",\n\t\t'Progress: update_goal status \"active\".',\n\t\t'update_goal with status \"complete\" after requirement-by-requirement audit; \"blocked\" only after same blocking condition lasts 3 consecutive goal turns; else continue.',\n\t].join(\"\\n\");\n}\n\n/**\n * Replace every historical goal continuation payload with one current compact projection. The\n * projection exists only in the provider request returned from context assembly; it is never\n * appended to the transcript or session log.\n */\nexport function injectCompactGoalContext(messages: AgentMessage[], state: GoalState | undefined): AgentMessage[] {\n\tconst continuationTurn = messages.some(\n\t\t(message) =>\n\t\t\t(message.role === \"custom\" && message.customType === GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE) ||\n\t\t\tmessageText(message).startsWith(LEGACY_GOAL_CONTINUATION_PREFIX),\n\t);\n\tconst filtered = messages.filter((message) => !isGoalContextMessage(message));\n\tif (!state || !isGoalExecutionActive(state.status)) return filtered;\n\treturn [\n\t\t...filtered,\n\t\tcreateCustomMessage(\n\t\t\tACTIVE_GOAL_CONTEXT_CUSTOM_TYPE,\n\t\t\tformatCompactGoalContext(state, continuationTurn),\n\t\t\tfalse,\n\t\t\t{ goalId: state.goalId, revision: state.revision ?? 0 },\n\t\t\tnew Date().toISOString(),\n\t\t),\n\t];\n}\n"]}
@@ -1,12 +1,10 @@
1
1
  import type { AgentSessionEvent, GoalContinuationLoopOptions, GoalContinuationLoopResult, PromptOptions } from "../agent-session.ts";
2
- import type { ModelCapabilityProfile } from "../model-capability.ts";
3
2
  import type { SettingsManager } from "../settings-manager.ts";
4
3
  import type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from "./goal-runtime-snapshot.ts";
5
4
  export interface GoalAutoContinueControllerDeps {
6
5
  isDisposed(): boolean;
7
6
  isGoalToolActive(): boolean;
8
7
  getSettingsManager(): SettingsManager;
9
- getModelCapabilityProfile(): ModelCapabilityProfile;
10
8
  getGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;
11
9
  hasInFlightLaneForGoal(goalId: string): boolean;
12
10
  continueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;
@@ -1 +1 @@
1
- {"version":3,"file":"goal-auto-continue-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAEnG,MAAM,WAAW,8BAA8B;IAC9C,UAAU,IAAI,OAAO,CAAC;IACtB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,kBAAkB,IAAI,eAAe,CAAC;IACtC,yBAAyB,IAAI,sBAAsB,CAAC;IACpD,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAAC;IACnF,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IAChD,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAC5F,gBAAgB,IAAI,OAAO,CAAC;IAC5B,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,uBAAuB,IAAI,IAAI,CAAC;IAChC,IAAI,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACrC;AAED,mFAAmF;AACnF,qBAAa,0BAA0B;IACtC,OAAO,CAAC,MAAM,CAA4C;IAC1D,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiC;IAEtD,YAAY,IAAI,EAAE,8BAA8B,EAE/C;IAED,UAAU,IAAI,IAAI,CAKjB;IAED,gBAAgB,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,IAAI,CAuB9C;IAEK,iBAAiB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAqBjG;IAED,OAAO,CAAC,iBAAiB;YAOX,YAAY;IAoB1B,OAAO,CAAC,aAAa;CAUrB"}
1
+ {"version":3,"file":"goal-auto-continue-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAEnG,MAAM,WAAW,8BAA8B;IAC9C,UAAU,IAAI,OAAO,CAAC;IACtB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,kBAAkB,IAAI,eAAe,CAAC;IACtC,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAAC;IACnF,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IAChD,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAC5F,gBAAgB,IAAI,OAAO,CAAC;IAC5B,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,uBAAuB,IAAI,IAAI,CAAC;IAChC,IAAI,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACrC;AAED,mFAAmF;AACnF,qBAAa,0BAA0B;IACtC,OAAO,CAAC,MAAM,CAA4C;IAC1D,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiC;IAEtD,YAAY,IAAI,EAAE,8BAA8B,EAE/C;IAED,UAAU,IAAI,IAAI,CAKjB;IAED,gBAAgB,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,IAAI,CAsB9C;IAEK,iBAAiB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAqBjG;IAED,OAAO,CAAC,iBAAiB;YAOX,YAAY;IAoB1B,OAAO,CAAC,aAAa;CAUrB"}
@@ -14,8 +14,6 @@ export class GoalAutoContinueController {
14
14
  scheduleFromIdle(options) {
15
15
  if (options?.autoContinueGoal === false || this._isContinuing || this.deps.isDisposed())
16
16
  return;
17
- if (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled)
18
- return;
19
17
  const { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps
20
18
  .getSettingsManager()
21
19
  .getAutonomySettings();
@@ -1 +1 @@
1
- {"version":3,"file":"goal-auto-continue-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAyBjE,mFAAmF;AACnF,MAAM,OAAO,0BAA0B;IAKtC,YAAY,IAAoC;QAHxC,kBAAa,GAAG,KAAK,CAAC;QAI7B,I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B,UAAU;YACV,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC;SACzF,CAAC;IACH,CAAC;CACD","sourcesContent":["import { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n} from \"../agent-session.ts\";\nimport type { ModelCapabilityProfile } from \"../model-capability.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goal-runtime-snapshot.ts\";\n\nexport interface GoalAutoContinueControllerDeps {\n\tisDisposed(): boolean;\n\tisGoalToolActive(): boolean;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\thasInFlightLaneForGoal(goalId: string): boolean;\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\tisForegroundBusy(): boolean;\n\twaitForForegroundIdle(): Promise<void>;\n\tmarkGoalToolUnavailable(): void;\n\temit(event: AgentSessionEvent): void;\n}\n\n/** Owns the single-flight goal continuation loop and its foreground-idle timer. */\nexport class GoalAutoContinueController {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _isContinuing = false;\n\tprivate readonly deps: GoalAutoContinueControllerDeps;\n\n\tconstructor(deps: GoalAutoContinueControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tclearTimer(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\tscheduleFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isContinuing || this.deps.isDisposed()) return;\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\tconst activeGoalId = snapshot.goalState?.goalId;\n\t\tif (activeGoalId !== undefined && this.deps.hasInFlightLaneForGoal(activeGoalId)) return;\n\n\t\tthis.clearTimer();\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tvoid this.runScheduled();\n\t\t}, goalAutoContinueDelayMs);\n\t\tconst timer = this._timer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tasync continueExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (this._isContinuing) return this.skippedResult(options, \"already_continuing\");\n\t\tconst initialGuard = this.unavailableResult(options);\n\t\tif (initialGuard) return initialGuard;\n\t\tthis._isContinuing = true;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tif (this.deps.isForegroundBusy()) await this.deps.waitForForegroundIdle();\n\t\t\t\tconst postWaitGuard = this.unavailableResult(options);\n\t\t\t\tif (postWaitGuard) return postWaitGuard;\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.deps.continueGoalLoop(options);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A different foreground owner can acquire the Agent after the idle event but before\n\t\t\t\t\t// prompt admission. Wait for that exact run and retry without terminalizing the goal.\n\t\t\t\t\tif (!(error instanceof AgentBusyError)) throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._isContinuing = false;\n\t\t}\n\t}\n\n\tprivate unavailableResult(options: GoalContinuationLoopOptions): GoalContinuationLoopResult | undefined {\n\t\tif (this.deps.isDisposed()) return this.skippedResult(options, \"session_disposed\");\n\t\tif (this.deps.isGoalToolActive()) return undefined;\n\t\tthis.deps.markGoalToolUnavailable();\n\t\treturn this.skippedResult(options, \"goal_tool_unavailable\");\n\t}\n\n\tprivate async runScheduled(): Promise<void> {\n\t\tif (this._isContinuing || this.deps.isDisposed()) return;\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\ttry {\n\t\t\tawait this.continueExclusive({\n\t\t\t\tmaxTurns: goalContinueTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t}\n\t}\n\n\tprivate skippedResult(\n\t\toptions: GoalContinuationLoopOptions,\n\t\tstopReason: \"already_continuing\" | \"session_disposed\" | \"goal_tool_unavailable\",\n\t): GoalContinuationLoopResult {\n\t\treturn {\n\t\t\tturnsSubmitted: 0,\n\t\t\tstopReason,\n\t\t\tfinalSnapshot: this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns }),\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"goal-auto-continue-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAuBjE,mFAAmF;AACnF,MAAM,OAAO,0BAA0B;IAKtC,YAAY,IAAoC;QAHxC,kBAAa,GAAG,KAAK,CAAC;QAI7B,IAA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O,CAAC,aAAa,EAAE,CAAC;SACzF,CAAC;IACH,CAAC;CACD","sourcesContent":["import { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n} from \"../agent-session.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goal-runtime-snapshot.ts\";\n\nexport interface GoalAutoContinueControllerDeps {\n\tisDisposed(): boolean;\n\tisGoalToolActive(): boolean;\n\tgetSettingsManager(): SettingsManager;\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\thasInFlightLaneForGoal(goalId: string): boolean;\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\tisForegroundBusy(): boolean;\n\twaitForForegroundIdle(): Promise<void>;\n\tmarkGoalToolUnavailable(): void;\n\temit(event: AgentSessionEvent): void;\n}\n\n/** Owns the single-flight goal continuation loop and its foreground-idle timer. */\nexport class GoalAutoContinueController {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _isContinuing = false;\n\tprivate readonly deps: GoalAutoContinueControllerDeps;\n\n\tconstructor(deps: GoalAutoContinueControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tclearTimer(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\tscheduleFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\tconst activeGoalId = snapshot.goalState?.goalId;\n\t\tif (activeGoalId !== undefined && this.deps.hasInFlightLaneForGoal(activeGoalId)) return;\n\n\t\tthis.clearTimer();\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tvoid this.runScheduled();\n\t\t}, goalAutoContinueDelayMs);\n\t\tconst timer = this._timer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tasync continueExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (this._isContinuing) return this.skippedResult(options, \"already_continuing\");\n\t\tconst initialGuard = this.unavailableResult(options);\n\t\tif (initialGuard) return initialGuard;\n\t\tthis._isContinuing = true;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tif (this.deps.isForegroundBusy()) await this.deps.waitForForegroundIdle();\n\t\t\t\tconst postWaitGuard = this.unavailableResult(options);\n\t\t\t\tif (postWaitGuard) return postWaitGuard;\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.deps.continueGoalLoop(options);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A different foreground owner can acquire the Agent after the idle event but before\n\t\t\t\t\t// prompt admission. Wait for that exact run and retry without terminalizing the goal.\n\t\t\t\t\tif (!(error instanceof AgentBusyError)) throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._isContinuing = false;\n\t\t}\n\t}\n\n\tprivate unavailableResult(options: GoalContinuationLoopOptions): GoalContinuationLoopResult | undefined {\n\t\tif (this.deps.isDisposed()) return this.skippedResult(options, \"session_disposed\");\n\t\tif (this.deps.isGoalToolActive()) return undefined;\n\t\tthis.deps.markGoalToolUnavailable();\n\t\treturn this.skippedResult(options, \"goal_tool_unavailable\");\n\t}\n\n\tprivate async runScheduled(): Promise<void> {\n\t\tif (this._isContinuing || this.deps.isDisposed()) return;\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\ttry {\n\t\t\tawait this.continueExclusive({\n\t\t\t\tmaxTurns: goalContinueTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t}\n\t}\n\n\tprivate skippedResult(\n\t\toptions: GoalContinuationLoopOptions,\n\t\tstopReason: \"already_continuing\" | \"session_disposed\" | \"goal_tool_unavailable\",\n\t): GoalContinuationLoopResult {\n\t\treturn {\n\t\t\tturnsSubmitted: 0,\n\t\t\tstopReason,\n\t\t\tfinalSnapshot: this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns }),\n\t\t};\n\t}\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { SessionManager } from "@caupulican/pi-agent-core/session";
2
- import type { AgentMessage } from "@caupulican/pi-agent-core/types";
2
+ import type { AgentMessage, AgentRunawayStopInfo } from "@caupulican/pi-agent-core/types";
3
3
  import type { AssistantMessage } from "@caupulican/pi-ai";
4
4
  import type { GoalContinuationLoopOptions, GoalContinuationLoopResult, GoalContinuationOnceOptions, GoalContinuationOnceResult, PromptOptions } from "../agent-session-contracts.ts";
5
5
  import type { LaneRecord } from "../autonomy/lane-tracker.ts";
@@ -70,11 +70,14 @@ export declare class GoalSessionController {
70
70
  }[]): void;
71
71
  endQueuedOwnerChatGoalExecution(): void;
72
72
  admitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission;
73
- /** Attribute turn/wall-clock telemetry after usage has already been charged per response. */
74
- recordContinuationPass(pass: {
73
+ /** Attribute turn/wall-clock telemetry without inferring progress (public/manual accounting seam). */
74
+ recordContinuationTelemetry(pass: {
75
75
  turns: number;
76
76
  wallClockMs: number;
77
77
  }): void;
78
+ /** Attribute one host-driven pass and derive stall state from the authoritative revision. */
79
+ private recordContinuationPass;
80
+ private persistContinuationPass;
78
81
  /** Begin one foreground execution whose provider usage belongs to the specified active goal. */
79
82
  beginExecution(goalId: string | undefined, options?: {
80
83
  adoptNewGoal?: boolean;
@@ -105,10 +108,7 @@ export declare class GoalSessionController {
105
108
  private resolveExecutionState;
106
109
  private flushPendingExecutionUsage;
107
110
  markToolUnavailable(): void;
108
- markRunawayBlocked(info: {
109
- signature: string;
110
- repeats: number;
111
- }): boolean;
111
+ markHarnessGuardBlocked(info: AgentRunawayStopInfo): boolean;
112
112
  markTerminalToolFailureBlocked(toolName: string): boolean;
113
113
  getRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;
114
114
  continueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult>;
@@ -1 +1 @@
1
- {"version":3,"file":"goal-session-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAC1B,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AA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KAAO,GACvE,kBAAkB,GAAG,SAAS,CAmBhC;IAED,YAAY,CAAC,KAAK,EAAE,kBAAkB,GAAG,SAAS,GAAG,IAAI,CAKxD;IAED,iHAAiH;IACjH,oBAAoB,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAmBpD;IAED,OAAO,CAAC,oBAAoB;IA4B5B,0BAA0B,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAaxD;IAED,iBAAiB,CAAC,SAAS,EAAE,0BAA0B,GAAG,SAAS,GAAG,IAAI,CAEzE;IAED,sBAAsB,CAAC,KAAK,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,GAAG,SAAS,CAU1E;IAED;;;;;;;;;OASG;IACH,mCAAmC,IAAI,OAAO,CAI7C;IAED,4FAA4F;IAC5F,oBAAoB,IAAI,MAAM,GAAG,SAAS,CA2CzC;IAED,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,0BAA0B;IAsBlC,mBAAmB,IAAI,IAAI,CAK1B;IAED,uBAAuB,CAAC,IAAI,EAAE,oBAAoB,GAAG,OAAO,CAM3D;IAED,8BAA8B,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAKxD;IAED,kBAAkB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAQ7E;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,kBAAkB,IAAI,IAAI,CAEzB;IAED,OAAO,CAAC,yBAAyB;IASjC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,cAAc;CAOtB"}
@@ -135,19 +135,38 @@ export class GoalSessionController {
135
135
  this.saveState(result.state, current ? getGoalStateRevision(current) : undefined);
136
136
  return { status: "started", state: result.state };
137
137
  }
138
- /** Attribute turn/wall-clock telemetry after usage has already been charged per response. */
138
+ /** Attribute turn/wall-clock telemetry without inferring progress (public/manual accounting seam). */
139
+ recordContinuationTelemetry(pass) {
140
+ this.persistContinuationPass(pass);
141
+ }
142
+ /** Attribute one host-driven pass and derive stall state from the authoritative revision. */
139
143
  recordContinuationPass(pass) {
144
+ this.persistContinuationPass(pass);
145
+ }
146
+ persistContinuationPass(pass) {
140
147
  const state = this.getState();
141
148
  if (!state)
142
149
  return;
143
- const updated = applyGoalEvent(state, {
150
+ if (pass.goalId !== undefined && state.goalId !== pass.goalId) {
151
+ this.deps.emitWarning(`Goal continuation accounting skipped because goal '${pass.goalId}' was replaced by '${state.goalId}' during the pass.`);
152
+ return;
153
+ }
154
+ const now = new Date().toISOString();
155
+ let updated = applyGoalEvent(state, {
144
156
  type: "record_continuation_budget",
145
157
  turns: pass.turns,
146
158
  wallClockMs: pass.wallClockMs,
147
159
  tokens: 0,
148
160
  spendUsd: 0,
149
- now: new Date().toISOString(),
161
+ now,
150
162
  });
163
+ if (pass.progressRevision !== undefined &&
164
+ pass.stallTurns !== undefined &&
165
+ isGoalExecutionActive(state.status) &&
166
+ (state.progressRevision ?? 0) <= pass.progressRevision &&
167
+ state.stallTurns <= pass.stallTurns) {
168
+ updated = applyGoalEvent(updated, { type: "no_progress", now });
169
+ }
151
170
  this.saveState(updated, getGoalStateRevision(state));
152
171
  }
153
172
  /** Begin one foreground execution whose provider usage belongs to the specified active goal. */
@@ -346,8 +365,11 @@ export class GoalSessionController {
346
365
  markToolUnavailable() {
347
366
  this.stopActiveGoal("blocked", "goal_tool_unavailable: the active capability surface cannot update durable goal state");
348
367
  }
349
- markRunawayBlocked(info) {
350
- return this.stopActiveGoal("blocked", `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`);
368
+ markHarnessGuardBlocked(info) {
369
+ const reason = info.reason === "provider_turn_limit"
370
+ ? `provider_turn_limit: reached the ${info.repeats}-request provider-turn cost fuse`
371
+ : `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;
372
+ return this.stopActiveGoal("blocked", reason);
351
373
  }
352
374
  markTerminalToolFailureBlocked(toolName) {
353
375
  return this.stopActiveGoal("blocked", `terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`);
@@ -1 +1 @@
1
- {"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAaxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAExE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvG,OAAO,EACN,wBAAwB,GAGxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAChH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAEN,qBAAqB,EACrB,mBAAmB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AAmBjC;;;;;;;;;;GAUG;AACH,MAAM,kCAAkC,GAAG,KAAK,CAAC;AAEjD,MAAM,wBAAwB,GAAkB,MAAM,CAAC,oBAAoB,CAAC,CAAC;AA2B7E;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAQjC,YAAY,IAA+B;QAH1B,yBAAoB,GAAG,IAAI,OAAO,EAAqC,CAAC;QAIxF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI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AAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC;QACxF,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,KAAK,kBAAkB,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC;QACtF,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC,CAAC;IACjE,CAAC;IAEO,iBAAiB,CAAC,MAAc;QACvC,IAAI,CAAC,cAAc,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAEO,cAAc,CAAC,MAAsD,EAAE,MAAc;QAC5F,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport {\n\ttype ExplicitGoalStartAuthority,\n\tparseExplicitChatGoal,\n\tpriorUserPromptText,\n} from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tgetBackgroundToolTasks(): readonly BackgroundToolTaskRef[];\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\ninterface QueuedOwnerChatGoal {\n\ttext: string;\n\tauthority: ExplicitGoalStartAuthority;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\tprivate readonly queuedOwnerChatGoals = new WeakMap<AgentMessage, QueuedOwnerChatGoal>();\n\tprivate queuedOwnerChatExecutionLease: GoalExecutionLease | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: (text, options) => this.deps.prompt(text, options),\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): ChatGoalAdmission {\n\t\treturn this.admitExplicitChatGoal(text, undefined, priorUserPromptText(messages, text));\n\t}\n\n\tstartOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): string | undefined {\n\t\tconst admission = this.admitOwnerChatGoal(text, messages);\n\t\tif (admission.status === \"started\") return admission.state.goalId;\n\t\tif (admission.status === \"unfinished_goal_exists\") {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Explicit chat goal was not started because unfinished goal '${admission.state.goalId}' is ${admission.state.status}. Complete, clear, or explicitly replace it first.`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tqueueOwnerChatGoal(message: AgentMessage, text: string, authority: ExplicitGoalStartAuthority): void {\n\t\tthis.queuedOwnerChatGoals.set(message, { text, authority });\n\t}\n\n\tactivateQueuedOwnerChatGoal(message: AgentMessage, messages: readonly { role: string; content?: unknown }[]): void {\n\t\tconst queued = this.queuedOwnerChatGoals.get(message);\n\t\tif (!queued) return;\n\t\tthis.queuedOwnerChatGoals.delete(message);\n\t\tconst goalId = this.startOwnerChatGoal(queued.text, messages);\n\t\tif (!goalId) return;\n\t\tthis.setStartAuthority(queued.authority);\n\t\tconst lease = this.beginExecution(goalId);\n\t\tif (!lease) {\n\t\t\tthis.setStartAuthority(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.queuedOwnerChatExecutionLease = lease;\n\t}\n\n\tendQueuedOwnerChatGoalExecution(): void {\n\t\tconst lease = this.queuedOwnerChatExecutionLease;\n\t\tif (!lease) return;\n\t\tthis.queuedOwnerChatExecutionLease = undefined;\n\t\tthis.setStartAuthority(undefined);\n\t\tthis.endExecution(lease);\n\t}\n\n\tadmitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission {\n\t\tconst admittedAt = now ?? new Date().toISOString();\n\t\tconst parsed = parseExplicitChatGoal(text, priorUserText);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${admittedAt}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tadmittedAt,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry after usage has already been charged per response. */\n\trecordContinuationPass(pass: { turns: number; wallClockMs: number }): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(input: { tokenBudget?: number }): string | undefined {\n\t\tconst authority = this.startAuthority;\n\t\tif (!authority) return \"goal start requires explicit owner authorization in the current prompt.\";\n\t\tif (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {\n\t\t\treturn \"tokenBudget requires an exact numeric token ceiling in the current owner prompt.\";\n\t\t}\n\t\tif (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {\n\t\t\treturn `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkRunawayBlocked(info: { signature: string; repeats: number }): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`,\n\t\t);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t\tbackgroundToolTasks: this.deps.getBackgroundToolTasks(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
1
+ {"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAaxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAExE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAA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\"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage, AgentRunawayStopInfo } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport {\n\ttype ExplicitGoalStartAuthority,\n\tparseExplicitChatGoal,\n\tpriorUserPromptText,\n} from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tgetBackgroundToolTasks(): readonly BackgroundToolTaskRef[];\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\ninterface QueuedOwnerChatGoal {\n\ttext: string;\n\tauthority: ExplicitGoalStartAuthority;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\tprivate readonly queuedOwnerChatGoals = new WeakMap<AgentMessage, QueuedOwnerChatGoal>();\n\tprivate queuedOwnerChatExecutionLease: GoalExecutionLease | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: (text, options) => this.deps.prompt(text, options),\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): ChatGoalAdmission {\n\t\treturn this.admitExplicitChatGoal(text, undefined, priorUserPromptText(messages, text));\n\t}\n\n\tstartOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): string | undefined {\n\t\tconst admission = this.admitOwnerChatGoal(text, messages);\n\t\tif (admission.status === \"started\") return admission.state.goalId;\n\t\tif (admission.status === \"unfinished_goal_exists\") {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Explicit chat goal was not started because unfinished goal '${admission.state.goalId}' is ${admission.state.status}. Complete, clear, or explicitly replace it first.`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tqueueOwnerChatGoal(message: AgentMessage, text: string, authority: ExplicitGoalStartAuthority): void {\n\t\tthis.queuedOwnerChatGoals.set(message, { text, authority });\n\t}\n\n\tactivateQueuedOwnerChatGoal(message: AgentMessage, messages: readonly { role: string; content?: unknown }[]): void {\n\t\tconst queued = this.queuedOwnerChatGoals.get(message);\n\t\tif (!queued) return;\n\t\tthis.queuedOwnerChatGoals.delete(message);\n\t\tconst goalId = this.startOwnerChatGoal(queued.text, messages);\n\t\tif (!goalId) return;\n\t\tthis.setStartAuthority(queued.authority);\n\t\tconst lease = this.beginExecution(goalId);\n\t\tif (!lease) {\n\t\t\tthis.setStartAuthority(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.queuedOwnerChatExecutionLease = lease;\n\t}\n\n\tendQueuedOwnerChatGoalExecution(): void {\n\t\tconst lease = this.queuedOwnerChatExecutionLease;\n\t\tif (!lease) return;\n\t\tthis.queuedOwnerChatExecutionLease = undefined;\n\t\tthis.setStartAuthority(undefined);\n\t\tthis.endExecution(lease);\n\t}\n\n\tadmitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission {\n\t\tconst admittedAt = now ?? new Date().toISOString();\n\t\tconst parsed = parseExplicitChatGoal(text, priorUserText);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${admittedAt}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tadmittedAt,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry without inferring progress (public/manual accounting seam). */\n\trecordContinuationTelemetry(pass: { turns: number; wallClockMs: number }): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\t/** Attribute one host-driven pass and derive stall state from the authoritative revision. */\n\tprivate recordContinuationPass(pass: {\n\t\tturns: number;\n\t\twallClockMs: number;\n\t\tgoalId: string;\n\t\tprogressRevision: number;\n\t\tstallTurns: number;\n\t}): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\tprivate persistContinuationPass(\n\t\tpass: { turns: number; wallClockMs: number } & Partial<\n\t\t\tPick<GoalState, \"goalId\" | \"progressRevision\" | \"stallTurns\">\n\t\t>,\n\t): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tif (pass.goalId !== undefined && state.goalId !== pass.goalId) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal continuation accounting skipped because goal '${pass.goalId}' was replaced by '${state.goalId}' during the pass.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst now = new Date().toISOString();\n\t\tlet updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow,\n\t\t});\n\t\tif (\n\t\t\tpass.progressRevision !== undefined &&\n\t\t\tpass.stallTurns !== undefined &&\n\t\t\tisGoalExecutionActive(state.status) &&\n\t\t\t(state.progressRevision ?? 0) <= pass.progressRevision &&\n\t\t\tstate.stallTurns <= pass.stallTurns\n\t\t) {\n\t\t\tupdated = applyGoalEvent(updated, { type: \"no_progress\", now });\n\t\t}\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(input: { tokenBudget?: number }): string | undefined {\n\t\tconst authority = this.startAuthority;\n\t\tif (!authority) return \"goal start requires explicit owner authorization in the current prompt.\";\n\t\tif (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {\n\t\t\treturn \"tokenBudget requires an exact numeric token ceiling in the current owner prompt.\";\n\t\t}\n\t\tif (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {\n\t\t\treturn `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkHarnessGuardBlocked(info: AgentRunawayStopInfo): boolean {\n\t\tconst reason =\n\t\t\tinfo.reason === \"provider_turn_limit\"\n\t\t\t\t? `provider_turn_limit: reached the ${info.repeats}-request provider-turn cost fuse`\n\t\t\t\t: `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;\n\t\treturn this.stopActiveGoal(\"blocked\", reason);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t\tbackgroundToolTasks: this.deps.getBackgroundToolTasks(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"goal-tool-core.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,qBAAqB,EAA0B,MAAM,uCAAuC,CAAC;AAI3G,OAAO,EAIN,KAAK,gBAAgB,EACrB,KAAK,SAAS,EAId,MAAM,iBAAiB,CAAC;AAQzB;;;;;;;;;GASG;AACH,MAAM,MAAM,UAAU,GACnB;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,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_TEXT_LENGTH = 4_000;
10
10
  const MAX_GOAL_URI_LENGTH = 4_096;
11
+ const MIN_AGENT_BLOCK_STALL_TURNS = 3;
11
12
  function requirementExists(state, requirementId) {
12
13
  return state.requirements.some((requirement) => requirement.id === requirementId);
13
14
  }
@@ -270,6 +271,12 @@ function toGoalEvent(state, action, now, options) {
270
271
  const reason = action.reason.trim();
271
272
  if (!reason)
272
273
  return { ok: false, error: "block_goal requires a non-empty reason." };
274
+ if (state.stallTurns < MIN_AGENT_BLOCK_STALL_TURNS) {
275
+ return {
276
+ ok: false,
277
+ error: `Cannot block goal: the host has recorded ${state.stallTurns}/${MIN_AGENT_BLOCK_STALL_TURNS} consecutive no-progress goal turns. Keep the goal active until the same blocker has persisted for at least three consecutive goal turns.`,
278
+ };
279
+ }
273
280
  return { ok: true, event: { type: "block_goal", reason, now } };
274
281
  }
275
282
  default: