@caupulican/pi-adaptative 0.91.4 → 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 (208) hide show
  1. package/CHANGELOG.md +43 -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/cli.js +6 -1
  7. package/dist/cli.js.map +1 -1
  8. package/dist/core/agent-session-contracts.d.ts +1 -0
  9. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  10. package/dist/core/agent-session-contracts.js.map +1 -1
  11. package/dist/core/agent-session-services.d.ts +1 -0
  12. package/dist/core/agent-session-services.d.ts.map +1 -1
  13. package/dist/core/agent-session-services.js +1 -0
  14. package/dist/core/agent-session-services.js.map +1 -1
  15. package/dist/core/agent-session.d.ts +1 -6
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +15 -13
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  20. package/dist/core/autonomy/lane-tool-surface.js +7 -1
  21. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  22. package/dist/core/background-lane-controller.d.ts +2 -4
  23. package/dist/core/background-lane-controller.d.ts.map +1 -1
  24. package/dist/core/background-lane-controller.js +0 -1
  25. package/dist/core/background-lane-controller.js.map +1 -1
  26. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  27. package/dist/core/bash-execution-controller.js +1 -0
  28. package/dist/core/bash-execution-controller.js.map +1 -1
  29. package/dist/core/bash-executor.d.ts +2 -0
  30. package/dist/core/bash-executor.d.ts.map +1 -1
  31. package/dist/core/bash-executor.js +13 -4
  32. package/dist/core/bash-executor.js.map +1 -1
  33. package/dist/core/compaction-controller.d.ts.map +1 -1
  34. package/dist/core/compaction-controller.js +2 -1
  35. package/dist/core/compaction-controller.js.map +1 -1
  36. package/dist/core/context/context-composition.d.ts +1 -1
  37. package/dist/core/context/context-composition.d.ts.map +1 -1
  38. package/dist/core/context/context-composition.js +1 -1
  39. package/dist/core/context/context-composition.js.map +1 -1
  40. package/dist/core/default-tool-surface.d.ts +0 -10
  41. package/dist/core/default-tool-surface.d.ts.map +1 -1
  42. package/dist/core/default-tool-surface.js +3 -1
  43. package/dist/core/default-tool-surface.js.map +1 -1
  44. package/dist/core/extensions/bundled-virtual-modules.js +8 -0
  45. package/dist/core/extensions/bundled-virtual-modules.js.map +1 -1
  46. package/dist/core/extensions/runner.d.ts +1 -1
  47. package/dist/core/extensions/runner.d.ts.map +1 -1
  48. package/dist/core/extensions/runner.js +1 -1
  49. package/dist/core/extensions/runner.js.map +1 -1
  50. package/dist/core/extensions/virtual-modules.d.ts +4 -0
  51. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  52. package/dist/core/extensions/virtual-modules.js +4 -0
  53. package/dist/core/extensions/virtual-modules.js.map +1 -1
  54. package/dist/core/goal-loop-controller.d.ts +6 -2
  55. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  56. package/dist/core/goal-loop-controller.js +15 -4
  57. package/dist/core/goal-loop-controller.js.map +1 -1
  58. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  59. package/dist/core/goals/compact-goal-context.js +10 -14
  60. package/dist/core/goals/compact-goal-context.js.map +1 -1
  61. package/dist/core/goals/goal-auto-continue-controller.d.ts +0 -2
  62. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
  63. package/dist/core/goals/goal-auto-continue-controller.js +0 -2
  64. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  65. package/dist/core/goals/goal-session-controller.d.ts +7 -7
  66. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  67. package/dist/core/goals/goal-session-controller.js +27 -5
  68. package/dist/core/goals/goal-session-controller.js.map +1 -1
  69. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  70. package/dist/core/goals/goal-tool-core.js +7 -0
  71. package/dist/core/goals/goal-tool-core.js.map +1 -1
  72. package/dist/core/goals/goal-tool-names.d.ts +7 -0
  73. package/dist/core/goals/goal-tool-names.d.ts.map +1 -0
  74. package/dist/core/goals/goal-tool-names.js +8 -0
  75. package/dist/core/goals/goal-tool-names.js.map +1 -0
  76. package/dist/core/model-capability.d.ts +1 -1
  77. package/dist/core/model-capability.d.ts.map +1 -1
  78. package/dist/core/model-capability.js +3 -1
  79. package/dist/core/model-capability.js.map +1 -1
  80. package/dist/core/models/perf-profile.d.ts +2 -1
  81. package/dist/core/models/perf-profile.d.ts.map +1 -1
  82. package/dist/core/models/perf-profile.js +1 -1
  83. package/dist/core/models/perf-profile.js.map +1 -1
  84. package/dist/core/provider-request-context-controller.d.ts.map +1 -1
  85. package/dist/core/provider-request-context-controller.js +6 -5
  86. package/dist/core/provider-request-context-controller.js.map +1 -1
  87. package/dist/core/provider-request-runtime-controller.d.ts.map +1 -1
  88. package/dist/core/provider-request-runtime-controller.js +3 -2
  89. package/dist/core/provider-request-runtime-controller.js.map +1 -1
  90. package/dist/core/runtime-builder.d.ts.map +1 -1
  91. package/dist/core/runtime-builder.js +13 -4
  92. package/dist/core/runtime-builder.js.map +1 -1
  93. package/dist/core/sdk.d.ts +3 -1
  94. package/dist/core/sdk.d.ts.map +1 -1
  95. package/dist/core/sdk.js +3 -1
  96. package/dist/core/sdk.js.map +1 -1
  97. package/dist/core/session-analytics.d.ts +2 -2
  98. package/dist/core/session-analytics.d.ts.map +1 -1
  99. package/dist/core/session-analytics.js +3 -2
  100. package/dist/core/session-analytics.js.map +1 -1
  101. package/dist/core/session-manager-factory.d.ts +1 -1
  102. package/dist/core/session-manager-factory.d.ts.map +1 -1
  103. package/dist/core/session-manager-factory.js +1 -1
  104. package/dist/core/session-manager-factory.js.map +1 -1
  105. package/dist/core/session-role.d.ts.map +1 -1
  106. package/dist/core/session-role.js +2 -0
  107. package/dist/core/session-role.js.map +1 -1
  108. package/dist/core/session-tree-navigator.d.ts +2 -2
  109. package/dist/core/session-tree-navigator.d.ts.map +1 -1
  110. package/dist/core/session-tree-navigator.js +1 -1
  111. package/dist/core/session-tree-navigator.js.map +1 -1
  112. package/dist/core/skill-vault.d.ts +6 -7
  113. package/dist/core/skill-vault.d.ts.map +1 -1
  114. package/dist/core/skill-vault.js +12 -12
  115. package/dist/core/skill-vault.js.map +1 -1
  116. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  117. package/dist/core/tool-capability-policy.js +2 -1
  118. package/dist/core/tool-capability-policy.js.map +1 -1
  119. package/dist/core/tools/bash.d.ts +2 -0
  120. package/dist/core/tools/bash.d.ts.map +1 -1
  121. package/dist/core/tools/bash.js +27 -12
  122. package/dist/core/tools/bash.js.map +1 -1
  123. package/dist/core/tools/early-powershell-session.d.ts +21 -0
  124. package/dist/core/tools/early-powershell-session.d.ts.map +1 -0
  125. package/dist/core/tools/early-powershell-session.js +137 -0
  126. package/dist/core/tools/early-powershell-session.js.map +1 -0
  127. package/dist/core/tools/edit.d.ts +1 -1
  128. package/dist/core/tools/edit.d.ts.map +1 -1
  129. package/dist/core/tools/edit.js +1 -1
  130. package/dist/core/tools/edit.js.map +1 -1
  131. package/dist/core/tools/file-failure-recovery.d.ts +1 -1
  132. package/dist/core/tools/file-failure-recovery.d.ts.map +1 -1
  133. package/dist/core/tools/file-failure-recovery.js +1 -1
  134. package/dist/core/tools/file-failure-recovery.js.map +1 -1
  135. package/dist/core/tools/goal.d.ts +9 -2
  136. package/dist/core/tools/goal.d.ts.map +1 -1
  137. package/dist/core/tools/goal.js +64 -1
  138. package/dist/core/tools/goal.js.map +1 -1
  139. package/dist/core/tools/grep.d.ts +2 -2
  140. package/dist/core/tools/grep.d.ts.map +1 -1
  141. package/dist/core/tools/grep.js +1 -1
  142. package/dist/core/tools/grep.js.map +1 -1
  143. package/dist/core/tools/output-accumulator.d.ts +2 -0
  144. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  145. package/dist/core/tools/output-accumulator.js +2 -1
  146. package/dist/core/tools/output-accumulator.js.map +1 -1
  147. package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -1
  148. package/dist/core/tools/persistent-process-coordinator.js +2 -11
  149. package/dist/core/tools/persistent-process-coordinator.js.map +1 -1
  150. package/dist/core/tools/read.d.ts +2 -2
  151. package/dist/core/tools/read.d.ts.map +1 -1
  152. package/dist/core/tools/read.js +1 -1
  153. package/dist/core/tools/read.js.map +1 -1
  154. package/dist/core/tools/render-utils.d.ts +1 -0
  155. package/dist/core/tools/render-utils.d.ts.map +1 -1
  156. package/dist/core/tools/render-utils.js +11 -9
  157. package/dist/core/tools/render-utils.js.map +1 -1
  158. package/dist/core/tools/shell-output-decoder.d.ts +7 -0
  159. package/dist/core/tools/shell-output-decoder.d.ts.map +1 -0
  160. package/dist/core/tools/shell-output-decoder.js +135 -0
  161. package/dist/core/tools/shell-output-decoder.js.map +1 -0
  162. package/dist/core/tools/shell-session.d.ts +23 -6
  163. package/dist/core/tools/shell-session.d.ts.map +1 -1
  164. package/dist/core/tools/shell-session.js +275 -88
  165. package/dist/core/tools/shell-session.js.map +1 -1
  166. package/dist/core/tools/skill.js +2 -2
  167. package/dist/core/tools/skill.js.map +1 -1
  168. package/dist/core/tools/write.d.ts +1 -1
  169. package/dist/core/tools/write.d.ts.map +1 -1
  170. package/dist/core/tools/write.js +1 -1
  171. package/dist/core/tools/write.js.map +1 -1
  172. package/dist/index.d.ts +1 -1
  173. package/dist/index.d.ts.map +1 -1
  174. package/dist/index.js +1 -1
  175. package/dist/index.js.map +1 -1
  176. package/dist/main.d.ts.map +1 -1
  177. package/dist/main.js +2 -0
  178. package/dist/main.js.map +1 -1
  179. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  180. package/dist/modes/interactive/components/bash-execution.js +4 -33
  181. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  182. package/dist/modes/interactive/components/tool-execution.d.ts +3 -0
  183. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  184. package/dist/modes/interactive/components/tool-execution.js +63 -27
  185. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  186. package/dist/utils/child-process-ref.d.ts +4 -0
  187. package/dist/utils/child-process-ref.d.ts.map +1 -0
  188. package/dist/utils/child-process-ref.js +15 -0
  189. package/dist/utils/child-process-ref.js.map +1 -0
  190. package/dist/utils/powershell-session-protocol.d.ts +16 -0
  191. package/dist/utils/powershell-session-protocol.d.ts.map +1 -0
  192. package/dist/utils/powershell-session-protocol.js +63 -0
  193. package/dist/utils/powershell-session-protocol.js.map +1 -0
  194. package/dist/utils/shell.d.ts +7 -4
  195. package/dist/utils/shell.d.ts.map +1 -1
  196. package/dist/utils/shell.js +38 -23
  197. package/dist/utils/shell.js.map +1 -1
  198. package/docs/settings.md +2 -2
  199. package/docs/windows.md +9 -8
  200. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  201. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  202. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  203. package/examples/extensions/sandbox/package-lock.json +2 -2
  204. package/examples/extensions/sandbox/package.json +2 -2
  205. package/examples/extensions/with-deps/package-lock.json +2 -2
  206. package/examples/extensions/with-deps/package.json +1 -1
  207. package/npm-shrinkwrap.json +318 -332
  208. package/package.json +4 -4
