@caupulican/pi-adaptative 0.93.2 → 0.93.4

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 (224) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +6 -6
  3. package/dist/cli/args.js +1 -1
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/core/agent-session-contracts.d.ts +2 -2
  6. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  7. package/dist/core/agent-session-contracts.js.map +1 -1
  8. package/dist/core/agent-session.d.ts.map +1 -1
  9. package/dist/core/agent-session.js +16 -11
  10. package/dist/core/agent-session.js.map +1 -1
  11. package/dist/core/autonomy/approval-gate.d.ts +1 -0
  12. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  13. package/dist/core/autonomy/approval-gate.js +4 -1
  14. package/dist/core/autonomy/approval-gate.js.map +1 -1
  15. package/dist/core/autonomy/composite-tool-gate.d.ts +13 -0
  16. package/dist/core/autonomy/composite-tool-gate.d.ts.map +1 -0
  17. package/dist/core/autonomy/composite-tool-gate.js +44 -0
  18. package/dist/core/autonomy/composite-tool-gate.js.map +1 -0
  19. package/dist/core/autonomy/envelope-enforcement.d.ts +2 -0
  20. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  21. package/dist/core/autonomy/envelope-enforcement.js +48 -7
  22. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  23. package/dist/core/autonomy/gates.d.ts.map +1 -1
  24. package/dist/core/autonomy/gates.js +48 -76
  25. package/dist/core/autonomy/gates.js.map +1 -1
  26. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  27. package/dist/core/autonomy/path-scope.js +7 -7
  28. package/dist/core/autonomy/path-scope.js.map +1 -1
  29. package/dist/core/autonomy/subagent-prompt.d.ts +1 -1
  30. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  31. package/dist/core/background-tool-task-controller.d.ts +2 -0
  32. package/dist/core/background-tool-task-controller.d.ts.map +1 -1
  33. package/dist/core/background-tool-task-controller.js +13 -5
  34. package/dist/core/background-tool-task-controller.js.map +1 -1
  35. package/dist/core/compaction-controller.d.ts +3 -0
  36. package/dist/core/compaction-controller.d.ts.map +1 -1
  37. package/dist/core/compaction-controller.js +132 -97
  38. package/dist/core/compaction-controller.js.map +1 -1
  39. package/dist/core/cost-guard.js +1 -1
  40. package/dist/core/cost-guard.js.map +1 -1
  41. package/dist/core/delegation/session-root-mailbox.d.ts.map +1 -1
  42. package/dist/core/delegation/session-root-mailbox.js +14 -1
  43. package/dist/core/delegation/session-root-mailbox.js.map +1 -1
  44. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  45. package/dist/core/delegation/worker-agent-control-coordinator.js +6 -9
  46. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  47. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  48. package/dist/core/delegation/worker-attempt-executor.js +7 -5
  49. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  50. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
  51. package/dist/core/delegation/worker-authority-resolver.js +3 -2
  52. package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
  53. package/dist/core/delegation/worker-delegation-request.d.ts +5 -2
  54. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  55. package/dist/core/delegation/worker-delegation-request.js +1 -1
  56. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  57. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  58. package/dist/core/delegation/worker-execution-policy.js +10 -8
  59. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  60. package/dist/core/foreground-recovery-controller.d.ts +2 -0
  61. package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
  62. package/dist/core/foreground-recovery-controller.js +18 -9
  63. package/dist/core/foreground-recovery-controller.js.map +1 -1
  64. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  65. package/dist/core/goal-loop-controller.js +3 -5
  66. package/dist/core/goal-loop-controller.js.map +1 -1
  67. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
  68. package/dist/core/goals/goal-auto-continue-controller.js +6 -0
  69. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  70. package/dist/core/goals/goal-session-controller.js +1 -1
  71. package/dist/core/goals/goal-session-controller.js.map +1 -1
  72. package/dist/core/goals/goal-state.d.ts.map +1 -1
  73. package/dist/core/goals/goal-state.js +1 -0
  74. package/dist/core/goals/goal-state.js.map +1 -1
  75. package/dist/core/goals/goal-tool-core.d.ts +2 -0
  76. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  77. package/dist/core/goals/goal-tool-core.js +1 -1
  78. package/dist/core/goals/goal-tool-core.js.map +1 -1
  79. package/dist/core/model-router-controller.js +2 -2
  80. package/dist/core/model-router-controller.js.map +1 -1
  81. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  82. package/dist/core/orchestration/capability-gateway.js +32 -9
  83. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  84. package/dist/core/orchestration/lane-tool-manifests.js +5 -5
  85. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  86. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
  87. package/dist/core/orchestration/policy-compiler.js +7 -0
  88. package/dist/core/orchestration/policy-compiler.js.map +1 -1
  89. package/dist/core/orchestration/profile-registry.js +2 -2
  90. package/dist/core/orchestration/profile-registry.js.map +1 -1
  91. package/dist/core/orchestration/risk-budget.d.ts +0 -10
  92. package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
  93. package/dist/core/orchestration/risk-budget.js +0 -14
  94. package/dist/core/orchestration/risk-budget.js.map +1 -1
  95. package/dist/core/pipelines/active-context.d.ts +16 -0
  96. package/dist/core/pipelines/active-context.d.ts.map +1 -0
  97. package/dist/core/pipelines/active-context.js +29 -0
  98. package/dist/core/pipelines/active-context.js.map +1 -0
  99. package/dist/core/pipelines/context.d.ts +1 -1
  100. package/dist/core/pipelines/context.d.ts.map +1 -1
  101. package/dist/core/pipelines/context.js +40 -31
  102. package/dist/core/pipelines/context.js.map +1 -1
  103. package/dist/core/pipelines/discover.d.ts +5 -1
  104. package/dist/core/pipelines/discover.d.ts.map +1 -1
  105. package/dist/core/pipelines/discover.js +91 -33
  106. package/dist/core/pipelines/discover.js.map +1 -1
  107. package/dist/core/pipelines/increment.d.ts +0 -2
  108. package/dist/core/pipelines/increment.d.ts.map +1 -1
  109. package/dist/core/pipelines/increment.js +35 -13
  110. package/dist/core/pipelines/increment.js.map +1 -1
  111. package/dist/core/pipelines/index.d.ts +4 -3
  112. package/dist/core/pipelines/index.d.ts.map +1 -1
  113. package/dist/core/pipelines/index.js +4 -3
  114. package/dist/core/pipelines/index.js.map +1 -1
  115. package/dist/core/pipelines/run-state.d.ts +8 -0
  116. package/dist/core/pipelines/run-state.d.ts.map +1 -1
  117. package/dist/core/pipelines/run-state.js +172 -38
  118. package/dist/core/pipelines/run-state.js.map +1 -1
  119. package/dist/core/pipelines/types.d.ts +2 -0
  120. package/dist/core/pipelines/types.d.ts.map +1 -1
  121. package/dist/core/pipelines/types.js +21 -4
  122. package/dist/core/pipelines/types.js.map +1 -1
  123. package/dist/core/provider-prompt-contracts.d.ts +1 -0
  124. package/dist/core/provider-prompt-contracts.d.ts.map +1 -1
  125. package/dist/core/provider-prompt-contracts.js +6 -5
  126. package/dist/core/provider-prompt-contracts.js.map +1 -1
  127. package/dist/core/reflection-controller.js +1 -1
  128. package/dist/core/reflection-controller.js.map +1 -1
  129. package/dist/core/runtime-builder.d.ts +2 -1
  130. package/dist/core/runtime-builder.d.ts.map +1 -1
  131. package/dist/core/runtime-builder.js +46 -10
  132. package/dist/core/runtime-builder.js.map +1 -1
  133. package/dist/core/settings-manager.d.ts +5 -6
  134. package/dist/core/settings-manager.d.ts.map +1 -1
  135. package/dist/core/settings-manager.js +8 -13
  136. package/dist/core/settings-manager.js.map +1 -1
  137. package/dist/core/system-prompt-builder.d.ts +2 -4
  138. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  139. package/dist/core/system-prompt-builder.js +35 -11
  140. package/dist/core/system-prompt-builder.js.map +1 -1
  141. package/dist/core/system-prompt.d.ts.map +1 -1
  142. package/dist/core/system-prompt.js +6 -1
  143. package/dist/core/system-prompt.js.map +1 -1
  144. package/dist/core/tasks/task-projection.d.ts +2 -0
  145. package/dist/core/tasks/task-projection.d.ts.map +1 -1
  146. package/dist/core/tasks/task-projection.js +2 -0
  147. package/dist/core/tasks/task-projection.js.map +1 -1
  148. package/dist/core/tasks/task-state.d.ts +10 -0
  149. package/dist/core/tasks/task-state.d.ts.map +1 -1
  150. package/dist/core/tasks/task-state.js +43 -2
  151. package/dist/core/tasks/task-state.js.map +1 -1
  152. package/dist/core/tool-capability-policy.d.ts +13 -3
  153. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  154. package/dist/core/tool-capability-policy.js +136 -28
  155. package/dist/core/tool-capability-policy.js.map +1 -1
  156. package/dist/core/tools/delegate.d.ts +0 -16
  157. package/dist/core/tools/delegate.d.ts.map +1 -1
  158. package/dist/core/tools/delegate.js +21 -11
  159. package/dist/core/tools/delegate.js.map +1 -1
  160. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  161. package/dist/core/tools/edit-diff.js +45 -7
  162. package/dist/core/tools/edit-diff.js.map +1 -1
  163. package/dist/core/tools/edit.d.ts.map +1 -1
  164. package/dist/core/tools/edit.js +5 -1
  165. package/dist/core/tools/edit.js.map +1 -1
  166. package/dist/core/tools/goal.d.ts.map +1 -1
  167. package/dist/core/tools/goal.js +17 -1
  168. package/dist/core/tools/goal.js.map +1 -1
  169. package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
  170. package/dist/core/tools/orchestration-panel.js +1 -0
  171. package/dist/core/tools/orchestration-panel.js.map +1 -1
  172. package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -1
  173. package/dist/core/tools/persistent-process-coordinator.js +12 -7
  174. package/dist/core/tools/persistent-process-coordinator.js.map +1 -1
  175. package/dist/core/tools/pipeline.d.ts +1 -0
  176. package/dist/core/tools/pipeline.d.ts.map +1 -1
  177. package/dist/core/tools/pipeline.js +95 -44
  178. package/dist/core/tools/pipeline.js.map +1 -1
  179. package/dist/core/tools/profile-writer.d.ts +0 -9
  180. package/dist/core/tools/profile-writer.d.ts.map +1 -1
  181. package/dist/core/tools/profile-writer.js +0 -3
  182. package/dist/core/tools/profile-writer.js.map +1 -1
  183. package/dist/core/tools/secret-store.d.ts.map +1 -1
  184. package/dist/core/tools/secret-store.js +2 -1
  185. package/dist/core/tools/secret-store.js.map +1 -1
  186. package/dist/core/tools/shell-session.d.ts.map +1 -1
  187. package/dist/core/tools/shell-session.js +6 -1
  188. package/dist/core/tools/shell-session.js.map +1 -1
  189. package/dist/core/tools/task-steps.d.ts +10 -0
  190. package/dist/core/tools/task-steps.d.ts.map +1 -1
  191. package/dist/core/tools/task-steps.js +70 -29
  192. package/dist/core/tools/task-steps.js.map +1 -1
  193. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
  194. package/dist/core/tools/windows-shell-engine.js +6 -1
  195. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  196. package/dist/core/util/bounded-file.d.ts +8 -0
  197. package/dist/core/util/bounded-file.d.ts.map +1 -1
  198. package/dist/core/util/bounded-file.js +81 -16
  199. package/dist/core/util/bounded-file.js.map +1 -1
  200. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  201. package/dist/modes/interactive/components/settings-selector.js +7 -16
  202. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  203. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  204. package/dist/modes/interactive/components/thinking-selector.js +2 -11
  205. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  206. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  207. package/dist/modes/interactive/local-model-commands.js +1 -10
  208. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  209. package/dist/modes/interactive/thinking-level-descriptions.d.ts +4 -0
  210. package/dist/modes/interactive/thinking-level-descriptions.d.ts.map +1 -0
  211. package/dist/modes/interactive/thinking-level-descriptions.js +12 -0
  212. package/dist/modes/interactive/thinking-level-descriptions.js.map +1 -0
  213. package/docs/resources.md +1 -1
  214. package/docs/settings.md +7 -5
  215. package/docs/worker-profiles.md +3 -3
  216. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  217. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  218. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  219. package/examples/extensions/sandbox/package-lock.json +2 -2
  220. package/examples/extensions/sandbox/package.json +1 -1
  221. package/examples/extensions/with-deps/package-lock.json +2 -2
  222. package/examples/extensions/with-deps/package.json +1 -1
  223. package/npm-shrinkwrap.json +12 -12
  224. package/package.json +4 -4
