@caupulican/pi-adaptative 0.81.41 → 0.81.42

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 (237) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +5 -1
  3. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +3 -3
  4. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +8 -0
  5. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +26 -3
  6. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +3 -0
  7. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +4 -1
  8. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +2 -1
  9. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +2 -0
  10. package/dist/core/agent-paths.d.ts +32 -0
  11. package/dist/core/agent-paths.d.ts.map +1 -1
  12. package/dist/core/agent-paths.js +65 -0
  13. package/dist/core/agent-paths.js.map +1 -1
  14. package/dist/core/agent-session-contracts.d.ts +19 -1
  15. package/dist/core/agent-session-contracts.d.ts.map +1 -1
  16. package/dist/core/agent-session-contracts.js.map +1 -1
  17. package/dist/core/agent-session.d.ts.map +1 -1
  18. package/dist/core/agent-session.js +4 -9
  19. package/dist/core/agent-session.js.map +1 -1
  20. package/dist/core/autonomy/contracts.d.ts +2 -0
  21. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  22. package/dist/core/autonomy/contracts.js.map +1 -1
  23. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  24. package/dist/core/autonomy/envelope-enforcement.js +4 -9
  25. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  26. package/dist/core/autonomy/lane-tool-surface.d.ts +3 -1
  27. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  28. package/dist/core/autonomy/lane-tool-surface.js +17 -4
  29. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  30. package/dist/core/autonomy/path-scope.d.ts +14 -0
  31. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  32. package/dist/core/autonomy/path-scope.js +37 -6
  33. package/dist/core/autonomy/path-scope.js.map +1 -1
  34. package/dist/core/background-lane-controller.d.ts +27 -1
  35. package/dist/core/background-lane-controller.d.ts.map +1 -1
  36. package/dist/core/background-lane-controller.js +32 -1
  37. package/dist/core/background-lane-controller.js.map +1 -1
  38. package/dist/core/delegation/managed-lane-controller.d.ts +11 -1
  39. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -1
  40. package/dist/core/delegation/managed-lane-controller.js +84 -41
  41. package/dist/core/delegation/managed-lane-controller.js.map +1 -1
  42. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -1
  43. package/dist/core/delegation/session-worker-claim.js +4 -3
  44. package/dist/core/delegation/session-worker-claim.js.map +1 -1
  45. package/dist/core/delegation/worker-action-journal.d.ts +73 -0
  46. package/dist/core/delegation/worker-action-journal.d.ts.map +1 -0
  47. package/dist/core/delegation/worker-action-journal.js +297 -0
  48. package/dist/core/delegation/worker-action-journal.js.map +1 -0
  49. package/dist/core/delegation/worker-actions.d.ts +36 -1
  50. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  51. package/dist/core/delegation/worker-actions.js +171 -46
  52. package/dist/core/delegation/worker-actions.js.map +1 -1
  53. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +75 -0
  54. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -0
  55. package/dist/core/delegation/worker-agent-control-coordinator.js +218 -0
  56. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -0
  57. package/dist/core/delegation/worker-agent-control.d.ts +66 -0
  58. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -0
  59. package/dist/core/delegation/worker-agent-control.js +163 -0
  60. package/dist/core/delegation/worker-agent-control.js.map +1 -0
  61. package/dist/core/delegation/worker-attempt-executor.d.ts +80 -0
  62. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -0
  63. package/dist/core/delegation/worker-attempt-executor.js +343 -0
  64. package/dist/core/delegation/worker-attempt-executor.js.map +1 -0
  65. package/dist/core/delegation/worker-claim.d.ts +30 -0
  66. package/dist/core/delegation/worker-claim.d.ts.map +1 -1
  67. package/dist/core/delegation/worker-claim.js +205 -53
  68. package/dist/core/delegation/worker-claim.js.map +1 -1
  69. package/dist/core/delegation/worker-conversation-store.d.ts +116 -0
  70. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -0
  71. package/dist/core/delegation/worker-conversation-store.js +442 -0
  72. package/dist/core/delegation/worker-conversation-store.js.map +1 -0
  73. package/dist/core/delegation/worker-delegation-controller.d.ts +21 -5
  74. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  75. package/dist/core/delegation/worker-delegation-controller.js +386 -251
  76. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  77. package/dist/core/delegation/worker-delegation-request.d.ts +14 -0
  78. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  79. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  80. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +4 -2
  81. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
  82. package/dist/core/delegation/worker-dispatch-scheduler.js +16 -6
  83. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
  84. package/dist/core/delegation/worker-execution-policy.d.ts +2 -1
  85. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  86. package/dist/core/delegation/worker-execution-policy.js +5 -7
  87. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  88. package/dist/core/delegation/worker-lifecycle.d.ts +44 -1
  89. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  90. package/dist/core/delegation/worker-lifecycle.js +120 -0
  91. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  92. package/dist/core/delegation/worker-process-owner.d.ts +18 -0
  93. package/dist/core/delegation/worker-process-owner.d.ts.map +1 -0
  94. package/dist/core/delegation/worker-process-owner.js +54 -0
  95. package/dist/core/delegation/worker-process-owner.js.map +1 -0
  96. package/dist/core/delegation/worker-profile-resolver.d.ts +5 -1
  97. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
  98. package/dist/core/delegation/worker-profile-resolver.js +8 -0
  99. package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
  100. package/dist/core/delegation/worker-recovery-coordinator.d.ts +54 -0
  101. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -0
  102. package/dist/core/delegation/worker-recovery-coordinator.js +181 -0
  103. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -0
  104. package/dist/core/delegation/worker-resource-catalog.d.ts +32 -0
  105. package/dist/core/delegation/worker-resource-catalog.d.ts.map +1 -0
  106. package/dist/core/delegation/worker-resource-catalog.js +116 -0
  107. package/dist/core/delegation/worker-resource-catalog.js.map +1 -0
  108. package/dist/core/delegation/worker-resource-materializer.d.ts +47 -0
  109. package/dist/core/delegation/worker-resource-materializer.d.ts.map +1 -0
  110. package/dist/core/delegation/worker-resource-materializer.js +137 -0
  111. package/dist/core/delegation/worker-resource-materializer.js.map +1 -0
  112. package/dist/core/delegation/worker-runner.d.ts +3 -1
  113. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  114. package/dist/core/delegation/worker-runner.js +189 -54
  115. package/dist/core/delegation/worker-runner.js.map +1 -1
  116. package/dist/core/delegation/worker-terminal-finalizer.d.ts +23 -0
  117. package/dist/core/delegation/worker-terminal-finalizer.d.ts.map +1 -0
  118. package/dist/core/delegation/worker-terminal-finalizer.js +12 -0
  119. package/dist/core/delegation/worker-terminal-finalizer.js.map +1 -0
  120. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts +38 -0
  121. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -0
  122. package/dist/core/delegation/worker-write-reservation-coordinator.js +107 -0
  123. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -0
  124. package/dist/core/delegation/worker-write-reservation.d.ts +90 -0
  125. package/dist/core/delegation/worker-write-reservation.d.ts.map +1 -0
  126. package/dist/core/delegation/worker-write-reservation.js +348 -0
  127. package/dist/core/delegation/worker-write-reservation.js.map +1 -0
  128. package/dist/core/models/model-endpoint.d.ts +3 -0
  129. package/dist/core/models/model-endpoint.d.ts.map +1 -0
  130. package/dist/core/models/model-endpoint.js +11 -0
  131. package/dist/core/models/model-endpoint.js.map +1 -0
  132. package/dist/core/orchestration/agent-resume.d.ts +2 -0
  133. package/dist/core/orchestration/agent-resume.d.ts.map +1 -1
  134. package/dist/core/orchestration/agent-resume.js +7 -0
  135. package/dist/core/orchestration/agent-resume.js.map +1 -1
  136. package/dist/core/orchestration/attempt-usage.d.ts +28 -0
  137. package/dist/core/orchestration/attempt-usage.d.ts.map +1 -0
  138. package/dist/core/orchestration/attempt-usage.js +168 -0
  139. package/dist/core/orchestration/attempt-usage.js.map +1 -0
  140. package/dist/core/orchestration/capability-gateway.d.ts +19 -1
  141. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  142. package/dist/core/orchestration/capability-gateway.js +128 -28
  143. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  144. package/dist/core/orchestration/contracts.d.ts +35 -0
  145. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  146. package/dist/core/orchestration/contracts.js +17 -0
  147. package/dist/core/orchestration/contracts.js.map +1 -1
  148. package/dist/core/orchestration/delegation-ledger.d.ts +17 -2
  149. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  150. package/dist/core/orchestration/delegation-ledger.js +78 -3
  151. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  152. package/dist/core/orchestration/event-store.d.ts +1 -0
  153. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  154. package/dist/core/orchestration/event-store.js +78 -38
  155. package/dist/core/orchestration/event-store.js.map +1 -1
  156. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  157. package/dist/core/orchestration/profile-registry.js +81 -41
  158. package/dist/core/orchestration/profile-registry.js.map +1 -1
  159. package/dist/core/orchestration/profile-store.d.ts.map +1 -1
  160. package/dist/core/orchestration/profile-store.js +18 -4
  161. package/dist/core/orchestration/profile-store.js.map +1 -1
  162. package/dist/core/orchestration/risk-budget.d.ts +2 -0
  163. package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
  164. package/dist/core/orchestration/risk-budget.js +26 -0
  165. package/dist/core/orchestration/risk-budget.js.map +1 -1
  166. package/dist/core/orchestration/task-runtime.d.ts +13 -1
  167. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  168. package/dist/core/orchestration/task-runtime.js +127 -16
  169. package/dist/core/orchestration/task-runtime.js.map +1 -1
  170. package/dist/core/orchestration/worker-execution-contract.d.ts +3 -1
  171. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  172. package/dist/core/orchestration/worker-execution-contract.js +75 -23
  173. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  174. package/dist/core/orchestration/worker-result-adapter.d.ts +9 -3
  175. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -1
  176. package/dist/core/orchestration/worker-result-adapter.js +167 -14
  177. package/dist/core/orchestration/worker-result-adapter.js.map +1 -1
  178. package/dist/core/reflection-controller.d.ts +1 -1
  179. package/dist/core/reflection-controller.d.ts.map +1 -1
  180. package/dist/core/reflection-controller.js +90 -54
  181. package/dist/core/reflection-controller.js.map +1 -1
  182. package/dist/core/research/evidence-bundle.d.ts +20 -0
  183. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  184. package/dist/core/research/evidence-bundle.js +173 -69
  185. package/dist/core/research/evidence-bundle.js.map +1 -1
  186. package/dist/core/runtime-builder.d.ts +7 -0
  187. package/dist/core/runtime-builder.d.ts.map +1 -1
  188. package/dist/core/runtime-builder.js +15 -1
  189. package/dist/core/runtime-builder.js.map +1 -1
  190. package/dist/core/session-artifact-bundle.d.ts +35 -0
  191. package/dist/core/session-artifact-bundle.d.ts.map +1 -0
  192. package/dist/core/session-artifact-bundle.js +61 -0
  193. package/dist/core/session-artifact-bundle.js.map +1 -0
  194. package/dist/core/tools/delegate-status.d.ts +6 -1
  195. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  196. package/dist/core/tools/delegate-status.js +100 -18
  197. package/dist/core/tools/delegate-status.js.map +1 -1
  198. package/dist/core/tools/delegate.d.ts +9 -1
  199. package/dist/core/tools/delegate.d.ts.map +1 -1
  200. package/dist/core/tools/delegate.js +323 -61
  201. package/dist/core/tools/delegate.js.map +1 -1
  202. package/dist/core/tools/run-process.d.ts +1 -1
  203. package/dist/core/tools/run-process.d.ts.map +1 -1
  204. package/dist/core/tools/run-process.js +69 -9
  205. package/dist/core/tools/run-process.js.map +1 -1
  206. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  207. package/dist/core/tools/shell-contract-router.js +12 -5
  208. package/dist/core/tools/shell-contract-router.js.map +1 -1
  209. package/dist/core/util/bounded-file.d.ts +15 -0
  210. package/dist/core/util/bounded-file.d.ts.map +1 -0
  211. package/dist/core/util/bounded-file.js +120 -0
  212. package/dist/core/util/bounded-file.js.map +1 -0
  213. package/dist/core/util/bounded-jsonl.d.ts.map +1 -1
  214. package/dist/core/util/bounded-jsonl.js +119 -9
  215. package/dist/core/util/bounded-jsonl.js.map +1 -1
  216. package/dist/core/util/bounded-value.d.ts +3 -0
  217. package/dist/core/util/bounded-value.d.ts.map +1 -0
  218. package/dist/core/util/bounded-value.js +12 -0
  219. package/dist/core/util/bounded-value.js.map +1 -0
  220. package/dist/core/util/value-guards.d.ts +2 -0
  221. package/dist/core/util/value-guards.d.ts.map +1 -1
  222. package/dist/core/util/value-guards.js +5 -0
  223. package/dist/core/util/value-guards.js.map +1 -1
  224. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  225. package/dist/modes/interactive/components/session-selector.js +27 -44
  226. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  227. package/docs/tool-repair.md +3 -0
  228. package/docs/windows.md +4 -2
  229. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  230. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  231. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  232. package/examples/extensions/sandbox/package-lock.json +2 -2
  233. package/examples/extensions/sandbox/package.json +1 -1
  234. package/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/examples/extensions/with-deps/package.json +1 -1
  236. package/npm-shrinkwrap.json +12 -12
  237. package/package.json +4 -4
@@ -16,6 +16,7 @@
16
16
  import type { Api, Model } from "@caupulican/pi-ai";
17
17
  import type { GoalContinuationLoopOptions, GoalContinuationLoopResult, PromptOptions, ResearchLaneRunOutcome, WorkerDelegationRunOutcome } from "./agent-session-contracts.ts";
18
18
  import { type LaneRecord } from "./autonomy/lane-tracker.ts";
19
+ import type { WorkerAgentControlPort } from "./delegation/worker-agent-control.ts";
19
20
  import { type WorkerDelegationControllerDeps } from "./delegation/worker-delegation-controller.ts";
20
21
  import type { WorkerDelegationRequest } from "./delegation/worker-delegation-request.ts";
21
22
  import type { ManagedLaneEvent } from "./extensions/types.ts";
@@ -45,7 +46,7 @@ export interface BackgroundLaneControllerDeps extends WorkerDelegationController
45
46
  /** Persist an explicit stopped state when the selected surface cannot drive the active goal. */
46
47
  markGoalToolUnavailable(): void;
47
48
  }