@@ -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,CA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AAC,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,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;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c,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, 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,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GAC3E;IAAE,MAAM,EAAE,iBAAiB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GACpG;IAAE,MAAM,EAAE,qBAAqB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GACzF;IAAE,MAAM,EAAE,mBAAmB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACtE;IAAE,MAAM,EAAE,oBAAoB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAA;CAAE,GACvD;IACA,MAAM,EAAE,iBAAiB,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC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GAC3E,MAAM,CAeR;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B;AAuBD;;;GAGG;AACH,wBAAgB,mCAAmC,CAClD,KAAK,EAAE,SAAS,EAChB,cAAc,EAAE,SAAS,MAAM,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"}
@@ -8,6 +8,7 @@ const MAX_GOAL_REQUIREMENTS = 256;
8
8
  const MAX_GOAL_EVIDENCE = 512;
9
9
  const MAX_GOAL_LEDGER_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:
@@ -1 +1 @@
1
- {"version":3,"file":"goal-tool-core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AAED;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CACjD,MAAkB,EAClB,KAAgB,EAChB,aAAqD;IAErD,IAAI,CAAC,aAAa,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAC5D,IAAI,MAAM,CAAC,MAAM,KAAK,qBAAqB,EAAE,CAAC;QAC7C,OAAO,mCAAmC,CAAC,KAAK,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,EAAE,aAAa,CAAC,CAAC;IACjG,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY;aACrC,MAAM,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,KAAK,WAAW,CAAC;aAC3D,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type BackgroundToolTaskRef, findBackgroundToolTask } from \"../background-tool-task-controller.ts\";\nimport { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalExecutionActive,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string; dependencies?: readonly string[] }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"increment\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n\t/**\n\t * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any of\n\t * these still reference a requirement of the goal being closed.\n\t */\n\topenTaskSteps?: readonly OpenTaskStepRef[];\n\t/** Live background tool_task records used to re-check kind:\"tool\" evidence at complete time. */\n\tbackgroundToolTasks?: readonly BackgroundToolTaskRef[];\n\t/** Active ICM pipeline run; agent complete refuses while a joined or any active run remains. */\n\tactivePipeline?: { runId: string; pipelineName: string; goalId?: string; status: string };\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tif (action.action === \"increment\") {\n\t\tconst firstOpen = current.requirements.find((requirement) => requirement.status === \"open\");\n\t\tif (firstOpen) {\n\t\t\tconst used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));\n\t\t\tconst unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);\n\t\t\tif (unused.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn applyGoalAction(\n\t\t\t\tcurrent,\n\t\t\t\t{ action: \"satisfy_requirement\", requirementId: firstOpen.id, evidenceIds: unused },\n\t\t\t\tnow,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\t\treturn applyGoalAction(current, { action: \"complete\" }, now, options);\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\tif (action.dependencies) {\n\t\t\t\tfor (const depId of action.dependencies) {\n\t\t\t\t\tif (!requirementExists(state, depId) && depId !== id) {\n\t\t\t\t\t\treturn { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, dependencies: action.dependencies, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tconst requirement = state.requirements.find((r) => r.id === id);\n\t\t\tif (!requirement) return { ok: false, error: `Requirement '${id}' does not exist.` };\n\t\t\tif (requirement.status !== \"open\") {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };\n\t\t\t}\n\t\t\tif (requirement.dependencies) {\n\t\t\t\tconst unsatisfied = requirement.dependencies.filter((depId) => {\n\t\t\t\t\tconst dep = state.requirements.find((r) => r.id === depId);\n\t\t\t\t\treturn !dep || dep.status !== \"satisfied\";\n\t\t\t\t});\n\t\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(\", \")}].`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"increment\":\n\t\t\treturn { ok: false, error: \"increment must be expanded by applyGoalAction.\" };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst linkedOpenSteps = findLinkedOpenTaskSteps(state, options?.openTaskSteps);\n\t\t\tif (linkedOpenSteps.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: open task_steps still reference this goal (${linkedOpenSteps.join(\", \")}). Update them via task_steps first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pendingToolTasks = findNonterminalCitedToolTasks(state, options?.backgroundToolTasks);\n\t\t\tif (pendingToolTasks.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: cited tool_task(s) are not complete (${pendingToolTasks.join(\", \")}). Wait once via tool_task, then record the terminal result.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst activePipeline = options?.activePipeline;\n\t\t\tif (activePipeline && activePipeline.status === \"active\") {\n\t\t\t\tconst joined = !activePipeline.goalId || activePipeline.goalId === state.goalId;\n\t\t\t\tif (joined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n\tevidence?: readonly string[];\n}\n\nfunction findLinkedOpenTaskSteps(state: GoalState, openTaskSteps: readonly OpenTaskStepRef[] | undefined): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\treturn openTaskSteps\n\t\t.filter((step) => state.requirements.some((requirement) => taskStepReferencesRequirement(step, requirement)))\n\t\t.map((step) => step.id);\n}\n\nfunction findNonterminalCitedToolTasks(\n\tstate: GoalState,\n\tbackgroundToolTasks: readonly BackgroundToolTaskRef[] | undefined,\n): string[] {\n\tif (!backgroundToolTasks || backgroundToolTasks.length === 0) return [];\n\tconst pending = new Set<string>();\n\tfor (const evidence of state.evidence) {\n\t\tif (evidence.kind !== \"tool\" || !evidence.uri) continue;\n\t\tconst task = findBackgroundToolTask(backgroundToolTasks, evidence.uri);\n\t\tif (task && task.status !== \"completed\") pending.add(task.taskId);\n\t}\n\treturn [...pending];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
1
+ {"version":3,"file":"goal-tool-core.js","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACN,cAAc,EACd,eAAe,EAIf,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,GACzB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAC1C,MAAM,mBAAmB,GAAG,KAAK,CAAC;AAClC,MAAM,2BAA2B,GAAG,CAAC,CAAC;AAkFtC,SAAS,iBAAiB,CAAC,KAAgB,EAAE,aAAqB;IACjE,OAAO,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,KAAK,aAAa,CAAC,CAAC;AACnF,CAAC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C,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type BackgroundToolTaskRef, findBackgroundToolTask } from \"../background-tool-task-controller.ts\";\nimport { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalExecutionActive,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\nconst MIN_AGENT_BLOCK_STALL_TURNS = 3;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string; dependencies?: readonly string[] }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"increment\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n\t/**\n\t * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any of\n\t * these still reference a requirement of the goal being closed.\n\t */\n\topenTaskSteps?: readonly OpenTaskStepRef[];\n\t/** Live background tool_task records used to re-check kind:\"tool\" evidence at complete time. */\n\tbackgroundToolTasks?: readonly BackgroundToolTaskRef[];\n\t/** Active ICM pipeline run; agent complete refuses while a joined or any active run remains. */\n\tactivePipeline?: { runId: string; pipelineName: string; goalId?: string; status: string };\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tif (action.action === \"increment\") {\n\t\tconst firstOpen = current.requirements.find((requirement) => requirement.status === \"open\");\n\t\tif (firstOpen) {\n\t\t\tconst used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));\n\t\t\tconst unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);\n\t\t\tif (unused.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn applyGoalAction(\n\t\t\t\tcurrent,\n\t\t\t\t{ action: \"satisfy_requirement\", requirementId: firstOpen.id, evidenceIds: unused },\n\t\t\t\tnow,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\t\treturn applyGoalAction(current, { action: \"complete\" }, now, options);\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\tif (action.dependencies) {\n\t\t\t\tfor (const depId of action.dependencies) {\n\t\t\t\t\tif (!requirementExists(state, depId) && depId !== id) {\n\t\t\t\t\t\treturn { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, dependencies: action.dependencies, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tconst requirement = state.requirements.find((r) => r.id === id);\n\t\t\tif (!requirement) return { ok: false, error: `Requirement '${id}' does not exist.` };\n\t\t\tif (requirement.status !== \"open\") {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };\n\t\t\t}\n\t\t\tif (requirement.dependencies) {\n\t\t\t\tconst unsatisfied = requirement.dependencies.filter((depId) => {\n\t\t\t\t\tconst dep = state.requirements.find((r) => r.id === depId);\n\t\t\t\t\treturn !dep || dep.status !== \"satisfied\";\n\t\t\t\t});\n\t\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(\", \")}].`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"increment\":\n\t\t\treturn { ok: false, error: \"increment must be expanded by applyGoalAction.\" };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst linkedOpenSteps = findLinkedOpenTaskSteps(state, options?.openTaskSteps);\n\t\t\tif (linkedOpenSteps.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: open task_steps still reference this goal (${linkedOpenSteps.join(\", \")}). Update them via task_steps first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pendingToolTasks = findNonterminalCitedToolTasks(state, options?.backgroundToolTasks);\n\t\t\tif (pendingToolTasks.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: cited tool_task(s) are not complete (${pendingToolTasks.join(\", \")}). Wait once via tool_task, then record the terminal result.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst activePipeline = options?.activePipeline;\n\t\t\tif (activePipeline && activePipeline.status === \"active\") {\n\t\t\t\tconst joined = !activePipeline.goalId || activePipeline.goalId === state.goalId;\n\t\t\t\tif (joined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\tif (state.stallTurns < MIN_AGENT_BLOCK_STALL_TURNS) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `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.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n\tevidence?: readonly string[];\n}\n\nfunction findLinkedOpenTaskSteps(state: GoalState, openTaskSteps: readonly OpenTaskStepRef[] | undefined): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\treturn openTaskSteps\n\t\t.filter((step) => state.requirements.some((requirement) => taskStepReferencesRequirement(step, requirement)))\n\t\t.map((step) => step.id);\n}\n\nfunction findNonterminalCitedToolTasks(\n\tstate: GoalState,\n\tbackgroundToolTasks: readonly BackgroundToolTaskRef[] | undefined,\n): string[] {\n\tif (!backgroundToolTasks || backgroundToolTasks.length === 0) return [];\n\tconst pending = new Set<string>();\n\tfor (const evidence of state.evidence) {\n\t\tif (evidence.kind !== \"tool\" || !evidence.uri) continue;\n\t\tconst task = findBackgroundToolTask(backgroundToolTasks, evidence.uri);\n\t\tif (task && task.status !== \"completed\") pending.add(task.taskId);\n\t}\n\treturn [...pending];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export declare const LEGACY_GOAL_TOOL_NAME: "goal";
2
+ /** Compact provider-neutral lifecycle surface mirrored from Codex's durable goal contract. */
3
+ export declare const GOAL_LIFECYCLE_TOOL_NAMES: readonly ["create_goal", "get_goal", "update_goal"];
4
+ export type GoalLifecycleToolName = (typeof GOAL_LIFECYCLE_TOOL_NAMES)[number];
5
+ /** A continuation needs a tool that can terminalize the goal, not merely inspect it. */
6
+ export declare function hasGoalContinuationControl(toolNames: readonly string[]): boolean;
7
+ //# sourceMappingURL=goal-tool-names.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goal-tool-names.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-names.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,qBAAqB,EAAG,MAAe,CAAC;AAErD,8FAA8F;AAC9F,eAAO,MAAM,yBAAyB,YAAI,aAAa,EAAE,UAAU,EAAE,aAAa,CAAU,CAAC;AAE7F,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,yBAAyB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/E,wFAAwF;AACxF,wBAAgB,0BAA0B,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAEhF"}
@@ -0,0 +1,8 @@
1
+ export const LEGACY_GOAL_TOOL_NAME = "goal";
2
+ /** Compact provider-neutral lifecycle surface mirrored from Codex's durable goal contract. */
3
+ export const GOAL_LIFECYCLE_TOOL_NAMES = ["create_goal", "get_goal", "update_goal"];
4
+ /** A continuation needs a tool that can terminalize the goal, not merely inspect it. */
5
+ export function hasGoalContinuationControl(toolNames) {
6
+ return toolNames.includes(LEGACY_GOAL_TOOL_NAME) || toolNames.includes("update_goal");
7
+ }
8
+ //# sourceMappingURL=goal-tool-names.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goal-tool-names.js","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-names.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAe,CAAC;AAErD,8FAA8F;AAC9F,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,aAAa,EAAE,UAAU,EAAE,aAAa,CAAU,CAAC;AAI7F,wFAAwF;AACxF,MAAM,UAAU,0BAA0B,CAAC,SAA4B;IACtE,OAAO,SAAS,CAAC,QAAQ,CAAC,qBAAqB,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;AACvF,CAAC","sourcesContent":["export const LEGACY_GOAL_TOOL_NAME = \"goal\" as const;\n\n/** Compact provider-neutral lifecycle surface mirrored from Codex's durable goal contract. */\nexport const GOAL_LIFECYCLE_TOOL_NAMES = [\"create_goal\", \"get_goal\", \"update_goal\"] as const;\n\nexport type GoalLifecycleToolName = (typeof GOAL_LIFECYCLE_TOOL_NAMES)[number];\n\n/** A continuation needs a tool that can terminalize the goal, not merely inspect it. */\nexport function hasGoalContinuationControl(toolNames: readonly string[]): boolean {\n\treturn toolNames.includes(LEGACY_GOAL_TOOL_NAME) || toolNames.includes(\"update_goal\");\n}\n"]}
@@ -20,7 +20,7 @@ export interface ModelCapabilityProfile {
20
20
  allowedToolNames?: readonly string[];
21
21
  /** Block-list applied after the allow-list; undefined = nothing blocked. */
22
22
  blockedToolNames?: readonly string[];
23
- /** Whether idle background lanes (goal auto-continue, research) may run on this model. */
23
+ /** Whether resource-heavy research/delegation background lanes may run on this model. */
24
24
  backgroundLanesEnabled: boolean;
25
25
  /** Output-token cap for lane isolated completions, scaled to the window. */
26
26
  laneMaxOutputTokens: number;
@@ -1 +1 @@
1
- {"version":3,"file":"model-capability.d.ts","sourceRoot":"","sources":["../../src/core/model-capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,oBAAoB,GAAG,MAAM,GAAG,MAAM,GAA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;AACH,MAAM,MAAM,uBAAuB,GAChC,6BAA6B,GAC7B,wBAAwB,GACxB,2BAA2B,GAC3B,sBAAsB,CAAC;AAE1B,MAAM,WAAW,iBAAiB;IACjC,MAAM,EAAE,uBAAuB,CAAC;IAChC,eAAe,EAAE,oBAAoB,CAAC;IACtC,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE;IAC/C,eAAe,EAAE,oBAAoB,CAAC;IACtC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,qBAAqB,EAAE,OAAO,CAAC;IAC/B,kBAAkB,EAAE,OAAO,CAAC;CAC5B,GAAG,iBAAiB,GAAG,SAAS,CAOhC;AAED,6EAA6E;AAC7E,eAAO,MAAM,0BAA0B,uCAAuC,CAAC;AAE/E,0GAA0G;AAC1G,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAI5F"}
@@ -8,6 +8,7 @@
8
8
  * window keeps today's full behavior rather than guessing). Detection can be disabled or forced
9
9
  * per class via the `modelCapability.mode` setting.
10
10
  */
11
+ import { GOAL_LIFECYCLE_TOOL_NAMES } from "./goals/goal-tool-names.js";
11
12
  /** Windows at or above this keep the full harness surface. */
12
13
  export const MODEL_CAPABILITY_FULL_MIN_CONTEXT = 32_768;
13
14
  /** Windows at or above this keep core tools but shed background-autonomy extras. */
@@ -46,11 +47,12 @@ export const MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS = [
46
47
  "powershell",
47
48
  "edit",
48
49
  "write",
50
+ ...GOAL_LIFECYCLE_TOOL_NAMES,
49
51
  "ask_question",
50
52
  // The executor tool: minimal-class models ARE the daily-ops executors, and its schema is tiny.
51
53
  "run_toolkit_script",
52
54
  ];
53
- export const MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS = [];
55
+ export const MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS = [...GOAL_LIFECYCLE_TOOL_NAMES];
54
56
  export const DEFAULT_LANE_MAX_OUTPUT_TOKENS = 2048;
55
57
  const MIN_LANE_MAX_OUTPUT_TOKENS = 256;
56
58
  function laneOutputTokensForWindow(contextWindow) {
@@ -1 +1 @@
1
- {"version":3,"file":"model-capability.js","sourceRoot":"","sources":["../../src/core/model-capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAsBH,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,oFAAoF;AACpF,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,oCAAoC,GAAG,KAAK,CAAC;AAE1D;;;;GAIG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAA+D;IACnH,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,KAAK;IACd,IAAI,EAAE,KAAK;CACX,CAAC;AAEF,MAAM,CAAC,MAAM,mCAAmC,GAAsB;IACrE,UAAU;IACV,eAAe;IACf,MAAM;IACN,UAAU;IACV,eAAe;IACf,kBAAkB;IAClB,cAAc;IACd,UAAU;IACV,eAAe;IACf,eAAe;IACf,oBAAoB;CACpB,CAAC;AACF,MAAM,CAAC,MAAM,sCAAsC,GAAsB;IACxE,MAAM;IACN,OAAO;IACP,MAAM;IACN,QAAQ;IACR,YAAY;IACZ,MAAM;IACN,OAAO;IACP,cAAc;IACd,+FAA+F;IAC/F,oBAAoB;CACpB,CAAC;AACF,MAAM,CAAC,MAAM,mCAAmC,GAAsB,EAAE,CAAC;AAEzE,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AACnD,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAEvC,SAAS,yBAAyB,CAAC,aAAiC;IACnE,IAAI,aAAa,KAAK,SAAS,IAAI,aAAa,IAAI,CAAC;QAAE,OAAO,8BAA8B,CAAC;IAC7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E,eAAe,EAAE,aAAa,EAAE,CAAC;IAClG,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,MAAM,0BAA0B,GAAG,oCAAoC,CAAC;AAE/E,0GAA0G;AAC1G,MAAM,UAAU,uBAAuB,CAAC,OAA0B,EAAE,OAAgB;IACnF,MAAM,UAAU,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnE,MAAM,UAAU,GAAG,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnG,OAAO,GAAG,0BAA0B,GAAG,UAAU,UAAU,OAAO,CAAC,eAAe,kBAAkB,UAAU,WAAW,OAAO,CAAC,MAAM,EAAE,CAAC;AAC3I,CAAC","sourcesContent":["/**\n * Model capability auto-detection: derive what the harness may load onto a model FROM the model's\n * own metadata (`Model.contextWindow`), so small open models (4k/8k/16k windows, sub-1B params)\n * can still hold a usable chat instead of drowning in the stable prompt, tool schemas, and\n * background-lane prompts. The same class is the single input to prompt shaping and tool/lane gates.\n *\n * Derivation is metadata-first; defaults apply only when the metadata is missing (unknown/zero\n * window keeps today's full behavior rather than guessing). Detection can be disabled or forced\n * per class via the `modelCapability.mode` setting.\n */\n\nexport type ModelCapabilityClass = \"full\" | \"lean\" | \"minimal\" | \"chat\";\n\nexport type ModelCapabilityMode = \"auto\" | \"off\" | ModelCapabilityClass;\n\nexport interface ModelCapabilityProfile {\n\tclass: ModelCapabilityClass;\n\tcontextWindow?: number;\n\treasonCode: string;\n\t/** Hard aggregate character envelope for the stable system prompt; undefined = intentionally unbounded. */\n\tsystemPromptMaxChars: number | undefined;\n\t/** Allow-list; undefined = no allow-list restriction. */\n\tallowedToolNames?: readonly string[];\n\t/** Block-list applied after the allow-list; undefined = nothing blocked. */\n\tblockedToolNames?: readonly string[];\n\t/** Whether idle background lanes (goal auto-continue, research) may run on this model. */\n\tbackgroundLanesEnabled: boolean;\n\t/** Output-token cap for lane isolated completions, scaled to the window. */\n\tlaneMaxOutputTokens: number;\n}\n\n/** Windows at or above this keep the full harness surface. */\nexport const MODEL_CAPABILITY_FULL_MIN_CONTEXT = 32_768;\n/** Windows at or above this keep core tools but shed background-autonomy extras. */\nexport const MODEL_CAPABILITY_LEAN_MIN_CONTEXT = 16_384;\n/** Windows at or above this get the minimal coding set; below is chat-only. */\nexport const MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT = 8_192;\n\n/**\n * Aggregate stable-prompt envelopes. These are deliberately owned beside the classification\n * thresholds so every harness expansion must fit the same profile that owns tools and lanes.\n * Full/off profiles are intentionally unbounded; constrained profiles fail visibly on overflow.\n */\nexport const MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS: Readonly<Record<ModelCapabilityClass, number | undefined>> = {\n\tfull: undefined,\n\tlean: 8_192,\n\tminimal: 4_096,\n\tchat: 2_048,\n};\n\nexport const MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS: readonly string[] = [\n\t\"delegate\",\n\t\"context_audit\",\n\t\"goal\",\n\t\"pipeline\",\n\t\"worktree_sync\",\n\t\"improvement_loop\",\n\t\"extensionify\",\n\t\"skillify\",\n\t\"model_fitness\",\n\t\"context_scout\",\n\t\"tmux_agent_manager\",\n];\nexport const MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS: readonly string[] = [\n\t\"read\",\n\t\"skill\",\n\t\"bash\",\n\t\"python\",\n\t\"powershell\",\n\t\"edit\",\n\t\"write\",\n\t\"ask_question\",\n\t// The executor tool: minimal-class models ARE the daily-ops executors, and its schema is tiny.\n\t\"run_toolkit_script\",\n];\nexport const MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS: readonly string[] = [];\n\nexport const DEFAULT_LANE_MAX_OUTPUT_TOKENS = 2048;\nconst MIN_LANE_MAX_OUTPUT_TOKENS = 256;\n\nfunction laneOutputTokensForWindow(contextWindow: number | undefined): number {\n\tif (contextWindow === undefined || contextWindow <= 0) return DEFAULT_LANE_MAX_OUTPUT_TOKENS;\n\t// A lane completion may use at most an eighth of the window for output, floored so tiny\n\t// windows still produce something parseable.\n\treturn Math.min(DEFAULT_LANE_MAX_OUTPUT_TOKENS, Math.max(MIN_LANE_MAX_OUTPUT_TOKENS, Math.floor(contextWindow / 8)));\n}\n\nfunction profileForClass(\n\tcapabilityClass: ModelCapabilityClass,\n\treasonCode: string,\n\tcontextWindow: number | undefined,\n): ModelCapabilityProfile {\n\tconst base = {\n\t\tclass: capabilityClass,\n\t\treasonCode,\n\t\tsystemPromptMaxChars: MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS[capabilityClass],\n\t\tbackgroundLanesEnabled: true,\n\t\tlaneMaxOutputTokens: laneOutputTokensForWindow(contextWindow),\n\t\t...(contextWindow !== undefined && contextWindow > 0 ? { contextWindow } : {}),\n\t};\n\tswitch (capabilityClass) {\n\t\tcase \"full\":\n\t\t\treturn base;\n\t\tcase \"lean\":\n\t\t\treturn { ...base, blockedToolNames: MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS };\n\t\tcase \"minimal\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t\tcase \"chat\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t}\n}\n\n/**\n * Mandatory provider-neutral gate for a final system prompt. This intentionally rejects rather\n * than truncates: arbitrary truncation can silently remove security, repair, or project rules.\n */\nexport function enforceModelCapabilitySystemPromptBudget(\n\tsystemPrompt: string,\n\tprofile: Pick<ModelCapabilityProfile, \"class\" | \"systemPromptMaxChars\">,\n): string {\n\tconst maxChars = profile.systemPromptMaxChars;\n\tif (maxChars === undefined || systemPrompt.length <= maxChars) return systemPrompt;\n\tthrow new Error(\n\t\t`${profile.class} system prompt exceeds its ${maxChars}-character capability budget (${systemPrompt.length} characters). Reduce custom, extension, or harness prompt guidance, or select a more capable profile.`,\n\t);\n}\n\nexport function deriveModelCapabilityProfile(args: {\n\tcontextWindow?: number;\n\tmode?: ModelCapabilityMode;\n}): ModelCapabilityProfile {\n\tconst mode = args.mode ?? \"auto\";\n\tconst contextWindow =\n\t\targs.contextWindow !== undefined && Number.isFinite(args.contextWindow) && args.contextWindow > 0\n\t\t\t? args.contextWindow\n\t\t\t: undefined;\n\tif (mode === \"off\") {\n\t\treturn profileForClass(\"full\", \"detection_disabled\", contextWindow);\n\t}\n\tif (mode !== \"auto\") {\n\t\treturn profileForClass(mode, \"forced_by_setting\", contextWindow);\n\t}\n\n\tif (contextWindow === undefined) {\n\t\t// Metadata missing: defaults, never guesses.\n\t\treturn profileForClass(\"full\", \"unknown_context_window_defaults\", undefined);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_FULL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"full\", \"large_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_LEAN_MIN_CONTEXT) {\n\t\treturn profileForClass(\"lean\", \"lean_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"minimal\", \"minimal_context_window\", contextWindow);\n\t}\n\treturn profileForClass(\"chat\", \"chat_only_context_window\", contextWindow);\n}\n\n/** Apply the profile's allow/block lists to a requested tool-name list, preserving order. */\nexport function filterToolNamesForCapability(toolNames: readonly string[], profile: ModelCapabilityProfile): string[] {\n\tlet filtered = [...toolNames];\n\tif (profile.allowedToolNames !== undefined) {\n\t\tconst allowed = new Set(profile.allowedToolNames);\n\t\tfiltered = filtered.filter((name) => allowed.has(name));\n\t}\n\tif (profile.blockedToolNames !== undefined) {\n\t\tconst blocked = new Set(profile.blockedToolNames);\n\t\tfiltered = filtered.filter((name) => !blocked.has(name));\n\t}\n\treturn filtered;\n}\n\n/**\n * Lane-worker eligibility: a session bound to a worktree-sync lane (`--worktree-lane` /\n * `PI_WORKTREE_LANE`, see worktree-sync/runtime.ts) is expected to drive the FULL multi-step\n * lane-gate/recovery surface -- sync, conflict recovery, land -- unattended. A sub-full capability\n * class or a model with no working native tool-call path cannot reliably drive that surface. This\n * rides the SAME capability system every other adaptation in this file rides (class + context\n * window + the `/toolprobe` verdict) -- no parallel mechanism, no new env var, no new registry field.\n */\nexport type LaneWorkerRefusalReason =\n\t| \"capability_class_below_full\"\n\t| \"context_window_unknown\"\n\t| \"tool_calling_unadvertised\"\n\t| \"tool_calling_demoted\";\n\nexport interface LaneWorkerRefusal {\n\treason: LaneWorkerRefusalReason;\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow?: number;\n}\n\n/**\n * Decide whether the model described by `args` may drive a worktree-sync lane worker. First\n * failure wins, in order: capability class below full; an unknown/undeclared context window (the\n * classifier's own registry-derived SSOT -- see `deriveModelCapabilityProfile`; a full class can\n * still carry an undefined window via the `unknown_context_window_defaults` fallback); no\n * ADVERTISED native tool-call path (`Model.textToolCallProtocol` unset/false -- set true means\n * phone-only); or a GRADED `/toolprobe` demotion to \"text-protocol\"/\"none\". An UNPROBED model (no\n * verdict on record yet) is eligible on its advertised support alone -- unprobed is never treated\n * as demoted. `undefined` means eligible.\n */\nexport function evaluateLaneWorkerRefusal(args: {\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow: number | undefined;\n\ttoolCallingAdvertised: boolean;\n\ttoolCallingDemoted: boolean;\n}): LaneWorkerRefusal | undefined {\n\tconst { capabilityClass, contextWindow, toolCallingAdvertised, toolCallingDemoted } = args;\n\tif (capabilityClass !== \"full\") return { reason: \"capability_class_below_full\", capabilityClass, contextWindow };\n\tif (contextWindow === undefined) return { reason: \"context_window_unknown\", capabilityClass, contextWindow };\n\tif (!toolCallingAdvertised) return { reason: \"tool_calling_unadvertised\", capabilityClass, contextWindow };\n\tif (toolCallingDemoted) return { reason: \"tool_calling_demoted\", capabilityClass, contextWindow };\n\treturn undefined;\n}\n\n/** Stable, greppable prefix for {@link formatLaneWorkerRefusal}'s output. */\nexport const LANE_WORKER_REFUSAL_PREFIX = \"worktree-sync lane-worker refusal:\";\n\n/** Format a refusal into one deterministic, greppable line naming the lane, class, window, and reason. */\nexport function formatLaneWorkerRefusal(refusal: LaneWorkerRefusal, laneKey?: string): string {\n\tconst laneSuffix = laneKey !== undefined ? ` lane=${laneKey}` : \"\";\n\tconst windowText = refusal.contextWindow !== undefined ? String(refusal.contextWindow) : \"unknown\";\n\treturn `${LANE_WORKER_REFUSAL_PREFIX}${laneSuffix} class=${refusal.capabilityClass} contextWindow=${windowText} reason=${refusal.reason}`;\n}\n"]}
1
+ {"version":3,"file":"model-capability.js","sourceRoot":"","sources":["../../src/core/model-capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAsBvE,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,oFAAoF;AACpF,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,oCAAoC,GAAG,KAAK,CAAC;AAE1D;;;;GAIG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAA+D;IACnH,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,KAAK;IACd,IAAI,EAAE,KAAK;CACX,CAAC;AAEF,MAAM,CAAC,MAAM,mCAAmC,GAAsB;IACrE,UAAU;IACV,eAAe;IACf,MAAM;IACN,UAAU;IACV,eAAe;IACf,kBAAkB;IAClB,cAAc;IACd,UAAU;IACV,eAAe;IACf,eAAe;IACf,oBAAoB;CACpB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,CAAC,IAKzC;IACA,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAAC;IAC3F,IAAI,eAAe,KAAK,MAAM;QAAE,OAAO,EAAE,MAAM,EAAE,6BAA6B,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IACjH,IAAI,aAAa,KAAK,SAAS;QAAE,OAAO,EAAE,MAAM,EAAE,wBAAwB,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IAC7G,IAAI,CAAC,qBAAqB;QAAE,OAAO,EAAE,MAAM,EAAE,2BAA2B,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IAC3G,IAAI,kBAAkB;QAAE,OAAO,EAAE,MAAM,EAAE,sBAAsB,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IAClG,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,MAAM,0BAA0B,GAAG,oCAAoC,CAAC;AAE/E,0GAA0G;AAC1G,MAAM,UAAU,uBAAuB,CAAC,OAA0B,EAAE,OAAgB;IACnF,MAAM,UAAU,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnE,MAAM,UAAU,GAAG,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnG,OAAO,GAAG,0BAA0B,GAAG,UAAU,UAAU,OAAO,CAAC,eAAe,kBAAkB,UAAU,WAAW,OAAO,CAAC,MAAM,EAAE,CAAC;AAC3I,CAAC","sourcesContent":["/**\n * Model capability auto-detection: derive what the harness may load onto a model FROM the model's\n * own metadata (`Model.contextWindow`), so small open models (4k/8k/16k windows, sub-1B params)\n * can still hold a usable chat instead of drowning in the stable prompt, tool schemas, and\n * background-lane prompts. The same class is the single input to prompt shaping and tool/lane gates.\n *\n * Derivation is metadata-first; defaults apply only when the metadata is missing (unknown/zero\n * window keeps today's full behavior rather than guessing). Detection can be disabled or forced\n * per class via the `modelCapability.mode` setting.\n */\n\nimport { GOAL_LIFECYCLE_TOOL_NAMES } from \"./goals/goal-tool-names.ts\";\n\nexport type ModelCapabilityClass = \"full\" | \"lean\" | \"minimal\" | \"chat\";\n\nexport type ModelCapabilityMode = \"auto\" | \"off\" | ModelCapabilityClass;\n\nexport interface ModelCapabilityProfile {\n\tclass: ModelCapabilityClass;\n\tcontextWindow?: number;\n\treasonCode: string;\n\t/** Hard aggregate character envelope for the stable system prompt; undefined = intentionally unbounded. */\n\tsystemPromptMaxChars: number | undefined;\n\t/** Allow-list; undefined = no allow-list restriction. */\n\tallowedToolNames?: readonly string[];\n\t/** Block-list applied after the allow-list; undefined = nothing blocked. */\n\tblockedToolNames?: readonly string[];\n\t/** Whether resource-heavy research/delegation background lanes may run on this model. */\n\tbackgroundLanesEnabled: boolean;\n\t/** Output-token cap for lane isolated completions, scaled to the window. */\n\tlaneMaxOutputTokens: number;\n}\n\n/** Windows at or above this keep the full harness surface. */\nexport const MODEL_CAPABILITY_FULL_MIN_CONTEXT = 32_768;\n/** Windows at or above this keep core tools but shed background-autonomy extras. */\nexport const MODEL_CAPABILITY_LEAN_MIN_CONTEXT = 16_384;\n/** Windows at or above this get the minimal coding set; below is chat-only. */\nexport const MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT = 8_192;\n\n/**\n * Aggregate stable-prompt envelopes. These are deliberately owned beside the classification\n * thresholds so every harness expansion must fit the same profile that owns tools and lanes.\n * Full/off profiles are intentionally unbounded; constrained profiles fail visibly on overflow.\n */\nexport const MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS: Readonly<Record<ModelCapabilityClass, number | undefined>> = {\n\tfull: undefined,\n\tlean: 8_192,\n\tminimal: 4_096,\n\tchat: 2_048,\n};\n\nexport const MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS: readonly string[] = [\n\t\"delegate\",\n\t\"context_audit\",\n\t\"goal\",\n\t\"pipeline\",\n\t\"worktree_sync\",\n\t\"improvement_loop\",\n\t\"extensionify\",\n\t\"skillify\",\n\t\"model_fitness\",\n\t\"context_scout\",\n\t\"tmux_agent_manager\",\n];\nexport const MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS: readonly string[] = [\n\t\"read\",\n\t\"skill\",\n\t\"bash\",\n\t\"python\",\n\t\"powershell\",\n\t\"edit\",\n\t\"write\",\n\t...GOAL_LIFECYCLE_TOOL_NAMES,\n\t\"ask_question\",\n\t// The executor tool: minimal-class models ARE the daily-ops executors, and its schema is tiny.\n\t\"run_toolkit_script\",\n];\nexport const MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS: readonly string[] = [...GOAL_LIFECYCLE_TOOL_NAMES];\n\nexport const DEFAULT_LANE_MAX_OUTPUT_TOKENS = 2048;\nconst MIN_LANE_MAX_OUTPUT_TOKENS = 256;\n\nfunction laneOutputTokensForWindow(contextWindow: number | undefined): number {\n\tif (contextWindow === undefined || contextWindow <= 0) return DEFAULT_LANE_MAX_OUTPUT_TOKENS;\n\t// A lane completion may use at most an eighth of the window for output, floored so tiny\n\t// windows still produce something parseable.\n\treturn Math.min(DEFAULT_LANE_MAX_OUTPUT_TOKENS, Math.max(MIN_LANE_MAX_OUTPUT_TOKENS, Math.floor(contextWindow / 8)));\n}\n\nfunction profileForClass(\n\tcapabilityClass: ModelCapabilityClass,\n\treasonCode: string,\n\tcontextWindow: number | undefined,\n): ModelCapabilityProfile {\n\tconst base = {\n\t\tclass: capabilityClass,\n\t\treasonCode,\n\t\tsystemPromptMaxChars: MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS[capabilityClass],\n\t\tbackgroundLanesEnabled: true,\n\t\tlaneMaxOutputTokens: laneOutputTokensForWindow(contextWindow),\n\t\t...(contextWindow !== undefined && contextWindow > 0 ? { contextWindow } : {}),\n\t};\n\tswitch (capabilityClass) {\n\t\tcase \"full\":\n\t\t\treturn base;\n\t\tcase \"lean\":\n\t\t\treturn { ...base, blockedToolNames: MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS };\n\t\tcase \"minimal\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t\tcase \"chat\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t}\n}\n\n/**\n * Mandatory provider-neutral gate for a final system prompt. This intentionally rejects rather\n * than truncates: arbitrary truncation can silently remove security, repair, or project rules.\n */\nexport function enforceModelCapabilitySystemPromptBudget(\n\tsystemPrompt: string,\n\tprofile: Pick<ModelCapabilityProfile, \"class\" | \"systemPromptMaxChars\">,\n): string {\n\tconst maxChars = profile.systemPromptMaxChars;\n\tif (maxChars === undefined || systemPrompt.length <= maxChars) return systemPrompt;\n\tthrow new Error(\n\t\t`${profile.class} system prompt exceeds its ${maxChars}-character capability budget (${systemPrompt.length} characters). Reduce custom, extension, or harness prompt guidance, or select a more capable profile.`,\n\t);\n}\n\nexport function deriveModelCapabilityProfile(args: {\n\tcontextWindow?: number;\n\tmode?: ModelCapabilityMode;\n}): ModelCapabilityProfile {\n\tconst mode = args.mode ?? \"auto\";\n\tconst contextWindow =\n\t\targs.contextWindow !== undefined && Number.isFinite(args.contextWindow) && args.contextWindow > 0\n\t\t\t? args.contextWindow\n\t\t\t: undefined;\n\tif (mode === \"off\") {\n\t\treturn profileForClass(\"full\", \"detection_disabled\", contextWindow);\n\t}\n\tif (mode !== \"auto\") {\n\t\treturn profileForClass(mode, \"forced_by_setting\", contextWindow);\n\t}\n\n\tif (contextWindow === undefined) {\n\t\t// Metadata missing: defaults, never guesses.\n\t\treturn profileForClass(\"full\", \"unknown_context_window_defaults\", undefined);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_FULL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"full\", \"large_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_LEAN_MIN_CONTEXT) {\n\t\treturn profileForClass(\"lean\", \"lean_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"minimal\", \"minimal_context_window\", contextWindow);\n\t}\n\treturn profileForClass(\"chat\", \"chat_only_context_window\", contextWindow);\n}\n\n/** Apply the profile's allow/block lists to a requested tool-name list, preserving order. */\nexport function filterToolNamesForCapability(toolNames: readonly string[], profile: ModelCapabilityProfile): string[] {\n\tlet filtered = [...toolNames];\n\tif (profile.allowedToolNames !== undefined) {\n\t\tconst allowed = new Set(profile.allowedToolNames);\n\t\tfiltered = filtered.filter((name) => allowed.has(name));\n\t}\n\tif (profile.blockedToolNames !== undefined) {\n\t\tconst blocked = new Set(profile.blockedToolNames);\n\t\tfiltered = filtered.filter((name) => !blocked.has(name));\n\t}\n\treturn filtered;\n}\n\n/**\n * Lane-worker eligibility: a session bound to a worktree-sync lane (`--worktree-lane` /\n * `PI_WORKTREE_LANE`, see worktree-sync/runtime.ts) is expected to drive the FULL multi-step\n * lane-gate/recovery surface -- sync, conflict recovery, land -- unattended. A sub-full capability\n * class or a model with no working native tool-call path cannot reliably drive that surface. This\n * rides the SAME capability system every other adaptation in this file rides (class + context\n * window + the `/toolprobe` verdict) -- no parallel mechanism, no new env var, no new registry field.\n */\nexport type LaneWorkerRefusalReason =\n\t| \"capability_class_below_full\"\n\t| \"context_window_unknown\"\n\t| \"tool_calling_unadvertised\"\n\t| \"tool_calling_demoted\";\n\nexport interface LaneWorkerRefusal {\n\treason: LaneWorkerRefusalReason;\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow?: number;\n}\n\n/**\n * Decide whether the model described by `args` may drive a worktree-sync lane worker. First\n * failure wins, in order: capability class below full; an unknown/undeclared context window (the\n * classifier's own registry-derived SSOT -- see `deriveModelCapabilityProfile`; a full class can\n * still carry an undefined window via the `unknown_context_window_defaults` fallback); no\n * ADVERTISED native tool-call path (`Model.textToolCallProtocol` unset/false -- set true means\n * phone-only); or a GRADED `/toolprobe` demotion to \"text-protocol\"/\"none\". An UNPROBED model (no\n * verdict on record yet) is eligible on its advertised support alone -- unprobed is never treated\n * as demoted. `undefined` means eligible.\n */\nexport function evaluateLaneWorkerRefusal(args: {\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow: number | undefined;\n\ttoolCallingAdvertised: boolean;\n\ttoolCallingDemoted: boolean;\n}): LaneWorkerRefusal | undefined {\n\tconst { capabilityClass, contextWindow, toolCallingAdvertised, toolCallingDemoted } = args;\n\tif (capabilityClass !== \"full\") return { reason: \"capability_class_below_full\", capabilityClass, contextWindow };\n\tif (contextWindow === undefined) return { reason: \"context_window_unknown\", capabilityClass, contextWindow };\n\tif (!toolCallingAdvertised) return { reason: \"tool_calling_unadvertised\", capabilityClass, contextWindow };\n\tif (toolCallingDemoted) return { reason: \"tool_calling_demoted\", capabilityClass, contextWindow };\n\treturn undefined;\n}\n\n/** Stable, greppable prefix for {@link formatLaneWorkerRefusal}'s output. */\nexport const LANE_WORKER_REFUSAL_PREFIX = \"worktree-sync lane-worker refusal:\";\n\n/** Format a refusal into one deterministic, greppable line naming the lane, class, window, and reason. */\nexport function formatLaneWorkerRefusal(refusal: LaneWorkerRefusal, laneKey?: string): string {\n\tconst laneSuffix = laneKey !== undefined ? ` lane=${laneKey}` : \"\";\n\tconst windowText = refusal.contextWindow !== undefined ? String(refusal.contextWindow) : \"unknown\";\n\treturn `${LANE_WORKER_REFUSAL_PREFIX}${laneSuffix} class=${refusal.capabilityClass} contextWindow=${windowText} reason=${refusal.reason}`;\n}\n"]}
@@ -1,4 +1,5 @@
1
- import { type StreamFn, type StreamIdleOptions } from "@caupulican/pi-agent-core";
1
+ import type { StreamIdleOptions } from "@caupulican/pi-agent-core/reliability";
2
+ import type { StreamFn } from "@caupulican/pi-agent-core/types";
2
3
  import type { Api, Context, Model } from "@caupulican/pi-ai/types";
3
4
  export declare const DEFAULT_ADAPTIVE_STREAM_IDLE_CEILING_MS: number;
4
5
  export interface ModelPerfProfile {
@@ -1 +1 @@
1
- {"version":3,"file":"perf-profile.d.ts","sourceRoot":"","sources":["../../../src/core/models/perf-profile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiC,KAAK,QAAQ,EAAE,KAAK,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAEjH,OAAO,KAAK,EACX,GAAG,EAGH,OAAO,EACP,KAAK,EAEL,MAAM,yBAAyB,CAAC;AAMjC,eAAO,MAAM,uCAAuC,QAAiB,CAAC;AAEtE,MAAM,WAAW,gBAAgB;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC/B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,EAAE,CAAC,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,uBAAuB;IACvC,IAAI,EAAE,iBAAiB,CAAC;IACxB,OAAO,CAAC,EAAE,gBAAgB,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,8BAA8B;IAC9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B,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA0B3G;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAEpE;AAED,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,8BAA8B,GAAG,QAAQ,CA4D3G"}
@@ -1,4 +1,4 @@
1
- import { estimateProviderRequestTokens } from "@caupulican/pi-agent-core";
1
+ import { estimateProviderRequestTokens } from "@caupulican/pi-agent-core/provider-request-estimator";
2
2
  import { createAssistantMessageEventStream } from "@caupulican/pi-ai/event-stream";
3
3
  import { createEmptyUsage } from "@caupulican/pi-ai/usage";
4
4
  const PERF_EWMA_ALPHA = 0.3;