@@ -4,9 +4,12 @@ import { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from "../default-tool
4
4
  import { buildLaneToolManifests } from "../orchestration/lane-tool-manifests.js";
5
5
  import { ExecutionPolicyCompiler } from "../orchestration/policy-compiler.js";
6
6
  import { intersectRiskBudgets } from "../orchestration/risk-budget.js";
7
- import { getToolCapabilityPolicy } from "../tool-capability-policy.js";
7
+ import { getToolCapabilityPolicy, requiredEnvelopeCapabilities } from "../tool-capability-policy.js";
8
8
  const READ_TOOL_NAMES = ["read", "grep", "find", "ls"];
9
9
  const WRITE_TOOL_NAMES = ["write", "edit"];
10
+ function delegatedToolCapabilities(toolName) {
11
+ return toolName === "memory" ? ["memory.query"] : requiredEnvelopeCapabilities(toolName);
12
+ }
10
13
  function intersectPathScopes(admittedPaths, currentPaths) {
11
14
  const intersections = admittedPaths.flatMap((admitted) => currentPaths.flatMap((current) => {
12
15
  if (isPathWithinScope(current, admitted))
@@ -69,18 +72,17 @@ export function buildWorkerExecutionPlan(args) {
69
72
  const enabledToolNames = [
70
73
  ...(grantsRead ? READ_TOOL_NAMES : []),
71
74
  ...(writeEligible ? WRITE_TOOL_NAMES : []),
72
- ...(memoryEligible ? ["memory"] : []),
73
75
  ...enabledProcessToolNames,
74
76
  ...(profileToolNames.has("delegate") && args.profile.capabilityCeiling.includes("workflow.delegate")
75
77
  ? ["delegate"]
76
78
  : []),
77
79
  ];
78
80
  const toolManifests = buildLaneToolManifests(args.profile, enabledToolNames);
79
- if (memoryEligible && !toolManifests.some((manifest) => manifest.toolName === "memory")) {
81
+ if (memoryEligible) {
80
82
  toolManifests.push({
81
83
  toolName: "memory",
82
84
  moduleSpecifier: "../tools/memory.ts",
83
- capabilities: ["memory.query"],
85
+ capabilities: delegatedToolCapabilities("memory"),
84
86
  roles: [args.profile.role],
85
87
  enforcements: ["memory-broker"],
86
88
  });
@@ -140,17 +142,17 @@ export function compileManagedProcessExecutionGrant(args) {
140
142
  const unknownTools = [];
141
143
  for (const toolName of [...new Set(args.allowedTools)]) {
142
144
  const policy = getToolCapabilityPolicy(toolName);
143
- const capability = policy?.capabilityCandidates[0];
144
- if (!policy || !capability) {
145
+ const capabilities = delegatedToolCapabilities(toolName);
146
+ if (!policy || capabilities.length === 0) {
145
147
  unknownTools.push(toolName);
146
148
  continue;
147
149
  }
148
150
  manifests.push({
149
151
  toolName,
150
152
  moduleSpecifier: `managed-process:${toolName}`,
151
- capabilities: [capability],
153
+ capabilities,
152
154
  roles: [args.role],
153
- enforcements: [policy.enforcement],
155
+ enforcements: policy.enforcements,
154
156
  });
155
157
  }
156
158
  if (unknownTools.length > 0)
@@ -1 +1 @@
1
- {"version":3,"file":"worker-execution-policy.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-execution-policy.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAW7F,OAAO,EAAE,sBAAs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O,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE;QACtD,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CACzC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAC5E;QACD,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACjE,eAAe,EAAE,IAAI,CAAC,MAAM;QAC5B,eAAe,EAAE,IAAI,CAAC,MAAM;QAC5B,aAAa,EAAE,oBAAoB;KACnC,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,OAAO,KAAK,OAAO;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;IAC1F,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import path from \"node:path\";\nimport { isPathWithinScope } from \"../autonomy/path-scope.ts\";\nimport { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport type {\n\tExecutionGrant,\n\tHarnessCapability,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tRiskBudget,\n\tToolCapabilityManifest,\n\tWorkerExecutionAuthorityContract,\n\tWorkerRole,\n} from \"../orchestration/contracts.ts\";\nimport { buildLaneToolManifests } from \"../orchestration/lane-tool-manifests.ts\";\nimport { ExecutionPolicyCompiler } from \"../orchestration/policy-compiler.ts\";\nimport { intersectRiskBudgets } from \"../orchestration/risk-budget.ts\";\nimport type { ResolvedWorkerDelegationSettings } from \"../settings-manager.ts\";\nimport { getToolCapabilityPolicy } from \"../tool-capability-policy.ts\";\n\nconst READ_TOOL_NAMES = [\"read\", \"grep\", \"find\", \"ls\"] as const;\nconst WRITE_TOOL_NAMES = [\"write\", \"edit\"] as const;\n\nexport interface WorkerExecutionPlan {\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\trequiredCapabilities: readonly HarnessCapability[];\n\treadPaths: readonly string[];\n\twritePaths: readonly string[];\n\tdeniedPaths: readonly string[];\n\treadMemory: boolean;\n\twriteEnabled: boolean;\n\tprocessEnabled: boolean;\n\tbudget: RiskBudget;\n}\n\nfunction intersectPathScopes(admittedPaths: readonly string[], currentPaths: readonly string[]): string[] {\n\tconst intersections = admittedPaths.flatMap((admitted) =>\n\t\tcurrentPaths.flatMap((current) => {\n\t\t\tif (isPathWithinScope(current, admitted)) return [current];\n\t\t\tif (isPathWithinScope(admitted, current)) return [admitted];\n\t\t\treturn [];\n\t\t}),\n\t);\n\treturn [...new Set(intersections.map((entry) => path.resolve(entry)))];\n}\n\nexport function workerExecutionAuthorityFromPlan(plan: WorkerExecutionPlan): WorkerExecutionAuthorityContract {\n\treturn {\n\t\tcapabilities: [...plan.requiredCapabilities],\n\t\ttoolNames: plan.toolManifests.map((manifest) => manifest.toolName),\n\t\treadPaths: [...plan.readPaths],\n\t\twritePaths: [...plan.writePaths],\n\t\tdeniedPaths: [...plan.deniedPaths],\n\t\tbudget: { ...plan.budget },\n\t};\n}\n\n/** Apply live revocations to admitted authority without allowing later settings to widen it. */\nexport function narrowWorkerExecutionPlan(\n\tadmitted: WorkerExecutionAuthorityContract,\n\tcurrent: WorkerExecutionPlan,\n): WorkerExecutionPlan {\n\tconst admittedTools = new Set(mapToolNamesForPlatform(admitted.toolNames));\n\tconst admittedCapabilities = new Set(admitted.capabilities);\n\tconst toolManifests = current.toolManifests.filter(\n\t\t(manifest) =>\n\t\t\tadmittedTools.has(manifest.toolName) &&\n\t\t\tmanifest.capabilities.every((capability) => admittedCapabilities.has(capability)),\n\t);\n\tconst requiredCapabilities = [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))];\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = requiredCapabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities,\n\t\treadPaths: readEnabled ? intersectPathScopes(admitted.readPaths, current.readPaths) : [],\n\t\twritePaths: writeEnabled ? intersectPathScopes(admitted.writePaths, current.writePaths) : [],\n\t\tdeniedPaths: [...new Set([...admitted.deniedPaths, ...current.deniedPaths].map((entry) => path.resolve(entry)))],\n\t\treadMemory: grantedTools.has(\"memory\"),\n\t\twriteEnabled,\n\t\tprocessEnabled: grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME),\n\t\tbudget: intersectRiskBudgets(admitted.budget, current.budget),\n\t};\n}\n\nexport function buildWorkerExecutionPlan(args: {\n\tprofile: OrchestrationProfile;\n\tsettings: ResolvedWorkerDelegationSettings;\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tforegroundMaxCostUsd?: number;\n\tmemoryEnabled: boolean;\n\trequestedReadPaths?: readonly string[];\n\trequestedWritePaths?: readonly string[];\n}): WorkerExecutionPlan {\n\tconst profileToolNames = new Set(mapToolNamesForPlatform(args.profile.toolNames));\n\tconst grantsRead =\n\t\targs.profile.capabilityCeiling.includes(\"filesystem.read\") ||\n\t\targs.profile.capabilityCeiling.includes(\"worktree.read\");\n\tconst writeEligible =\n\t\targs.settings.writeEnabled &&\n\t\targs.settings.writePaths.length > 0 &&\n\t\t(args.profile.capabilityCeiling.includes(\"filesystem.write\") ||\n\t\t\targs.profile.capabilityCeiling.includes(\"worktree.mutate\"));\n\tconst memoryEligible = args.memoryEnabled;\n\tconst processEligible =\n\t\targs.profile.capabilityCeiling.includes(\"process.exec\") ||\n\t\targs.profile.capabilityCeiling.includes(\"tests.execute\");\n\tconst enabledProcessToolNames = processEligible\n\t\t? [\n\t\t\t\t...(args.profile.executionPolicy && profileToolNames.has(\"run_process\") ? ([\"run_process\"] as const) : []),\n\t\t\t\t...(profileToolNames.has(STABLE_SHELL_TOOL_NAME) ? [STABLE_SHELL_TOOL_NAME] : []),\n\t\t\t]\n\t\t: [];\n\tconst enabledToolNames = [\n\t\t...(grantsRead ? READ_TOOL_NAMES : []),\n\t\t...(writeEligible ? WRITE_TOOL_NAMES : []),\n\t\t...(memoryEligible ? ([\"memory\"] as const) : []),\n\t\t...enabledProcessToolNames,\n\t\t...(profileToolNames.has(\"delegate\") && args.profile.capabilityCeiling.includes(\"workflow.delegate\")\n\t\t\t? ([\"delegate\"] as const)\n\t\t\t: []),\n\t];\n\tconst toolManifests = buildLaneToolManifests(args.profile, enabledToolNames);\n\tif (memoryEligible && !toolManifests.some((manifest) => manifest.toolName === \"memory\")) {\n\t\ttoolManifests.push({\n\t\t\ttoolName: \"memory\",\n\t\t\tmoduleSpecifier: \"../tools/memory.ts\",\n\t\t\tcapabilities: [\"memory.query\"],\n\t\t\troles: [args.profile.role],\n\t\t\tenforcements: [\"memory-broker\"],\n\t\t});\n\t}\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = toolManifests.some((manifest) =>\n\t\tmanifest.capabilities.some((capability) => capability === \"filesystem.read\" || capability === \"worktree.read\"),\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\tconst readMemory = grantedTools.has(\"memory\");\n\tconst processEnabled = grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME);\n\tconst budget = intersectRiskBudgets(\n\t\targs.profile.budget,\n\t\t...(args.settings.maxUsd > 0 ? [{ maxCostUsd: args.settings.maxUsd }] : []),\n\t\t...(args.foregroundMaxCostUsd !== undefined ? [{ maxCostUsd: args.foregroundMaxCostUsd }] : []),\n\t\t...(args.settings.maxWallClockMs > 0 ? [{ maxWallClockMs: args.settings.maxWallClockMs }] : []),\n\t);\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities: [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))],\n\t\treadPaths: readEnabled\n\t\t\t? (args.requestedReadPaths ?? [args.cwd]).map((entry) =>\n\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t)\n\t\t\t: [],\n\t\twritePaths: writeEnabled\n\t\t\t? intersectPathScopes(\n\t\t\t\t\targs.settings.writePaths.map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t\t(args.requestedWritePaths ?? args.settings.writePaths).map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [],\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\treadMemory,\n\t\twriteEnabled,\n\t\tprocessEnabled,\n\t\tbudget,\n\t};\n}\n\nexport function compileWorkerExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tprofile: OrchestrationProfile;\n\tplan: WorkerExecutionPlan;\n\tresources: readonly ResourcePointer[];\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst authorityCapabilities =\n\t\targs.plan.readMemory && !args.profile.capabilityCeiling.includes(\"memory.query\")\n\t\t\t? [...args.profile.capabilityCeiling, \"memory.query\" as const]\n\t\t\t: args.profile.capabilityCeiling;\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\tobjectiveId: args.target.objectiveId,\n\t\ttaskId: args.target.taskId,\n\t\tattemptId: args.target.attemptId,\n\t\tsubjectId: `in-process:${args.target.attemptId}`,\n\t\trole: args.profile.role,\n\t\trequiredCapabilities: args.plan.requiredCapabilities,\n\t\trequestedCapabilities: args.plan.requiredCapabilities,\n\t\tauthorityCapabilities,\n\t\trequestedTools: args.plan.toolManifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: args.plan.toolManifests,\n\t\tresources: args.resources,\n\t\treadPaths: args.plan.readPaths,\n\t\twritePaths: args.plan.writePaths,\n\t\tdeniedPaths: args.plan.deniedPaths,\n\t\trequestedBudget: args.plan.budget,\n\t\tauthorityBudget: args.plan.budget,\n\t\tpolicyVersion: \"worker-profile-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n\n/** Compile the host's durable authority record before an externally managed process is launched. */\nexport function compileManagedProcessExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tlaneId: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\tallowedTools: readonly string[];\n\twritePaths: readonly string[];\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tbudget: RiskBudget;\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst manifests: ToolCapabilityManifest[] = [];\n\tconst unknownTools: string[] = [];\n\tfor (const toolName of [...new Set(args.allowedTools)]) {\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capability = policy?.capabilityCandidates[0];\n\t\tif (!policy || !capability) {\n\t\t\tunknownTools.push(toolName);\n\t\t\tcontinue;\n\t\t}\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `managed-process:${toolName}`,\n\t\t\tcapabilities: [capability],\n\t\t\troles: [args.role],\n\t\t\tenforcements: [policy.enforcement],\n\t\t});\n\t}\n\tif (unknownTools.length > 0) return { ok: false, reasonCodes: unknownTools.map((name) => `unknown_tool:${name}`) };\n\tconst capabilities = [...new Set(manifests.flatMap((manifest) => manifest.capabilities))];\n\tconst readEnabled = capabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\t...args.target,\n\t\tsubjectId: `managed:${args.laneId}:${args.authorizationId}`,\n\t\trole: args.role,\n\t\trequiredCapabilities: capabilities,\n\t\trequestedCapabilities: capabilities,\n\t\tauthorityCapabilities: capabilities,\n\t\trequestedTools: manifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: manifests,\n\t\treadPaths: readEnabled ? [path.resolve(args.cwd)] : [],\n\t\twritePaths: args.writePaths.map((entry) =>\n\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t),\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\trequestedBudget: args.budget,\n\t\tauthorityBudget: args.budget,\n\t\tpolicyVersion: \"managed-process-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n"]}
1
+ {"version":3,"file":"worker-execution-policy.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-execution-policy.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAW7F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAEvE,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAErG,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAU,CAAC;AAChE,MAAM,gBAAgB,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C,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACjE,eAAe,EAAE,IAAI,CAAC,MAAM;QAC5B,eAAe,EAAE,IAAI,CAAC,MAAM;QAC5B,aAAa,EAAE,oBAAoB;KACnC,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,OAAO,KAAK,OAAO;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;IAC1F,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import path from \"node:path\";\nimport { isPathWithinScope } from \"../autonomy/path-scope.ts\";\nimport { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport type {\n\tExecutionGrant,\n\tHarnessCapability,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tRiskBudget,\n\tToolCapabilityManifest,\n\tWorkerExecutionAuthorityContract,\n\tWorkerRole,\n} from \"../orchestration/contracts.ts\";\nimport { buildLaneToolManifests } from \"../orchestration/lane-tool-manifests.ts\";\nimport { ExecutionPolicyCompiler } from \"../orchestration/policy-compiler.ts\";\nimport { intersectRiskBudgets } from \"../orchestration/risk-budget.ts\";\nimport type { ResolvedWorkerDelegationSettings } from \"../settings-manager.ts\";\nimport { getToolCapabilityPolicy, requiredEnvelopeCapabilities } from \"../tool-capability-policy.ts\";\n\nconst READ_TOOL_NAMES = [\"read\", \"grep\", \"find\", \"ls\"] as const;\nconst WRITE_TOOL_NAMES = [\"write\", \"edit\"] as const;\n\nfunction delegatedToolCapabilities(toolName: string): readonly HarnessCapability[] {\n\treturn toolName === \"memory\" ? [\"memory.query\"] : requiredEnvelopeCapabilities(toolName);\n}\n\nexport interface WorkerExecutionPlan {\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\trequiredCapabilities: readonly HarnessCapability[];\n\treadPaths: readonly string[];\n\twritePaths: readonly string[];\n\tdeniedPaths: readonly string[];\n\treadMemory: boolean;\n\twriteEnabled: boolean;\n\tprocessEnabled: boolean;\n\tbudget: RiskBudget;\n}\n\nfunction intersectPathScopes(admittedPaths: readonly string[], currentPaths: readonly string[]): string[] {\n\tconst intersections = admittedPaths.flatMap((admitted) =>\n\t\tcurrentPaths.flatMap((current) => {\n\t\t\tif (isPathWithinScope(current, admitted)) return [current];\n\t\t\tif (isPathWithinScope(admitted, current)) return [admitted];\n\t\t\treturn [];\n\t\t}),\n\t);\n\treturn [...new Set(intersections.map((entry) => path.resolve(entry)))];\n}\n\nexport function workerExecutionAuthorityFromPlan(plan: WorkerExecutionPlan): WorkerExecutionAuthorityContract {\n\treturn {\n\t\tcapabilities: [...plan.requiredCapabilities],\n\t\ttoolNames: plan.toolManifests.map((manifest) => manifest.toolName),\n\t\treadPaths: [...plan.readPaths],\n\t\twritePaths: [...plan.writePaths],\n\t\tdeniedPaths: [...plan.deniedPaths],\n\t\tbudget: { ...plan.budget },\n\t};\n}\n\n/** Apply live revocations to admitted authority without allowing later settings to widen it. */\nexport function narrowWorkerExecutionPlan(\n\tadmitted: WorkerExecutionAuthorityContract,\n\tcurrent: WorkerExecutionPlan,\n): WorkerExecutionPlan {\n\tconst admittedTools = new Set(mapToolNamesForPlatform(admitted.toolNames));\n\tconst admittedCapabilities = new Set(admitted.capabilities);\n\tconst toolManifests = current.toolManifests.filter(\n\t\t(manifest) =>\n\t\t\tadmittedTools.has(manifest.toolName) &&\n\t\t\tmanifest.capabilities.every((capability) => admittedCapabilities.has(capability)),\n\t);\n\tconst requiredCapabilities = [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))];\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = requiredCapabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities,\n\t\treadPaths: readEnabled ? intersectPathScopes(admitted.readPaths, current.readPaths) : [],\n\t\twritePaths: writeEnabled ? intersectPathScopes(admitted.writePaths, current.writePaths) : [],\n\t\tdeniedPaths: [...new Set([...admitted.deniedPaths, ...current.deniedPaths].map((entry) => path.resolve(entry)))],\n\t\treadMemory: grantedTools.has(\"memory\"),\n\t\twriteEnabled,\n\t\tprocessEnabled: grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME),\n\t\tbudget: intersectRiskBudgets(admitted.budget, current.budget),\n\t};\n}\n\nexport function buildWorkerExecutionPlan(args: {\n\tprofile: OrchestrationProfile;\n\tsettings: ResolvedWorkerDelegationSettings;\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tforegroundMaxCostUsd?: number;\n\tmemoryEnabled: boolean;\n\trequestedReadPaths?: readonly string[];\n\trequestedWritePaths?: readonly string[];\n}): WorkerExecutionPlan {\n\tconst profileToolNames = new Set(mapToolNamesForPlatform(args.profile.toolNames));\n\tconst grantsRead =\n\t\targs.profile.capabilityCeiling.includes(\"filesystem.read\") ||\n\t\targs.profile.capabilityCeiling.includes(\"worktree.read\");\n\tconst writeEligible =\n\t\targs.settings.writeEnabled &&\n\t\targs.settings.writePaths.length > 0 &&\n\t\t(args.profile.capabilityCeiling.includes(\"filesystem.write\") ||\n\t\t\targs.profile.capabilityCeiling.includes(\"worktree.mutate\"));\n\tconst memoryEligible = args.memoryEnabled;\n\tconst processEligible =\n\t\targs.profile.capabilityCeiling.includes(\"process.exec\") ||\n\t\targs.profile.capabilityCeiling.includes(\"tests.execute\");\n\tconst enabledProcessToolNames = processEligible\n\t\t? [\n\t\t\t\t...(args.profile.executionPolicy && profileToolNames.has(\"run_process\") ? ([\"run_process\"] as const) : []),\n\t\t\t\t...(profileToolNames.has(STABLE_SHELL_TOOL_NAME) ? [STABLE_SHELL_TOOL_NAME] : []),\n\t\t\t]\n\t\t: [];\n\tconst enabledToolNames = [\n\t\t...(grantsRead ? READ_TOOL_NAMES : []),\n\t\t...(writeEligible ? WRITE_TOOL_NAMES : []),\n\t\t...enabledProcessToolNames,\n\t\t...(profileToolNames.has(\"delegate\") && args.profile.capabilityCeiling.includes(\"workflow.delegate\")\n\t\t\t? ([\"delegate\"] as const)\n\t\t\t: []),\n\t];\n\tconst toolManifests = buildLaneToolManifests(args.profile, enabledToolNames);\n\tif (memoryEligible) {\n\t\ttoolManifests.push({\n\t\t\ttoolName: \"memory\",\n\t\t\tmoduleSpecifier: \"../tools/memory.ts\",\n\t\t\tcapabilities: delegatedToolCapabilities(\"memory\"),\n\t\t\troles: [args.profile.role],\n\t\t\tenforcements: [\"memory-broker\"],\n\t\t});\n\t}\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = toolManifests.some((manifest) =>\n\t\tmanifest.capabilities.some((capability) => capability === \"filesystem.read\" || capability === \"worktree.read\"),\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\tconst readMemory = grantedTools.has(\"memory\");\n\tconst processEnabled = grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME);\n\tconst budget = intersectRiskBudgets(\n\t\targs.profile.budget,\n\t\t...(args.settings.maxUsd > 0 ? [{ maxCostUsd: args.settings.maxUsd }] : []),\n\t\t...(args.foregroundMaxCostUsd !== undefined ? [{ maxCostUsd: args.foregroundMaxCostUsd }] : []),\n\t\t...(args.settings.maxWallClockMs > 0 ? [{ maxWallClockMs: args.settings.maxWallClockMs }] : []),\n\t);\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities: [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))],\n\t\treadPaths: readEnabled\n\t\t\t? (args.requestedReadPaths ?? [args.cwd]).map((entry) =>\n\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t)\n\t\t\t: [],\n\t\twritePaths: writeEnabled\n\t\t\t? intersectPathScopes(\n\t\t\t\t\targs.settings.writePaths.map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t\t(args.requestedWritePaths ?? args.settings.writePaths).map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [],\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\treadMemory,\n\t\twriteEnabled,\n\t\tprocessEnabled,\n\t\tbudget,\n\t};\n}\n\nexport function compileWorkerExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tprofile: OrchestrationProfile;\n\tplan: WorkerExecutionPlan;\n\tresources: readonly ResourcePointer[];\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst authorityCapabilities =\n\t\targs.plan.readMemory && !args.profile.capabilityCeiling.includes(\"memory.query\")\n\t\t\t? [...args.profile.capabilityCeiling, \"memory.query\" as const]\n\t\t\t: args.profile.capabilityCeiling;\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\tobjectiveId: args.target.objectiveId,\n\t\ttaskId: args.target.taskId,\n\t\tattemptId: args.target.attemptId,\n\t\tsubjectId: `in-process:${args.target.attemptId}`,\n\t\trole: args.profile.role,\n\t\trequiredCapabilities: args.plan.requiredCapabilities,\n\t\trequestedCapabilities: args.plan.requiredCapabilities,\n\t\tauthorityCapabilities,\n\t\trequestedTools: args.plan.toolManifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: args.plan.toolManifests,\n\t\tresources: args.resources,\n\t\treadPaths: args.plan.readPaths,\n\t\twritePaths: args.plan.writePaths,\n\t\tdeniedPaths: args.plan.deniedPaths,\n\t\trequestedBudget: args.plan.budget,\n\t\tauthorityBudget: args.plan.budget,\n\t\tpolicyVersion: \"worker-profile-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n\n/** Compile the host's durable authority record before an externally managed process is launched. */\nexport function compileManagedProcessExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tlaneId: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\tallowedTools: readonly string[];\n\twritePaths: readonly string[];\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tbudget: RiskBudget;\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst manifests: ToolCapabilityManifest[] = [];\n\tconst unknownTools: string[] = [];\n\tfor (const toolName of [...new Set(args.allowedTools)]) {\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capabilities = delegatedToolCapabilities(toolName);\n\t\tif (!policy || capabilities.length === 0) {\n\t\t\tunknownTools.push(toolName);\n\t\t\tcontinue;\n\t\t}\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `managed-process:${toolName}`,\n\t\t\tcapabilities,\n\t\t\troles: [args.role],\n\t\t\tenforcements: policy.enforcements,\n\t\t});\n\t}\n\tif (unknownTools.length > 0) return { ok: false, reasonCodes: unknownTools.map((name) => `unknown_tool:${name}`) };\n\tconst capabilities = [...new Set(manifests.flatMap((manifest) => manifest.capabilities))];\n\tconst readEnabled = capabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\t...args.target,\n\t\tsubjectId: `managed:${args.laneId}:${args.authorizationId}`,\n\t\trole: args.role,\n\t\trequiredCapabilities: capabilities,\n\t\trequestedCapabilities: capabilities,\n\t\tauthorityCapabilities: capabilities,\n\t\trequestedTools: manifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: manifests,\n\t\treadPaths: readEnabled ? [path.resolve(args.cwd)] : [],\n\t\twritePaths: args.writePaths.map((entry) =>\n\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t),\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\trequestedBudget: args.budget,\n\t\tauthorityBudget: args.budget,\n\t\tpolicyVersion: \"managed-process-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n"]}
@@ -36,6 +36,7 @@ export interface ForegroundRecoveryControllerDeps {
36
36
  onSuccessfulAssistant(): void;
37
37
  prepareRun(): Promise<void>;
38
38
  afterRun(): Promise<void>;
39
+ isCompacting?: () => boolean;
39
40
  }
40
41
  /** Owns the complete logical foreground run plus retry/failover/compaction recovery ordering. */
41
42
  export declare class ForegroundRecoveryController {
@@ -59,6 +60,7 @@ export declare class ForegroundRecoveryController {
59
60
  ownsSubmission(lease: ForegroundSubmissionLease | undefined): boolean;
60
61
  releaseSubmission(lease: ForegroundSubmissionLease): void;
61
62
  runAgentPrompt(messages: AgentMessage | AgentMessage[], submissionLease?: ForegroundSubmissionLease): Promise<void>;
63
+ wakeIdleWaiters(): void;
62
64
  waitForIdle(): Promise<void>;
63
65
  shutdown(): void;
64
66
  private resolveIdleWaiters;
@@ -1 +1 @@
1
- {"version":3,"file":"foreground-recovery-controller.d.ts","sourceRoot":"","sources":["../../src/core/foreground-recovery-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAkB,MAAM,iCAAiC,CAAC;AAO7E,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAG1D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACjE,OA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KAAK,EAAE,yBAAyB,GAAG,IAAI,CAQxD;IAEK,cAAc,CACnB,QAAQ,EAAE,YAAY,GAAG,YAAY,EAAE,EACvC,eAAe,CAAC,EAAE,yBAAyB,GACzC,OAAO,CAAC,IAAI,CAAC,CAsCf;IAED,eAAe,IAAI,IAAI,CAEtB;IAEK,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAUjC;IAED,QAAQ,IAAI,IAAI,CAIf;IAED,OAAO,CAAC,kBAAkB;IAM1B,UAAU,IAAI,IAAI,CAEjB;IAED,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAErC;IAED,iBAAiB,IAAI,yBAAyB,CAE7C;IAED,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAShD;IAED,sBAAsB,CAAC,KAAK,EAAE,OAAO,CAAC,UAAU,EAAE;QAAE,IAAI,EAAE,WAAW,CAAA;KAAE,CAAC,GAAG,OAAO,CAQjF;IAEK,kBAAkB,IAAI,OAAO,CAAC,OAAO,CAAC,CAoB3C;IAED,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,sBAAsB;CAQ9B"}
@@ -27,7 +27,7 @@ export class ForegroundRecoveryController {
27
27
  modelRegistry: deps.modelRegistry,
28
28
  exhausted: new ExhaustedProviderRegistry(),
29
29
  subscriptionHop: deps.settingsManager.getFailoverSettings().subscriptionHop,
30
- emit: deps.emit,
30
+ emit: (event) => deps.emit(event),
31
31
  recordFailure: (record) => deps.failureCorpus.record(record),
32
32
  });
33
33
  }
@@ -41,7 +41,11 @@ export class ForegroundRecoveryController {
41
41
  return this.activeRuns > 0;
42
42
  }
43
43
  get isBusy() {
44
- return (this.submissionLease !== undefined || this.isRunActive || this.deps.agent.state.isStreaming || this.isRetrying);
44
+ return (this.submissionLease !== undefined ||
45
+ this.isRunActive ||
46
+ this.deps.agent.state.isStreaming ||
47
+ this.isRetrying ||
48
+ this.deps.isCompacting?.() === true);
45
49
  }
46
50
  /** Atomically reserve the full foreground lifecycle, including asynchronous prompt preparation. */
47
51
  tryAcquireSubmission() {
@@ -69,11 +73,10 @@ export class ForegroundRecoveryController {
69
73
  if (!this.ownsSubmission(lease)) {
70
74
  throw new Error("Cannot release foreground submission authority owned by another caller");
71
75
  }
72
- if (this.activeRuns > 0) {
73
- throw new Error("Cannot release foreground submission authority while its agent run is active");
74
- }
75
76
  this.submissionLease = undefined;
76
- this.resolveIdleWaiters();
77
+ if (this.activeRuns === 0) {
78
+ this.resolveIdleWaiters();
79
+ }
77
80
  }
78
81
  async runAgentPrompt(messages, submissionLease) {
79
82
  let lease = submissionLease;
@@ -90,7 +93,7 @@ export class ForegroundRecoveryController {
90
93
  releaseLease = true;
91
94
  }
92
95
  if (this.activeRuns > 0) {
93
- if (releaseLease)
96
+ if (releaseLease && lease)
94
97
  this.releaseSubmission(lease);
95
98
  throw new AgentBusyError("Agent is already processing.");
96
99
  }
@@ -111,16 +114,22 @@ export class ForegroundRecoveryController {
111
114
  }
112
115
  finally {
113
116
  this.activeRuns--;
114
- if (releaseLease)
117
+ if (releaseLease && lease && this.ownsSubmission(lease))
115
118
  this.releaseSubmission(lease);
119
+ if (this.activeRuns === 0 && this.submissionLease === undefined) {
120
+ this.resolveIdleWaiters();
121
+ }
116
122
  }
117
123
  }
118
124
  }
125
+ wakeIdleWaiters() {
126
+ this.resolveIdleWaiters();
127
+ }
119
128
  async waitForIdle() {
120
129
  while (true) {
121
130
  if (this.shutdownReason)
122
131
  return;
123
- if (this.submissionLease !== undefined || this.activeRuns > 0) {
132
+ if (this.submissionLease !== undefined || this.activeRuns > 0 || this.deps.isCompacting?.() === true) {
124
133
  await new Promise((resolve) => this.idleWaiters.add(resolve));
125
134
  continue;
126
135
  }
@@ -1 +1 @@
1
- {"version":3,"file":"foreground-recovery-controller.js","sourceRoot":"","sources":["../../src/core/foreground-recovery-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EA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C,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;QAClF,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC;YAAE,OAAO,IAAI,CAAC;QAC1D,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,EAAE,CAAC;IAC5C,CAAC;IAEO,WAAW,CAAC,OAAgB,EAAE,UAAmB;QACxD,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC;YAAE,OAAO;QACrC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;QAC7F,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAEO,sBAAsB,CAAC,OAAyB;QACvD,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;YAAE,OAAO,SAAS,CAAC;QAC9E,OAAO,eAAe,CAAC;YACtB,OAAO,EAAE,OAAO,CAAC,YAAY;YAC7B,eAAe,EAAE,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACzE,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC1B,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { type Agent, AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport {\n\ttype ClassifiedError,\n\tclassifyFailure,\n\tDEFAULT_RETRY_POLICY,\n\tRetryController,\n} from \"@caupulican/pi-agent-core/reliability\";\nimport type { AgentEvent, AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport { isContextOverflow } from \"@caupulican/pi-ai/overflow\";\nimport { BillingFailoverController, ExhaustedProviderRegistry } from \"./billing-failover-controller.ts\";\nimport type { FailureCorpusRecorder } from \"./failure-corpus.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\ntype ForegroundRecoveryEvent =\n\t| { type: \"warning\"; message: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string };\n\nconst foregroundSubmissionLeaseMarker: unique symbol = Symbol(\"foregroundSubmissionLease\");\n\n/** Identity-bound authority to prepare and execute one logical foreground submission. */\nexport interface ForegroundSubmissionLease {\n\treadonly [foregroundSubmissionLeaseMarker]: true;\n}\n\nexport interface ForegroundRecoveryControllerDeps {\n\tagent: Agent;\n\tsettingsManager: SettingsManager;\n\tmodelRegistry: ModelRegistry;\n\tfailureCorpus: FailureCorpusRecorder;\n\tgetContextWindow(): number;\n\temit(event: ForegroundRecoveryEvent): void;\n\tcheckCompaction(message: AssistantMessage): Promise<boolean>;\n\tonSuccessfulAssistant(): void;\n\tprepareRun(): Promise<void>;\n\tafterRun(): Promise<void>;\n}\n\n/** Owns the complete logical foreground run plus retry/failover/compaction recovery ordering. */\nexport class ForegroundRecoveryController {\n\tprivate readonly retry: RetryController;\n\tprivate readonly billingFailover: BillingFailoverController;\n\tprivate lastAssistantMessage: AssistantMessage | undefined;\n\tprivate activeRuns = 0;\n\tprivate submissionLease: ForegroundSubmissionLease | undefined;\n\tprivate shutdownReason: Error | undefined;\n\tprivate readonly idleWaiters = new Set<() => void>();\n\tprivate readonly deps: ForegroundRecoveryControllerDeps;\n\n\tconstructor(deps: ForegroundRecoveryControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.retry = new RetryController(\n\t\t\tdeps.agent,\n\t\t\t() => {\n\t\t\t\tconst retry = deps.settingsManager.getRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\tenabled: retry.enabled,\n\t\t\t\t\tmaxAttempts: retry.maxRetries,\n\t\t\t\t\tbaseDelayMs: retry.baseDelayMs,\n\t\t\t\t\tmaxDelayMs: DEFAULT_RETRY_POLICY.maxDelayMs,\n\t\t\t\t\tjitterRatio: 0,\n\t\t\t\t};\n\t\t\t},\n\t\t\t{\n\t\t\t\tonRetryStart: (info) => deps.emit({ type: \"auto_retry_start\", ...info }),\n\t\t\t\tonRetryEnd: (info) => deps.emit({ type: \"auto_retry_end\", ...info }),\n\t\t\t},\n\t\t\tdeps.getContextWindow,\n\t\t);\n\t\tthis.billingFailover = new BillingFailoverController({\n\t\t\tagent: deps.agent,\n\t\t\tmodelRegistry: deps.modelRegistry,\n\t\t\texhausted: new ExhaustedProviderRegistry(),\n\t\t\tsubscriptionHop: deps.settingsManager.getFailoverSettings().subscriptionHop,\n\t\t\temit: deps.emit,\n\t\t\trecordFailure: (record) => deps.failureCorpus.record(record),\n\t\t});\n\t}\n\n\tget attempt(): number {\n\t\treturn this.retry.attempt;\n\t}\n\n\tget isRetrying(): boolean {\n\t\treturn this.retry.isRetrying;\n\t}\n\n\tget isRunActive(): boolean {\n\t\treturn this.activeRuns > 0;\n\t}\n\n\tget isBusy(): boolean {\n\t\treturn (\n\t\t\tthis.submissionLease !== undefined || this.isRunActive || this.deps.agent.state.isStreaming || this.isRetrying\n\t\t);\n\t}\n\n\t/** Atomically reserve the full foreground lifecycle, including asynchronous prompt preparation. */\n\ttryAcquireSubmission(): ForegroundSubmissionLease | undefined {\n\t\tif (this.shutdownReason || this.isBusy) return undefined;\n\t\tconst lease: ForegroundSubmissionLease = { [foregroundSubmissionLeaseMarker]: true };\n\t\tthis.submissionLease = lease;\n\t\treturn lease;\n\t}\n\n\t/** Wait until foreground ownership can be acquired without a check-then-act gap. */\n\tasync acquireSubmission(): Promise<ForegroundSubmissionLease> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) throw this.shutdownReason;\n\t\t\tconst lease = this.tryAcquireSubmission();\n\t\t\tif (lease) return lease;\n\t\t\tawait this.waitForIdle();\n\t\t}\n\t}\n\n\townsSubmission(lease: ForegroundSubmissionLease | undefined): boolean {\n\t\treturn lease !== undefined && lease === this.submissionLease;\n\t}\n\n\treleaseSubmission(lease: ForegroundSubmissionLease): void {\n\t\tif (!this.ownsSubmission(lease)) {\n\t\t\tthrow new Error(\"Cannot release foreground submission authority owned by another caller\");\n\t\t}\n\t\tif (this.activeRuns > 0) {\n\t\t\tthrow new Error(\"Cannot release foreground submission authority while its agent run is active\");\n\t\t}\n\t\tthis.submissionLease = undefined;\n\t\tthis.resolveIdleWaiters();\n\t}\n\n\tasync runAgentPrompt(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\tsubmissionLease?: ForegroundSubmissionLease,\n\t): Promise<void> {\n\t\tlet lease = submissionLease;\n\t\tlet releaseLease = false;\n\t\tif (lease) {\n\t\t\tif (!this.ownsSubmission(lease)) {\n\t\t\t\tthrow new AgentBusyError(\"Foreground submission authority is no longer active.\");\n\t\t\t}\n\t\t} else {\n\t\t\tlease = this.tryAcquireSubmission();\n\t\t\tif (!lease) throw new AgentBusyError(\"Agent is already processing.\");\n\t\t\treleaseLease = true;\n\t\t}\n\t\tif (this.activeRuns > 0) {\n\t\t\tif (releaseLease) this.releaseSubmission(lease);\n\t\t\tthrow new AgentBusyError(\"Agent is already processing.\");\n\t\t}\n\n\t\tthis.activeRuns++;\n\t\ttry {\n\t\t\tconst maxGoalLoopRounds = this.deps.settingsManager.getAutonomySettings().maxStallTurns;\n\t\t\tawait this.deps.prepareRun();\n\t\t\tlet goalLoopRounds = 1;\n\t\t\tawait this.deps.agent.prompt(messages);\n\t\t\twhile ((maxGoalLoopRounds === 0 || goalLoopRounds < maxGoalLoopRounds) && (await this.handlePostAgentRun())) {\n\t\t\t\tawait this.deps.agent.continue();\n\t\t\t\tgoalLoopRounds++;\n\t\t\t}\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait this.deps.afterRun();\n\t\t\t} finally {\n\t\t\t\tthis.activeRuns--;\n\t\t\t\tif (releaseLease) this.releaseSubmission(lease);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) return;\n\t\t\tif (this.submissionLease !== undefined || this.activeRuns > 0) {\n\t\t\t\tawait new Promise<void>((resolve) => this.idleWaiters.add(resolve));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait this.deps.agent.waitForIdle();\n\t\t\tif (!this.isBusy) return;\n\t\t}\n\t}\n\n\tshutdown(): void {\n\t\tthis.shutdownReason ??= new Error(\"Session disposed before foreground submission authority was acquired\");\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tprivate resolveIdleWaiters(): void {\n\t\tif (this.submissionLease !== undefined || this.activeRuns > 0) return;\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tabortRetry(): void {\n\t\tthis.retry.abort();\n\t}\n\n\tisModelExhausted(ref: string): boolean {\n\t\treturn this.billingFailover.isExhausted(ref);\n\t}\n\n\tgetFailoverStatus(): ModelRouterFailoverStatus {\n\t\treturn this.billingFailover.getStatus();\n\t}\n\n\tobserveAssistant(message: AssistantMessage): void {\n\t\tthis.lastAssistantMessage = message;\n\t\tif (message.stopReason === \"error\") return;\n\t\tif (message.stopReason === \"aborted\") {\n\t\t\tthis.finishRetry(false, message.errorMessage ?? \"Retry aborted\");\n\t\t\treturn;\n\t\t}\n\t\tthis.deps.onSuccessfulAssistant();\n\t\tthis.finishRetry(true);\n\t}\n\n\twillRetryAfterAgentEnd(event: Extract<AgentEvent, { type: \"agent_end\" }>): boolean {\n\t\tconst settings = this.deps.settingsManager.getRetrySettings();\n\t\tif (!settings.enabled || this.retry.attempt >= settings.maxRetries) return false;\n\t\tfor (let index = event.messages.length - 1; index >= 0; index--) {\n\t\t\tconst message = event.messages[index];\n\t\t\tif (message.role === \"assistant\") return this.classifyAssistantError(message)?.retryable ?? false;\n\t\t}\n\t\treturn false;\n\t}\n\n\tasync handlePostAgentRun(): Promise<boolean> {\n\t\tconst message = this.lastAssistantMessage;\n\t\tthis.lastAssistantMessage = undefined;\n\t\tif (!message) return false;\n\n\t\tconst classified = this.classifyAssistantError(message);\n\t\tif (classified) {\n\t\t\tthis.deps.failureCorpus.record({\n\t\t\t\tprovider: message.provider,\n\t\t\t\tmodelId: message.model,\n\t\t\t\tmessage: message.errorMessage ?? \"\",\n\t\t\t\tclassified,\n\t\t\t});\n\t\t}\n\t\tif (classified?.retryable && (await this.retry.prepareRetry(message))) return true;\n\t\tif (await this.billingFailover.handleAssistantError(message, classified)) return false;\n\n\t\tif (message.stopReason === \"error\") this.finishRetry(false, message.errorMessage);\n\t\tif (await this.deps.checkCompaction(message)) return true;\n\t\treturn this.deps.agent.hasQueuedMessages();\n\t}\n\n\tprivate finishRetry(success: boolean, finalError?: string): void {\n\t\tif (this.retry.attempt === 0) return;\n\t\tthis.deps.emit({ type: \"auto_retry_end\", success, attempt: this.retry.attempt, finalError });\n\t\tthis.retry.reset();\n\t}\n\n\tprivate classifyAssistantError(message: AssistantMessage): ClassifiedError | undefined {\n\t\tif (message.stopReason !== \"error\" || !message.errorMessage) return undefined;\n\t\treturn classifyFailure({\n\t\t\tmessage: message.errorMessage,\n\t\t\tcontextOverflow: isContextOverflow(message, this.deps.getContextWindow()),\n\t\t\tprovider: message.provider,\n\t\t});\n\t}\n}\n"]}
1
+ {"version":3,"file":"foreground-recovery-controller.js","sourceRoot":"","sources":["../../src/core/foreground-recovery-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAEN,eAAe,EACf,oBAAoB,EACpB,eAAe,GACf,MAAM,uCAAuC,CAAC;AAG/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,MAA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ETRY_POLICY,\n\tRetryController,\n} from \"@caupulican/pi-agent-core/reliability\";\nimport type { AgentEvent, AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport { isContextOverflow } from \"@caupulican/pi-ai/overflow\";\nimport { BillingFailoverController, ExhaustedProviderRegistry } from \"./billing-failover-controller.ts\";\nimport type { FailureCorpusRecorder } from \"./failure-corpus.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\ntype ForegroundRecoveryEvent =\n\t| { type: \"warning\"; message: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string };\n\nconst foregroundSubmissionLeaseMarker: unique symbol = Symbol(\"foregroundSubmissionLease\");\n\n/** Identity-bound authority to prepare and execute one logical foreground submission. */\nexport interface ForegroundSubmissionLease {\n\treadonly [foregroundSubmissionLeaseMarker]: true;\n}\n\nexport interface ForegroundRecoveryControllerDeps {\n\tagent: Agent;\n\tsettingsManager: SettingsManager;\n\tmodelRegistry: ModelRegistry;\n\tfailureCorpus: FailureCorpusRecorder;\n\tgetContextWindow(): number;\n\temit(event: ForegroundRecoveryEvent): void;\n\tcheckCompaction(message: AssistantMessage): Promise<boolean>;\n\tonSuccessfulAssistant(): void;\n\tprepareRun(): Promise<void>;\n\tafterRun(): Promise<void>;\n\tisCompacting?: () => boolean;\n}\n\n/** Owns the complete logical foreground run plus retry/failover/compaction recovery ordering. */\nexport class ForegroundRecoveryController {\n\tprivate readonly retry: RetryController;\n\tprivate readonly billingFailover: BillingFailoverController;\n\tprivate lastAssistantMessage: AssistantMessage | undefined;\n\tprivate activeRuns = 0;\n\tprivate submissionLease: ForegroundSubmissionLease | undefined;\n\tprivate shutdownReason: Error | undefined;\n\tprivate readonly idleWaiters = new Set<() => void>();\n\tprivate readonly deps: ForegroundRecoveryControllerDeps;\n\n\tconstructor(deps: ForegroundRecoveryControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.retry = new RetryController(\n\t\t\tdeps.agent,\n\t\t\t() => {\n\t\t\t\tconst retry = deps.settingsManager.getRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\tenabled: retry.enabled,\n\t\t\t\t\tmaxAttempts: retry.maxRetries,\n\t\t\t\t\tbaseDelayMs: retry.baseDelayMs,\n\t\t\t\t\tmaxDelayMs: DEFAULT_RETRY_POLICY.maxDelayMs,\n\t\t\t\t\tjitterRatio: 0,\n\t\t\t\t};\n\t\t\t},\n\t\t\t{\n\t\t\t\tonRetryStart: (info) => deps.emit({ type: \"auto_retry_start\", ...info }),\n\t\t\t\tonRetryEnd: (info) => deps.emit({ type: \"auto_retry_end\", ...info }),\n\t\t\t},\n\t\t\tdeps.getContextWindow,\n\t\t);\n\t\tthis.billingFailover = new BillingFailoverController({\n\t\t\tagent: deps.agent,\n\t\t\tmodelRegistry: deps.modelRegistry,\n\t\t\texhausted: new ExhaustedProviderRegistry(),\n\t\t\tsubscriptionHop: deps.settingsManager.getFailoverSettings().subscriptionHop,\n\t\t\temit: (event) => deps.emit(event),\n\t\t\trecordFailure: (record) => deps.failureCorpus.record(record),\n\t\t});\n\t}\n\n\tget attempt(): number {\n\t\treturn this.retry.attempt;\n\t}\n\n\tget isRetrying(): boolean {\n\t\treturn this.retry.isRetrying;\n\t}\n\n\tget isRunActive(): boolean {\n\t\treturn this.activeRuns > 0;\n\t}\n\n\tget isBusy(): boolean {\n\t\treturn (\n\t\t\tthis.submissionLease !== undefined ||\n\t\t\tthis.isRunActive ||\n\t\t\tthis.deps.agent.state.isStreaming ||\n\t\t\tthis.isRetrying ||\n\t\t\tthis.deps.isCompacting?.() === true\n\t\t);\n\t}\n\n\t/** Atomically reserve the full foreground lifecycle, including asynchronous prompt preparation. */\n\ttryAcquireSubmission(): ForegroundSubmissionLease | undefined {\n\t\tif (this.shutdownReason || this.isBusy) return undefined;\n\t\tconst lease: ForegroundSubmissionLease = { [foregroundSubmissionLeaseMarker]: true };\n\t\tthis.submissionLease = lease;\n\t\treturn lease;\n\t}\n\n\t/** Wait until foreground ownership can be acquired without a check-then-act gap. */\n\tasync acquireSubmission(): Promise<ForegroundSubmissionLease> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) throw this.shutdownReason;\n\t\t\tconst lease = this.tryAcquireSubmission();\n\t\t\tif (lease) return lease;\n\t\t\tawait this.waitForIdle();\n\t\t}\n\t}\n\n\townsSubmission(lease: ForegroundSubmissionLease | undefined): boolean {\n\t\treturn lease !== undefined && lease === this.submissionLease;\n\t}\n\n\treleaseSubmission(lease: ForegroundSubmissionLease): void {\n\t\tif (!this.ownsSubmission(lease)) {\n\t\t\tthrow new Error(\"Cannot release foreground submission authority owned by another caller\");\n\t\t}\n\t\tthis.submissionLease = undefined;\n\t\tif (this.activeRuns === 0) {\n\t\t\tthis.resolveIdleWaiters();\n\t\t}\n\t}\n\n\tasync runAgentPrompt(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\tsubmissionLease?: ForegroundSubmissionLease,\n\t): Promise<void> {\n\t\tlet lease = submissionLease;\n\t\tlet releaseLease = false;\n\t\tif (lease) {\n\t\t\tif (!this.ownsSubmission(lease)) {\n\t\t\t\tthrow new AgentBusyError(\"Foreground submission authority is no longer active.\");\n\t\t\t}\n\t\t} else {\n\t\t\tlease = this.tryAcquireSubmission();\n\t\t\tif (!lease) throw new AgentBusyError(\"Agent is already processing.\");\n\t\t\treleaseLease = true;\n\t\t}\n\t\tif (this.activeRuns > 0) {\n\t\t\tif (releaseLease && lease) this.releaseSubmission(lease);\n\t\t\tthrow new AgentBusyError(\"Agent is already processing.\");\n\t\t}\n\n\t\tthis.activeRuns++;\n\t\ttry {\n\t\t\tconst maxGoalLoopRounds = this.deps.settingsManager.getAutonomySettings().maxStallTurns;\n\t\t\tawait this.deps.prepareRun();\n\t\t\tlet goalLoopRounds = 1;\n\t\t\tawait this.deps.agent.prompt(messages);\n\t\t\twhile ((maxGoalLoopRounds === 0 || goalLoopRounds < maxGoalLoopRounds) && (await this.handlePostAgentRun())) {\n\t\t\t\tawait this.deps.agent.continue();\n\t\t\t\tgoalLoopRounds++;\n\t\t\t}\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait this.deps.afterRun();\n\t\t\t} finally {\n\t\t\t\tthis.activeRuns--;\n\t\t\t\tif (releaseLease && lease && this.ownsSubmission(lease)) this.releaseSubmission(lease);\n\t\t\t\tif (this.activeRuns === 0 && this.submissionLease === undefined) {\n\t\t\t\t\tthis.resolveIdleWaiters();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\twakeIdleWaiters(): void {\n\t\tthis.resolveIdleWaiters();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) return;\n\t\t\tif (this.submissionLease !== undefined || this.activeRuns > 0 || this.deps.isCompacting?.() === true) {\n\t\t\t\tawait new Promise<void>((resolve) => this.idleWaiters.add(resolve));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait this.deps.agent.waitForIdle();\n\t\t\tif (!this.isBusy) return;\n\t\t}\n\t}\n\n\tshutdown(): void {\n\t\tthis.shutdownReason ??= new Error(\"Session disposed before foreground submission authority was acquired\");\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tprivate resolveIdleWaiters(): void {\n\t\tif (this.submissionLease !== undefined || this.activeRuns > 0) return;\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tabortRetry(): void {\n\t\tthis.retry.abort();\n\t}\n\n\tisModelExhausted(ref: string): boolean {\n\t\treturn this.billingFailover.isExhausted(ref);\n\t}\n\n\tgetFailoverStatus(): ModelRouterFailoverStatus {\n\t\treturn this.billingFailover.getStatus();\n\t}\n\n\tobserveAssistant(message: AssistantMessage): void {\n\t\tthis.lastAssistantMessage = message;\n\t\tif (message.stopReason === \"error\") return;\n\t\tif (message.stopReason === \"aborted\") {\n\t\t\tthis.finishRetry(false, message.errorMessage ?? \"Retry aborted\");\n\t\t\treturn;\n\t\t}\n\t\tthis.deps.onSuccessfulAssistant();\n\t\tthis.finishRetry(true);\n\t}\n\n\twillRetryAfterAgentEnd(event: Extract<AgentEvent, { type: \"agent_end\" }>): boolean {\n\t\tconst settings = this.deps.settingsManager.getRetrySettings();\n\t\tif (!settings.enabled || this.retry.attempt >= settings.maxRetries) return false;\n\t\tfor (let index = event.messages.length - 1; index >= 0; index--) {\n\t\t\tconst message = event.messages[index];\n\t\t\tif (message.role === \"assistant\") return this.classifyAssistantError(message)?.retryable ?? false;\n\t\t}\n\t\treturn false;\n\t}\n\n\tasync handlePostAgentRun(): Promise<boolean> {\n\t\tconst message = this.lastAssistantMessage;\n\t\tthis.lastAssistantMessage = undefined;\n\t\tif (!message) return false;\n\n\t\tconst classified = this.classifyAssistantError(message);\n\t\tif (classified) {\n\t\t\tthis.deps.failureCorpus.record({\n\t\t\t\tprovider: message.provider,\n\t\t\t\tmodelId: message.model,\n\t\t\t\tmessage: message.errorMessage ?? \"\",\n\t\t\t\tclassified,\n\t\t\t});\n\t\t}\n\t\tif (classified?.retryable && (await this.retry.prepareRetry(message))) return true;\n\t\tif (await this.billingFailover.handleAssistantError(message, classified)) return false;\n\n\t\tif (message.stopReason === \"error\") this.finishRetry(false, message.errorMessage);\n\t\tif (await this.deps.checkCompaction(message)) return true;\n\t\treturn this.deps.agent.hasQueuedMessages();\n\t}\n\n\tprivate finishRetry(success: boolean, finalError?: string): void {\n\t\tif (this.retry.attempt === 0) return;\n\t\tthis.deps.emit({ type: \"auto_retry_end\", success, attempt: this.retry.attempt, finalError });\n\t\tthis.retry.reset();\n\t}\n\n\tprivate classifyAssistantError(message: AssistantMessage): ClassifiedError | undefined {\n\t\tif (message.stopReason !== \"error\" || !message.errorMessage) return undefined;\n\t\treturn classifyFailure({\n\t\t\tmessage: message.errorMessage,\n\t\t\tcontextOverflow: isContextOverflow(message, this.deps.getContextWindow()),\n\t\t\tprovider: message.provider,\n\t\t});\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"goal-loop-controller.d.ts","sourceRoot":"","sources":["../../src/core/goal-loop-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAE1B,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,8BAA8B,CAAC;AAMtC,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AA4BzG,MAAM,WAAW,sBAAsB;IACtC,mGAAmG;IACnG,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAAC;IACnF,0EAA0E;IAC1E,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D;;;;OAIG;IACH,0BAA0B,CAAC,IAAI,EAAE;QAChC,KAAK,EAAE,MAAM,CAAC;QACd,WAAW,EAAE,MAAM,CAAC;QACpB,MAAM,EAAE,MAAM,CAAC;QACf,gBAAgB,EAAE,MAAM,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;KACnB,GAAG,IAAI,CAAC;IACT,uFAAuF;IACvF,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IACpD,gFAAgF;IAChF,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C;AAED,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAE9C,YAAY,IAAI,EAAE,sBAAsB,EAEvC;IAEK,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC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OAAO,CAAC,0BAA0B,CAAC,CA0FhG;CACD"}
@@ -107,15 +107,13 @@ export class GoalLoopController {
107
107
  // coordination, not a consumed goal turn and not evidence that the goal is blocked.
108
108
  if (error instanceof AgentBusyError)
109
109
  throw error;
110
- turnsSubmitted++;
111
- this.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });
112
110
  if (error instanceof GoalBudgetExhaustedError) {
113
111
  // The goal already stopped itself durably (markBudgetLimited ran synchronously before
114
- // this signal was thrown) — surface the existing clean stop instead of reclassifying an
115
- // intentional, already-recorded stop as a generic continuation failure and rejecting
116
- // the whole loop promise.
112
+ // this signal was thrown) — surface the existing clean stop instead of charging a turn.
117
113
  return { turnsSubmitted, stopReason: "goal_budget_exhausted", finalSnapshot: snapshot() };
118
114
  }
115
+ turnsSubmitted++;
116
+ this.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });
119
117
  this.deps.recordGoalContinuationFailure(error);
120
118
  throw error;
121
119
  }
@@ -1 +1 @@
1
- {"version":3,"file":"goal-loop-controller.js","sourceRoot":"","sources":["../../src/core/goal-loop-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AASjE,OAAO,EACN,2BAA2B,EAC3B,qCAAqC,GACrC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,OAAO,EAAkB,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAE9E;;;;GAIG;AACH,SAAS,+BAA+B,CAAC,KAA4B;IACpE,IAAI,CAAC,KAAK,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IACrE,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC,IAAI,KAAK,CAAC,WA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,OAAO;YACN,cAAc;YACd,UAAU,EAAE,mBAAmB;YAC/B,aAAa,EAAE,QAAQ,EAAE;SACzB,CAAC;IACH,CAAC;CACD","sourcesContent":["/**\n * Goal auto-continuation loop.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Drives the bounded \"keep the\n * active goal moving\" loop: each pass reads the goal runtime snapshot, and — only while the snapshot\n * says `continue` — submits one continuation prompt back through the session's own prompt path. It\n * owns no state; the goal state lives in the session log and is read fresh every pass. Termination is\n * gated only by real terminal conditions and limits the owner explicitly supplied: an optional\n * per-invocation turn cap, an optional per-invocation wall-clock cap, and an optional durable token\n * budget on the goal. Each submitted pass still reports turn/wall-clock telemetry; provider usage\n * and spend are attributed at the response boundary. The host compares each pass's authoritative\n * progress revision and records unchanged passes as stalls, so a model cannot bypass the stall\n * limit by omitting a voluntary `no_progress` call.\n */\n\nimport { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationLoopStopReason,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"./agent-session-contracts.ts\";\nimport {\n\tbuildGoalContinuationPrompt,\n\tGOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n} from \"./goals/goal-continuation-prompt.ts\";\nimport { GoalBudgetExhaustedError } from \"./goals/goal-execution-errors.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport { type GoalState, isGoalExecutionActive } from \"./goals/goal-state.ts\";\n\n/**\n * Resolve an owner-supplied durable goal budget. Wall-clock and spend counters are deliberately\n * absent here: they are telemetry unless the public goal contract grows matching explicit limits.\n * Execution limits are policy inputs, not hidden runtime defaults.\n */\nfunction getExplicitGoalBudgetExhaustion(state: GoalState | undefined): string | undefined {\n\tif (!state || !isGoalExecutionActive(state.status)) return undefined;\n\tif (state.tokenBudget !== undefined && (state.tokensUsed ?? 0) >= state.tokenBudget) {\n\t\treturn `token budget exhausted (${state.tokensUsed ?? 0}/${state.tokenBudget})`;\n\t}\n\treturn undefined;\n}\n\n/**\n * Maps a non-\"continue\" continuation action onto the loop's own stopReason vocabulary.\n * `\"waiting\"` (a worker is dispatched against an open requirement) gets its OWN benign stopReason so\n * a wait is never misreported as `continuation_not_allowed` (which reads as a terminal refusal) —\n * callers/telemetry can tell \"paused, will resume on its own\" apart from \"stopped, needs a human or a\n * new decision.\" Every other non-continue action (ask-user/finalize/stop) keeps the existing\n * `continuation_not_allowed` stopReason unchanged.\n */\nfunction nonContinueStopReason(snapshot: GoalRuntimeSnapshot): GoalContinuationLoopStopReason {\n\treturn snapshot.continuation.action === \"waiting\" ? \"worker_in_flight\" : \"continuation_not_allowed\";\n}\n\nexport interface GoalLoopControllerDeps {\n\t/** Read the current goal runtime snapshot (continuation decision + goal state) fresh each pass. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Submit a continuation prompt through the session's own prompt path. */\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t/**\n\t * Persist one submitted pass's turn and active-wall-clock contribution. Provider usage is charged\n\t * at each assistant response before another request can be admitted. Called once per\n\t * pass actually SUBMITTED (never for a no-op `continueGoalOnce` call).\n\t */\n\trecordGoalContinuationPass(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/** Persist an exhausted/non-retryable continuation failure as a stopped goal state. */\n\trecordGoalContinuationFailure(error: unknown): void;\n\t/** Persist a reason-specific budget terminal state before returning control. */\n\tmarkGoalBudgetLimited(reason: string): void;\n}\n\nexport class GoalLoopController {\n\tprivate readonly deps: GoalLoopControllerDeps;\n\n\tconstructor(deps: GoalLoopControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync continueGoalOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (snapshot.continuation.action !== \"continue\") {\n\t\t\treturn { submitted: false, snapshot };\n\t\t}\n\n\t\tconst prompt = buildGoalContinuationPrompt();\n\t\tawait this.deps.prompt(prompt.text, {\n\t\t\texpandPromptTemplates: false,\n\t\t\tprocessSlashCommands: false,\n\t\t\tautoContinueGoal: false,\n\t\t\tinternalContextType: GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n\t\t\tgoalExecutionId: snapshot.goalState?.goalId,\n\t\t});\n\n\t\treturn { submitted: true, snapshot, prompt };\n\t}\n\n\tasync continueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (!Number.isSafeInteger(options.maxTurns) || options.maxTurns < 0) {\n\t\t\tthrow new Error(\"Goal continuation maxTurns must be a non-negative safe integer; 0 means unbounded.\");\n\t\t}\n\t\tlet turnsSubmitted = 0;\n\t\tconst hasExplicitTurnLimit = options.maxTurns > 0;\n\t\tconst now = options.now ?? Date.now;\n\t\tconst maxWallClockMs =\n\t\t\ttypeof options.maxWallClockMinutes === \"number\" && options.maxWallClockMinutes > 0\n\t\t\t\t? options.maxWallClockMinutes * 60_000\n\t\t\t\t: undefined;\n\t\tconst startedAt = now();\n\t\tconst hasReachedWallClockBudget = () => maxWallClockMs !== undefined && now() - startedAt >= maxWallClockMs;\n\t\tconst snapshot = () => this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (hasReachedWallClockBudget()) {\n\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t}\n\n\t\twhile (!hasExplicitTurnLimit || turnsSubmitted < options.maxTurns) {\n\t\t\tconst beforeSnapshot = snapshot();\n\t\t\tif (beforeSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(beforeSnapshot), finalSnapshot: beforeSnapshot };\n\t\t\t}\n\n\t\t\t// Owner-supplied durable token budget — read fresh every pass so an invocation stops as\n\t\t\t// soon as its own latest persisted usage crosses the explicit ceiling.\n\t\t\tconst beforeBudgetExhaustion = getExplicitGoalBudgetExhaustion(beforeSnapshot.goalState);\n\t\t\tif (beforeBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(beforeBudgetExhaustion);\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tconst passStartedAt = now();\n\t\t\tconst beforeGoal = beforeSnapshot.goalState;\n\t\t\tif (!beforeGoal) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"continuation_not_allowed\", finalSnapshot: beforeSnapshot };\n\t\t\t}\n\t\t\tconst passAccounting = {\n\t\t\t\tturns: 1,\n\t\t\t\tgoalId: beforeGoal.goalId,\n\t\t\t\tprogressRevision: beforeGoal.progressRevision ?? 0,\n\t\t\t\tstallTurns: beforeGoal.stallTurns,\n\t\t\t};\n\t\t\tlet result: GoalContinuationOnceResult;\n\t\t\ttry {\n\t\t\t\tresult = await this.continueGoalOnce(options);\n\t\t\t} catch (error) {\n\t\t\t\t// Prompt admission did not happen. A concurrent foreground owner is transient session\n\t\t\t\t// coordination, not a consumed goal turn and not evidence that the goal is blocked.\n\t\t\t\tif (error instanceof AgentBusyError) throw error;\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t\tif (error instanceof GoalBudgetExhaustedError) {\n\t\t\t\t\t// The goal already stopped itself durably (markBudgetLimited ran synchronously before\n\t\t\t\t\t// this signal was thrown) — surface the existing clean stop instead of reclassifying an\n\t\t\t\t\t// intentional, already-recorded stop as a generic continuation failure and rejecting\n\t\t\t\t\t// the whole loop promise.\n\t\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t\t}\n\t\t\t\tthis.deps.recordGoalContinuationFailure(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (result.submitted) {\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t}\n\n\t\t\tif (hasReachedWallClockBudget()) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tlet afterSnapshot = snapshot();\n\t\t\tif (afterSnapshot.goalState?.status === \"budget_limited\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tconst afterBudgetExhaustion = getExplicitGoalBudgetExhaustion(afterSnapshot.goalState);\n\t\t\tif (afterBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(afterBudgetExhaustion);\n\t\t\t\tafterSnapshot = snapshot();\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tif (afterSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(afterSnapshot), finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tturnsSubmitted,\n\t\t\tstopReason: \"max_turns_reached\",\n\t\t\tfinalSnapshot: snapshot(),\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"goal-loop-controller.js","sourceRoot":"","sources":["../../src/core/goal-loop-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AASjE,OAAO,EACN,2BAA2B,EAC3B,qCAAqC,GACrC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,wBAAw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AE,CAAC;gBAC3B,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,uBAAuB,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;YAC9F,CAAC;YACD,IAAI,aAAa,CAAC,YAAY,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;gBACtD,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,qBAAqB,CAAC,aAAa,CAAC,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;YAC3G,CAAC;QACF,CAAC;QAED,OAAO;YACN,cAAc;YACd,UAAU,EAAE,mBAAmB;YAC/B,aAAa,EAAE,QAAQ,EAAE;SACzB,CAAC;IACH,CAAC;CACD","sourcesContent":["/**\n * Goal auto-continuation loop.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Drives the bounded \"keep the\n * active goal moving\" loop: each pass reads the goal runtime snapshot, and — only while the snapshot\n * says `continue` — submits one continuation prompt back through the session's own prompt path. It\n * owns no state; the goal state lives in the session log and is read fresh every pass. Termination is\n * gated only by real terminal conditions and limits the owner explicitly supplied: an optional\n * per-invocation turn cap, an optional per-invocation wall-clock cap, and an optional durable token\n * budget on the goal. Each submitted pass still reports turn/wall-clock telemetry; provider usage\n * and spend are attributed at the response boundary. The host compares each pass's authoritative\n * progress revision and records unchanged passes as stalls, so a model cannot bypass the stall\n * limit by omitting a voluntary `no_progress` call.\n */\n\nimport { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationLoopStopReason,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"./agent-session-contracts.ts\";\nimport {\n\tbuildGoalContinuationPrompt,\n\tGOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n} from \"./goals/goal-continuation-prompt.ts\";\nimport { GoalBudgetExhaustedError } from \"./goals/goal-execution-errors.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport { type GoalState, isGoalExecutionActive } from \"./goals/goal-state.ts\";\n\n/**\n * Resolve an owner-supplied durable goal budget. Wall-clock and spend counters are deliberately\n * absent here: they are telemetry unless the public goal contract grows matching explicit limits.\n * Execution limits are policy inputs, not hidden runtime defaults.\n */\nfunction getExplicitGoalBudgetExhaustion(state: GoalState | undefined): string | undefined {\n\tif (!state || !isGoalExecutionActive(state.status)) return undefined;\n\tif (state.tokenBudget !== undefined && (state.tokensUsed ?? 0) >= state.tokenBudget) {\n\t\treturn `token budget exhausted (${state.tokensUsed ?? 0}/${state.tokenBudget})`;\n\t}\n\treturn undefined;\n}\n\n/**\n * Maps a non-\"continue\" continuation action onto the loop's own stopReason vocabulary.\n * `\"waiting\"` (a worker is dispatched against an open requirement) gets its OWN benign stopReason so\n * a wait is never misreported as `continuation_not_allowed` (which reads as a terminal refusal) —\n * callers/telemetry can tell \"paused, will resume on its own\" apart from \"stopped, needs a human or a\n * new decision.\" Every other non-continue action (ask-user/finalize/stop) keeps the existing\n * `continuation_not_allowed` stopReason unchanged.\n */\nfunction nonContinueStopReason(snapshot: GoalRuntimeSnapshot): GoalContinuationLoopStopReason {\n\treturn snapshot.continuation.action === \"waiting\" ? \"worker_in_flight\" : \"continuation_not_allowed\";\n}\n\nexport interface GoalLoopControllerDeps {\n\t/** Read the current goal runtime snapshot (continuation decision + goal state) fresh each pass. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Submit a continuation prompt through the session's own prompt path. */\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t/**\n\t * Persist one submitted pass's turn and active-wall-clock contribution. Provider usage is charged\n\t * at each assistant response before another request can be admitted. Called once per\n\t * pass actually SUBMITTED (never for a no-op `continueGoalOnce` call).\n\t */\n\trecordGoalContinuationPass(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/** Persist an exhausted/non-retryable continuation failure as a stopped goal state. */\n\trecordGoalContinuationFailure(error: unknown): void;\n\t/** Persist a reason-specific budget terminal state before returning control. */\n\tmarkGoalBudgetLimited(reason: string): void;\n}\n\nexport class GoalLoopController {\n\tprivate readonly deps: GoalLoopControllerDeps;\n\n\tconstructor(deps: GoalLoopControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync continueGoalOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (snapshot.continuation.action !== \"continue\") {\n\t\t\treturn { submitted: false, snapshot };\n\t\t}\n\n\t\tconst prompt = buildGoalContinuationPrompt();\n\t\tawait this.deps.prompt(prompt.text, {\n\t\t\texpandPromptTemplates: false,\n\t\t\tprocessSlashCommands: false,\n\t\t\tautoContinueGoal: false,\n\t\t\tinternalContextType: GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n\t\t\tgoalExecutionId: snapshot.goalState?.goalId,\n\t\t});\n\n\t\treturn { submitted: true, snapshot, prompt };\n\t}\n\n\tasync continueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (!Number.isSafeInteger(options.maxTurns) || options.maxTurns < 0) {\n\t\t\tthrow new Error(\"Goal continuation maxTurns must be a non-negative safe integer; 0 means unbounded.\");\n\t\t}\n\t\tlet turnsSubmitted = 0;\n\t\tconst hasExplicitTurnLimit = options.maxTurns > 0;\n\t\tconst now = options.now ?? Date.now;\n\t\tconst maxWallClockMs =\n\t\t\ttypeof options.maxWallClockMinutes === \"number\" && options.maxWallClockMinutes > 0\n\t\t\t\t? options.maxWallClockMinutes * 60_000\n\t\t\t\t: undefined;\n\t\tconst startedAt = now();\n\t\tconst hasReachedWallClockBudget = () => maxWallClockMs !== undefined && now() - startedAt >= maxWallClockMs;\n\t\tconst snapshot = () => this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (hasReachedWallClockBudget()) {\n\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t}\n\n\t\twhile (!hasExplicitTurnLimit || turnsSubmitted < options.maxTurns) {\n\t\t\tconst beforeSnapshot = snapshot();\n\t\t\tif (beforeSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(beforeSnapshot), finalSnapshot: beforeSnapshot };\n\t\t\t}\n\n\t\t\t// Owner-supplied durable token budget — read fresh every pass so an invocation stops as\n\t\t\t// soon as its own latest persisted usage crosses the explicit ceiling.\n\t\t\tconst beforeBudgetExhaustion = getExplicitGoalBudgetExhaustion(beforeSnapshot.goalState);\n\t\t\tif (beforeBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(beforeBudgetExhaustion);\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tconst passStartedAt = now();\n\t\t\tconst beforeGoal = beforeSnapshot.goalState;\n\t\t\tif (!beforeGoal) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"continuation_not_allowed\", finalSnapshot: beforeSnapshot };\n\t\t\t}\n\t\t\tconst passAccounting = {\n\t\t\t\tturns: 1,\n\t\t\t\tgoalId: beforeGoal.goalId,\n\t\t\t\tprogressRevision: beforeGoal.progressRevision ?? 0,\n\t\t\t\tstallTurns: beforeGoal.stallTurns,\n\t\t\t};\n\t\t\tlet result: GoalContinuationOnceResult;\n\t\t\ttry {\n\t\t\t\tresult = await this.continueGoalOnce(options);\n\t\t\t} catch (error) {\n\t\t\t\t// Prompt admission did not happen. A concurrent foreground owner is transient session\n\t\t\t\t// coordination, not a consumed goal turn and not evidence that the goal is blocked.\n\t\t\t\tif (error instanceof AgentBusyError) throw error;\n\t\t\t\tif (error instanceof GoalBudgetExhaustedError) {\n\t\t\t\t\t// The goal already stopped itself durably (markBudgetLimited ran synchronously before\n\t\t\t\t\t// this signal was thrown) — surface the existing clean stop instead of charging a turn.\n\t\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t\t}\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t\tthis.deps.recordGoalContinuationFailure(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (result.submitted) {\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t}\n\n\t\t\tif (hasReachedWallClockBudget()) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tlet afterSnapshot = snapshot();\n\t\t\tif (afterSnapshot.goalState?.status === \"budget_limited\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tconst afterBudgetExhaustion = getExplicitGoalBudgetExhaustion(afterSnapshot.goalState);\n\t\t\tif (afterBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(afterBudgetExhaustion);\n\t\t\t\tafterSnapshot = snapshot();\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tif (afterSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(afterSnapshot), finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tturnsSubmitted,\n\t\t\tstopReason: \"max_turns_reached\",\n\t\t\tfinalSnapshot: snapshot(),\n\t\t};\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"goal-auto-continue-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAEnG,MAAM,WAAW,8BAA8B;IAC9C,UAAU,IAAI,OAAO,CAAC;IACtB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,kBAAkB,IAAI,eAAe,CAAC;IACtC,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAAC;IACnF,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IAChD,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAC5F,gBAAgB,IAAI,OAAO,CAAC;IAC5B,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,uBAAuB,IAAI,IAAI,CAAC;IAChC,IAAI,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACrC;AAED,mFAAmF;AACnF,qBAAa,0BAA0B;IACtC,OAAO,CAAC,MAAM,CAA4C;IAC1D,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiC;IAEtD,YAAY,IAAI,EAAE,8BAA8B,EAE/C;IAED,UAAU,IAAI,IAAI,CAKjB;IAED,gBAAgB,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,IAAI,CAsB9C;IAEK,iBAAiB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAqBjG;IAED,OAAO,CAAC,iBAAiB;YAOX,YAAY;IAoB1B,OAAO,CAAC,aAAa;CAUrB"}
1
+ {"version":3,"file":"goal-auto-continue-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAEnG,MAAM,WAAW,8BAA8B;IAC9C,UAAU,IAAI,OAAO,CAAC;IACtB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,kBAAkB,IAAI,eAAe,CAAC;IACtC,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAAC;IACnF,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IAChD,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAC5F,gBAAgB,IAAI,OAAO,CAAC;IAC5B,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,uBAAuB,IAAI,IAAI,CAAC;IAChC,IAAI,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACrC;AAED,mFAAmF;AACnF,qBAAa,0BAA0B;IACtC,OAAO,CAAC,MAAM,CAA4C;IAC1D,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiC;IAEtD,YAAY,IAAI,EAAE,8BAA8B,EAE/C;IAED,UAAU,IAAI,IAAI,CAKjB;IAED,gBAAgB,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,IAAI,CAsB9C;IAEK,iBAAiB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAqBjG;IAED,OAAO,CAAC,iBAAiB;YAOX,YAAY;IA0B1B,OAAO,CAAC,aAAa;CAUrB"}
@@ -90,6 +90,12 @@ export class GoalAutoContinueController {
90
90
  maxStallTurns,
91
91
  maxWallClockMinutes: goalContinueMaxWallClockMinutes,
92
92
  });
93
+ if (!this.deps.isDisposed()) {
94
+ const nextSnapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });
95
+ if (nextSnapshot.continuation.action === "continue") {
96
+ this.scheduleFromIdle();
97
+ }
98
+ }
93
99
  }
94
100
  catch (error) {
95
101
  const message = error instanceof Error ? error.message : String(error);
@@ -1 +1 @@
1
- {"version":3,"file":"goal-auto-continue-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAuBjE,mFAAmF;AACnF,MAAM,OAAO,0BAA0B;IAKtC,YAAY,IAAoC;QAHxC,kBAAa,GAAG,KAAK,CAAC;QAI7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED,UAAU;QACT,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAC/B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACzB,CAAC;IACF,CAAC;IAED,gBAAgB,CAAC,OAAuB;QACvC,IAAI,OAAO,EAAE,gBAAgB,KAAK,KAAK,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YAAE,OAAO;QAEhG,MAAM,EAAE,aAAa,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC,IAAI;aAC5E,kBAAkB,EAAE;aACpB,mBAAmB,EAAE,CAAC;QACxB,IAAI,CAAC,gBAAgB;YAAE,OAAO;QAC9B,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,sBAA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OAAO;QACxD,IAAI,CAAC;YACJ,MAAM,IAAI,CAAC,iBAAiB,CAAC;gBAC5B,QAAQ,EAAE,iBAAiB;gBAC3B,aAAa;gBACb,mBAAmB,EAAE,+BAA+B;aACpD,CAAC,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,kCAAkC,OAAO,EAAE,EAAE,CAAC,CAAC;QAC3F,CAAC;IACF,CAAC;IAEO,aAAa,CACpB,OAAoC,EACpC,UAA+E;QAE/E,OAAO;YACN,cAAc,EAAE,CAAC;YACjB,UAAU;YACV,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC;SACzF,CAAC;IACH,CAAC;CACD","sourcesContent":["import { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n} from \"../agent-session.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goal-runtime-snapshot.ts\";\n\nexport interface GoalAutoContinueControllerDeps {\n\tisDisposed(): boolean;\n\tisGoalToolActive(): boolean;\n\tgetSettingsManager(): SettingsManager;\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\thasInFlightLaneForGoal(goalId: string): boolean;\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\tisForegroundBusy(): boolean;\n\twaitForForegroundIdle(): Promise<void>;\n\tmarkGoalToolUnavailable(): void;\n\temit(event: AgentSessionEvent): void;\n}\n\n/** Owns the single-flight goal continuation loop and its foreground-idle timer. */\nexport class GoalAutoContinueController {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _isContinuing = false;\n\tprivate readonly deps: GoalAutoContinueControllerDeps;\n\n\tconstructor(deps: GoalAutoContinueControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tclearTimer(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\tscheduleFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\tconst activeGoalId = snapshot.goalState?.goalId;\n\t\tif (activeGoalId !== undefined && this.deps.hasInFlightLaneForGoal(activeGoalId)) return;\n\n\t\tthis.clearTimer();\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tvoid this.runScheduled();\n\t\t}, goalAutoContinueDelayMs);\n\t\tconst timer = this._timer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tasync continueExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (this._isContinuing) return this.skippedResult(options, \"already_continuing\");\n\t\tconst initialGuard = this.unavailableResult(options);\n\t\tif (initialGuard) return initialGuard;\n\t\tthis._isContinuing = true;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tif (this.deps.isForegroundBusy()) await this.deps.waitForForegroundIdle();\n\t\t\t\tconst postWaitGuard = this.unavailableResult(options);\n\t\t\t\tif (postWaitGuard) return postWaitGuard;\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.deps.continueGoalLoop(options);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A different foreground owner can acquire the Agent after the idle event but before\n\t\t\t\t\t// prompt admission. Wait for that exact run and retry without terminalizing the goal.\n\t\t\t\t\tif (!(error instanceof AgentBusyError)) throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._isContinuing = false;\n\t\t}\n\t}\n\n\tprivate unavailableResult(options: GoalContinuationLoopOptions): GoalContinuationLoopResult | undefined {\n\t\tif (this.deps.isDisposed()) return this.skippedResult(options, \"session_disposed\");\n\t\tif (this.deps.isGoalToolActive()) return undefined;\n\t\tthis.deps.markGoalToolUnavailable();\n\t\treturn this.skippedResult(options, \"goal_tool_unavailable\");\n\t}\n\n\tprivate async runScheduled(): Promise<void> {\n\t\tif (this._isContinuing || this.deps.isDisposed()) return;\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\ttry {\n\t\t\tawait this.continueExclusive({\n\t\t\t\tmaxTurns: goalContinueTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t}\n\t}\n\n\tprivate skippedResult(\n\t\toptions: GoalContinuationLoopOptions,\n\t\tstopReason: \"already_continuing\" | \"session_disposed\" | \"goal_tool_unavailable\",\n\t): GoalContinuationLoopResult {\n\t\treturn {\n\t\t\tturnsSubmitted: 0,\n\t\t\tstopReason,\n\t\t\tfinalSnapshot: this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns }),\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"goal-auto-continue-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAuBjE,mFAAmF;AACnF,MAAM,OAAO,0BAA0B;IAKtC,YAAY,IAAoC;QAHxC,kBAAa,GAAG,KAAK,CAAC;QAI7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED,UAAU;QACT,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAC/B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACzB,CAAC;IACF,CAAC;IAED,gBAAgB,CAAC,OAAuB;QACvC,IAAI,OAAO,EAAE,gBAAgB,KAAK,KAAK,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YAAE,OAAO;QAEhG,MAAM,EAAE,aAAa,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC,IAAI;aAC5E,kBAAkB,EAAE;aACpB,mBAAmB,EAAE,CAAC;QACxB,IAAI,CAAC,gBAAgB;YAAE,OAAO;QAC9B,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC;QACrE,IAAI,QAAQ,CAAC,YAAY,CAAC,MAAM,KAAK,UAAU;YAAE,OAAO;QACxD,MAAM,YAAY,GAAG,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;QAChD,IAAI,YAAY,KAAK,SAAS,IAAI,IA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EAAE,CAAC;gBAC7B,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC;gBACzE,IAAI,YAAY,CAAC,YAAY,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;oBACrD,IAAI,CAAC,gBAAgB,EAAE,CAAC;gBACzB,CAAC;YACF,CAAC;QACF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,kCAAkC,OAAO,EAAE,EAAE,CAAC,CAAC;QAC3F,CAAC;IACF,CAAC;IAEO,aAAa,CACpB,OAAoC,EACpC,UAA+E;QAE/E,OAAO;YACN,cAAc,EAAE,CAAC;YACjB,UAAU;YACV,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC;SACzF,CAAC;IACH,CAAC;CACD","sourcesContent":["import { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n} from \"../agent-session.ts\";\nimport type { SettingsManager } from \"../settings-manager.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goal-runtime-snapshot.ts\";\n\nexport interface GoalAutoContinueControllerDeps {\n\tisDisposed(): boolean;\n\tisGoalToolActive(): boolean;\n\tgetSettingsManager(): SettingsManager;\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\thasInFlightLaneForGoal(goalId: string): boolean;\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\tisForegroundBusy(): boolean;\n\twaitForForegroundIdle(): Promise<void>;\n\tmarkGoalToolUnavailable(): void;\n\temit(event: AgentSessionEvent): void;\n}\n\n/** Owns the single-flight goal continuation loop and its foreground-idle timer. */\nexport class GoalAutoContinueController {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _isContinuing = false;\n\tprivate readonly deps: GoalAutoContinueControllerDeps;\n\n\tconstructor(deps: GoalAutoContinueControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tclearTimer(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\tscheduleFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\tconst activeGoalId = snapshot.goalState?.goalId;\n\t\tif (activeGoalId !== undefined && this.deps.hasInFlightLaneForGoal(activeGoalId)) return;\n\n\t\tthis.clearTimer();\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tvoid this.runScheduled();\n\t\t}, goalAutoContinueDelayMs);\n\t\tconst timer = this._timer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tasync continueExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (this._isContinuing) return this.skippedResult(options, \"already_continuing\");\n\t\tconst initialGuard = this.unavailableResult(options);\n\t\tif (initialGuard) return initialGuard;\n\t\tthis._isContinuing = true;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tif (this.deps.isForegroundBusy()) await this.deps.waitForForegroundIdle();\n\t\t\t\tconst postWaitGuard = this.unavailableResult(options);\n\t\t\t\tif (postWaitGuard) return postWaitGuard;\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.deps.continueGoalLoop(options);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A different foreground owner can acquire the Agent after the idle event but before\n\t\t\t\t\t// prompt admission. Wait for that exact run and retry without terminalizing the goal.\n\t\t\t\t\tif (!(error instanceof AgentBusyError)) throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._isContinuing = false;\n\t\t}\n\t}\n\n\tprivate unavailableResult(options: GoalContinuationLoopOptions): GoalContinuationLoopResult | undefined {\n\t\tif (this.deps.isDisposed()) return this.skippedResult(options, \"session_disposed\");\n\t\tif (this.deps.isGoalToolActive()) return undefined;\n\t\tthis.deps.markGoalToolUnavailable();\n\t\treturn this.skippedResult(options, \"goal_tool_unavailable\");\n\t}\n\n\tprivate async runScheduled(): Promise<void> {\n\t\tif (this._isContinuing || this.deps.isDisposed()) return;\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\t\ttry {\n\t\t\tawait this.continueExclusive({\n\t\t\t\tmaxTurns: goalContinueTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t\t});\n\t\t\tif (!this.deps.isDisposed()) {\n\t\t\t\tconst nextSnapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\t\t\tif (nextSnapshot.continuation.action === \"continue\") {\n\t\t\t\t\tthis.scheduleFromIdle();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t}\n\t}\n\n\tprivate skippedResult(\n\t\toptions: GoalContinuationLoopOptions,\n\t\tstopReason: \"already_continuing\" | \"session_disposed\" | \"goal_tool_unavailable\",\n\t): GoalContinuationLoopResult {\n\t\treturn {\n\t\t\tturnsSubmitted: 0,\n\t\t\tstopReason,\n\t\t\tfinalSnapshot: this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns }),\n\t\t};\n\t}\n}\n"]}
@@ -367,7 +367,7 @@ export class GoalSessionController {
367
367
  }
368
368
  markHarnessGuardBlocked(info) {
369
369
  const reason = info.reason === "provider_turn_limit"
370
- ? `provider_turn_limit: reached the ${info.repeats}-request provider-turn cost fuse`
370
+ ? `provider_turn_limit: reached the explicit ${info.repeats}-request provider-turn limit`
371
371
  : `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;
372
372
  return this.stopActiveGoal("blocked", reason);
373
373
  }