@caupulican/pi-adaptative 0.96.3 → 0.96.5

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 (47) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +8 -0
  3. package/dist/config.d.ts +2 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +3 -1
  6. package/dist/config.js.map +1 -1
  7. package/dist/core/agent-session-contracts.d.ts +1 -1
  8. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  9. package/dist/core/agent-session-contracts.js.map +1 -1
  10. package/dist/core/agent-session.d.ts +2 -0
  11. package/dist/core/agent-session.d.ts.map +1 -1
  12. package/dist/core/agent-session.js +29 -14
  13. package/dist/core/agent-session.js.map +1 -1
  14. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -1
  15. package/dist/core/goals/goal-lifecycle.js +5 -1
  16. package/dist/core/goals/goal-lifecycle.js.map +1 -1
  17. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  18. package/dist/core/goals/goal-session-controller.js +3 -1
  19. package/dist/core/goals/goal-session-controller.js.map +1 -1
  20. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  21. package/dist/core/goals/goal-tool-core.js +32 -7
  22. package/dist/core/goals/goal-tool-core.js.map +1 -1
  23. package/dist/core/learning/durable-learning-state.d.ts +76 -0
  24. package/dist/core/learning/durable-learning-state.d.ts.map +1 -0
  25. package/dist/core/learning/durable-learning-state.js +493 -0
  26. package/dist/core/learning/durable-learning-state.js.map +1 -0
  27. package/dist/core/reflection-controller.d.ts +37 -7
  28. package/dist/core/reflection-controller.d.ts.map +1 -1
  29. package/dist/core/reflection-controller.js +278 -49
  30. package/dist/core/reflection-controller.js.map +1 -1
  31. package/dist/core/settings-manager.js.map +1 -1
  32. package/dist/core/tools/goal.d.ts.map +1 -1
  33. package/dist/core/tools/goal.js +6 -3
  34. package/dist/core/tools/goal.js.map +1 -1
  35. package/dist/modes/interactive/components/settings-selector.js +1 -1
  36. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  37. package/docs/durable-learning-state-design.md +217 -0
  38. package/docs/settings.md +5 -3
  39. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  40. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  41. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  42. package/examples/extensions/sandbox/package-lock.json +2 -2
  43. package/examples/extensions/sandbox/package.json +1 -1
  44. package/examples/extensions/with-deps/package-lock.json +2 -2
  45. package/examples/extensions/with-deps/package.json +1 -1
  46. package/npm-shrinkwrap.json +12 -12
  47. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"goal-lifecycle.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,SAAS,EAKd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAmB,KAAK,iBAAiB,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAErG,MAAM,WAAW,iBAAiB;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,GAAG,iBAAiB,CAExE;AAID,8GAA8G;AAC9G,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS,GAAG,OAAO,CAsBzE;AAED,qFAAqF;AACrF,MAAM,WAAW,sBAAsB;IACtC,oBAAoB,IAAI,SAAS,GAAG,SAAS,CAAC;IAC9C,qBAAqB,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,iBAAiB,GAAG,MAAM,CAAC;IAC9E,sBAAsB,CAAC,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CAC/D;AAgBD,wBAAgB,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,SAAS,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IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAAG,iBAAiB,CAAC;AAE1F,wBAAgB,kBAAkB,CACjC,IAAI,EAAE,sBAAsB,EAC5B,GAAG,SAA2B,GAC5B,wBAAwB,CAM1B"}
@@ -3,7 +3,11 @@ import { applyGoalAction } from "./goal-tool-core.js";
3
3
  export function getGoalStateRevision(state) {
4
4
  return { goalId: state.goalId, revision: state.revision ?? 0 };
5
5
  }
6
- const AUTO_RESUMABLE_SYSTEM_STOP_REASON_PREFIXES = ["runaway_tool_loop:", "provider_turn_limit:"];
6
+ const AUTO_RESUMABLE_SYSTEM_STOP_REASON_PREFIXES = [
7
+ "stagnant_tool_cycle:",
8
+ "runaway_tool_loop:",
9
+ "provider_turn_limit:",
10
+ ];
7
11
  /** True only when a bounded runaway/provider-turn guard caused the block, not owner/model/terminal intent. */