48
- export declare class BackgroundLaneController {
49
+ export declare class BackgroundLaneController implements WorkerAgentControlPort {
49
50
  /** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */
50
51
  private readonly _laneTracker;
51
52
  private readonly _laneModels;
@@ -141,6 +142,31 @@ export declare class BackgroundLaneController {
141
142
  started: true;
142
143
  record: LaneRecord;
143
144
  };
145
+ /** Durable logical-worker controls. Each checks UAC before materializing worker state. */
146
+ sendWorkerAgentMessage(agentId: string, message: string): {
147
+ messageId: string;
148
+ queued: true;
149
+ };
150
+ followUpWorkerAgent(agentId: string, message: string): {
151
+ started: boolean;
152
+ steering: boolean;
153
+ messageId: string;
154
+ record?: LaneRecord;
155
+ skipReason?: string;
156
+ };
157
+ interruptWorkerAgent(agentId: string): {
158
+ interrupted: boolean;
159
+ reason?: string;
160
+ };
161
+ resumeWorkerAgent(agentId: string): {
162
+ started: boolean;
163
+ record?: LaneRecord;
164
+ skipReason?: string;
165
+ };
166
+ cancelWorkerAgent(agentId: string, reasonCode?: string): LaneRecord | undefined;
167
+ waitForWorkerAgent(agentId: string, timeoutMs?: number): Promise<{
168
+ status: "active" | "suspended" | "idle" | "unknown";
169
+ }>;
144
170
  /** Run one worker immediately; used by focused integrations and tests. */
145
171
  runWorkerDelegationOnce(request: WorkerDelegationRequest, onStarted?: (record: LaneRecord) => void, existingRecord?: LaneRecord): Promise<WorkerDelegationRunOutcome>;
146
172
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"background-lane-controller.d.ts","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,sBAAsB,EACtB,0BAA0B,EAC1B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,KAAK,UAAU,EAAe,MAAM,4BAA4B,CAAC;AAG1E,OAAO,EAEN,KAAK,8BAA8B,EACnC,MAAM,8CAA8C,CAAC;AACtD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AAGzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AACzG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,KAAK,EAAE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AI,mBAAmB,EAAE,CAE/C;CACD","sourcesContent":["/**\n * Execution-plane coordinator for goal continuation, research, managed lanes, worker delegation,\n * and model fitness.\n *\n * Coordination state is owned by focused controllers. This coordinator retains one AgentSession\n * composition seam and a shared lane read model. Everything it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session-contracts.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { ManagedLaneController } from \"./delegation/managed-lane-controller.ts\";\nimport {\n\tWorkerDelegationController,\n\ttype WorkerDelegationControllerDeps,\n} from \"./delegation/worker-delegation-controller.ts\";\nimport type { WorkerDelegationRequest } from \"./delegation/worker-delegation-request.ts\";\nimport { WorkerLifecycle } from \"./delegation/worker-lifecycle.ts\";\nimport { WorkerNotificationCoordinator } from \"./delegation/worker-notification-coordinator.ts\";\nimport type { ManagedLaneEvent } from \"./extensions/types.ts\";\nimport { GoalAutoContinueController } from \"./goals/goal-auto-continue-controller.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { TaskRuntimeProjection } from \"./orchestration/task-runtime.ts\";\nimport { LaneModelResolver, type LaneModelResolverDeps } from \"./research/lane-model-resolver.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport { ModelFitnessController, type ModelFitnessControllerDeps } from \"./research/model-fitness-controller.ts\";\nimport { ResearchLaneController, type ResearchLaneControllerDeps } from \"./research/research-lane-controller.ts\";\nimport { getActiveSessionBranchEntries } from \"./session-snapshot.ts\";\n\nexport { isLocalExecutionModel } from \"./delegation/worker-delegation-controller.ts\";\nexport { clampLaneMaxUsd } from \"./research/lane-model-resolver.ts\";\n\nexport interface BackgroundLaneControllerDeps\n\textends WorkerDelegationControllerDeps,\n\t\tResearchLaneControllerDeps,\n\t\tModelFitnessControllerDeps,\n\t\tLaneModelResolverDeps {\n\t/** True iff the `goal` tool is in the session's ACTIVE surface -- the capability-adaptive gate\n\t * for every goal-continuation loop (see `continueGoalLoopExclusive`): a surface without the\n\t * goal tool (lean capability blocklist, worker role ceiling, --tools/profile exclusion) must\n\t * never be driven with continuation prompts it cannot execute. */\n\tisGoalToolActive(): boolean;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Persist an explicit stopped state when the selected surface cannot drive the active goal. */\n\tmarkGoalToolUnavailable(): void;\n}\n\nexport class BackgroundLaneController {\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\tprivate readonly _laneModels: LaneModelResolver;\n\tprivate readonly _goalAutoContinue: GoalAutoContinueController;\n\tprivate readonly _research: ResearchLaneController;\n\tprivate readonly _fitness: ModelFitnessController;\n\t/** Lazily materialized only when managed-lane state is queried or reported. */\n\tprivate _managedLanes: ManagedLaneController | undefined;\n\t/** Lazily materialized so a UAC surface without `delegate` allocates no worker runtime state. */\n\tprivate _workers: WorkerDelegationController | undefined;\n\t/** One durable lifecycle shared by every worker execution adapter. */\n\tprivate _workerLifecycle: WorkerLifecycle | undefined;\n\t/** Shared terminal outbox for managed and in-process workers; lazy under UAC omission. */\n\tprivate _workerNotifications: WorkerNotificationCoordinator | undefined;\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\t/** Emit a warning without ever throwing — used from disposal-adjacent persistence where a\n\t * listener failure (or a bare test double missing `emit`) must never block or crash cleanup. */\n\tprivate _safeWarn(message: string): void {\n\t\ttry {\n\t\t\tthis.deps.emit({ type: \"warning\", message });\n\t\t} catch {\n\t\t\t// Dispose must never throw.\n\t\t}\n\t}\n\n\tprivate _recordWorkerTerminal(record: LaneRecord, durableNotificationId: string): void {\n\t\tthis._getWorkerNotificationCoordinator().recordTerminal(record, durableNotificationId);\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis._laneModels = new LaneModelResolver(deps);\n\t\tthis._research = new ResearchLaneController(deps, this._laneTracker, this._laneModels);\n\t\tthis._fitness = new ModelFitnessController(deps, this._laneModels);\n\t\tthis._goalAutoContinue = new GoalAutoContinueController({\n\t\t\tisDisposed: deps.isDisposed,\n\t\t\tisGoalToolActive: deps.isGoalToolActive,\n\t\t\tgetSettingsManager: deps.getSettingsManager,\n\t\t\tgetModelCapabilityProfile: deps.getModelCapabilityProfile,\n\t\t\tgetGoalRuntimeSnapshot: deps.getGoalRuntimeSnapshot,\n\t\t\thasInFlightLaneForGoal: (goalId) => this._hasInFlightLaneForGoal(goalId),\n\t\t\tcontinueGoalLoop: deps.continueGoalLoop,\n\t\t\tmarkGoalToolUnavailable: deps.markGoalToolUnavailable,\n\t\t\temit: deps.emit,\n\t\t});\n\t}\n\n\tprivate _getWorkerController(): WorkerDelegationController {\n\t\tthis._workers ??= new WorkerDelegationController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerNotificationCoordinator(),\n\t\t\tthis._getWorkerLifecycle(),\n\t\t);\n\t\treturn this._workers;\n\t}\n\n\tprivate _getWorkerLifecycle(): WorkerLifecycle {\n\t\tif (this._workerLifecycle) return this._workerLifecycle;\n\t\tconst lifecycle = new WorkerLifecycle({\n\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\tsessionId: this.deps.getSessionId(),\n\t\t});\n\t\tthis._workerLifecycle = lifecycle;\n\t\tfor (const notification of lifecycle.getPendingTerminalNotifications()) {\n\t\t\tthis._getWorkerNotificationCoordinator().recordTerminal(notification.record, notification.notificationId);\n\t\t}\n\t\treturn lifecycle;\n\t}\n\n\tprivate _getWorkerNotificationCoordinator(): WorkerNotificationCoordinator {\n\t\tthis._workerNotifications ??= new WorkerNotificationCoordinator({\n\t\t\tgetWorkerRecords: () => this._workerLifecycle?.getAllRecords() ?? [],\n\t\t\temitStatus: (status) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tterminalSinceFlush: [...status.terminalSinceFlush],\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// A partial integration must not crash the event-driven terminal outbox.\n\t\t\t\t}\n\t\t\t},\n\t\t\tnotify: (records) => this.deps.notifyWorkerTerminalHandoff(records),\n\t\t\twarn: (message) => this._safeWarn(message),\n\t\t\tmarkDurableDelivered: (notificationIds) => this._workerLifecycle?.markNotificationsDelivered(notificationIds),\n\t\t});\n\t\treturn this._workerNotifications;\n\t}\n\n\tprivate _getManagedLaneController(): ManagedLaneController {\n\t\tthis._managedLanes ??= new ManagedLaneController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerLifecycle(),\n\t\t\t(record, notificationId) => this._recordWorkerTerminal(record, notificationId),\n\t\t);\n\t\treturn this._managedLanes;\n\t}\n\n\tprivate _hydrateManagedLanes(): void {\n\t\tif (this._managedLanes) {\n\t\t\tthis._managedLanes.ensureHydrated();\n\t\t\treturn;\n\t\t}\n\t\tconst hasPersistedActiveManagedLane = getLatestLaneRecordSnapshots(\n\t\t\tgetActiveSessionBranchEntries(this.deps.getSessionManager()),\n\t\t).some((record) => record.type === \"tmux-worker\" && (record.status === \"queued\" || record.status === \"running\"));\n\t\tif (hasPersistedActiveManagedLane) this._getManagedLaneController().ensureHydrated();\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\tthis._hydrateManagedLanes();\n\t\tconst workerRecords =\n\t\t\tthis._workers?.getRecords() ??\n\t\t\t(this.deps.isDelegateToolActive?.() ? this._getWorkerController().getRecords() : []);\n\t\treturn [\n\t\t\t...this._laneTracker.getRecords(),\n\t\t\t...workerRecords,\n\t\t\t...(this._workerLifecycle?.getManagedRecords() ?? []),\n\t\t];\n\t}\n\n\t/** Does not materialize the worker controller when UAC omitted delegation. */\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined {\n\t\treturn this._workerLifecycle?.getTaskRuntimeSnapshot();\n\t}\n\n\t/** Reconcile only when delegation has already been materialized; UAC omission stays zero-load. */\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tthis._workers?.synchronizeGoalState(goal);\n\t}\n\n\t/**\n\t * Resolve a tracked managed-lane dispatch. The caller's stable id is also the canonical durable\n\t * lane id, so this is an existence check rather than an id translation.\n\t */\n\tresolveManagedLaneId(callerLaneId: string): string | undefined {\n\t\treturn this._getManagedLaneController().resolve(callerLaneId);\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this.getLaneRecords().filter((record) => record.status === \"queued\" || record.status === \"running\").length;\n\t}\n\n\t/** Belt-and-braces guard: whether ANY queued/running lane is tagged with this goalId. */\n\tprivate _hasInFlightLaneForGoal(goalId: string): boolean {\n\t\treturn this.getLaneRecords().some(\n\t\t\t(record) => record.goalId === goalId && (record.status === \"queued\" || record.status === \"running\"),\n\t\t);\n\t}\n\n\t/** Delegate the out-of-process dispatch/terminal claim to its single lifecycle owner. */\n\trecordManagedLane(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\treturn this._getManagedLaneController().record(event);\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._research.getLastSkipReason();\n\t}\n\n\t/**\n\t * Abort in-flight research and delegate worker disposal to its single owning controller.\n\t *\n\t * This synchronous body is the LAST provably-safe write window for canceled/in-flight work.\n\t * `dispose()` (agent-session.ts) has already set the session's own disposed flag but has not yet\n\t * returned — no successor session (e.g. a `/reload` adoption) can exist yet, so an append here\n\t * cannot interleave with one; a post-await continuation resuming AFTER this method returns must\n\t * not append (see the disposed branch in `runWorkerDelegationOnce`). Persist FIRST, then\n\t * complete-in-memory, so a throw from one lane's persist cannot skip another's; each persist gets\n\t * its own try/catch — dispose must never throw.\n\t */\n\tabortInFlightLanes(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t\tthis._research.abort();\n\t\tthis._fitness.abort();\n\t\tfor (const record of this._laneTracker.getRecords()) {\n\t\t\tif (record.status !== \"queued\" && record.status !== \"running\") continue;\n\t\t\tif (record.type === \"tmux-worker\") continue;\n\t\t\tconst canceled = this._laneTracker.complete(record.laneId, {\n\t\t\t\tstatus: \"canceled\",\n\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t});\n\t\t\tif (!canceled) continue;\n\t\t\ttry {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), canceled);\n\t\t\t} catch (error) {\n\t\t\t\tthis._safeWarn(\n\t\t\t\t\t`Failed to persist canceled lane record ${canceled.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._managedLanes?.release();\n\n\t\tthis._workers?.abort();\n\t\tthis._workerNotifications?.dispose();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tthis._goalAutoContinue.scheduleFromIdle(options);\n\t}\n\n\t/**\n\t * Single-flight entry point for EVERY goal-continuation loop invocation — idle autosteer\n\t * ({@link _runScheduledGoalAutoContinue}) AND the manual `/goal start` / `/goal-continue`\n\t * commands (reached through `AgentSession.continueGoalLoop`). Both paths ultimately submit\n\t * continuation prompts through the session's single `prompt()` path, so two loops racing throws\n\t * \"Agent is already processing\" from whichever submits second. `_isGoalAutoContinuing` is the\n\t * ONE owner of that mutex; `deps.continueGoalLoop` (the raw {@link GoalLoopController} loop)\n\t * must never be called directly outside this method, or the guard is bypassed.\n\t */\n\tasync continueGoalLoopExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this._goalAutoContinue.continueExclusive(options);\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tthis._research.clearTimer();\n\t}\n\n\tscheduleResearchLaneFromIdle(): void {\n\t\tthis._research.scheduleFromIdle();\n\t}\n\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\treturn this._laneModels.resolveModel(configuredPattern);\n\t}\n\n\tgetOrchestrationProfileCatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\treturn this._getWorkerController().getProfileCatalog();\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\treturn this._research.runOnce(request);\n\t}\n\t/** Start a durable, profile-bound worker delegation. */\n\tstartWorkerDelegation(\n\t\trequest: WorkerDelegationRequest,\n\t): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\treturn this._getWorkerController().start(request);\n\t}\n\n\t/** Run one worker immediately; used by focused integrations and tests. */\n\tasync runWorkerDelegationOnce(\n\t\trequest: WorkerDelegationRequest,\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\treturn this._getWorkerController().runOnce(request, onStarted, existingRecord);\n\t}\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t\t/** LLM tool-call id, present only via the model_fitness tool path — see model-fitness.ts. */\n\t\ttoolCallId?: string;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\treturn this._fitness.run(args);\n\t}\n\n\t/** Start every capacity-eligible queued worker at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tif (this.deps.isDelegateToolActive?.()) this._getWorkerController().drain();\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\treturn this._fitness.getStoredReports();\n\t}\n}\n"]}
1
+ {"version":3,"file":"background-lane-controller.d.ts","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,GAAG,EAA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EAAE,MAAM,CAAC;QACd,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,+FAA6F;QAC7F,UAAU,CAAC,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,kBAAkB,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC,CAEjH;IAED,mGAAmG;IACnG,4BAA4B,IAAI,IAAI,CAEnC;IAED,mGAAmG;IACnG,uBAAuB,IAAI,mBAAmB,EAAE,CAE/C;CACD","sourcesContent":["/**\n * Execution-plane coordinator for goal continuation, research, managed lanes, worker delegation,\n * and model fitness.\n *\n * Coordination state is owned by focused controllers. This coordinator retains one AgentSession\n * composition seam and a shared lane read model. Everything it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session-contracts.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { ManagedLaneController } from \"./delegation/managed-lane-controller.ts\";\nimport type { WorkerAgentControlPort } from \"./delegation/worker-agent-control.ts\";\nimport {\n\tWorkerDelegationController,\n\ttype WorkerDelegationControllerDeps,\n} from \"./delegation/worker-delegation-controller.ts\";\nimport type { WorkerDelegationRequest } from \"./delegation/worker-delegation-request.ts\";\nimport { WorkerLifecycle } from \"./delegation/worker-lifecycle.ts\";\nimport { WorkerNotificationCoordinator } from \"./delegation/worker-notification-coordinator.ts\";\nimport type { ManagedLaneEvent } from \"./extensions/types.ts\";\nimport { GoalAutoContinueController } from \"./goals/goal-auto-continue-controller.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { TaskRuntimeProjection } from \"./orchestration/task-runtime.ts\";\nimport { LaneModelResolver, type LaneModelResolverDeps } from \"./research/lane-model-resolver.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport { ModelFitnessController, type ModelFitnessControllerDeps } from \"./research/model-fitness-controller.ts\";\nimport { ResearchLaneController, type ResearchLaneControllerDeps } from \"./research/research-lane-controller.ts\";\nimport { getActiveSessionBranchEntries } from \"./session-snapshot.ts\";\n\nexport { isLocalExecutionModel } from \"./delegation/worker-delegation-controller.ts\";\nexport { clampLaneMaxUsd } from \"./research/lane-model-resolver.ts\";\n\nexport interface BackgroundLaneControllerDeps\n\textends WorkerDelegationControllerDeps,\n\t\tResearchLaneControllerDeps,\n\t\tModelFitnessControllerDeps,\n\t\tLaneModelResolverDeps {\n\t/** True iff the `goal` tool is in the session's ACTIVE surface -- the capability-adaptive gate\n\t * for every goal-continuation loop (see `continueGoalLoopExclusive`): a surface without the\n\t * goal tool (lean capability blocklist, worker role ceiling, --tools/profile exclusion) must\n\t * never be driven with continuation prompts it cannot execute. */\n\tisGoalToolActive(): boolean;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Persist an explicit stopped state when the selected surface cannot drive the active goal. */\n\tmarkGoalToolUnavailable(): void;\n}\n\nexport class BackgroundLaneController implements WorkerAgentControlPort {\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\tprivate readonly _laneModels: LaneModelResolver;\n\tprivate readonly _goalAutoContinue: GoalAutoContinueController;\n\tprivate readonly _research: ResearchLaneController;\n\tprivate readonly _fitness: ModelFitnessController;\n\t/** Lazily materialized only when managed-lane state is queried or reported. */\n\tprivate _managedLanes: ManagedLaneController | undefined;\n\t/** Lazily materialized so a UAC surface without `delegate` allocates no worker runtime state. */\n\tprivate _workers: WorkerDelegationController | undefined;\n\t/** One durable lifecycle shared by every worker execution adapter. */\n\tprivate _workerLifecycle: WorkerLifecycle | undefined;\n\t/** Shared terminal outbox for managed and in-process workers; lazy under UAC omission. */\n\tprivate _workerNotifications: WorkerNotificationCoordinator | undefined;\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\t/** Emit a warning without ever throwing — used from disposal-adjacent persistence where a\n\t * listener failure (or a bare test double missing `emit`) must never block or crash cleanup. */\n\tprivate _safeWarn(message: string): void {\n\t\ttry {\n\t\t\tthis.deps.emit({ type: \"warning\", message });\n\t\t} catch {\n\t\t\t// Dispose must never throw.\n\t\t}\n\t}\n\n\tprivate _recordWorkerTerminal(record: LaneRecord, durableNotificationId: string): void {\n\t\tthis._getWorkerNotificationCoordinator().recordTerminal(record, durableNotificationId);\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis._laneModels = new LaneModelResolver(deps);\n\t\tthis._research = new ResearchLaneController(deps, this._laneTracker, this._laneModels);\n\t\tthis._fitness = new ModelFitnessController(deps, this._laneModels);\n\t\tthis._goalAutoContinue = new GoalAutoContinueController({\n\t\t\tisDisposed: deps.isDisposed,\n\t\t\tisGoalToolActive: deps.isGoalToolActive,\n\t\t\tgetSettingsManager: deps.getSettingsManager,\n\t\t\tgetModelCapabilityProfile: deps.getModelCapabilityProfile,\n\t\t\tgetGoalRuntimeSnapshot: deps.getGoalRuntimeSnapshot,\n\t\t\thasInFlightLaneForGoal: (goalId) => this._hasInFlightLaneForGoal(goalId),\n\t\t\tcontinueGoalLoop: deps.continueGoalLoop,\n\t\t\tmarkGoalToolUnavailable: deps.markGoalToolUnavailable,\n\t\t\temit: deps.emit,\n\t\t});\n\t}\n\n\tprivate _getWorkerController(): WorkerDelegationController {\n\t\tthis._workers ??= new WorkerDelegationController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerNotificationCoordinator(),\n\t\t\tthis._getWorkerLifecycle(),\n\t\t);\n\t\treturn this._workers;\n\t}\n\n\tprivate _getWorkerLifecycle(): WorkerLifecycle {\n\t\tif (this._workerLifecycle) return this._workerLifecycle;\n\t\tconst lifecycle = new WorkerLifecycle({\n\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\tsessionId: this.deps.getSessionId(),\n\t\t});\n\t\tthis._workerLifecycle = lifecycle;\n\t\tfor (const notification of lifecycle.getPendingTerminalNotifications()) {\n\t\t\tthis._getWorkerNotificationCoordinator().recordTerminal(notification.record, notification.notificationId);\n\t\t}\n\t\treturn lifecycle;\n\t}\n\n\tprivate _getWorkerNotificationCoordinator(): WorkerNotificationCoordinator {\n\t\tthis._workerNotifications ??= new WorkerNotificationCoordinator({\n\t\t\tgetWorkerRecords: () => this._workerLifecycle?.getAllRecords() ?? [],\n\t\t\temitStatus: (status) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tterminalSinceFlush: [...status.terminalSinceFlush],\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// A partial integration must not crash the event-driven terminal outbox.\n\t\t\t\t}\n\t\t\t},\n\t\t\tnotify: (records) => this.deps.notifyWorkerTerminalHandoff(records),\n\t\t\twarn: (message) => this._safeWarn(message),\n\t\t\tmarkDurableDelivered: (notificationIds) => this._workerLifecycle?.markNotificationsDelivered(notificationIds),\n\t\t});\n\t\treturn this._workerNotifications;\n\t}\n\n\tprivate _getManagedLaneController(): ManagedLaneController {\n\t\tthis._managedLanes ??= new ManagedLaneController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerLifecycle(),\n\t\t\t(record, notificationId) => this._recordWorkerTerminal(record, notificationId),\n\t\t\t(message) => this._safeWarn(message),\n\t\t);\n\t\treturn this._managedLanes;\n\t}\n\n\tprivate _hydrateManagedLanes(): void {\n\t\tif (this._managedLanes) {\n\t\t\tthis._managedLanes.ensureHydrated();\n\t\t\treturn;\n\t\t}\n\t\tconst hasPersistedActiveManagedLane = getLatestLaneRecordSnapshots(\n\t\t\tgetActiveSessionBranchEntries(this.deps.getSessionManager()),\n\t\t).some((record) => record.type === \"tmux-worker\" && (record.status === \"queued\" || record.status === \"running\"));\n\t\tif (hasPersistedActiveManagedLane) this._getManagedLaneController().ensureHydrated();\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\tthis._hydrateManagedLanes();\n\t\tconst workerRecords =\n\t\t\tthis._workers?.getRecords() ??\n\t\t\t(this.deps.isDelegateToolActive?.() ? this._getWorkerController().getRecords() : []);\n\t\treturn [\n\t\t\t...this._laneTracker.getRecords(),\n\t\t\t...workerRecords,\n\t\t\t...(this._workerLifecycle?.getManagedRecords() ?? []),\n\t\t];\n\t}\n\n\t/** Does not materialize the worker controller when UAC omitted delegation. */\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined {\n\t\treturn this._workerLifecycle?.getTaskRuntimeSnapshot();\n\t}\n\n\t/** Reconcile only when delegation has already been materialized; UAC omission stays zero-load. */\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tthis._workers?.synchronizeGoalState(goal);\n\t}\n\n\t/**\n\t * Resolve a tracked managed-lane dispatch. The caller's stable id is also the canonical durable\n\t * lane id, so this is an existence check rather than an id translation.\n\t */\n\tresolveManagedLaneId(callerLaneId: string): string | undefined {\n\t\treturn this._getManagedLaneController().resolve(callerLaneId);\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this.getLaneRecords().filter((record) => record.status === \"queued\" || record.status === \"running\").length;\n\t}\n\n\t/** Belt-and-braces guard: whether ANY queued/running lane is tagged with this goalId. */\n\tprivate _hasInFlightLaneForGoal(goalId: string): boolean {\n\t\treturn this.getLaneRecords().some(\n\t\t\t(record) => record.goalId === goalId && (record.status === \"queued\" || record.status === \"running\"),\n\t\t);\n\t}\n\n\t/** Delegate the out-of-process dispatch/terminal claim to its single lifecycle owner. */\n\trecordManagedLane(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\treturn this._getManagedLaneController().record(event);\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._research.getLastSkipReason();\n\t}\n\n\t/**\n\t * Abort in-flight research and delegate worker disposal to its single owning controller.\n\t *\n\t * This synchronous body is the LAST provably-safe write window for canceled/in-flight work.\n\t * `dispose()` (agent-session.ts) has already set the session's own disposed flag but has not yet\n\t * returned — no successor session (e.g. a `/reload` adoption) can exist yet, so an append here\n\t * cannot interleave with one; a post-await continuation resuming AFTER this method returns must\n\t * not append (see the disposed branch in `runWorkerDelegationOnce`). Persist FIRST, then\n\t * complete-in-memory, so a throw from one lane's persist cannot skip another's; each persist gets\n\t * its own try/catch — dispose must never throw.\n\t */\n\tabortInFlightLanes(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t\tthis._research.abort();\n\t\tthis._fitness.abort();\n\t\tfor (const record of this._laneTracker.getRecords()) {\n\t\t\tif (record.status !== \"queued\" && record.status !== \"running\") continue;\n\t\t\tif (record.type === \"tmux-worker\") continue;\n\t\t\tconst canceled = this._laneTracker.complete(record.laneId, {\n\t\t\t\tstatus: \"canceled\",\n\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t});\n\t\t\tif (!canceled) continue;\n\t\t\ttry {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), canceled);\n\t\t\t} catch (error) {\n\t\t\t\tthis._safeWarn(\n\t\t\t\t\t`Failed to persist canceled lane record ${canceled.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._managedLanes?.release();\n\n\t\tthis._workers?.abort();\n\t\tthis._workerNotifications?.dispose();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tthis._goalAutoContinue.scheduleFromIdle(options);\n\t}\n\n\t/**\n\t * Single-flight entry point for EVERY goal-continuation loop invocation — idle autosteer\n\t * ({@link _runScheduledGoalAutoContinue}) AND the manual `/goal start` / `/goal-continue`\n\t * commands (reached through `AgentSession.continueGoalLoop`). Both paths ultimately submit\n\t * continuation prompts through the session's single `prompt()` path, so two loops racing throws\n\t * \"Agent is already processing\" from whichever submits second. `_isGoalAutoContinuing` is the\n\t * ONE owner of that mutex; `deps.continueGoalLoop` (the raw {@link GoalLoopController} loop)\n\t * must never be called directly outside this method, or the guard is bypassed.\n\t */\n\tasync continueGoalLoopExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this._goalAutoContinue.continueExclusive(options);\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tthis._research.clearTimer();\n\t}\n\n\tscheduleResearchLaneFromIdle(): void {\n\t\tthis._research.scheduleFromIdle();\n\t}\n\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\treturn this._laneModels.resolveModel(configuredPattern);\n\t}\n\n\tgetOrchestrationProfileCatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\treturn this._getWorkerController().getProfileCatalog();\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\treturn this._research.runOnce(request);\n\t}\n\t/** Start a durable, profile-bound worker delegation. */\n\tstartWorkerDelegation(\n\t\trequest: WorkerDelegationRequest,\n\t): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\treturn this._getWorkerController().start(request);\n\t}\n\n\t/** Durable logical-worker controls. Each checks UAC before materializing worker state. */\n\tsendWorkerAgentMessage(agentId: string, message: string): { messageId: string; queued: true } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().sendWorkerAgentMessage(agentId, message);\n\t}\n\n\tfollowUpWorkerAgent(\n\t\tagentId: string,\n\t\tmessage: string,\n\t): { started: boolean; steering: boolean; messageId: string; record?: LaneRecord; skipReason?: string } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().followUpWorkerAgent(agentId, message);\n\t}\n\n\tinterruptWorkerAgent(agentId: string): { interrupted: boolean; reason?: string } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().interruptWorkerAgent(agentId);\n\t}\n\n\tresumeWorkerAgent(agentId: string): { started: boolean; record?: LaneRecord; skipReason?: string } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().resumeWorkerAgent(agentId);\n\t}\n\n\tcancelWorkerAgent(agentId: string, reasonCode?: string): LaneRecord | undefined {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().cancelWorkerAgent(agentId, reasonCode);\n\t}\n\n\twaitForWorkerAgent(\n\t\tagentId: string,\n\t\ttimeoutMs?: number,\n\t): Promise<{ status: \"active\" | \"suspended\" | \"idle\" | \"unknown\" }> {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().waitForWorkerAgent(agentId, timeoutMs);\n\t}\n\n\t/** Run one worker immediately; used by focused integrations and tests. */\n\tasync runWorkerDelegationOnce(\n\t\trequest: WorkerDelegationRequest,\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\treturn this._getWorkerController().runOnce(request, onStarted, existingRecord);\n\t}\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t\t/** LLM tool-call id, present only via the model_fitness tool path — see model-fitness.ts. */\n\t\ttoolCallId?: string;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\treturn this._fitness.run(args);\n\t}\n\n\t/** Start every capacity-eligible queued worker at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tif (this.deps.isDelegateToolActive?.()) this._getWorkerController().drain();\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\treturn this._fitness.getStoredReports();\n\t}\n}\n"]}
@@ -111,7 +111,7 @@ export class BackgroundLaneController {
111
111
  return this._workerNotifications;
112
112
  }
113
113
  _getManagedLaneController() {
114
- this._managedLanes ??= new ManagedLaneController(this.deps, this._getWorkerLifecycle(), (record, notificationId) => this._recordWorkerTerminal(record, notificationId));
114
+ this._managedLanes ??= new ManagedLaneController(this.deps, this._getWorkerLifecycle(), (record, notificationId) => this._recordWorkerTerminal(record, notificationId), (message) => this._safeWarn(message));
115
115
  return this._managedLanes;
116
116
  }
117
117
  _hydrateManagedLanes() {
@@ -245,6 +245,37 @@ export class BackgroundLaneController {
245
245
  startWorkerDelegation(request) {
246
246
  return this._getWorkerController().start(request);
247
247
  }
248
+ /** Durable logical-worker controls. Each checks UAC before materializing worker state. */
249
+ sendWorkerAgentMessage(agentId, message) {
250
+ if (!this.deps.isDelegateToolActive())
251
+ throw new Error("Worker delegation control is unavailable in this UAC surface.");
252
+ return this._getWorkerController().getAgentControl().sendWorkerAgentMessage(agentId, message);
253
+ }
254
+ followUpWorkerAgent(agentId, message) {
255
+ if (!this.deps.isDelegateToolActive())
256
+ throw new Error("Worker delegation control is unavailable in this UAC surface.");
257
+ return this._getWorkerController().getAgentControl().followUpWorkerAgent(agentId, message);
258
+ }
259
+ interruptWorkerAgent(agentId) {
260
+ if (!this.deps.isDelegateToolActive())
261
+ throw new Error("Worker delegation control is unavailable in this UAC surface.");
262
+ return this._getWorkerController().getAgentControl().interruptWorkerAgent(agentId);
263
+ }
264
+ resumeWorkerAgent(agentId) {
265
+ if (!this.deps.isDelegateToolActive())
266
+ throw new Error("Worker delegation control is unavailable in this UAC surface.");
267
+ return this._getWorkerController().getAgentControl().resumeWorkerAgent(agentId);
268
+ }
269
+ cancelWorkerAgent(agentId, reasonCode) {
270
+ if (!this.deps.isDelegateToolActive())
271
+ throw new Error("Worker delegation control is unavailable in this UAC surface.");
272
+ return this._getWorkerController().getAgentControl().cancelWorkerAgent(agentId, reasonCode);
273
+ }
274
+ waitForWorkerAgent(agentId, timeoutMs) {
275
+ if (!this.deps.isDelegateToolActive())
276
+ throw new Error("Worker delegation control is unavailable in this UAC surface.");
277
+ return this._getWorkerController().getAgentControl().waitForWorkerAgent(agentId, timeoutMs);
278
+ }
248
279
  /** Run one worker immediately; used by focused integrations and tests. */
249
280
  async runWorkerDelegationOnce(request, onStarted, existingRecord) {
250
281
  return this._getWorkerController().runOnce(request, onStarted, existingRecord);
@@ -1 +1 @@
1
- {"version":3,"file":"background-lane-controller.js","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAUH,OAAO,EAAmB,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAC3G,OAAO,EAAE,qBAAqB,EAAE,MAAM,yCAAyC,CAAC;AAChF,OAAO,EACN,0BAA0B,GAE1B,MAAM,8CAA8C,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAEhG,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AAMtF,OAAO,EAAE,iBAAiB,EAA8B,MAAM,mCAAmC,CAAC;AAElG,OAAO,EAAE,sBAAsB,EAAmC,MAAM,wCAAwC,CAAC;AACjH,OAAO,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CAAC,CAAC;IAAA,CACxD;IAED,8BAA8B,GAAoE;QACjG,OAAO,IAAI,CAAC,oBAAoB,EAAE,CAAC,iBAAiB,EAAE,CAAC;IAAA,CACvD;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,OAIzB,EAAmC;QACnC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAAA,CACvC;IACD,wDAAwD;IACxD,qBAAqB,CACpB,OAAgC,EACiD;QACjF,OAAO,IAAI,CAAC,oBAAoB,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAAA,CAClD;IAED,0EAA0E;IAC1E,KAAK,CAAC,uBAAuB,CAC5B,OAAgC,EAChC,SAAwC,EACxC,cAA2B,EACW;QACtC,OAAO,IAAI,CAAC,oBAAoB,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,cAAc,CAAC,CAAC;IAAA,CAC/E;IACD;;;;;OAKG;IACH,KAAK,CAAC,eAAe,CAAC,IAKrB,EAAkH;QAClH,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAAA,CAC/B;IAED,mGAAmG;IACnG,4BAA4B,GAAS;QACpC,IAAI,IAAI,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE;YAAE,IAAI,CAAC,oBAAoB,EAAE,CAAC,KAAK,EAAE,CAAC;IAAA,CAC5E;IAED,mGAAmG;IACnG,uBAAuB,GAA0B;QAChD,OAAO,IAAI,CAAC,QAAQ,CAAC,gBAAgB,EAAE,CAAC;IAAA,CACxC;CACD","sourcesContent":["/**\n * Execution-plane coordinator for goal continuation, research, managed lanes, worker delegation,\n * and model fitness.\n *\n * Coordination state is owned by focused controllers. This coordinator retains one AgentSession\n * composition seam and a shared lane read model. Everything it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session-contracts.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { ManagedLaneController } from \"./delegation/managed-lane-controller.ts\";\nimport {\n\tWorkerDelegationController,\n\ttype WorkerDelegationControllerDeps,\n} from \"./delegation/worker-delegation-controller.ts\";\nimport type { WorkerDelegationRequest } from \"./delegation/worker-delegation-request.ts\";\nimport { WorkerLifecycle } from \"./delegation/worker-lifecycle.ts\";\nimport { WorkerNotificationCoordinator } from \"./delegation/worker-notification-coordinator.ts\";\nimport type { ManagedLaneEvent } from \"./extensions/types.ts\";\nimport { GoalAutoContinueController } from \"./goals/goal-auto-continue-controller.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { TaskRuntimeProjection } from \"./orchestration/task-runtime.ts\";\nimport { LaneModelResolver, type LaneModelResolverDeps } from \"./research/lane-model-resolver.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport { ModelFitnessController, type ModelFitnessControllerDeps } from \"./research/model-fitness-controller.ts\";\nimport { ResearchLaneController, type ResearchLaneControllerDeps } from \"./research/research-lane-controller.ts\";\nimport { getActiveSessionBranchEntries } from \"./session-snapshot.ts\";\n\nexport { isLocalExecutionModel } from \"./delegation/worker-delegation-controller.ts\";\nexport { clampLaneMaxUsd } from \"./research/lane-model-resolver.ts\";\n\nexport interface BackgroundLaneControllerDeps\n\textends WorkerDelegationControllerDeps,\n\t\tResearchLaneControllerDeps,\n\t\tModelFitnessControllerDeps,\n\t\tLaneModelResolverDeps {\n\t/** True iff the `goal` tool is in the session's ACTIVE surface -- the capability-adaptive gate\n\t * for every goal-continuation loop (see `continueGoalLoopExclusive`): a surface without the\n\t * goal tool (lean capability blocklist, worker role ceiling, --tools/profile exclusion) must\n\t * never be driven with continuation prompts it cannot execute. */\n\tisGoalToolActive(): boolean;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Persist an explicit stopped state when the selected surface cannot drive the active goal. */\n\tmarkGoalToolUnavailable(): void;\n}\n\nexport class BackgroundLaneController {\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\tprivate readonly _laneModels: LaneModelResolver;\n\tprivate readonly _goalAutoContinue: GoalAutoContinueController;\n\tprivate readonly _research: ResearchLaneController;\n\tprivate readonly _fitness: ModelFitnessController;\n\t/** Lazily materialized only when managed-lane state is queried or reported. */\n\tprivate _managedLanes: ManagedLaneController | undefined;\n\t/** Lazily materialized so a UAC surface without `delegate` allocates no worker runtime state. */\n\tprivate _workers: WorkerDelegationController | undefined;\n\t/** One durable lifecycle shared by every worker execution adapter. */\n\tprivate _workerLifecycle: WorkerLifecycle | undefined;\n\t/** Shared terminal outbox for managed and in-process workers; lazy under UAC omission. */\n\tprivate _workerNotifications: WorkerNotificationCoordinator | undefined;\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\t/** Emit a warning without ever throwing — used from disposal-adjacent persistence where a\n\t * listener failure (or a bare test double missing `emit`) must never block or crash cleanup. */\n\tprivate _safeWarn(message: string): void {\n\t\ttry {\n\t\t\tthis.deps.emit({ type: \"warning\", message });\n\t\t} catch {\n\t\t\t// Dispose must never throw.\n\t\t}\n\t}\n\n\tprivate _recordWorkerTerminal(record: LaneRecord, durableNotificationId: string): void {\n\t\tthis._getWorkerNotificationCoordinator().recordTerminal(record, durableNotificationId);\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis._laneModels = new LaneModelResolver(deps);\n\t\tthis._research = new ResearchLaneController(deps, this._laneTracker, this._laneModels);\n\t\tthis._fitness = new ModelFitnessController(deps, this._laneModels);\n\t\tthis._goalAutoContinue = new GoalAutoContinueController({\n\t\t\tisDisposed: deps.isDisposed,\n\t\t\tisGoalToolActive: deps.isGoalToolActive,\n\t\t\tgetSettingsManager: deps.getSettingsManager,\n\t\t\tgetModelCapabilityProfile: deps.getModelCapabilityProfile,\n\t\t\tgetGoalRuntimeSnapshot: deps.getGoalRuntimeSnapshot,\n\t\t\thasInFlightLaneForGoal: (goalId) => this._hasInFlightLaneForGoal(goalId),\n\t\t\tcontinueGoalLoop: deps.continueGoalLoop,\n\t\t\tmarkGoalToolUnavailable: deps.markGoalToolUnavailable,\n\t\t\temit: deps.emit,\n\t\t});\n\t}\n\n\tprivate _getWorkerController(): WorkerDelegationController {\n\t\tthis._workers ??= new WorkerDelegationController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerNotificationCoordinator(),\n\t\t\tthis._getWorkerLifecycle(),\n\t\t);\n\t\treturn this._workers;\n\t}\n\n\tprivate _getWorkerLifecycle(): WorkerLifecycle {\n\t\tif (this._workerLifecycle) return this._workerLifecycle;\n\t\tconst lifecycle = new WorkerLifecycle({\n\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\tsessionId: this.deps.getSessionId(),\n\t\t});\n\t\tthis._workerLifecycle = lifecycle;\n\t\tfor (const notification of lifecycle.getPendingTerminalNotifications()) {\n\t\t\tthis._getWorkerNotificationCoordinator().recordTerminal(notification.record, notification.notificationId);\n\t\t}\n\t\treturn lifecycle;\n\t}\n\n\tprivate _getWorkerNotificationCoordinator(): WorkerNotificationCoordinator {\n\t\tthis._workerNotifications ??= new WorkerNotificationCoordinator({\n\t\t\tgetWorkerRecords: () => this._workerLifecycle?.getAllRecords() ?? [],\n\t\t\temitStatus: (status) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tterminalSinceFlush: [...status.terminalSinceFlush],\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// A partial integration must not crash the event-driven terminal outbox.\n\t\t\t\t}\n\t\t\t},\n\t\t\tnotify: (records) => this.deps.notifyWorkerTerminalHandoff(records),\n\t\t\twarn: (message) => this._safeWarn(message),\n\t\t\tmarkDurableDelivered: (notificationIds) => this._workerLifecycle?.markNotificationsDelivered(notificationIds),\n\t\t});\n\t\treturn this._workerNotifications;\n\t}\n\n\tprivate _getManagedLaneController(): ManagedLaneController {\n\t\tthis._managedLanes ??= new ManagedLaneController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerLifecycle(),\n\t\t\t(record, notificationId) => this._recordWorkerTerminal(record, notificationId),\n\t\t);\n\t\treturn this._managedLanes;\n\t}\n\n\tprivate _hydrateManagedLanes(): void {\n\t\tif (this._managedLanes) {\n\t\t\tthis._managedLanes.ensureHydrated();\n\t\t\treturn;\n\t\t}\n\t\tconst hasPersistedActiveManagedLane = getLatestLaneRecordSnapshots(\n\t\t\tgetActiveSessionBranchEntries(this.deps.getSessionManager()),\n\t\t).some((record) => record.type === \"tmux-worker\" && (record.status === \"queued\" || record.status === \"running\"));\n\t\tif (hasPersistedActiveManagedLane) this._getManagedLaneController().ensureHydrated();\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\tthis._hydrateManagedLanes();\n\t\tconst workerRecords =\n\t\t\tthis._workers?.getRecords() ??\n\t\t\t(this.deps.isDelegateToolActive?.() ? this._getWorkerController().getRecords() : []);\n\t\treturn [\n\t\t\t...this._laneTracker.getRecords(),\n\t\t\t...workerRecords,\n\t\t\t...(this._workerLifecycle?.getManagedRecords() ?? []),\n\t\t];\n\t}\n\n\t/** Does not materialize the worker controller when UAC omitted delegation. */\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined {\n\t\treturn this._workerLifecycle?.getTaskRuntimeSnapshot();\n\t}\n\n\t/** Reconcile only when delegation has already been materialized; UAC omission stays zero-load. */\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tthis._workers?.synchronizeGoalState(goal);\n\t}\n\n\t/**\n\t * Resolve a tracked managed-lane dispatch. The caller's stable id is also the canonical durable\n\t * lane id, so this is an existence check rather than an id translation.\n\t */\n\tresolveManagedLaneId(callerLaneId: string): string | undefined {\n\t\treturn this._getManagedLaneController().resolve(callerLaneId);\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this.getLaneRecords().filter((record) => record.status === \"queued\" || record.status === \"running\").length;\n\t}\n\n\t/** Belt-and-braces guard: whether ANY queued/running lane is tagged with this goalId. */\n\tprivate _hasInFlightLaneForGoal(goalId: string): boolean {\n\t\treturn this.getLaneRecords().some(\n\t\t\t(record) => record.goalId === goalId && (record.status === \"queued\" || record.status === \"running\"),\n\t\t);\n\t}\n\n\t/** Delegate the out-of-process dispatch/terminal claim to its single lifecycle owner. */\n\trecordManagedLane(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\treturn this._getManagedLaneController().record(event);\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._research.getLastSkipReason();\n\t}\n\n\t/**\n\t * Abort in-flight research and delegate worker disposal to its single owning controller.\n\t *\n\t * This synchronous body is the LAST provably-safe write window for canceled/in-flight work.\n\t * `dispose()` (agent-session.ts) has already set the session's own disposed flag but has not yet\n\t * returned — no successor session (e.g. a `/reload` adoption) can exist yet, so an append here\n\t * cannot interleave with one; a post-await continuation resuming AFTER this method returns must\n\t * not append (see the disposed branch in `runWorkerDelegationOnce`). Persist FIRST, then\n\t * complete-in-memory, so a throw from one lane's persist cannot skip another's; each persist gets\n\t * its own try/catch — dispose must never throw.\n\t */\n\tabortInFlightLanes(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t\tthis._research.abort();\n\t\tthis._fitness.abort();\n\t\tfor (const record of this._laneTracker.getRecords()) {\n\t\t\tif (record.status !== \"queued\" && record.status !== \"running\") continue;\n\t\t\tif (record.type === \"tmux-worker\") continue;\n\t\t\tconst canceled = this._laneTracker.complete(record.laneId, {\n\t\t\t\tstatus: \"canceled\",\n\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t});\n\t\t\tif (!canceled) continue;\n\t\t\ttry {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), canceled);\n\t\t\t} catch (error) {\n\t\t\t\tthis._safeWarn(\n\t\t\t\t\t`Failed to persist canceled lane record ${canceled.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._managedLanes?.release();\n\n\t\tthis._workers?.abort();\n\t\tthis._workerNotifications?.dispose();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tthis._goalAutoContinue.scheduleFromIdle(options);\n\t}\n\n\t/**\n\t * Single-flight entry point for EVERY goal-continuation loop invocation — idle autosteer\n\t * ({@link _runScheduledGoalAutoContinue}) AND the manual `/goal start` / `/goal-continue`\n\t * commands (reached through `AgentSession.continueGoalLoop`). Both paths ultimately submit\n\t * continuation prompts through the session's single `prompt()` path, so two loops racing throws\n\t * \"Agent is already processing\" from whichever submits second. `_isGoalAutoContinuing` is the\n\t * ONE owner of that mutex; `deps.continueGoalLoop` (the raw {@link GoalLoopController} loop)\n\t * must never be called directly outside this method, or the guard is bypassed.\n\t */\n\tasync continueGoalLoopExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this._goalAutoContinue.continueExclusive(options);\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tthis._research.clearTimer();\n\t}\n\n\tscheduleResearchLaneFromIdle(): void {\n\t\tthis._research.scheduleFromIdle();\n\t}\n\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\treturn this._laneModels.resolveModel(configuredPattern);\n\t}\n\n\tgetOrchestrationProfileCatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\treturn this._getWorkerController().getProfileCatalog();\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\treturn this._research.runOnce(request);\n\t}\n\t/** Start a durable, profile-bound worker delegation. */\n\tstartWorkerDelegation(\n\t\trequest: WorkerDelegationRequest,\n\t): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\treturn this._getWorkerController().start(request);\n\t}\n\n\t/** Run one worker immediately; used by focused integrations and tests. */\n\tasync runWorkerDelegationOnce(\n\t\trequest: WorkerDelegationRequest,\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\treturn this._getWorkerController().runOnce(request, onStarted, existingRecord);\n\t}\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t\t/** LLM tool-call id, present only via the model_fitness tool path — see model-fitness.ts. */\n\t\ttoolCallId?: string;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\treturn this._fitness.run(args);\n\t}\n\n\t/** Start every capacity-eligible queued worker at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tif (this.deps.isDelegateToolActive?.()) this._getWorkerController().drain();\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\treturn this._fitness.getStoredReports();\n\t}\n}\n"]}
1
+ {"version":3,"file":"background-lane-controller.js","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAUH,OAAO,EAAmB,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAC3G,OAAO,EAAE,qBAAqB,EAAE,MAAM,yCAAyC,CAAC;AAEhF,OAAO,EACN,0BAA0B,GAE1B,MAAM,8CAA8C,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,EAAE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A,CAC/E;IACD;;;;;OAKG;IACH,KAAK,CAAC,eAAe,CAAC,IAKrB,EAAkH;QAClH,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAAA,CAC/B;IAED,mGAAmG;IACnG,4BAA4B,GAAS;QACpC,IAAI,IAAI,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE;YAAE,IAAI,CAAC,oBAAoB,EAAE,CAAC,KAAK,EAAE,CAAC;IAAA,CAC5E;IAED,mGAAmG;IACnG,uBAAuB,GAA0B;QAChD,OAAO,IAAI,CAAC,QAAQ,CAAC,gBAAgB,EAAE,CAAC;IAAA,CACxC;CACD","sourcesContent":["/**\n * Execution-plane coordinator for goal continuation, research, managed lanes, worker delegation,\n * and model fitness.\n *\n * Coordination state is owned by focused controllers. This coordinator retains one AgentSession\n * composition seam and a shared lane read model. Everything it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session-contracts.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { ManagedLaneController } from \"./delegation/managed-lane-controller.ts\";\nimport type { WorkerAgentControlPort } from \"./delegation/worker-agent-control.ts\";\nimport {\n\tWorkerDelegationController,\n\ttype WorkerDelegationControllerDeps,\n} from \"./delegation/worker-delegation-controller.ts\";\nimport type { WorkerDelegationRequest } from \"./delegation/worker-delegation-request.ts\";\nimport { WorkerLifecycle } from \"./delegation/worker-lifecycle.ts\";\nimport { WorkerNotificationCoordinator } from \"./delegation/worker-notification-coordinator.ts\";\nimport type { ManagedLaneEvent } from \"./extensions/types.ts\";\nimport { GoalAutoContinueController } from \"./goals/goal-auto-continue-controller.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { TaskRuntimeProjection } from \"./orchestration/task-runtime.ts\";\nimport { LaneModelResolver, type LaneModelResolverDeps } from \"./research/lane-model-resolver.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport { ModelFitnessController, type ModelFitnessControllerDeps } from \"./research/model-fitness-controller.ts\";\nimport { ResearchLaneController, type ResearchLaneControllerDeps } from \"./research/research-lane-controller.ts\";\nimport { getActiveSessionBranchEntries } from \"./session-snapshot.ts\";\n\nexport { isLocalExecutionModel } from \"./delegation/worker-delegation-controller.ts\";\nexport { clampLaneMaxUsd } from \"./research/lane-model-resolver.ts\";\n\nexport interface BackgroundLaneControllerDeps\n\textends WorkerDelegationControllerDeps,\n\t\tResearchLaneControllerDeps,\n\t\tModelFitnessControllerDeps,\n\t\tLaneModelResolverDeps {\n\t/** True iff the `goal` tool is in the session's ACTIVE surface -- the capability-adaptive gate\n\t * for every goal-continuation loop (see `continueGoalLoopExclusive`): a surface without the\n\t * goal tool (lean capability blocklist, worker role ceiling, --tools/profile exclusion) must\n\t * never be driven with continuation prompts it cannot execute. */\n\tisGoalToolActive(): boolean;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Persist an explicit stopped state when the selected surface cannot drive the active goal. */\n\tmarkGoalToolUnavailable(): void;\n}\n\nexport class BackgroundLaneController implements WorkerAgentControlPort {\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\tprivate readonly _laneModels: LaneModelResolver;\n\tprivate readonly _goalAutoContinue: GoalAutoContinueController;\n\tprivate readonly _research: ResearchLaneController;\n\tprivate readonly _fitness: ModelFitnessController;\n\t/** Lazily materialized only when managed-lane state is queried or reported. */\n\tprivate _managedLanes: ManagedLaneController | undefined;\n\t/** Lazily materialized so a UAC surface without `delegate` allocates no worker runtime state. */\n\tprivate _workers: WorkerDelegationController | undefined;\n\t/** One durable lifecycle shared by every worker execution adapter. */\n\tprivate _workerLifecycle: WorkerLifecycle | undefined;\n\t/** Shared terminal outbox for managed and in-process workers; lazy under UAC omission. */\n\tprivate _workerNotifications: WorkerNotificationCoordinator | undefined;\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\t/** Emit a warning without ever throwing — used from disposal-adjacent persistence where a\n\t * listener failure (or a bare test double missing `emit`) must never block or crash cleanup. */\n\tprivate _safeWarn(message: string): void {\n\t\ttry {\n\t\t\tthis.deps.emit({ type: \"warning\", message });\n\t\t} catch {\n\t\t\t// Dispose must never throw.\n\t\t}\n\t}\n\n\tprivate _recordWorkerTerminal(record: LaneRecord, durableNotificationId: string): void {\n\t\tthis._getWorkerNotificationCoordinator().recordTerminal(record, durableNotificationId);\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis._laneModels = new LaneModelResolver(deps);\n\t\tthis._research = new ResearchLaneController(deps, this._laneTracker, this._laneModels);\n\t\tthis._fitness = new ModelFitnessController(deps, this._laneModels);\n\t\tthis._goalAutoContinue = new GoalAutoContinueController({\n\t\t\tisDisposed: deps.isDisposed,\n\t\t\tisGoalToolActive: deps.isGoalToolActive,\n\t\t\tgetSettingsManager: deps.getSettingsManager,\n\t\t\tgetModelCapabilityProfile: deps.getModelCapabilityProfile,\n\t\t\tgetGoalRuntimeSnapshot: deps.getGoalRuntimeSnapshot,\n\t\t\thasInFlightLaneForGoal: (goalId) => this._hasInFlightLaneForGoal(goalId),\n\t\t\tcontinueGoalLoop: deps.continueGoalLoop,\n\t\t\tmarkGoalToolUnavailable: deps.markGoalToolUnavailable,\n\t\t\temit: deps.emit,\n\t\t});\n\t}\n\n\tprivate _getWorkerController(): WorkerDelegationController {\n\t\tthis._workers ??= new WorkerDelegationController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerNotificationCoordinator(),\n\t\t\tthis._getWorkerLifecycle(),\n\t\t);\n\t\treturn this._workers;\n\t}\n\n\tprivate _getWorkerLifecycle(): WorkerLifecycle {\n\t\tif (this._workerLifecycle) return this._workerLifecycle;\n\t\tconst lifecycle = new WorkerLifecycle({\n\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\tsessionId: this.deps.getSessionId(),\n\t\t});\n\t\tthis._workerLifecycle = lifecycle;\n\t\tfor (const notification of lifecycle.getPendingTerminalNotifications()) {\n\t\t\tthis._getWorkerNotificationCoordinator().recordTerminal(notification.record, notification.notificationId);\n\t\t}\n\t\treturn lifecycle;\n\t}\n\n\tprivate _getWorkerNotificationCoordinator(): WorkerNotificationCoordinator {\n\t\tthis._workerNotifications ??= new WorkerNotificationCoordinator({\n\t\t\tgetWorkerRecords: () => this._workerLifecycle?.getAllRecords() ?? [],\n\t\t\temitStatus: (status) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tterminalSinceFlush: [...status.terminalSinceFlush],\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// A partial integration must not crash the event-driven terminal outbox.\n\t\t\t\t}\n\t\t\t},\n\t\t\tnotify: (records) => this.deps.notifyWorkerTerminalHandoff(records),\n\t\t\twarn: (message) => this._safeWarn(message),\n\t\t\tmarkDurableDelivered: (notificationIds) => this._workerLifecycle?.markNotificationsDelivered(notificationIds),\n\t\t});\n\t\treturn this._workerNotifications;\n\t}\n\n\tprivate _getManagedLaneController(): ManagedLaneController {\n\t\tthis._managedLanes ??= new ManagedLaneController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerLifecycle(),\n\t\t\t(record, notificationId) => this._recordWorkerTerminal(record, notificationId),\n\t\t\t(message) => this._safeWarn(message),\n\t\t);\n\t\treturn this._managedLanes;\n\t}\n\n\tprivate _hydrateManagedLanes(): void {\n\t\tif (this._managedLanes) {\n\t\t\tthis._managedLanes.ensureHydrated();\n\t\t\treturn;\n\t\t}\n\t\tconst hasPersistedActiveManagedLane = getLatestLaneRecordSnapshots(\n\t\t\tgetActiveSessionBranchEntries(this.deps.getSessionManager()),\n\t\t).some((record) => record.type === \"tmux-worker\" && (record.status === \"queued\" || record.status === \"running\"));\n\t\tif (hasPersistedActiveManagedLane) this._getManagedLaneController().ensureHydrated();\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\tthis._hydrateManagedLanes();\n\t\tconst workerRecords =\n\t\t\tthis._workers?.getRecords() ??\n\t\t\t(this.deps.isDelegateToolActive?.() ? this._getWorkerController().getRecords() : []);\n\t\treturn [\n\t\t\t...this._laneTracker.getRecords(),\n\t\t\t...workerRecords,\n\t\t\t...(this._workerLifecycle?.getManagedRecords() ?? []),\n\t\t];\n\t}\n\n\t/** Does not materialize the worker controller when UAC omitted delegation. */\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined {\n\t\treturn this._workerLifecycle?.getTaskRuntimeSnapshot();\n\t}\n\n\t/** Reconcile only when delegation has already been materialized; UAC omission stays zero-load. */\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tthis._workers?.synchronizeGoalState(goal);\n\t}\n\n\t/**\n\t * Resolve a tracked managed-lane dispatch. The caller's stable id is also the canonical durable\n\t * lane id, so this is an existence check rather than an id translation.\n\t */\n\tresolveManagedLaneId(callerLaneId: string): string | undefined {\n\t\treturn this._getManagedLaneController().resolve(callerLaneId);\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this.getLaneRecords().filter((record) => record.status === \"queued\" || record.status === \"running\").length;\n\t}\n\n\t/** Belt-and-braces guard: whether ANY queued/running lane is tagged with this goalId. */\n\tprivate _hasInFlightLaneForGoal(goalId: string): boolean {\n\t\treturn this.getLaneRecords().some(\n\t\t\t(record) => record.goalId === goalId && (record.status === \"queued\" || record.status === \"running\"),\n\t\t);\n\t}\n\n\t/** Delegate the out-of-process dispatch/terminal claim to its single lifecycle owner. */\n\trecordManagedLane(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\treturn this._getManagedLaneController().record(event);\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._research.getLastSkipReason();\n\t}\n\n\t/**\n\t * Abort in-flight research and delegate worker disposal to its single owning controller.\n\t *\n\t * This synchronous body is the LAST provably-safe write window for canceled/in-flight work.\n\t * `dispose()` (agent-session.ts) has already set the session's own disposed flag but has not yet\n\t * returned — no successor session (e.g. a `/reload` adoption) can exist yet, so an append here\n\t * cannot interleave with one; a post-await continuation resuming AFTER this method returns must\n\t * not append (see the disposed branch in `runWorkerDelegationOnce`). Persist FIRST, then\n\t * complete-in-memory, so a throw from one lane's persist cannot skip another's; each persist gets\n\t * its own try/catch — dispose must never throw.\n\t */\n\tabortInFlightLanes(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t\tthis._research.abort();\n\t\tthis._fitness.abort();\n\t\tfor (const record of this._laneTracker.getRecords()) {\n\t\t\tif (record.status !== \"queued\" && record.status !== \"running\") continue;\n\t\t\tif (record.type === \"tmux-worker\") continue;\n\t\t\tconst canceled = this._laneTracker.complete(record.laneId, {\n\t\t\t\tstatus: \"canceled\",\n\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t});\n\t\t\tif (!canceled) continue;\n\t\t\ttry {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), canceled);\n\t\t\t} catch (error) {\n\t\t\t\tthis._safeWarn(\n\t\t\t\t\t`Failed to persist canceled lane record ${canceled.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._managedLanes?.release();\n\n\t\tthis._workers?.abort();\n\t\tthis._workerNotifications?.dispose();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tthis._goalAutoContinue.scheduleFromIdle(options);\n\t}\n\n\t/**\n\t * Single-flight entry point for EVERY goal-continuation loop invocation — idle autosteer\n\t * ({@link _runScheduledGoalAutoContinue}) AND the manual `/goal start` / `/goal-continue`\n\t * commands (reached through `AgentSession.continueGoalLoop`). Both paths ultimately submit\n\t * continuation prompts through the session's single `prompt()` path, so two loops racing throws\n\t * \"Agent is already processing\" from whichever submits second. `_isGoalAutoContinuing` is the\n\t * ONE owner of that mutex; `deps.continueGoalLoop` (the raw {@link GoalLoopController} loop)\n\t * must never be called directly outside this method, or the guard is bypassed.\n\t */\n\tasync continueGoalLoopExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this._goalAutoContinue.continueExclusive(options);\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tthis._research.clearTimer();\n\t}\n\n\tscheduleResearchLaneFromIdle(): void {\n\t\tthis._research.scheduleFromIdle();\n\t}\n\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\treturn this._laneModels.resolveModel(configuredPattern);\n\t}\n\n\tgetOrchestrationProfileCatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\treturn this._getWorkerController().getProfileCatalog();\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\treturn this._research.runOnce(request);\n\t}\n\t/** Start a durable, profile-bound worker delegation. */\n\tstartWorkerDelegation(\n\t\trequest: WorkerDelegationRequest,\n\t): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\treturn this._getWorkerController().start(request);\n\t}\n\n\t/** Durable logical-worker controls. Each checks UAC before materializing worker state. */\n\tsendWorkerAgentMessage(agentId: string, message: string): { messageId: string; queued: true } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().sendWorkerAgentMessage(agentId, message);\n\t}\n\n\tfollowUpWorkerAgent(\n\t\tagentId: string,\n\t\tmessage: string,\n\t): { started: boolean; steering: boolean; messageId: string; record?: LaneRecord; skipReason?: string } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().followUpWorkerAgent(agentId, message);\n\t}\n\n\tinterruptWorkerAgent(agentId: string): { interrupted: boolean; reason?: string } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().interruptWorkerAgent(agentId);\n\t}\n\n\tresumeWorkerAgent(agentId: string): { started: boolean; record?: LaneRecord; skipReason?: string } {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().resumeWorkerAgent(agentId);\n\t}\n\n\tcancelWorkerAgent(agentId: string, reasonCode?: string): LaneRecord | undefined {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().cancelWorkerAgent(agentId, reasonCode);\n\t}\n\n\twaitForWorkerAgent(\n\t\tagentId: string,\n\t\ttimeoutMs?: number,\n\t): Promise<{ status: \"active\" | \"suspended\" | \"idle\" | \"unknown\" }> {\n\t\tif (!this.deps.isDelegateToolActive())\n\t\t\tthrow new Error(\"Worker delegation control is unavailable in this UAC surface.\");\n\t\treturn this._getWorkerController().getAgentControl().waitForWorkerAgent(agentId, timeoutMs);\n\t}\n\n\t/** Run one worker immediately; used by focused integrations and tests. */\n\tasync runWorkerDelegationOnce(\n\t\trequest: WorkerDelegationRequest,\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\treturn this._getWorkerController().runOnce(request, onStarted, existingRecord);\n\t}\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t\t/** LLM tool-call id, present only via the model_fitness tool path — see model-fitness.ts. */\n\t\ttoolCallId?: string;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\treturn this._fitness.run(args);\n\t}\n\n\t/** Start every capacity-eligible queued worker at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tif (this.deps.isDelegateToolActive?.()) this._getWorkerController().drain();\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\treturn this._fitness.getStoredReports();\n\t}\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { SessionManager } from "@caupulican/pi-agent-core/node";
2
+ import type { Usage } from "@caupulican/pi-ai";
2
3
  import type { CapabilityEnvelope, WorkerClaim, WorkerClaimStatus, WorkerRequest } from "../autonomy/contracts.ts";
3
4
  import { type LaneRecord, type LaneTerminalStatus } from "../autonomy/lane-tracker.ts";
4
5
  import type { ManagedLaneEvent } from "../extensions/types.ts";
@@ -14,21 +15,30 @@ export interface ManagedLaneControllerDeps {
14
15
  getGoalStateSnapshot(): GoalState | undefined;
15
16
  getCapabilityEnvelope(): CapabilityEnvelope | undefined;
16
17
  saveWorkerClaimSnapshot(claim: WorkerClaim, request?: WorkerRequest): string;
18
+ /** Optional only for minimal host embeddings; normal AgentSession integration always supplies this. */
19
+ addSpawnedUsage?(usage: Usage, opts: {
20
+ label?: string;
21
+ sourceSessionId?: string;
22
+ reportId: string;
23
+ }): string | undefined;
17
24
  }
18
25
  /** Out-of-process adapter over the same durable worker lifecycle used by in-process delegation. */
19
26
  export declare class ManagedLaneController {
20
27
  private readonly deps;
21
28
  private readonly lifecycle;
22
29
  private readonly recordTerminal;
30
+ private readonly warn;
23
31
  private readonly deregisterByLane;
24
32
  private hydrated;
25
- constructor(deps: ManagedLaneControllerDeps, lifecycle: WorkerLifecycle, recordTerminal: (record: LaneRecord, durableNotificationId: string) => void);
33
+ constructor(deps: ManagedLaneControllerDeps, lifecycle: WorkerLifecycle, recordTerminal: (record: LaneRecord, durableNotificationId: string) => void, warn?: (message: string) => void);
26
34
  ensureHydrated(): void;
27
35
  resolve(callerLaneId: string): string | undefined;
28
36
  record(event: ManagedLaneEvent): LaneRecord | undefined;
29
37
  release(): void;
30
38
  private ensureRegistration;
31
39
  private releaseRegistration;
40
+ /** A replay after a crash between claim append and lifecycle finalization must not duplicate the claim. */
41
+ private hasPersistedClaimForAttempt;
32
42
  private compileGrant;
33
43
  }
34
44
  //# sourceMappingURL=managed-lane-controller.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"managed-lane-controller.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/managed-lane-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAElH,OAAO,EAAwB,KAAK,UAAU,EAAE,KAAK,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAE7G,OAAO,KAAK,EAAuB,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAOxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAK7D,wBAAgB,gCAAgC,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,kBAAkB,CAc/F;AAED,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,kBAAkB,GAAG,iBAAiB,CAW1F;AAED,MAAM,WAAW,yBAAyB;IACzC,UAAU,IAAI,OAAO,CAAC;IACtB,WAAW,IAAI,MAAM,CAAC;IACtB,MAAM,IAAI,MAAM,CAAC;IACjB,iBAAiB,IAAI,cAAc,CAAC;IACpC,oBAAoB,IAAI,SAAS,GAAG,SAAS,CAAC;IAC9C,qBAAqB,IAAI,kBAAkB,GAAG,SAAS,CAAC;IACxD,uBAAuB,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM,CAAC;CAC7E;AAED,mGAAmG;AACnG,qBAAa,qBAAqB;IACjC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA4B;IACjD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAkB;IAC5C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAA8D;IAC7F,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAiC;IAClE,OAAO,CAAC,QAAQ,CAAS;IAEzB,YACC,IAAI,EAAE,yBAAyB,EAC/B,SAAS,EAAE,eAAe,EAC1B,cAAc,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,qBAAqB,EAAE,MAAM,KAAK,IAAI,EAK3E;IAED,cAAc,IAAI,IAAI,CAwCrB;IAED,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIhD;IAED,MAAM,CAAC,KAAK,EAAE,gBAAgB,GAAG,UAAU,GAAG,SAAS,CAmFtD;IAED,OAAO,IAAI,IAAI,CAGd;IAED,OAAO,CAAC,kBAAkB;IAK1B,OAAO,CAAC,mBAAmB;IAK3B,OAAO,CAAC,YAAY;CAyBpB","sourcesContent":["import type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { CapabilityEnvelope, WorkerClaim, WorkerClaimStatus, WorkerRequest } from \"../autonomy/contracts.ts\";\nimport { getPrivateLaneDeniedPaths } from \"../autonomy/lane-private-paths.ts\";\nimport { isLaneTerminalStatus, type LaneRecord, type LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"../autonomy/session-lane-record.ts\";\nimport type { ManagedLaneDispatch, ManagedLaneEvent } from \"../extensions/types.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport type { ExecutionGrant } from \"../orchestration/contracts.ts\";\nimport { createWorkerResultContract } from \"../orchestration/worker-result-adapter.ts\";\nimport { registerInFlightWork } from \"../reload-blockers.ts\";\nimport { getActiveSessionBranchEntries } from \"../session-snapshot.ts\";\nimport { reviewManagedLaneChangedFiles } from \"./worker-claim.ts\";\nimport { compileManagedProcessExecutionGrant } from \"./worker-execution-policy.ts\";\nimport type { WorkerLifecycle } from \"./worker-lifecycle.ts\";\n\nconst LEGACY_MANAGED_LEASE_TTL_MS = 24 * 60 * 60 * 1_000;\nconst LEGACY_MANAGED_READ_TOOLS = [\"read\", \"grep\", \"find\", \"ls\"] as const;\n\nexport function resolveManagedLaneTerminalStatus(status: string | undefined): LaneTerminalStatus {\n\tif (isLaneTerminalStatus(status)) return status;\n\tswitch (status) {\n\t\tcase \"done\":\n\t\tcase \"completed\":\n\t\t\treturn \"succeeded\";\n\t\tcase \"blocked\":\n\t\t\treturn \"failed\";\n\t\tcase \"dismissed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"canceled\";\n\t\tdefault:\n\t\t\treturn \"failed\";\n\t}\n}\n\nexport function mapManagedLaneTerminalStatus(status: LaneTerminalStatus): WorkerClaimStatus {\n\tswitch (status) {\n\t\tcase \"succeeded\":\n\t\t\treturn \"completed\";\n\t\tcase \"canceled\":\n\t\t\treturn \"cancelled\";\n\t\tcase \"failed\":\n\t\tcase \"timeout\":\n\t\tcase \"budget_exhausted\":\n\t\t\treturn \"failed\";\n\t}\n}\n\nexport interface ManagedLaneControllerDeps {\n\tisDisposed(): boolean;\n\tgetAgentDir(): string;\n\tgetCwd(): string;\n\tgetSessionManager(): SessionManager;\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\tsaveWorkerClaimSnapshot(claim: WorkerClaim, request?: WorkerRequest): string;\n}\n\n/** Out-of-process adapter over the same durable worker lifecycle used by in-process delegation. */\nexport class ManagedLaneController {\n\tprivate readonly deps: ManagedLaneControllerDeps;\n\tprivate readonly lifecycle: WorkerLifecycle;\n\tprivate readonly recordTerminal: (record: LaneRecord, durableNotificationId: string) => void;\n\tprivate readonly deregisterByLane = new Map<string, () => void>();\n\tprivate hydrated = false;\n\n\tconstructor(\n\t\tdeps: ManagedLaneControllerDeps,\n\t\tlifecycle: WorkerLifecycle,\n\t\trecordTerminal: (record: LaneRecord, durableNotificationId: string) => void,\n\t) {\n\t\tthis.deps = deps;\n\t\tthis.lifecycle = lifecycle;\n\t\tthis.recordTerminal = recordTerminal;\n\t}\n\n\tensureHydrated(): void {\n\t\tif (this.hydrated) return;\n\t\tthis.hydrated = true;\n\t\tconst durableIds = new Set(this.lifecycle.getManagedRecords().map((record) => record.laneId));\n\t\tfor (const legacy of getLatestLaneRecordSnapshots(getActiveSessionBranchEntries(this.deps.getSessionManager()))) {\n\t\t\tif (\n\t\t\t\tlegacy.type !== \"tmux-worker\" ||\n\t\t\t\t(legacy.status !== \"queued\" && legacy.status !== \"running\") ||\n\t\t\t\tdurableIds.has(legacy.laneId)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.lifecycle.prepareManaged({\n\t\t\t\tlaneId: legacy.laneId,\n\t\t\t\tdispatchSequence: 1,\n\t\t\t\tinstructions: legacy.label ?? `Resume externally managed lane ${legacy.laneId}`,\n\t\t\t\tprofileId: legacy.profileId ?? \"legacy-managed-process\",\n\t\t\t\tprovider: \"legacy\",\n\t\t\t\tauthorizationId: `legacy-session-lane:${legacy.laneId}`,\n\t\t\t\trole: \"implementer\",\n\t\t\t\triskBudget: { maxAttempts: 1, maxWallClockMs: LEGACY_MANAGED_LEASE_TTL_MS },\n\t\t\t\tleaseTtlMs: LEGACY_MANAGED_LEASE_TTL_MS,\n\t\t\t\tcompileGrant: (target) =>\n\t\t\t\t\tthis.compileGrant(target, legacy.laneId, {\n\t\t\t\t\t\tsequence: 1,\n\t\t\t\t\t\tinstructions: legacy.label ?? `Resume externally managed lane ${legacy.laneId}`,\n\t\t\t\t\t\tprofileId: legacy.profileId ?? \"legacy-managed-process\",\n\t\t\t\t\t\tprovider: \"legacy\",\n\t\t\t\t\t\tauthorizationId: `legacy-session-lane:${legacy.laneId}`,\n\t\t\t\t\t\tauthorizationKind: \"legacy-recovery\",\n\t\t\t\t\t\tallowedTools: LEGACY_MANAGED_READ_TOOLS,\n\t\t\t\t\t\twritePaths: [],\n\t\t\t\t\t\tleaseTtlMs: LEGACY_MANAGED_LEASE_TTL_MS,\n\t\t\t\t\t}),\n\t\t\t\t...(legacy.worktreeLaneKey ? { worktreeLaneKey: legacy.worktreeLaneKey } : {}),\n\t\t\t});\n\t\t}\n\t\tfor (const record of this.lifecycle.getManagedRecords()) {\n\t\t\tif (record.status === \"queued\" || record.status === \"running\") this.ensureRegistration(record.laneId);\n\t\t}\n\t}\n\n\tresolve(callerLaneId: string): string | undefined {\n\t\tthis.ensureHydrated();\n\t\tconst record = this.lifecycle.getManagedRecord(callerLaneId);\n\t\treturn record && (record.status === \"queued\" || record.status === \"running\") ? callerLaneId : undefined;\n\t}\n\n\trecord(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\tif (this.deps.isDisposed()) return undefined;\n\t\tthis.ensureHydrated();\n\t\tif (event.phase === \"dispatch\") {\n\t\t\tconst goal = this.deps.getGoalStateSnapshot();\n\t\t\tconst prepared = this.lifecycle.prepareManaged({\n\t\t\t\tlaneId: event.laneId,\n\t\t\t\tdispatchSequence: event.dispatch.sequence,\n\t\t\t\tinstructions: event.dispatch.instructions,\n\t\t\t\tprofileId: event.dispatch.profileId,\n\t\t\t\tprovider: event.dispatch.provider,\n\t\t\t\tauthorizationId: event.dispatch.authorizationId,\n\t\t\t\tleaseTtlMs: event.dispatch.leaseTtlMs,\n\t\t\t\tcompileGrant: (target) => this.compileGrant(target, event.laneId, event.dispatch),\n\t\t\t\trole: \"implementer\",\n\t\t\t\triskBudget: { maxAttempts: 1, maxWallClockMs: event.dispatch.leaseTtlMs },\n\t\t\t\t...(goal && Array.isArray(goal.requirements) && (!event.goalId || goal.goalId === event.goalId)\n\t\t\t\t\t? { goal }\n\t\t\t\t\t: {}),\n\t\t\t\t...(event.goalId ? { goalId: event.goalId } : {}),\n\t\t\t\t...(event.worktreeLaneKey ? { worktreeLaneKey: event.worktreeLaneKey } : {}),\n\t\t\t});\n\t\t\tif (!prepared.created) return undefined;\n\t\t\tthis.ensureRegistration(event.laneId);\n\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), prepared.record);\n\t\t\treturn prepared.record;\n\t\t}\n\n\t\tconst attempt = this.lifecycle.getManagedAttempt(event.laneId);\n\t\tconst handle = this.lifecycle.getManagedHandle(event.laneId);\n\t\tif (!attempt || !handle || (attempt.status !== \"leased\" && attempt.status !== \"running\")) return undefined;\n\t\tconst resolvedStatus = resolveManagedLaneTerminalStatus(event.status);\n\t\tconst changedFiles = event.changedFiles ? [...event.changedFiles] : [];\n\t\tconst review = reviewManagedLaneChangedFiles({\n\t\t\tchangedFiles,\n\t\t\tenvelope: this.deps.getCapabilityEnvelope() ?? {},\n\t\t\tcwd: this.deps.getCwd(),\n\t\t});\n\t\tconst claim: WorkerClaim = {\n\t\t\trequestId: event.laneId,\n\t\t\tstatus: mapManagedLaneTerminalStatus(resolvedStatus),\n\t\t\tsummary: `Managed worker lane ${event.laneId} reported terminal status \"${event.status ?? \"unknown\"}\"${\n\t\t\t\tevent.reasonCode ? ` (${event.reasonCode})` : \"\"\n\t\t\t}.${review.reviewRequired ? ` Changed files require parent review (${review.reasonCode}).` : \"\"}`,\n\t\t\tchangedFiles,\n\t\t\tparentReviewRequired: review.reviewRequired,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t\tlet record: LaneRecord | undefined;\n\t\ttry {\n\t\t\tthis.deps.saveWorkerClaimSnapshot(claim);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tconst usage = event.usage;\n\t\t\t\trecord = this.lifecycle.finish(\n\t\t\t\t\tcreateWorkerResultContract({\n\t\t\t\t\t\thandle,\n\t\t\t\t\t\tclaim,\n\t\t\t\t\t\taccepted: resolvedStatus === \"succeeded\" && !review.reviewRequired,\n\t\t\t\t\t\tcostUsd: usage?.cost.total,\n\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t\t...(usage\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tinputTokens: usage.input,\n\t\t\t\t\t\t\t\t\toutputTokens: usage.output,\n\t\t\t\t\t\t\t\t\ttotalTokens: usage.totalTokens,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\twallClockMs: Math.max(0, Date.now() - Date.parse(attempt.createdAt)),\n\t\t\t\t\t\ttoolCalls: 0,\n\t\t\t\t\t\treasonCode: review.reviewRequired\n\t\t\t\t\t\t\t? `parent_review_required:${review.reasonCode}`\n\t\t\t\t\t\t\t: (event.reasonCode ?? `managed_worker_${resolvedStatus}`),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst notification = this.lifecycle.getTerminalNotification(event.laneId);\n\t\t\t\tif (notification) this.recordTerminal(record, notification.notificationId);\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t} finally {\n\t\t\t\tthis.releaseRegistration(event.laneId);\n\t\t\t}\n\t\t}\n\t\treturn record;\n\t}\n\n\trelease(): void {\n\t\tfor (const deregister of this.deregisterByLane.values()) deregister();\n\t\tthis.deregisterByLane.clear();\n\t}\n\n\tprivate ensureRegistration(laneId: string): void {\n\t\tif (this.deregisterByLane.has(laneId)) return;\n\t\tthis.deregisterByLane.set(laneId, registerInFlightWork(this.deps.getAgentDir(), \"lane\", `tmux:${laneId}`));\n\t}\n\n\tprivate releaseRegistration(laneId: string): void {\n\t\tthis.deregisterByLane.get(laneId)?.();\n\t\tthis.deregisterByLane.delete(laneId);\n\t}\n\n\tprivate compileGrant(\n\t\ttarget: { objectiveId: string; taskId: string; attemptId: string },\n\t\tlaneId: string,\n\t\tdispatch: ManagedLaneDispatch,\n\t): ExecutionGrant {\n\t\tconst compiled = compileManagedProcessExecutionGrant({\n\t\t\ttarget,\n\t\t\tlaneId,\n\t\t\tauthorizationId: dispatch.authorizationId,\n\t\t\trole: \"implementer\",\n\t\t\tallowedTools: dispatch.allowedTools,\n\t\t\twritePaths: dispatch.writePaths,\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tdeniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),\n\t\t\tbudget: {\n\t\t\t\tmaxAttempts: 1,\n\t\t\t\tmaxWallClockMs: dispatch.leaseTtlMs,\n\t\t\t\t...(dispatch.maxCostUsd !== undefined ? { maxCostUsd: dispatch.maxCostUsd } : {}),\n\t\t\t},\n\t\t});\n\t\tif (!compiled.ok) {\n\t\t\tthrow new Error(`Managed worker '${laneId}' execution grant was denied: ${compiled.reasonCodes.join(\", \")}`);\n\t\t}\n\t\treturn compiled.grant;\n\t}\n}\n"]}
1
+ {"version":3,"file":"managed-lane-controller.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/managed-lane-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAElH,OAAO,EAAwB,KAAK,UAAU,EAAE,KAAK,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAE7G,OAAO,KAAK,EAAuB,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAYxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAM7D,wBAAgB,gCAAgC,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,kBAAkB,CAc/F;AAED,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,kB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sHtD;IAED,OAAO,IAAI,IAAI,CAGd;IAED,OAAO,CAAC,kBAAkB;IAK1B,OAAO,CAAC,mBAAmB;IAK3B,2GAA2G;IAC3G,OAAO,CAAC,2BAA2B;IASnC,OAAO,CAAC,YAAY;CAyBpB","sourcesContent":["import type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport type { CapabilityEnvelope, WorkerClaim, WorkerClaimStatus, WorkerRequest } from \"../autonomy/contracts.ts\";\nimport { getPrivateLaneDeniedPaths } from \"../autonomy/lane-private-paths.ts\";\nimport { isLaneTerminalStatus, type LaneRecord, type LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"../autonomy/session-lane-record.ts\";\nimport type { ManagedLaneDispatch, ManagedLaneEvent } from \"../extensions/types.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport { validateProviderUsage } from \"../orchestration/attempt-usage.ts\";\nimport type { ExecutionGrant } from \"../orchestration/contracts.ts\";\nimport { registerInFlightWork } from \"../reload-blockers.ts\";\nimport { getActiveSessionBranchEntries } from \"../session-snapshot.ts\";\nimport { getLatestWorkerClaimSnapshot } from \"./session-worker-claim.ts\";\nimport {\n\tnormalizeWorkerClaimForHost,\n\tnormalizeWorkerClaimReasonCode,\n\treviewManagedLaneChangedFiles,\n} from \"./worker-claim.ts\";\nimport { compileManagedProcessExecutionGrant } from \"./worker-execution-policy.ts\";\nimport type { WorkerLifecycle } from \"./worker-lifecycle.ts\";\nimport { finalizeWorkerClaim } from \"./worker-terminal-finalizer.ts\";\n\nconst LEGACY_MANAGED_LEASE_TTL_MS = 24 * 60 * 60 * 1_000;\nconst LEGACY_MANAGED_READ_TOOLS = [\"read\", \"grep\", \"find\", \"ls\"] as const;\n\nexport function resolveManagedLaneTerminalStatus(status: string | undefined): LaneTerminalStatus {\n\tif (isLaneTerminalStatus(status)) return status;\n\tswitch (status) {\n\t\tcase \"done\":\n\t\tcase \"completed\":\n\t\t\treturn \"succeeded\";\n\t\tcase \"blocked\":\n\t\t\treturn \"failed\";\n\t\tcase \"dismissed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"canceled\";\n\t\tdefault:\n\t\t\treturn \"failed\";\n\t}\n}\n\nexport function mapManagedLaneTerminalStatus(status: LaneTerminalStatus): WorkerClaimStatus {\n\tswitch (status) {\n\t\tcase \"succeeded\":\n\t\t\treturn \"completed\";\n\t\tcase \"canceled\":\n\t\t\treturn \"cancelled\";\n\t\tcase \"failed\":\n\t\tcase \"timeout\":\n\t\tcase \"budget_exhausted\":\n\t\t\treturn \"failed\";\n\t}\n}\n\nexport interface ManagedLaneControllerDeps {\n\tisDisposed(): boolean;\n\tgetAgentDir(): string;\n\tgetCwd(): string;\n\tgetSessionManager(): SessionManager;\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\tsaveWorkerClaimSnapshot(claim: WorkerClaim, request?: WorkerRequest): string;\n\t/** Optional only for minimal host embeddings; normal AgentSession integration always supplies this. */\n\taddSpawnedUsage?(\n\t\tusage: Usage,\n\t\topts: { label?: string; sourceSessionId?: string; reportId: string },\n\t): string | undefined;\n}\n\n/** Out-of-process adapter over the same durable worker lifecycle used by in-process delegation. */\nexport class ManagedLaneController {\n\tprivate readonly deps: ManagedLaneControllerDeps;\n\tprivate readonly lifecycle: WorkerLifecycle;\n\tprivate readonly recordTerminal: (record: LaneRecord, durableNotificationId: string) => void;\n\tprivate readonly warn: (message: string) => void;\n\tprivate readonly deregisterByLane = new Map<string, () => void>();\n\tprivate hydrated = false;\n\n\tconstructor(\n\t\tdeps: ManagedLaneControllerDeps,\n\t\tlifecycle: WorkerLifecycle,\n\t\trecordTerminal: (record: LaneRecord, durableNotificationId: string) => void,\n\t\twarn: (message: string) => void = () => {},\n\t) {\n\t\tthis.deps = deps;\n\t\tthis.lifecycle = lifecycle;\n\t\tthis.recordTerminal = recordTerminal;\n\t\tthis.warn = warn;\n\t}\n\n\tensureHydrated(): void {\n\t\tif (this.hydrated) return;\n\t\tthis.hydrated = true;\n\t\tconst durableIds = new Set(this.lifecycle.getManagedRecords().map((record) => record.laneId));\n\t\tfor (const legacy of getLatestLaneRecordSnapshots(getActiveSessionBranchEntries(this.deps.getSessionManager()))) {\n\t\t\tif (\n\t\t\t\tlegacy.type !== \"tmux-worker\" ||\n\t\t\t\t(legacy.status !== \"queued\" && legacy.status !== \"running\") ||\n\t\t\t\tdurableIds.has(legacy.laneId)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.lifecycle.prepareManaged({\n\t\t\t\tlaneId: legacy.laneId,\n\t\t\t\tdispatchSequence: 1,\n\t\t\t\tinstructions: legacy.label ?? `Resume externally managed lane ${legacy.laneId}`,\n\t\t\t\tprofileId: legacy.profileId ?? \"legacy-managed-process\",\n\t\t\t\tprovider: \"legacy\",\n\t\t\t\tauthorizationId: `legacy-session-lane:${legacy.laneId}`,\n\t\t\t\trole: \"implementer\",\n\t\t\t\triskBudget: { maxAttempts: 1, maxWallClockMs: LEGACY_MANAGED_LEASE_TTL_MS },\n\t\t\t\tleaseTtlMs: LEGACY_MANAGED_LEASE_TTL_MS,\n\t\t\t\tcompileGrant: (target) =>\n\t\t\t\t\tthis.compileGrant(target, legacy.laneId, {\n\t\t\t\t\t\tsequence: 1,\n\t\t\t\t\t\tinstructions: legacy.label ?? `Resume externally managed lane ${legacy.laneId}`,\n\t\t\t\t\t\tprofileId: legacy.profileId ?? \"legacy-managed-process\",\n\t\t\t\t\t\tprovider: \"legacy\",\n\t\t\t\t\t\tauthorizationId: `legacy-session-lane:${legacy.laneId}`,\n\t\t\t\t\t\tauthorizationKind: \"legacy-recovery\",\n\t\t\t\t\t\tallowedTools: LEGACY_MANAGED_READ_TOOLS,\n\t\t\t\t\t\twritePaths: [],\n\t\t\t\t\t\tleaseTtlMs: LEGACY_MANAGED_LEASE_TTL_MS,\n\t\t\t\t\t}),\n\t\t\t\t...(legacy.worktreeLaneKey ? { worktreeLaneKey: legacy.worktreeLaneKey } : {}),\n\t\t\t});\n\t\t}\n\t\tfor (const record of this.lifecycle.getManagedRecords()) {\n\t\t\tif (record.status === \"queued\" || record.status === \"running\") this.ensureRegistration(record.laneId);\n\t\t}\n\t}\n\n\tresolve(callerLaneId: string): string | undefined {\n\t\tthis.ensureHydrated();\n\t\tconst record = this.lifecycle.getManagedRecord(callerLaneId);\n\t\treturn record && (record.status === \"queued\" || record.status === \"running\") ? callerLaneId : undefined;\n\t}\n\n\trecord(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\tif (this.deps.isDisposed()) return undefined;\n\t\tthis.ensureHydrated();\n\t\tif (event.phase === \"dispatch\") {\n\t\t\tconst goal = this.deps.getGoalStateSnapshot();\n\t\t\tconst prepared = this.lifecycle.prepareManaged({\n\t\t\t\tlaneId: event.laneId,\n\t\t\t\tdispatchSequence: event.dispatch.sequence,\n\t\t\t\tinstructions: event.dispatch.instructions,\n\t\t\t\tprofileId: event.dispatch.profileId,\n\t\t\t\tprovider: event.dispatch.provider,\n\t\t\t\tauthorizationId: event.dispatch.authorizationId,\n\t\t\t\tleaseTtlMs: event.dispatch.leaseTtlMs,\n\t\t\t\tcompileGrant: (target) => this.compileGrant(target, event.laneId, event.dispatch),\n\t\t\t\trole: \"implementer\",\n\t\t\t\triskBudget: { maxAttempts: 1, maxWallClockMs: event.dispatch.leaseTtlMs },\n\t\t\t\t...(goal && Array.isArray(goal.requirements) && (!event.goalId || goal.goalId === event.goalId)\n\t\t\t\t\t? { goal }\n\t\t\t\t\t: {}),\n\t\t\t\t...(event.goalId ? { goalId: event.goalId } : {}),\n\t\t\t\t...(event.worktreeLaneKey ? { worktreeLaneKey: event.worktreeLaneKey } : {}),\n\t\t\t});\n\t\t\tif (!prepared.created) return undefined;\n\t\t\tthis.ensureRegistration(event.laneId);\n\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), prepared.record);\n\t\t\treturn prepared.record;\n\t\t}\n\n\t\tconst attempt = this.lifecycle.getManagedAttempt(event.laneId);\n\t\tconst handle = this.lifecycle.getManagedHandle(event.laneId);\n\t\tif (!attempt || !handle || (attempt.status !== \"leased\" && attempt.status !== \"running\")) return undefined;\n\t\tlet usage: Usage | undefined;\n\t\ttry {\n\t\t\tusage = event.usage ? validateProviderUsage(event.usage, \"managed lane usage\") : undefined;\n\t\t} catch (error) {\n\t\t\tthis.warn(\n\t\t\t\t`Rejected terminal report for managed worker ${event.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst resolvedStatus = resolveManagedLaneTerminalStatus(event.status);\n\t\tconst usageReportId = usage && this.deps.addSpawnedUsage ? `managed-worker:${handle.attemptId}` : undefined;\n\t\tlet claim: WorkerClaim;\n\t\ttry {\n\t\t\tclaim = normalizeWorkerClaimForHost({\n\t\t\t\trequestId: event.laneId,\n\t\t\t\tterminalAttemptId: handle.attemptId,\n\t\t\t\tstatus: mapManagedLaneTerminalStatus(resolvedStatus),\n\t\t\t\tsummary: `Managed worker lane ${event.laneId} reported terminal status \"${resolvedStatus}\".`,\n\t\t\t\tchangedFiles: event.changedFiles ?? [],\n\t\t\t\t...(usageReportId ? { usageReportId } : {}),\n\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.warn(\n\t\t\t\t`Rejected terminal report for managed worker ${event.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst review = reviewManagedLaneChangedFiles({\n\t\t\tchangedFiles: claim.changedFiles,\n\t\t\tenvelope: this.deps.getCapabilityEnvelope() ?? {},\n\t\t\tcwd: this.deps.getCwd(),\n\t\t});\n\t\tclaim = normalizeWorkerClaimForHost({\n\t\t\t...claim,\n\t\t\tsummary: `${claim.summary}${\n\t\t\t\treview.reviewRequired ? ` Changed files require parent review (${review.reasonCode}).` : \"\"\n\t\t\t}`,\n\t\t\tparentReviewRequired: review.reviewRequired,\n\t\t});\n\t\tlet record: LaneRecord | undefined;\n\t\tlet finalized = false;\n\t\ttry {\n\t\t\t// Accounting must commit before the lifecycle terminal transition. A failed append leaves the\n\t\t\t// fenced attempt active so the same terminal event can retry with this stable report id.\n\t\t\tif (usage && usageReportId) {\n\t\t\t\tthis.deps.addSpawnedUsage?.(usage, { label: \"managed-worker\", reportId: usageReportId });\n\t\t\t}\n\t\t\tif (!this.hasPersistedClaimForAttempt(claim)) this.deps.saveWorkerClaimSnapshot(claim);\n\t\t\tconst terminal = finalizeWorkerClaim(this.lifecycle, {\n\t\t\t\thandle,\n\t\t\t\tclaim,\n\t\t\t\taccepted: resolvedStatus === \"succeeded\" && !review.reviewRequired,\n\t\t\t\tcostUsd: usage?.cost.total,\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t...(usage\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tinputTokens: usage.input,\n\t\t\t\t\t\t\toutputTokens: usage.output,\n\t\t\t\t\t\t\ttotalTokens: usage.totalTokens,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\twallClockMs: Math.max(0, Date.now() - Date.parse(attempt.createdAt)),\n\t\t\t\ttoolCalls: 0,\n\t\t\t\treasonCode: normalizeWorkerClaimReasonCode(\n\t\t\t\t\treview.reviewRequired ? `parent_review_required:${review.reasonCode}` : event.reasonCode,\n\t\t\t\t\t`managed_worker_${resolvedStatus}`,\n\t\t\t\t),\n\t\t\t});\n\t\t\trecord = terminal.record;\n\t\t\tfinalized = true;\n\t\t\tif (terminal.notification) this.recordTerminal(record, terminal.notification.notificationId);\n\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (finalized) {\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Managed worker ${event.laneId} finalized, but terminal projection or handoff failed: ${message}`,\n\t\t\t\t);\n\t\t\t\treturn record;\n\t\t\t}\n\t\t\tthis.warn(`Managed worker ${event.laneId} terminal processing failed and remains retryable: ${message}`);\n\t\t\treturn undefined;\n\t\t} finally {\n\t\t\tif (finalized) this.releaseRegistration(event.laneId);\n\t\t}\n\t\treturn record;\n\t}\n\n\trelease(): void {\n\t\tfor (const deregister of this.deregisterByLane.values()) deregister();\n\t\tthis.deregisterByLane.clear();\n\t}\n\n\tprivate ensureRegistration(laneId: string): void {\n\t\tif (this.deregisterByLane.has(laneId)) return;\n\t\tthis.deregisterByLane.set(laneId, registerInFlightWork(this.deps.getAgentDir(), \"lane\", `tmux:${laneId}`));\n\t}\n\n\tprivate releaseRegistration(laneId: string): void {\n\t\tthis.deregisterByLane.get(laneId)?.();\n\t\tthis.deregisterByLane.delete(laneId);\n\t}\n\n\t/** A replay after a crash between claim append and lifecycle finalization must not duplicate the claim. */\n\tprivate hasPersistedClaimForAttempt(claim: WorkerClaim): boolean {\n\t\tif (!claim.terminalAttemptId) return false;\n\t\tconst latest = getLatestWorkerClaimSnapshot(\n\t\t\tgetActiveSessionBranchEntries(this.deps.getSessionManager()),\n\t\t\tclaim.requestId,\n\t\t);\n\t\treturn latest?.claim.terminalAttemptId === claim.terminalAttemptId;\n\t}\n\n\tprivate compileGrant(\n\t\ttarget: { objectiveId: string; taskId: string; attemptId: string },\n\t\tlaneId: string,\n\t\tdispatch: ManagedLaneDispatch,\n\t): ExecutionGrant {\n\t\tconst compiled = compileManagedProcessExecutionGrant({\n\t\t\ttarget,\n\t\t\tlaneId,\n\t\t\tauthorizationId: dispatch.authorizationId,\n\t\t\trole: \"implementer\",\n\t\t\tallowedTools: dispatch.allowedTools,\n\t\t\twritePaths: dispatch.writePaths,\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tdeniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),\n\t\t\tbudget: {\n\t\t\t\tmaxAttempts: 1,\n\t\t\t\tmaxWallClockMs: dispatch.leaseTtlMs,\n\t\t\t\t...(dispatch.maxCostUsd !== undefined ? { maxCostUsd: dispatch.maxCostUsd } : {}),\n\t\t\t},\n\t\t});\n\t\tif (!compiled.ok) {\n\t\t\tthrow new Error(`Managed worker '${laneId}' execution grant was denied: ${compiled.reasonCodes.join(\", \")}`);\n\t\t}\n\t\treturn compiled.grant;\n\t}\n}\n"]}
@@ -1,11 +1,13 @@
1
1
  import { getPrivateLaneDeniedPaths } from "../autonomy/lane-private-paths.js";
2
2
  import { isLaneTerminalStatus } from "../autonomy/lane-tracker.js";
3
3
  import { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from "../autonomy/session-lane-record.js";
4
- import { createWorkerResultContract } from "../orchestration/worker-result-adapter.js";
4
+ import { validateProviderUsage } from "../orchestration/attempt-usage.js";
5
5
  import { registerInFlightWork } from "../reload-blockers.js";
6
6
  import { getActiveSessionBranchEntries } from "../session-snapshot.js";
7
- import { reviewManagedLaneChangedFiles } from "./worker-claim.js";
7
+ import { getLatestWorkerClaimSnapshot } from "./session-worker-claim.js";
8
+ import { normalizeWorkerClaimForHost, normalizeWorkerClaimReasonCode, reviewManagedLaneChangedFiles, } from "./worker-claim.js";
8
9
  import { compileManagedProcessExecutionGrant } from "./worker-execution-policy.js";
10
+ import { finalizeWorkerClaim } from "./worker-terminal-finalizer.js";
9
11
  const LEGACY_MANAGED_LEASE_TTL_MS = 24 * 60 * 60 * 1_000;
10
12
  const LEGACY_MANAGED_READ_TOOLS = ["read", "grep", "find", "ls"];
11
13
  export function resolveManagedLaneTerminalStatus(status) {
@@ -41,12 +43,14 @@ export class ManagedLaneController {
41
43
  deps;
42
44
  lifecycle;
43
45
  recordTerminal;
46
+ warn;
44
47
  deregisterByLane = new Map();
45
48
  hydrated = false;
46
- constructor(deps, lifecycle, recordTerminal) {
49
+ constructor(deps, lifecycle, recordTerminal, warn = () => { }) {
47
50
  this.deps = deps;
48
51
  this.lifecycle = lifecycle;
49
52
  this.recordTerminal = recordTerminal;
53
+ this.warn = warn;
50
54
  }
51
55
  ensureHydrated() {
52
56
  if (this.hydrated)
@@ -126,55 +130,87 @@ export class ManagedLaneController {
126
130
  const handle = this.lifecycle.getManagedHandle(event.laneId);
127
131
  if (!attempt || !handle || (attempt.status !== "leased" && attempt.status !== "running"))
128
132
  return undefined;
133
+ let usage;
134
+ try {
135
+ usage = event.usage ? validateProviderUsage(event.usage, "managed lane usage") : undefined;
136
+ }
137
+ catch (error) {
138
+ this.warn(`Rejected terminal report for managed worker ${event.laneId}: ${error instanceof Error ? error.message : String(error)}`);
139
+ return undefined;
140
+ }
129
141
  const resolvedStatus = resolveManagedLaneTerminalStatus(event.status);
130
- const changedFiles = event.changedFiles ? [...event.changedFiles] : [];
142
+ const usageReportId = usage && this.deps.addSpawnedUsage ? `managed-worker:${handle.attemptId}` : undefined;
143
+ let claim;
144
+ try {
145
+ claim = normalizeWorkerClaimForHost({
146
+ requestId: event.laneId,
147
+ terminalAttemptId: handle.attemptId,
148
+ status: mapManagedLaneTerminalStatus(resolvedStatus),
149
+ summary: `Managed worker lane ${event.laneId} reported terminal status "${resolvedStatus}".`,
150
+ changedFiles: event.changedFiles ?? [],
151
+ ...(usageReportId ? { usageReportId } : {}),
152
+ createdAt: new Date().toISOString(),
153
+ });
154
+ }
155
+ catch (error) {
156
+ this.warn(`Rejected terminal report for managed worker ${event.laneId}: ${error instanceof Error ? error.message : String(error)}`);
157
+ return undefined;
158
+ }
131
159
  const review = reviewManagedLaneChangedFiles({
132
- changedFiles,
160
+ changedFiles: claim.changedFiles,
133
161
  envelope: this.deps.getCapabilityEnvelope() ?? {},
134
162
  cwd: this.deps.getCwd(),
135
163
  });
136
- const claim = {
137
- requestId: event.laneId,
138
- status: mapManagedLaneTerminalStatus(resolvedStatus),
139
- summary: `Managed worker lane ${event.laneId} reported terminal status "${event.status ?? "unknown"}"${event.reasonCode ? ` (${event.reasonCode})` : ""}.${review.reviewRequired ? ` Changed files require parent review (${review.reasonCode}).` : ""}`,
140
- changedFiles,
164
+ claim = normalizeWorkerClaimForHost({
165
+ ...claim,
166
+ summary: `${claim.summary}${review.reviewRequired ? ` Changed files require parent review (${review.reasonCode}).` : ""}`,
141
167
  parentReviewRequired: review.reviewRequired,
142
- createdAt: new Date().toISOString(),
143
- };
168
+ });
144
169
  let record;
170
+ let finalized = false;
145
171
  try {
146
- this.deps.saveWorkerClaimSnapshot(claim);
172
+ // Accounting must commit before the lifecycle terminal transition. A failed append leaves the
173
+ // fenced attempt active so the same terminal event can retry with this stable report id.
174
+ if (usage && usageReportId) {
175
+ this.deps.addSpawnedUsage?.(usage, { label: "managed-worker", reportId: usageReportId });
176
+ }
177
+ if (!this.hasPersistedClaimForAttempt(claim))
178
+ this.deps.saveWorkerClaimSnapshot(claim);
179
+ const terminal = finalizeWorkerClaim(this.lifecycle, {
180
+ handle,
181
+ claim,
182
+ accepted: resolvedStatus === "succeeded" && !review.reviewRequired,
183
+ costUsd: usage?.cost.total,
184
+ cwd: this.deps.getCwd(),
185
+ ...(usage
186
+ ? {
187
+ inputTokens: usage.input,
188
+ outputTokens: usage.output,
189
+ totalTokens: usage.totalTokens,
190
+ }
191
+ : {}),
192
+ wallClockMs: Math.max(0, Date.now() - Date.parse(attempt.createdAt)),
193
+ toolCalls: 0,
194
+ reasonCode: normalizeWorkerClaimReasonCode(review.reviewRequired ? `parent_review_required:${review.reasonCode}` : event.reasonCode, `managed_worker_${resolvedStatus}`),
195
+ });
196
+ record = terminal.record;
197
+ finalized = true;
198
+ if (terminal.notification)
199
+ this.recordTerminal(record, terminal.notification.notificationId);
200
+ appendLaneRecordSnapshot(this.deps.getSessionManager(), record);
147
201
  }
148
- finally {
149
- try {
150
- const usage = event.usage;
151
- record = this.lifecycle.finish(createWorkerResultContract({
152
- handle,
153
- claim,
154
- accepted: resolvedStatus === "succeeded" && !review.reviewRequired,
155
- costUsd: usage?.cost.total,
156
- cwd: this.deps.getCwd(),
157
- ...(usage
158
- ? {
159
- inputTokens: usage.input,
160
- outputTokens: usage.output,
161
- totalTokens: usage.totalTokens,
162
- }
163
- : {}),
164
- wallClockMs: Math.max(0, Date.now() - Date.parse(attempt.createdAt)),
165
- toolCalls: 0,
166
- reasonCode: review.reviewRequired
167
- ? `parent_review_required:${review.reasonCode}`
168
- : (event.reasonCode ?? `managed_worker_${resolvedStatus}`),
169
- }));
170
- const notification = this.lifecycle.getTerminalNotification(event.laneId);
171
- if (notification)
172
- this.recordTerminal(record, notification.notificationId);
173
- appendLaneRecordSnapshot(this.deps.getSessionManager(), record);
202
+ catch (error) {
203
+ const message = error instanceof Error ? error.message : String(error);
204
+ if (finalized) {
205
+ this.warn(`Managed worker ${event.laneId} finalized, but terminal projection or handoff failed: ${message}`);
206
+ return record;
174
207
  }
175
- finally {
208
+ this.warn(`Managed worker ${event.laneId} terminal processing failed and remains retryable: ${message}`);
209
+ return undefined;
210
+ }
211
+ finally {
212
+ if (finalized)
176
213
  this.releaseRegistration(event.laneId);
177
- }
178
214
  }
179
215
  return record;
180
216
  }
@@ -192,6 +228,13 @@ export class ManagedLaneController {
192
228
  this.deregisterByLane.get(laneId)?.();
193
229
  this.deregisterByLane.delete(laneId);
194
230
  }
231
+ /** A replay after a crash between claim append and lifecycle finalization must not duplicate the claim. */
232
+ hasPersistedClaimForAttempt(claim) {
233
+ if (!claim.terminalAttemptId)
234
+ return false;
235
+ const latest = getLatestWorkerClaimSnapshot(getActiveSessionBranchEntries(this.deps.getSessionManager()), claim.requestId);
236
+ return latest?.claim.terminalAttemptId === claim.terminalAttemptId;
237
+ }
195
238
  compileGrant(target, laneId, dispatch) {
196
239
  const compiled = compileManagedProcessExecutionGrant({
197
240
  target,