8
12
  export function isSystemBlockedGoal(state) {
9
13
  if (state?.status !== "blocked")
@@ -1 +1 @@
1
- {"version":3,"file":"goal-lifecycle.js","sourceRoot":"","sources":["../../../src/core/goals/goal-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,cAAc,EAEd,qBAAqB,EACrB,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,GACzB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAiD,MAAM,qBAAqB,CAAC;AAOrG,MAAM,UAAU,oBAAoB,CAAC,KAAgB;IACpD,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,IAAI,CAAC,EAAE,CAAC;AAChE,CAAC;AAED,MAAM,0CAA0C,GAAG,CAAC,oBAAoB,EAAE,sBAAsB,CAAU,CAAC;AAE3G,8GAA8G;AAC9G,MAAM,UAAU,mBAAmB,CAAC,KAA4B;IAC/D,IAAI,KAAK,EAAE,MAAM,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAC9C,KAAK,IAAI,KAAK,GAAG,KAAK,CAAC,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finishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\nimport { applyGoalAction, type GoalActionFailure, type GoalActionResult } from \"./goal-tool-core.ts\";\n\nexport interface GoalStateRevision {\n\tgoalId: string;\n\trevision: number;\n}\n\nexport function getGoalStateRevision(state: GoalState): GoalStateRevision {\n\treturn { goalId: state.goalId, revision: state.revision ?? 0 };\n}\n\nconst AUTO_RESUMABLE_SYSTEM_STOP_REASON_PREFIXES = [\"runaway_tool_loop:\", \"provider_turn_limit:\"] as const;\n\n/** True only when a bounded runaway/provider-turn guard caused the block, not owner/model/terminal intent. */\nexport function isSystemBlockedGoal(state: GoalState | undefined): boolean {\n\tif (state?.status !== \"blocked\") return false;\n\tfor (let index = state.events.length - 1; index >= 0; index--) {\n\t\tconst event = state.events[index];\n\t\tif (event?.type === \"system_stop_goal\") {\n\t\t\treturn (\n\t\t\t\tevent.status === \"blocked\" &&\n\t\t\t\tAUTO_RESUMABLE_SYSTEM_STOP_REASON_PREFIXES.some((prefix) => event.reason.startsWith(prefix))\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tevent?.type === \"block_goal\" ||\n\t\t\tevent?.type === \"pause_goal\" ||\n\t\t\tevent?.type === \"resume_goal\" ||\n\t\t\tevent?.type === \"complete_goal\" ||\n\t\t\tevent?.type === \"complete_goal_manually\" ||\n\t\t\tevent?.type === \"cancel_goal\"\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Minimal durable seam shared by CLI, tools, and in-process session restoration. */\nexport interface PersistedGoalStateHost {\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\tsaveGoalStateSnapshot(state: GoalState, expected?: GoalStateRevision): string;\n\tclearGoalStateSnapshot?(state: GoalState, now: string): string;\n}\n\nfunction missingGoal(action: string): GoalActionFailure {\n\treturn { ok: false, error: `No goal exists to ${action}.` };\n}\n\nfunction persistResult(\n\thost: PersistedGoalStateHost,\n\tcurrent: GoalState | undefined,\n\tresult: GoalActionResult,\n): GoalActionResult {\n\tif (!result.ok) return result;\n\thost.saveGoalStateSnapshot(result.state, current ? getGoalStateRevision(current) : undefined);\n\treturn result;\n}\n\nexport function pauseGoal(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) return missingGoal(\"pause\");\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is ${current.status}; only active goals can be paused.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"pause_goal\", now }) };\n}\n\nexport function resumeGoal(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) return missingGoal(\"resume\");\n\tif (!isGoalResumableStatus(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}; only paused, blocked, or usage-limited goals can be resumed.`,\n\t\t};\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"resume_goal\", now }) };\n}\n\nexport function editGoal(\n\tcurrent: GoalState | undefined,\n\targs: { userGoal: string; tokenBudget?: number },\n\tnow: string,\n): GoalActionResult {\n\tif (!current) return missingGoal(\"edit\");\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start a new goal instead.` };\n\t}\n\tconst userGoal = args.userGoal.trim();\n\tif (!userGoal) return { ok: false, error: \"Goal objective must not be empty.\" };\n\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\treturn { ok: false, error: `Goal objective must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t}\n\tif (args.tokenBudget !== undefined && (!Number.isSafeInteger(args.tokenBudget) || args.tokenBudget <= 0)) {\n\t\treturn { ok: false, error: \"Goal token budget must be a positive integer when provided.\" };\n\t}\n\treturn {\n\t\tok: true,\n\t\tstate: applyGoalEvent(current, { type: \"edit_goal\", userGoal, tokenBudget: args.tokenBudget, now }),\n\t};\n}\n\nexport function cancelGoal(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) return missingGoal(\"cancel\");\n\tif (!isGoalUnfinishedStatus(current.status)) {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already ${current.status}.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"cancel_goal\", now }) };\n}\n\n/** Explicit owner replacement. The old and new states cross one persistence boundary. */\nexport function replaceGoal(\n\targs: { goalId: string; userGoal: string; tokenBudget?: number },\n\tnow: string,\n): GoalActionResult {\n\treturn applyGoalAction(undefined, { action: \"start\", ...args }, now);\n}\n\nexport function stopGoalFromSystem(\n\tcurrent: GoalState | undefined,\n\targs: { status: \"blocked\" | \"usage_limited\" | \"budget_limited\"; reason: string },\n\tnow: string,\n): GoalActionResult {\n\tif (!current) return missingGoal(\"stop\");\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is ${current.status}; no system stop is needed.` };\n\t}\n\tconst reason = args.reason.trim();\n\tif (!reason) return { ok: false, error: \"System goal stop requires a reason.\" };\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"system_stop_goal\", ...args, reason, now }) };\n}\n\nexport function pausePersistedGoal(host: PersistedGoalStateHost, now = new Date().toISOString()): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, pauseGoal(current, now));\n}\n\nexport function resumePersistedGoal(host: PersistedGoalStateHost, now = new Date().toISOString()): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, resumeGoal(current, now));\n}\n\nexport function editPersistedGoal(\n\thost: PersistedGoalStateHost,\n\targs: { userGoal: string; tokenBudget?: number },\n\tnow = new Date().toISOString(),\n): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, editGoal(current, args, now));\n}\n\nexport function cancelPersistedGoal(host: PersistedGoalStateHost, now = new Date().toISOString()): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, cancelGoal(current, now));\n}\n\nexport type ClearPersistedGoalResult = { ok: true; cleared: boolean } | GoalActionFailure;\n\nexport function clearPersistedGoal(\n\thost: PersistedGoalStateHost,\n\tnow = new Date().toISOString(),\n): ClearPersistedGoalResult {\n\tconst current = host.getGoalStateSnapshot();\n\tif (!current) return { ok: true, cleared: false };\n\tif (!host.clearGoalStateSnapshot) return { ok: false, error: \"This session does not support clearing goals.\" };\n\thost.clearGoalStateSnapshot(current, now);\n\treturn { ok: true, cleared: true };\n}\n"]}
1
+ {"version":3,"file":"goal-lifecycle.js","sourceRoot":"","sources":["../../../src/core/goals/goal-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,cAAc,EAEd,qBAAqB,EACrB,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,GACzB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAiD,MAAM,qBAAqB,CAAC;AAOrG,MAAM,UAAU,oBAAoB,CAAC,KAAgB;IACpD,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,IAAI,CAAC,EAAE,CAAC;AAChE,CAAC;AAED,MAAM,0CAA0C,GAAG;IAClD,sBAAsB;IACtB,oBAAoB;IACpB,sBAAsB;CACb,CAAC;AAEX,8GAA8G;AAC9G,MAAM,UAAU,mBAAmB,CAAC,KAA4B;IAC/D,IAAI,KAAK,EAAE,MAAM,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAC9C,KAAK,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QAC/D,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAClC,IAAI,KAAK,EAAE,IAAI,KAAK,kBAAkB,EAAE,CAAC;YACxC,OAAO,CACN,KAAK,CAAC,MAAM,KAAK,SAAS;gBAC1B,0CAA0C,CAA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I,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACnE,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,IAA4B,EAAE,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;IAC/F,MAAM,OAAO,GAAG,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC5C,OAAO,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;AAC/D,CAAC;AAID,MAAM,UAAU,kBAAkB,CACjC,IAA4B,EAC5B,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;IAE9B,MAAM,OAAO,GAAG,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC5C,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAClD,IAAI,CAAC,IAAI,CAAC,sBAAsB;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,+CAA+C,EAAE,CAAC;IAC/G,IAAI,CAAC,sBAAsB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IAC1C,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import {\n\tapplyGoalEvent,\n\ttype GoalState,\n\tisGoalExecutionActive,\n\tisGoalResumableStatus,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\nimport { applyGoalAction, type GoalActionFailure, type GoalActionResult } from \"./goal-tool-core.ts\";\n\nexport interface GoalStateRevision {\n\tgoalId: string;\n\trevision: number;\n}\n\nexport function getGoalStateRevision(state: GoalState): GoalStateRevision {\n\treturn { goalId: state.goalId, revision: state.revision ?? 0 };\n}\n\nconst AUTO_RESUMABLE_SYSTEM_STOP_REASON_PREFIXES = [\n\t\"stagnant_tool_cycle:\",\n\t\"runaway_tool_loop:\",\n\t\"provider_turn_limit:\",\n] as const;\n\n/** True only when a bounded runaway/provider-turn guard caused the block, not owner/model/terminal intent. */\nexport function isSystemBlockedGoal(state: GoalState | undefined): boolean {\n\tif (state?.status !== \"blocked\") return false;\n\tfor (let index = state.events.length - 1; index >= 0; index--) {\n\t\tconst event = state.events[index];\n\t\tif (event?.type === \"system_stop_goal\") {\n\t\t\treturn (\n\t\t\t\tevent.status === \"blocked\" &&\n\t\t\t\tAUTO_RESUMABLE_SYSTEM_STOP_REASON_PREFIXES.some((prefix) => event.reason.startsWith(prefix))\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tevent?.type === \"block_goal\" ||\n\t\t\tevent?.type === \"pause_goal\" ||\n\t\t\tevent?.type === \"resume_goal\" ||\n\t\t\tevent?.type === \"complete_goal\" ||\n\t\t\tevent?.type === \"complete_goal_manually\" ||\n\t\t\tevent?.type === \"cancel_goal\"\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Minimal durable seam shared by CLI, tools, and in-process session restoration. */\nexport interface PersistedGoalStateHost {\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\tsaveGoalStateSnapshot(state: GoalState, expected?: GoalStateRevision): string;\n\tclearGoalStateSnapshot?(state: GoalState, now: string): string;\n}\n\nfunction missingGoal(action: string): GoalActionFailure {\n\treturn { ok: false, error: `No goal exists to ${action}.` };\n}\n\nfunction persistResult(\n\thost: PersistedGoalStateHost,\n\tcurrent: GoalState | undefined,\n\tresult: GoalActionResult,\n): GoalActionResult {\n\tif (!result.ok) return result;\n\thost.saveGoalStateSnapshot(result.state, current ? getGoalStateRevision(current) : undefined);\n\treturn result;\n}\n\nexport function pauseGoal(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) return missingGoal(\"pause\");\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is ${current.status}; only active goals can be paused.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"pause_goal\", now }) };\n}\n\nexport function resumeGoal(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) return missingGoal(\"resume\");\n\tif (!isGoalResumableStatus(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}; only paused, blocked, or usage-limited goals can be resumed.`,\n\t\t};\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"resume_goal\", now }) };\n}\n\nexport function editGoal(\n\tcurrent: GoalState | undefined,\n\targs: { userGoal: string; tokenBudget?: number },\n\tnow: string,\n): GoalActionResult {\n\tif (!current) return missingGoal(\"edit\");\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start a new goal instead.` };\n\t}\n\tconst userGoal = args.userGoal.trim();\n\tif (!userGoal) return { ok: false, error: \"Goal objective must not be empty.\" };\n\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\treturn { ok: false, error: `Goal objective must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t}\n\tif (args.tokenBudget !== undefined && (!Number.isSafeInteger(args.tokenBudget) || args.tokenBudget <= 0)) {\n\t\treturn { ok: false, error: \"Goal token budget must be a positive integer when provided.\" };\n\t}\n\treturn {\n\t\tok: true,\n\t\tstate: applyGoalEvent(current, { type: \"edit_goal\", userGoal, tokenBudget: args.tokenBudget, now }),\n\t};\n}\n\nexport function cancelGoal(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) return missingGoal(\"cancel\");\n\tif (!isGoalUnfinishedStatus(current.status)) {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already ${current.status}.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"cancel_goal\", now }) };\n}\n\n/** Explicit owner replacement. The old and new states cross one persistence boundary. */\nexport function replaceGoal(\n\targs: { goalId: string; userGoal: string; tokenBudget?: number },\n\tnow: string,\n): GoalActionResult {\n\treturn applyGoalAction(undefined, { action: \"start\", ...args }, now);\n}\n\nexport function stopGoalFromSystem(\n\tcurrent: GoalState | undefined,\n\targs: { status: \"blocked\" | \"usage_limited\" | \"budget_limited\"; reason: string },\n\tnow: string,\n): GoalActionResult {\n\tif (!current) return missingGoal(\"stop\");\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is ${current.status}; no system stop is needed.` };\n\t}\n\tconst reason = args.reason.trim();\n\tif (!reason) return { ok: false, error: \"System goal stop requires a reason.\" };\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"system_stop_goal\", ...args, reason, now }) };\n}\n\nexport function pausePersistedGoal(host: PersistedGoalStateHost, now = new Date().toISOString()): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, pauseGoal(current, now));\n}\n\nexport function resumePersistedGoal(host: PersistedGoalStateHost, now = new Date().toISOString()): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, resumeGoal(current, now));\n}\n\nexport function editPersistedGoal(\n\thost: PersistedGoalStateHost,\n\targs: { userGoal: string; tokenBudget?: number },\n\tnow = new Date().toISOString(),\n): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, editGoal(current, args, now));\n}\n\nexport function cancelPersistedGoal(host: PersistedGoalStateHost, now = new Date().toISOString()): GoalActionResult {\n\tconst current = host.getGoalStateSnapshot();\n\treturn persistResult(host, current, cancelGoal(current, now));\n}\n\nexport type ClearPersistedGoalResult = { ok: true; cleared: boolean } | GoalActionFailure;\n\nexport function clearPersistedGoal(\n\thost: PersistedGoalStateHost,\n\tnow = new Date().toISOString(),\n): ClearPersistedGoalResult {\n\tconst current = host.getGoalStateSnapshot();\n\tif (!current) return { ok: true, cleared: false };\n\tif (!host.clearGoalStateSnapshot) return { ok: false, error: \"This session does not support clearing goals.\" };\n\thost.clearGoalStateSnapshot(current, now);\n\treturn { ok: true, cleared: true };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"goal-session-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAEA,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACvG,OAAO,KAAK,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAC1F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EACN,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAE/B,KAAK,aAAa,EAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAGnF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAE9E,OAAO,EACN,KAAK,iBAAiB,EAKtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEN,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAChC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAkB,KAAK,SAAS,EAAiD,MAAM,iBAAiB,CAAC;AAEhH,OAAO,EACN,KAAK,0BAA0B,EAG/B,MAAM,4BAA4B,CAAC;AAOpC,MAAM,WAAW,yBAAyB;IACzC,iBAAiB,IAAI,cAAc,CAAC;IACpC,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAAC;IACvC,cAAc,IAAI,SAAS,UAAU,EAAE,CAAC;IACxC,sBAAsB,IAAI,qBAAqB,GAAG,SAAS,CAAC;IAC5D,sBAAsB,IAAI,SAAS,qBAAqB,EAAE,CAAC;IAC3D,oBAAoB,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAC;IA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AG,SAAS,GAAG,IAAI,CAKxD;IAED,mGAAmG;IACnG,kBAAkB,IAAI,MAAM,GAAG,SAAS,CAKvC;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,MAAM,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,GAAG,IAAI,CAEtE;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,CAO3D;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,OAAO,CAI5B;IAED,OAAO,CAAC,yBAAyB;IASjC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,cAAc;CAOtB"}
1
+ {"version":3,"file":"goal-session-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAEA,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACvG,O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GAAG,OAAO,CAaxD;IAED,iBAAiB,CAAC,SAAS,EAAE,0BAA0B,GAAG,SAAS,GAAG,IAAI,CAEzE;IAED,sBAAsB,CAAC,MAAM,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,GAAG,IAAI,CAEtE;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,CAS3D;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,OAAO,CAI5B;IAED,OAAO,CAAC,yBAAyB;IASjC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,cAAc;CAOtB"}
@@ -403,7 +403,9 @@ export class GoalSessionController {
403
403
  recoverFromHarnessGuard(info) {
404
404
  const reason = info.reason === "provider_turn_limit"
405
405
  ? `provider_turn_limit: reached the explicit ${info.repeats}-request provider-turn limit`
406
- : `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;
406
+ : info.reason === "stagnant_tool_cycle"
407
+ ? `stagnant_tool_cycle: repeated tool-call signature ${info.signature} ${info.repeats} times with identical results`
408
+ : `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;
407
409
  if (!this.stopActiveGoal("blocked", reason))
408
410
  return false;
409
411
  return this.resumeSystemBlockedGoal() !== undefined;
@@ -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;AACxE,OAAO,EAAE,6BAA6B,EAAuB,MAAM,mCAAmC,CAAC;AAGvG,OAAO,EAKN,gCAAgC,GAEhC,MAAM,+BAA+B,CAAC;AAGvC,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,EAEN,oBAAoB,EACpB,mBAAmB,EACnB,UAAU,EACV,kBAAkB,GAClB,MAAM,qBAAqB,CAAC;AAC7B,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,GAA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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 { MAX_SESSION_ENTRY_VISIT_COUNT, 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 {\n\ttype GoalContinuationLoopOptions,\n\ttype GoalContinuationLoopResult,\n\ttype GoalContinuationOnceOptions,\n\ttype GoalContinuationOnceResult,\n\tisInterruptedAssistantStopReason,\n\ttype PromptOptions,\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 {\n\ttype GoalStateRevision,\n\tgetGoalStateRevision,\n\tisSystemBlockedGoal,\n\tresumeGoal,\n\tstopGoalFromSystem,\n} 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: async (text, options) => {\n\t\t\t\tconst firstTurnEntryIndex = this.deps.getSessionManager().getEntryCount();\n\t\t\t\tawait this.deps.prompt(text, options);\n\t\t\t\treturn this.getContinuationTurnOutcome(firstTurnEntryIndex);\n\t\t\t},\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\tprivate getContinuationTurnOutcome(firstTurnEntryIndex: number): \"completed\" | \"interrupted\" {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst endIndex = sessionManager.getEntryCount();\n\t\tlet nextIndex = firstTurnEntryIndex;\n\t\tlet lastAssistantStopReason: AssistantMessage[\"stopReason\"] | undefined;\n\t\twhile (nextIndex < endIndex) {\n\t\t\tconst visitCount = Math.min(MAX_SESSION_ENTRY_VISIT_COUNT, endIndex - nextIndex);\n\t\t\tnextIndex = sessionManager.visitEntries(nextIndex, visitCount, (entry) => {\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tlastAssistantStopReason = entry.message.stopReason;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn isInterruptedAssistantStopReason(lastAssistantStopReason) ? \"interrupted\" : \"completed\";\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 * A bounded runaway/provider-turn guard stops one autonomous run, not the owner's durable intent.\n\t * Resume that narrow class immediately or during restoration while preserving deliberate blocks,\n\t * terminal tool failures, pauses, and quota/budget stops.\n\t */\n\tresumeSystemBlockedGoal(now = new Date().toISOString()): string | undefined {\n\t\tconst current = this.getState();\n\t\tif (!current || !isSystemBlockedGoal(current)) return undefined;\n\t\tconst resumed = resumeGoal(current, now);\n\t\tif (!resumed.ok) return undefined;\n\t\tthis.saveState(resumed.state, getGoalStateRevision(current));\n\t\treturn resumed.state.goalId;\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/** Goal identity authoritatively owned by the current foreground execution, if one was adopted. */\n\tgetExecutionGoalId(): string | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.resolveExecutionState(lease);\n\t\treturn lease.goalId;\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 }): number | null {\n\t\treturn this.startAuthority?.tokenBudget ?? null;\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\trecoverFromHarnessGuard(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 explicit ${info.repeats}-request provider-turn limit`\n\t\t\t\t: `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;\n\t\tif (!this.stopActiveGoal(\"blocked\", reason)) return false;\n\t\treturn this.resumeSystemBlockedGoal() !== undefined;\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(): boolean {\n\t\tconst resumedGoalId = this.resumeSystemBlockedGoal();\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t\treturn resumedGoalId !== undefined;\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;AACxE,OAAO,EAAE,6BAA6B,EAAuB,MAAM,mCAAmC,CAAC;AAGvG,OAAO,EAKN,gCAAgC,GAEhC,MAAM,+BAA+B,CAAC;AAGvC,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,EAEN,oBAAoB,EACpB,mBAAmB,EACnB,UAAU,EACV,kBAAkB,GAClB,MAAM,qBAAqB,CAAC;AAC7B,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,MA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C3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport { MAX_SESSION_ENTRY_VISIT_COUNT, 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 {\n\ttype GoalContinuationLoopOptions,\n\ttype GoalContinuationLoopResult,\n\ttype GoalContinuationOnceOptions,\n\ttype GoalContinuationOnceResult,\n\tisInterruptedAssistantStopReason,\n\ttype PromptOptions,\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 {\n\ttype GoalStateRevision,\n\tgetGoalStateRevision,\n\tisSystemBlockedGoal,\n\tresumeGoal,\n\tstopGoalFromSystem,\n} 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: async (text, options) => {\n\t\t\t\tconst firstTurnEntryIndex = this.deps.getSessionManager().getEntryCount();\n\t\t\t\tawait this.deps.prompt(text, options);\n\t\t\t\treturn this.getContinuationTurnOutcome(firstTurnEntryIndex);\n\t\t\t},\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\tprivate getContinuationTurnOutcome(firstTurnEntryIndex: number): \"completed\" | \"interrupted\" {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst endIndex = sessionManager.getEntryCount();\n\t\tlet nextIndex = firstTurnEntryIndex;\n\t\tlet lastAssistantStopReason: AssistantMessage[\"stopReason\"] | undefined;\n\t\twhile (nextIndex < endIndex) {\n\t\t\tconst visitCount = Math.min(MAX_SESSION_ENTRY_VISIT_COUNT, endIndex - nextIndex);\n\t\t\tnextIndex = sessionManager.visitEntries(nextIndex, visitCount, (entry) => {\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tlastAssistantStopReason = entry.message.stopReason;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn isInterruptedAssistantStopReason(lastAssistantStopReason) ? \"interrupted\" : \"completed\";\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 * A bounded runaway/provider-turn guard stops one autonomous run, not the owner's durable intent.\n\t * Resume that narrow class immediately or during restoration while preserving deliberate blocks,\n\t * terminal tool failures, pauses, and quota/budget stops.\n\t */\n\tresumeSystemBlockedGoal(now = new Date().toISOString()): string | undefined {\n\t\tconst current = this.getState();\n\t\tif (!current || !isSystemBlockedGoal(current)) return undefined;\n\t\tconst resumed = resumeGoal(current, now);\n\t\tif (!resumed.ok) return undefined;\n\t\tthis.saveState(resumed.state, getGoalStateRevision(current));\n\t\treturn resumed.state.goalId;\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/** Goal identity authoritatively owned by the current foreground execution, if one was adopted. */\n\tgetExecutionGoalId(): string | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.resolveExecutionState(lease);\n\t\treturn lease.goalId;\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 }): number | null {\n\t\treturn this.startAuthority?.tokenBudget ?? null;\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\trecoverFromHarnessGuard(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 explicit ${info.repeats}-request provider-turn limit`\n\t\t\t\t: info.reason === \"stagnant_tool_cycle\"\n\t\t\t\t\t? `stagnant_tool_cycle: repeated tool-call signature ${info.signature} ${info.repeats} times with identical results`\n\t\t\t\t\t: `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;\n\t\tif (!this.stopActiveGoal(\"blocked\", reason)) return false;\n\t\treturn this.resumeSystemBlockedGoal() !== undefined;\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(): boolean {\n\t\tconst resumedGoalId = this.resumeSystemBlockedGoal();\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t\treturn resumedGoalId !== undefined;\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;AASzB;;;;;;;;;GASG;AACH,MAAM,MAAM,UAAU,GACnB;IAAE,MAAM,E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AM,EAAE,EACjC,aAAa,EAAE,SAAS,eAAe,EAAE,GACvC,MAAM,EAAE,CAcV;AAED;;;;;GAKG;AACH,wBAAgB,kCAAkC,CACjD,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,SAAS,EAChB,aAAa,EAAE,SAAS,eAAe,EAAE,GAAG,SAAS,GACnD,MAAM,EAAE,CAYV"}
@@ -1,6 +1,6 @@
1
1
  import { findBackgroundToolTask } from "../background-tool-task-controller.js";
2
2
  import { taskStepReferencesRequirement } from "../tasks/task-projection.js";
3
- import { getUnprovenGoalRequirementIds } from "./goal-acceptance.js";
3
+ import { getTrustedRequirementEvidence, getUnprovenGoalRequirementIds, isTrustedGoalEvidence, } from "./goal-acceptance.js";
4
4
  import { formatGoalRecord, projectGoalRecord } from "./goal-record.js";
5
5
  import { applyGoalEvent, createGoalState, isGoalExecutionActive, isGoalUnfinishedStatus, MAX_GOAL_OBJECTIVE_LENGTH, } from "./goal-state.js";
6
6
  const MAX_GOAL_ID_LENGTH = 128;
@@ -57,17 +57,25 @@ export function applyGoalAction(current, action, now, options) {
57
57
  };
58
58
  }
59
59
  if (action.action === "increment") {
60
- const firstOpen = current.requirements.find((requirement) => requirement.status === "open");
61
- if (firstOpen) {
60
+ const requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;
61
+ const firstPending = current.requirements.find((requirement) => requirement.status === "open" ||
62
+ (requireVerifiedEvidence &&
63
+ requirement.status === "satisfied" &&
64
+ getTrustedRequirementEvidence(current, requirement).length === 0));
65
+ if (firstPending) {
62
66
  const used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));
63
- const unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);
67
+ const unused = current.evidence
68
+ .filter((evidence) => !used.has(evidence.id) && (!requireVerifiedEvidence || isTrustedGoalEvidence(evidence)))
69
+ .map((evidence) => evidence.id);
64
70
  if (unused.length === 0) {
71
+ const evidenceKind = requireVerifiedEvidence ? " accepted as verified or user-confirmed" : "";
72
+ const requirementState = firstPending.status === "open" ? "open" : "unproven";
65
73
  return {
66
74
  ok: false,
67
- error: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,
75
+ error: `Cannot increment goal: ${requirementState} requirement '${firstPending.id}' has no unused evidence${evidenceKind}. Record evidence, then increment.`,
68
76
  };
69
77
  }
70
- return applyGoalAction(current, { action: "satisfy_requirement", requirementId: firstOpen.id, evidenceIds: unused }, now, options);
78
+ return applyGoalAction(current, { action: "satisfy_requirement", requirementId: firstPending.id, evidenceIds: unused }, now, options);
71
79
  }
72
80
  return applyGoalAction(current, { action: "complete" }, now, options);
73
81
  }
@@ -122,6 +130,15 @@ function toGoalEvent(state, action, now, options) {
122
130
  };
123
131
  }
124
132
  }
133
+ if (options?.requireVerifiedEvidenceForCompletion !== false) {
134
+ const trustedEvidence = state.evidence.some((evidence) => evidenceIds.includes(evidence.id) && isTrustedGoalEvidence(evidence));
135
+ if (!trustedEvidence) {
136
+ return {
137
+ ok: false,
138
+ error: `Cannot satisfy requirement '${id}': cite at least one verified or user-confirmed evidence entry.`,
139
+ };
140
+ }
141
+ }
125
142
  return { ok: true, event: { type: "satisfy_requirement", id, evidenceIds: [...evidenceIds], now } };
126
143
  }
127
144
  case "block_requirement": {
@@ -312,7 +329,15 @@ export function summarizeGoalState(state, options) {
312
329
  .filter((requirement) => requirement.status === "open")
313
330
  .slice(0, 20)
314
331
  .map((requirement) => requirement.id);
315
- lines.push(`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(", ")}` : ""}.`);
332
+ const unprovenIds = state.requirements
333
+ .filter((requirement) => requirement.status === "satisfied" && getTrustedRequirementEvidence(state, requirement).length === 0)
334
+ .slice(0, 20)
335
+ .map((requirement) => requirement.id);
336
+ const pending = [
337
+ ...(openIds.length > 0 ? [`open: ${openIds.join(", ")}`] : []),
338
+ ...(unprovenIds.length > 0 ? [`unproven: ${unprovenIds.join(", ")}`] : []),
339
+ ];
340
+ lines.push(`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${pending.length > 0 ? `; ${pending.join("; ")}` : ""}.`);
316
341
  }
317
342
  if (options?.action) {
318
343
  lines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));