@caupulican/pi-adaptative 0.86.3 → 0.86.6

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 (247) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/core/agent-paths.d.ts +13 -0
  3. package/dist/core/agent-paths.d.ts.map +1 -1
  4. package/dist/core/agent-paths.js +23 -0
  5. package/dist/core/agent-paths.js.map +1 -1
  6. package/dist/core/autonomy/bounded-completion.d.ts +7 -0
  7. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  8. package/dist/core/autonomy/bounded-completion.js +12 -4
  9. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  10. package/dist/core/autonomy/lane-tool-surface.d.ts +2 -0
  11. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  12. package/dist/core/autonomy/lane-tool-surface.js +6 -3
  13. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  14. package/dist/core/autonomy/subagent-prompt.js +1 -1
  15. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  16. package/dist/core/background-lane-controller.d.ts +25 -2
  17. package/dist/core/background-lane-controller.d.ts.map +1 -1
  18. package/dist/core/background-lane-controller.js +67 -0
  19. package/dist/core/background-lane-controller.js.map +1 -1
  20. package/dist/core/delegation/replay-safe-mailbox-bounds.d.ts +4 -0
  21. package/dist/core/delegation/replay-safe-mailbox-bounds.d.ts.map +1 -0
  22. package/dist/core/delegation/replay-safe-mailbox-bounds.js +20 -0
  23. package/dist/core/delegation/replay-safe-mailbox-bounds.js.map +1 -0
  24. package/dist/core/delegation/sanitized-context-fork.d.ts +25 -0
  25. package/dist/core/delegation/sanitized-context-fork.d.ts.map +1 -0
  26. package/dist/core/delegation/sanitized-context-fork.js +299 -0
  27. package/dist/core/delegation/sanitized-context-fork.js.map +1 -0
  28. package/dist/core/delegation/session-root-mailbox.d.ts +75 -0
  29. package/dist/core/delegation/session-root-mailbox.d.ts.map +1 -0
  30. package/dist/core/delegation/session-root-mailbox.js +627 -0
  31. package/dist/core/delegation/session-root-mailbox.js.map +1 -0
  32. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +102 -9
  33. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  34. package/dist/core/delegation/worker-agent-control-coordinator.js +1307 -125
  35. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  36. package/dist/core/delegation/worker-agent-control.d.ts +183 -8
  37. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  38. package/dist/core/delegation/worker-agent-control.js +778 -48
  39. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  40. package/dist/core/delegation/worker-attempt-executor.d.ts +9 -0
  41. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  42. package/dist/core/delegation/worker-attempt-executor.js +479 -214
  43. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  44. package/dist/core/delegation/worker-authority-resolver.d.ts +9 -0
  45. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
  46. package/dist/core/delegation/worker-authority-resolver.js +21 -2
  47. package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
  48. package/dist/core/delegation/worker-context-fork-store.d.ts +71 -0
  49. package/dist/core/delegation/worker-context-fork-store.d.ts.map +1 -0
  50. package/dist/core/delegation/worker-context-fork-store.js +437 -0
  51. package/dist/core/delegation/worker-context-fork-store.js.map +1 -0
  52. package/dist/core/delegation/worker-context-inheritance-policy.d.ts +18 -0
  53. package/dist/core/delegation/worker-context-inheritance-policy.d.ts.map +1 -0
  54. package/dist/core/delegation/worker-context-inheritance-policy.js +28 -0
  55. package/dist/core/delegation/worker-context-inheritance-policy.js.map +1 -0
  56. package/dist/core/delegation/worker-conversation-revision.d.ts +31 -0
  57. package/dist/core/delegation/worker-conversation-revision.d.ts.map +1 -0
  58. package/dist/core/delegation/worker-conversation-revision.js +203 -0
  59. package/dist/core/delegation/worker-conversation-revision.js.map +1 -0
  60. package/dist/core/delegation/worker-conversation-store.d.ts +130 -18
  61. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
  62. package/dist/core/delegation/worker-conversation-store.js +1263 -79
  63. package/dist/core/delegation/worker-conversation-store.js.map +1 -1
  64. package/dist/core/delegation/worker-delegation-controller.d.ts +30 -2
  65. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  66. package/dist/core/delegation/worker-delegation-controller.js +675 -111
  67. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  68. package/dist/core/delegation/worker-delegation-request.d.ts +2 -0
  69. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  70. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  71. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +20 -1
  72. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
  73. package/dist/core/delegation/worker-dispatch-scheduler.js +210 -37
  74. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
  75. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  76. package/dist/core/delegation/worker-execution-policy.js +14 -2
  77. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  78. package/dist/core/delegation/worker-fleet-limits.d.ts +38 -0
  79. package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -0
  80. package/dist/core/delegation/worker-fleet-limits.js +113 -0
  81. package/dist/core/delegation/worker-fleet-limits.js.map +1 -0
  82. package/dist/core/delegation/worker-lane-projection.d.ts +1 -0
  83. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
  84. package/dist/core/delegation/worker-lane-projection.js +6 -2
  85. package/dist/core/delegation/worker-lane-projection.js.map +1 -1
  86. package/dist/core/delegation/worker-lifecycle.d.ts +20 -3
  87. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  88. package/dist/core/delegation/worker-lifecycle.js +42 -18
  89. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  90. package/dist/core/delegation/worker-notification-coordinator.d.ts +4 -0
  91. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  92. package/dist/core/delegation/worker-notification-coordinator.js +45 -4
  93. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  94. package/dist/core/delegation/worker-provider-turn-protocol.d.ts +50 -0
  95. package/dist/core/delegation/worker-provider-turn-protocol.d.ts.map +1 -0
  96. package/dist/core/delegation/worker-provider-turn-protocol.js +185 -0
  97. package/dist/core/delegation/worker-provider-turn-protocol.js.map +1 -0
  98. package/dist/core/delegation/worker-recovery-coordinator.d.ts +45 -4
  99. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  100. package/dist/core/delegation/worker-recovery-coordinator.js +223 -17
  101. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  102. package/dist/core/delegation/worker-retry-policy.d.ts +36 -0
  103. package/dist/core/delegation/worker-retry-policy.d.ts.map +1 -0
  104. package/dist/core/delegation/worker-retry-policy.js +41 -0
  105. package/dist/core/delegation/worker-retry-policy.js.map +1 -0
  106. package/dist/core/delegation/worker-runner.d.ts +3 -1
  107. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  108. package/dist/core/delegation/worker-runner.js +4 -2
  109. package/dist/core/delegation/worker-runner.js.map +1 -1
  110. package/dist/core/delegation/worker-task-view.d.ts +43 -0
  111. package/dist/core/delegation/worker-task-view.d.ts.map +1 -0
  112. package/dist/core/delegation/worker-task-view.js +194 -0
  113. package/dist/core/delegation/worker-task-view.js.map +1 -0
  114. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts +55 -0
  115. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts.map +1 -0
  116. package/dist/core/delegation/worker-terminal-handoff-coordinator.js +179 -0
  117. package/dist/core/delegation/worker-terminal-handoff-coordinator.js.map +1 -0
  118. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +2 -2
  119. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
  120. package/dist/core/delegation/worker-tree-budget-coordinator.js +12 -46
  121. package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
  122. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  123. package/dist/core/goals/goal-continuation-controller.js +15 -0
  124. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  125. package/dist/core/goals/goal-state.d.ts +6 -0
  126. package/dist/core/goals/goal-state.d.ts.map +1 -1
  127. package/dist/core/goals/goal-state.js +1 -0
  128. package/dist/core/goals/goal-state.js.map +1 -1
  129. package/dist/core/goals/goal-tool-core.d.ts +1 -0
  130. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  131. package/dist/core/goals/goal-tool-core.js +25 -3
  132. package/dist/core/goals/goal-tool-core.js.map +1 -1
  133. package/dist/core/keybindings.d.ts +10 -0
  134. package/dist/core/keybindings.d.ts.map +1 -1
  135. package/dist/core/keybindings.js +2 -0
  136. package/dist/core/keybindings.js.map +1 -1
  137. package/dist/core/orchestration/attempt-ordering.d.ts +9 -0
  138. package/dist/core/orchestration/attempt-ordering.d.ts.map +1 -0
  139. package/dist/core/orchestration/attempt-ordering.js +29 -0
  140. package/dist/core/orchestration/attempt-ordering.js.map +1 -0
  141. package/dist/core/orchestration/capability-gateway.d.ts +19 -0
  142. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  143. package/dist/core/orchestration/capability-gateway.js +19 -2
  144. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  145. package/dist/core/orchestration/contracts.d.ts +43 -3
  146. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  147. package/dist/core/orchestration/contracts.js +24 -0
  148. package/dist/core/orchestration/contracts.js.map +1 -1
  149. package/dist/core/orchestration/delegation-ledger.d.ts +8 -3
  150. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  151. package/dist/core/orchestration/delegation-ledger.js +148 -55
  152. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  153. package/dist/core/orchestration/event-store.d.ts +6 -3
  154. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  155. package/dist/core/orchestration/event-store.js +228 -30
  156. package/dist/core/orchestration/event-store.js.map +1 -1
  157. package/dist/core/orchestration/task-runtime-codecs.d.ts +31 -0
  158. package/dist/core/orchestration/task-runtime-codecs.d.ts.map +1 -0
  159. package/dist/core/orchestration/task-runtime-codecs.js +1471 -0
  160. package/dist/core/orchestration/task-runtime-codecs.js.map +1 -0
  161. package/dist/core/orchestration/task-runtime-projection.d.ts +30 -0
  162. package/dist/core/orchestration/task-runtime-projection.d.ts.map +1 -0
  163. package/dist/core/orchestration/task-runtime-projection.js +340 -0
  164. package/dist/core/orchestration/task-runtime-projection.js.map +1 -0
  165. package/dist/core/orchestration/task-runtime-reducer.d.ts +38 -0
  166. package/dist/core/orchestration/task-runtime-reducer.d.ts.map +1 -0
  167. package/dist/core/orchestration/task-runtime-reducer.js +1270 -0
  168. package/dist/core/orchestration/task-runtime-reducer.js.map +1 -0
  169. package/dist/core/orchestration/task-runtime-state.d.ts +142 -0
  170. package/dist/core/orchestration/task-runtime-state.d.ts.map +1 -0
  171. package/dist/core/orchestration/task-runtime-state.js +14 -0
  172. package/dist/core/orchestration/task-runtime-state.js.map +1 -0
  173. package/dist/core/orchestration/task-runtime.d.ts +44 -98
  174. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  175. package/dist/core/orchestration/task-runtime.js +357 -1113
  176. package/dist/core/orchestration/task-runtime.js.map +1 -1
  177. package/dist/core/orchestration/worker-context-fork-reference.d.ts +20 -0
  178. package/dist/core/orchestration/worker-context-fork-reference.d.ts.map +1 -0
  179. package/dist/core/orchestration/worker-context-fork-reference.js +53 -0
  180. package/dist/core/orchestration/worker-context-fork-reference.js.map +1 -0
  181. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  182. package/dist/core/orchestration/worker-execution-contract.js +4 -2
  183. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  184. package/dist/core/research/research-runner.d.ts +2 -0
  185. package/dist/core/research/research-runner.d.ts.map +1 -1
  186. package/dist/core/research/research-runner.js +1 -0
  187. package/dist/core/research/research-runner.js.map +1 -1
  188. package/dist/core/runtime-builder.d.ts.map +1 -1
  189. package/dist/core/runtime-builder.js +8 -0
  190. package/dist/core/runtime-builder.js.map +1 -1
  191. package/dist/core/secrets/credential-project.d.ts.map +1 -1
  192. package/dist/core/secrets/credential-project.js +24 -2
  193. package/dist/core/secrets/credential-project.js.map +1 -1
  194. package/dist/core/security/secret-text.d.ts +3 -0
  195. package/dist/core/security/secret-text.d.ts.map +1 -1
  196. package/dist/core/security/secret-text.js +15 -0
  197. package/dist/core/security/secret-text.js.map +1 -1
  198. package/dist/core/settings-manager.d.ts +3 -0
  199. package/dist/core/settings-manager.d.ts.map +1 -1
  200. package/dist/core/settings-manager.js +160 -8
  201. package/dist/core/settings-manager.js.map +1 -1
  202. package/dist/core/tools/delegate.d.ts +33 -15
  203. package/dist/core/tools/delegate.d.ts.map +1 -1
  204. package/dist/core/tools/delegate.js +763 -115
  205. package/dist/core/tools/delegate.js.map +1 -1
  206. package/dist/core/tools/goal.d.ts +1 -0
  207. package/dist/core/tools/goal.d.ts.map +1 -1
  208. package/dist/core/tools/goal.js +9 -1
  209. package/dist/core/tools/goal.js.map +1 -1
  210. package/dist/main.d.ts.map +1 -1
  211. package/dist/main.js +1 -0
  212. package/dist/main.js.map +1 -1
  213. package/dist/modes/interactive/components/activity-lane.d.ts +5 -0
  214. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  215. package/dist/modes/interactive/components/activity-lane.js +133 -49
  216. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  217. package/dist/modes/interactive/components/agents-overlay.d.ts +40 -0
  218. package/dist/modes/interactive/components/agents-overlay.d.ts.map +1 -0
  219. package/dist/modes/interactive/components/agents-overlay.js +153 -0
  220. package/dist/modes/interactive/components/agents-overlay.js.map +1 -0
  221. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  222. package/dist/modes/interactive/components/settings-selector.js +18 -13
  223. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  224. package/dist/modes/interactive/interactive-event-controller.d.ts +1 -1
  225. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -1
  226. package/dist/modes/interactive/interactive-event-controller.js +6 -3
  227. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  228. package/dist/modes/interactive/interactive-mode.d.ts +5 -0
  229. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  230. package/dist/modes/interactive/interactive-mode.js +51 -0
  231. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  232. package/dist/modes/interactive/key-handlers.d.ts +1 -0
  233. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  234. package/dist/modes/interactive/key-handlers.js +1 -0
  235. package/dist/modes/interactive/key-handlers.js.map +1 -1
  236. package/docs/harness-architecture.md +61 -17
  237. package/docs/settings.md +17 -9
  238. package/docs/worker-profiles.md +6 -2
  239. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  240. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  241. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  242. package/examples/extensions/sandbox/package-lock.json +2 -2
  243. package/examples/extensions/sandbox/package.json +1 -1
  244. package/examples/extensions/with-deps/package-lock.json +2 -2
  245. package/examples/extensions/with-deps/package.json +1 -1
  246. package/npm-shrinkwrap.json +12 -12
  247. package/package.json +4 -4
@@ -1,7 +1,8 @@
1
1
  import { sameAgentResumeIdentity } from "../orchestration/agent-resume.js";
2
+ import { latestAgentAttemptByDurableOrder } from "../orchestration/attempt-ordering.js";
2
3
  import { DelegationOrchestrationLedger, } from "../orchestration/delegation-ledger.js";
3
4
  import { verifierWorkerExecutionContract } from "../orchestration/worker-execution-contract.js";
4
- import { ACTIVE_WORKER_ATTEMPT_STATUSES, isManagedWorkerAttempt, projectManagedWorkerLaneRecords, projectWorkerLaneRecord, selectedManagedWorkerAttempt, selectedWorkerAttempt, } from "./worker-lane-projection.js";
5
+ import { ACTIVE_WORKER_ATTEMPT_STATUSES, isManagedWorkerAttempt, NONTERMINAL_WORKER_ATTEMPT_STATUSES, projectManagedWorkerLaneRecords, projectWorkerLaneRecord, selectedManagedWorkerAttempt, selectedWorkerAttempt, } from "./worker-lane-projection.js";
5
6
  import { isLocalProcessAlive, isLocalWorkerProcessOwnerProvenDead } from "./worker-process-owner.js";
6
7
  /**
7
8
  * Sole owner of in-process worker lifecycle state. LaneRecord is a compatibility/UI projection;
@@ -20,18 +21,26 @@ export class WorkerLifecycle {
20
21
  }
21
22
  prepare(input, laneId) {
22
23
  let selectedLaneId = laneId;
24
+ const generatedLaneId = !selectedLaneId;
23
25
  if (!selectedLaneId) {
24
- const snapshot = this.ledger.runtime.getSnapshot();
25
- while (snapshot.tasks[`worker-${this.nextLaneNumber}`])
26
- this.nextLaneNumber += 1;
27
- selectedLaneId = `worker-${this.nextLaneNumber++}`;
26
+ selectedLaneId = this.getNextAvailableLaneIdCandidate();
28
27
  }
29
28
  const attempt = this.ledger.prepare({ ...input, laneId: selectedLaneId });
29
+ if (generatedLaneId)
30
+ this.nextLaneNumber = Number(selectedLaneId.slice("worker-".length)) + 1;
30
31
  const record = this.getRecord(selectedLaneId);
31
32
  if (!record)
32
33
  throw new Error(`Durable worker '${selectedLaneId}' was not projected after enqueue.`);
33
34
  return { record, attempt };
34
35
  }
36
+ /** Return the next generated lane id without reserving it or changing lifecycle state. */
37
+ getNextAvailableLaneIdCandidate() {
38
+ const snapshot = this.ledger.runtime.getSnapshot();
39
+ let candidateNumber = this.nextLaneNumber;
40
+ while (snapshot.tasks[`worker-${candidateNumber}`])
41
+ candidateNumber += 1;
42
+ return `worker-${candidateNumber}`;
43
+ }
35
44
  /** Queue the next distinct task/attempt for an idle logical agent. */
36
45
  prepareAgentTurn(input) {
37
46
  const attempt = this.ledger.prepareAgentTurn(input);
@@ -52,6 +61,10 @@ export class WorkerLifecycle {
52
61
  }
53
62
  return existing;
54
63
  }
64
+ /** Retire one idle logical worker while retaining its durable binding and transcript identity. */
65
+ retireAgent(agentId) {
66
+ return this.ledger.runtime.retireAgent(agentId);
67
+ }
55
68
  prepareManaged(input) {
56
69
  const before = selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), input.laneId);
57
70
  if (before?.dispatch.dispatchSequence === input.dispatchSequence) {
@@ -173,17 +186,19 @@ export class WorkerLifecycle {
173
186
  leaseId: args.leaseId,
174
187
  fencingToken: args.fencingToken,
175
188
  reasonCode: args.reasonCode,
189
+ ...(args.retry ? { retry: args.retry } : {}),
176
190
  });
177
191
  }
178
192
  resumeAgent(laneId, agentId, leaseTtlMs, ownerId = agentId) {
179
193
  const attempt = this.getActiveAttempt(laneId);
180
194
  if (!attempt)
181
195
  throw new Error(`Durable worker '${laneId}' has no resumable attempt.`);
182
- this.ledger.runtime.requestAgentResume(agentId);
196
+ this.ledger.runtime.assertAttemptReadyForResume(attempt.attemptId);
197
+ this.ledger.runtime.requestAgentResume(agentId, attempt.attemptId);
183
198
  const lease = this.ledger.runtime.resumeAttempt(attempt.attemptId, agentId, leaseTtlMs, ownerId);
184
199
  return this.startedHandle(this.ledger.runtime.startAttempt(attempt.attemptId, lease.leaseId, lease.fencingToken));
185
200
  }
186
- suspendAgent(laneId, agentId, ownerId, reasonCode = "agent_interrupted") {
201
+ suspendAgent(laneId, agentId, ownerId, reasonCode = "agent_interrupted", retry) {
187
202
  const attempt = this.getActiveAttempt(laneId);
188
203
  if (!attempt || attempt.agentId !== agentId || !attempt.lease) {
189
204
  throw new Error(`Logical worker '${agentId}' has no live attempt for interruption.`);
@@ -194,8 +209,16 @@ export class WorkerLifecycle {
194
209
  leaseId: attempt.lease.leaseId,
195
210
  fencingToken: attempt.lease.fencingToken,
196
211
  reasonCode,
212
+ ...(retry ? { retry } : {}),
197
213
  });
198
214
  }
215
+ scheduleAgentRetry(args) {
216
+ this.suspendAgent(args.laneId, args.agentId, args.ownerId, args.reasonCode, args.retry);
217
+ const attempt = this.getActiveAttempt(args.laneId);
218
+ if (!attempt)
219
+ throw new Error(`Durable worker '${args.laneId}' disappeared after retry suspension.`);
220
+ return attempt;
221
+ }
199
222
  bindGrant(attemptId, grant) {
200
223
  this.ledger.runtime.bindAttemptGrant(attemptId, grant);
201
224
  }
@@ -260,7 +283,6 @@ export class WorkerLifecycle {
260
283
  return [];
261
284
  const verifier = Object.values(snapshot.tasks)
262
285
  .filter((candidate) => candidate.task.verificationOfTaskId === subject.task.taskId)
263
- .sort((left, right) => left.task.createdAt.localeCompare(right.task.createdAt))
264
286
  .at(-1);
265
287
  if (!verifier) {
266
288
  const verifierExecutionContract = implementationAttempt.dispatch.executionContract
@@ -278,13 +300,14 @@ export class WorkerLifecycle {
278
300
  ];
279
301
  }
280
302
  const verifierAttempt = selectedWorkerAttempt(snapshot, verifier.task.taskId);
281
- if (!verifierAttempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(verifierAttempt.status))
303
+ if (!verifierAttempt || NONTERMINAL_WORKER_ATTEMPT_STATUSES.has(verifierAttempt.status))
282
304
  return [];
283
- const review = verifierAttempt.result?.evidence.find((evidence) => evidence.kind === "review" && evidence.metadata?.subjectTaskId === subject.task.taskId);
305
+ const review = verifierAttempt.result?.evidence.find((evidence) => evidence.trusted &&
306
+ evidence.kind === "review" &&
307
+ evidence.metadata?.subjectTaskId === subject.task.taskId &&
308
+ (evidence.metadata.verdict === "accepted" || evidence.metadata.verdict === "rejected"));
284
309
  const verdictValue = review?.metadata?.verdict;
285
- const verdict = review?.trusted && (verdictValue === "accepted" || verdictValue === "rejected")
286
- ? verdictValue
287
- : "inconclusive";
310
+ const verdict = verdictValue === "accepted" || verdictValue === "rejected" ? verdictValue : "inconclusive";
288
311
  const reasonCodesValue = review?.metadata?.reasonCodes;
289
312
  const reasonCodes = Array.isArray(reasonCodesValue)
290
313
  ? reasonCodesValue.filter((reasonCode) => typeof reasonCode === "string")
@@ -312,14 +335,15 @@ export class WorkerLifecycle {
312
335
  return this.ledger.runtime.getSnapshot().agents[agentId];
313
336
  }
314
337
  getLatestAgentAttempt(agentId) {
315
- return Object.values(this.ledger.runtime.getSnapshot().attempts)
316
- .filter((attempt) => attempt.agentId === agentId || attempt.dispatch.logicalLaneId === agentId)
317
- .sort((left, right) => left.createdAt.localeCompare(right.createdAt))
318
- .at(-1);
338
+ return latestAgentAttemptByDurableOrder(this.ledger.runtime.getSnapshot(), agentId);
319
339
  }
320
340
  getTaskRuntimeSnapshot() {
321
341
  return this.ledger.runtime.getSnapshot();
322
342
  }
343
+ /** Read-only dispatch gate for an already persisted queued worker attempt. */
344
+ getAttemptDispatchReadiness(attemptId) {
345
+ return this.ledger.runtime.getAttemptDispatchReadiness(attemptId);
346
+ }
323
347
  getRecords() {
324
348
  const snapshot = this.ledger.runtime.getSnapshot();
325
349
  return Object.keys(snapshot.tasks).flatMap((taskId) => {
@@ -407,7 +431,7 @@ export class WorkerLifecycle {
407
431
  }
408
432
  enqueueTerminalNotification(record) {
409
433
  const attempt = this.getActiveAttempt(record.laneId) ?? this.getManagedAttempt(record.laneId);
410
- if (!attempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status))
434
+ if (!attempt || NONTERMINAL_WORKER_ATTEMPT_STATUSES.has(attempt.status))
411
435
  return;
412
436
  const snapshot = this.ledger.runtime.getSnapshot();
413
437
  const task = snapshot.tasks[attempt.taskId];
@@ -1 +1 @@
1
- {"version":3,"file":"worker-lifecycle.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-lifecycle.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAU3E,OAAO,EACN,6BAA6B,GAI7B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC;AAChG,OAAO,EACN,8BAA8B,EAC9B,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,EACvB,4BAA4B,EAC5B,qBAAqB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,mBAAm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AO,CAAC,MAAM,CAAC,CAAC;QACrE,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,CAAC,SAAS,wBAAwB,CAAC,CAAC;QAC1F,MAAM,KAAK,GAAG,YAAY,CAAC;YAC1B,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW;YAClC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM;YACxB,SAAS,EAAE,OAAO,CAAC,SAAS;SAC5B,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QACzC,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CACvB,OAAO,CAAC,SAAS,EACjB,UAAU,EACV,WAAW,OAAO,CAAC,QAAQ,CAAC,aAAa,IAAI,OAAO,CAAC,MAAM,EAAE,CAC7D,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport { sameAgentResumeIdentity } from \"../orchestration/agent-resume.ts\";\nimport type {\n\tAgentBindingContract,\n\tAgentResumeContext,\n\tAttemptUsageSnapshot,\n\tExecutionGrant,\n\tWorkerExecutionContract,\n\tWorkerResultContract,\n\tWorkerRole,\n} from \"../orchestration/contracts.ts\";\nimport {\n\tDelegationOrchestrationLedger,\n\ttype PrepareDelegationInput,\n\ttype PrepareManagedDelegationInput,\n\ttype StartedDelegationAttempt,\n} from \"../orchestration/delegation-ledger.ts\";\nimport type { AttemptRuntimeState, TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { verifierWorkerExecutionContract } from \"../orchestration/worker-execution-contract.ts\";\nimport {\n\tACTIVE_WORKER_ATTEMPT_STATUSES,\n\tisManagedWorkerAttempt,\n\tprojectManagedWorkerLaneRecords,\n\tprojectWorkerLaneRecord,\n\tselectedManagedWorkerAttempt,\n\tselectedWorkerAttempt,\n} from \"./worker-lane-projection.ts\";\nimport { isLocalProcessAlive, isLocalWorkerProcessOwnerProvenDead } from \"./worker-process-owner.ts\";\n\nexport type PendingVerificationRecovery =\n\t| {\n\t\t\taction: \"dispatch\";\n\t\t\tsubjectTaskId: string;\n\t\t\timplementationProfileId: string;\n\t\t\tsummary: string;\n\t\t\tartifactUris: readonly string[];\n\t\t\tverifierExecutionContract?: WorkerExecutionContract;\n\t }\n\t| {\n\t\t\taction: \"reconcile\";\n\t\t\tsubjectTaskId: string;\n\t\t\tverifierTaskId: string;\n\t\t\tverifierAttemptId: string;\n\t\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\t\treasonCode: string;\n\t };\n\n/**\n * Sole owner of in-process worker lifecycle state. LaneRecord is a compatibility/UI projection;\n * all transitions are committed through DurableTaskRuntime before the projection is returned.\n */\nexport class WorkerLifecycle {\n\treadonly ledger: DelegationOrchestrationLedger;\n\tprivate nextLaneNumber: number;\n\tprivate readonly isProcessAlive: (pid: number) => boolean;\n\n\tconstructor(options: { agentDir: string; sessionId: string; isProcessAlive?: (pid: number) => boolean }) {\n\t\tthis.ledger = new DelegationOrchestrationLedger(options);\n\t\tthis.isProcessAlive = options.isProcessAlive ?? isLocalProcessAlive;\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst highest = Object.keys(snapshot.tasks).reduce((current, taskId) => {\n\t\t\tconst suffix = /^worker-(\\d+)$/.exec(taskId)?.[1];\n\t\t\treturn suffix ? Math.max(current, Number(suffix)) : current;\n\t\t}, 0);\n\t\tthis.nextLaneNumber = highest + 1;\n\t}\n\n\tprepare(\n\t\tinput: Omit<PrepareDelegationInput, \"laneId\">,\n\t\tlaneId?: string,\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t} {\n\t\tlet selectedLaneId = laneId;\n\t\tif (!selectedLaneId) {\n\t\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\t\twhile (snapshot.tasks[`worker-${this.nextLaneNumber}`]) this.nextLaneNumber += 1;\n\t\t\tselectedLaneId = `worker-${this.nextLaneNumber++}`;\n\t\t}\n\t\tconst attempt = this.ledger.prepare({ ...input, laneId: selectedLaneId });\n\t\tconst record = this.getRecord(selectedLaneId);\n\t\tif (!record) throw new Error(`Durable worker '${selectedLaneId}' was not projected after enqueue.`);\n\t\treturn { record, attempt };\n\t}\n\n\t/** Queue the next distinct task/attempt for an idle logical agent. */\n\tprepareAgentTurn(input: { agentId: string; instructions: string }): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t} {\n\t\tconst attempt = this.ledger.prepareAgentTurn(input);\n\t\tconst record = this.getRecord(attempt.taskId);\n\t\tif (!record) throw new Error(`Logical worker '${input.agentId}' turn was not projected after enqueue.`);\n\t\treturn { record, attempt };\n\t}\n\n\tensureAgent(input: {\n\t\tagentId: string;\n\t\tparentAgentId?: string;\n\t\trole: WorkerRole;\n\t\tresumeContext: AgentResumeContext;\n\t}): AgentBindingContract {\n\t\tconst agentId = input.agentId.trim();\n\t\tconst existing = this.ledger.runtime.getSnapshot().agents[agentId];\n\t\tif (!existing) return this.ledger.runtime.registerAgent(input);\n\t\tif (\n\t\t\texisting.role !== input.role ||\n\t\t\texisting.parentAgentId !== input.parentAgentId ||\n\t\t\t!sameAgentResumeIdentity(existing.resumeContext, input.resumeContext)\n\t\t) {\n\t\t\tthrow new Error(`Agent '${agentId}' was re-registered with conflicting identity.`);\n\t\t}\n\t\treturn existing;\n\t}\n\n\tprepareManaged(\n\t\tinput: PrepareManagedDelegationInput & {\n\t\t\tleaseTtlMs: number;\n\t\t\tcompileGrant(target: { objectiveId: string; taskId: string; attemptId: string }): ExecutionGrant;\n\t\t},\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\thandle: StartedDelegationAttempt;\n\t\tcreated: boolean;\n\t} {\n\t\tconst before = selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), input.laneId);\n\t\tif (before?.dispatch.dispatchSequence === input.dispatchSequence) {\n\t\t\tif (\n\t\t\t\tbefore.dispatch.provider !== \"legacy\" &&\n\t\t\t\t(before.dispatch.instructions !== input.instructions ||\n\t\t\t\t\tbefore.dispatch.profileId !== input.profileId ||\n\t\t\t\t\tbefore.dispatch.provider !== input.provider ||\n\t\t\t\t\tbefore.dispatch.worktreeLaneKey !== input.worktreeLaneKey ||\n\t\t\t\t\tbefore.dispatch.authorizationId !== input.authorizationId)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Managed worker '${input.laneId}' turn ${input.dispatchSequence} was re-reported with conflicting dispatch data.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (before.status === \"queued\") {\n\t\t\t\tconst handle = this.startPreparedManagedAttempt(before, input.leaseTtlMs, input.compileGrant);\n\t\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\t\treturn {\n\t\t\t\t\trecord,\n\t\t\t\t\tattempt: this.ledger.runtime.getSnapshot().attempts[before.attemptId]!,\n\t\t\t\t\thandle,\n\t\t\t\t\tcreated: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\tif (!before.lease) throw new Error(`Managed worker '${input.laneId}' has no durable lease.`);\n\t\t\treturn {\n\t\t\t\trecord,\n\t\t\t\tattempt: before,\n\t\t\t\thandle: this.startedHandle(before),\n\t\t\t\tcreated: false,\n\t\t\t};\n\t\t}\n\t\tif (before && ACTIVE_WORKER_ATTEMPT_STATUSES.has(before.status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Managed worker '${input.laneId}' cannot dispatch turn ${input.dispatchSequence} while turn ${before.dispatch.dispatchSequence ?? 1} is active.`,\n\t\t\t);\n\t\t}\n\t\tconst attempt = this.ledger.prepareManaged(input);\n\t\tconst handle = this.startPreparedManagedAttempt(attempt, input.leaseTtlMs, input.compileGrant);\n\t\tconst record = this.getManagedRecord(input.laneId);\n\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected after dispatch.`);\n\t\treturn { record, attempt: this.ledger.runtime.getSnapshot().attempts[attempt.attemptId]!, handle, created: true };\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): LaneRecord[] {\n\t\tconst before = new Map(this.getRecords().map((record) => [record.laneId, record.status]));\n\t\tthis.ledger.synchronizeGoalState(goal);\n\t\treturn this.getRecords().filter((record) => {\n\t\t\tconst previous = before.get(record.laneId);\n\t\t\treturn (\n\t\t\t\t(previous === \"queued\" || previous === \"running\") &&\n\t\t\t\trecord.status !== \"queued\" &&\n\t\t\t\trecord.status !== \"running\"\n\t\t\t);\n\t\t});\n\t}\n\n\tstart(laneId: string, leaseTtlMs: number): StartedDelegationAttempt {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\treturn this.ledger.start(attempt.attemptId, leaseTtlMs);\n\t}\n\n\tstartAgent(laneId: string, agentId: string, leaseTtlMs: number, ownerId = agentId): StartedDelegationAttempt {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\treturn this.ledger.start(attempt.attemptId, leaseTtlMs, ownerId, agentId);\n\t}\n\n\tcheckpoint(\n\t\tlaneId: string,\n\t\tinput: {\n\t\t\tsummary: string;\n\t\t\tartifactIds?: readonly string[];\n\t\t\tevidenceIds?: readonly string[];\n\t\t\tusage?: AttemptUsageSnapshot;\n\t\t},\n\t) {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\tif (!attempt.lease) throw new Error(`Durable worker '${laneId}' has no live lease.`);\n\t\treturn this.ledger.runtime.checkpointAttempt({\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\tsummary: input.summary,\n\t\t\t...(input.artifactIds ? { artifactIds: input.artifactIds } : {}),\n\t\t\t...(input.evidenceIds ? { evidenceIds: input.evidenceIds } : {}),\n\t\t\t...(input.usage ? { usage: input.usage } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * Suspend only attempts whose exact controller owner is known (explicit shutdown) or whose\n\t * recorded local owner PID is proven gone (recovery). A live/unknown owner is never stolen.\n\t */\n\tsuspendBoundInProcessAttemptsForRestart(ownerId?: string): string[] {\n\t\tconst suspended: string[] = [];\n\t\tfor (const attempt of Object.values(this.ledger.runtime.getSnapshot().attempts)) {\n\t\t\tif (\n\t\t\t\t(attempt.status !== \"leased\" && attempt.status !== \"running\") ||\n\t\t\t\t!attempt.agentId ||\n\t\t\t\tattempt.dispatch.executionKind === \"managed-process\" ||\n\t\t\t\t!attempt.lease\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst ownsAttempt =\n\t\t\t\townerId !== undefined\n\t\t\t\t\t? attempt.lease.ownerId === ownerId\n\t\t\t\t\t: isLocalWorkerProcessOwnerProvenDead(attempt.lease.ownerId, this.isProcessAlive);\n\t\t\tif (!ownsAttempt) continue;\n\t\t\tthis.suspendBoundAttempt({\n\t\t\t\tlaneId: attempt.taskId,\n\t\t\t\townerId: attempt.lease.ownerId,\n\t\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\t\treasonCode:\n\t\t\t\t\townerId === undefined ? \"agent_process_recovered_after_owner_exit\" : \"agent_process_interrupted\",\n\t\t\t});\n\t\t\tsuspended.push(attempt.attemptId);\n\t\t}\n\t\treturn suspended;\n\t}\n\n\t/**\n\t * Applies an explicitly authorized restart suspension. The caller must identify both the logical\n\t * lane and the current lease fence; process liveness policy is intentionally kept by this class.\n\t */\n\tsuspendBoundAttempt(args: {\n\t\tlaneId: string;\n\t\townerId: string;\n\t\tleaseId: string;\n\t\tfencingToken: number;\n\t\treasonCode: string;\n\t}): void {\n\t\tconst attempt = this.getActiveAttempt(args.laneId);\n\t\tif (!attempt || !attempt.agentId || !attempt.lease) {\n\t\t\tthrow new Error(`Durable worker '${args.laneId}' has no live agent-bound attempt for suspension.`);\n\t\t}\n\t\tthis.ledger.runtime.suspendBoundAttempt({\n\t\t\tattemptId: attempt.attemptId,\n\t\t\townerId: args.ownerId,\n\t\t\tleaseId: args.leaseId,\n\t\t\tfencingToken: args.fencingToken,\n\t\t\treasonCode: args.reasonCode,\n\t\t});\n\t}\n\n\tresumeAgent(laneId: string, agentId: string, leaseTtlMs: number, ownerId = agentId): StartedDelegationAttempt {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt) throw new Error(`Durable worker '${laneId}' has no resumable attempt.`);\n\t\tthis.ledger.runtime.requestAgentResume(agentId);\n\t\tconst lease = this.ledger.runtime.resumeAttempt(attempt.attemptId, agentId, leaseTtlMs, ownerId);\n\t\treturn this.startedHandle(this.ledger.runtime.startAttempt(attempt.attemptId, lease.leaseId, lease.fencingToken));\n\t}\n\n\tsuspendAgent(laneId: string, agentId: string, ownerId: string, reasonCode = \"agent_interrupted\"): void {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt || attempt.agentId !== agentId || !attempt.lease) {\n\t\t\tthrow new Error(`Logical worker '${agentId}' has no live attempt for interruption.`);\n\t\t}\n\t\tthis.suspendBoundAttempt({\n\t\t\tlaneId,\n\t\t\townerId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\treasonCode,\n\t\t});\n\t}\n\n\tbindGrant(attemptId: string, grant: ExecutionGrant): void {\n\t\tthis.ledger.runtime.bindAttemptGrant(attemptId, grant);\n\t}\n\n\tfinish(result: WorkerResultContract, options: { notify?: boolean } = {}): LaneRecord {\n\t\tthis.ledger.runtime.finishAttempt(result);\n\t\tconst record = this.getRecord(result.taskId);\n\t\tif (!record) throw new Error(`Durable worker '${result.taskId}' was not projected after completion.`);\n\t\tif (options.notify !== false) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\treconcileVerification(args: {\n\t\tsubjectTaskId: string;\n\t\tverifierTaskId: string;\n\t\tverifierAttemptId: string;\n\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\treasonCode: string;\n\t}): LaneRecord {\n\t\tthis.ledger.runtime.finishVerification({\n\t\t\ttaskId: args.subjectTaskId,\n\t\t\tverifierTaskId: args.verifierTaskId,\n\t\t\tverifierAttemptId: args.verifierAttemptId,\n\t\t\tverdict: args.verdict,\n\t\t\treasonCode: args.reasonCode,\n\t\t});\n\t\tconst subject = this.getRecord(args.subjectTaskId);\n\t\tif (!subject) throw new Error(`Verified worker '${args.subjectTaskId}' was not projected.`);\n\t\tthis.enqueueTerminalNotification(subject);\n\t\treturn subject;\n\t}\n\n\tcancel(laneId: string, reasonCode: string): LaneRecord | undefined {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt) return this.getRecord(laneId);\n\t\tthis.ledger.cancel(attempt.attemptId, reasonCode);\n\t\tconst record = this.getRecord(laneId);\n\t\tif (record) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\trecoverQueued(): Array<{\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\tverificationOfTaskId?: string;\n\t}> {\n\t\treturn this.ledger.recoverQueuedDispatches().flatMap((attempt) => {\n\t\t\tif (isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = this.getRecord(attempt.taskId);\n\t\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId]?.task;\n\t\t\treturn record\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trecord,\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t...(task?.verificationOfTaskId ? { verificationOfTaskId: task.verificationOfTaskId } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [];\n\t\t});\n\t}\n\n\t/** Close crash windows between implementation completion, verifier dispatch, and reconciliation. */\n\tgetPendingVerificationRecoveries(): PendingVerificationRecovery[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.tasks).flatMap<PendingVerificationRecovery>((subject) => {\n\t\t\tif (subject.verification) return [];\n\t\t\tconst implementationAttempt = selectedWorkerAttempt(snapshot, subject.task.taskId);\n\t\t\tif (implementationAttempt?.result?.nextAction !== \"independent_verification_required\") return [];\n\t\t\tconst verifier = Object.values(snapshot.tasks)\n\t\t\t\t.filter((candidate) => candidate.task.verificationOfTaskId === subject.task.taskId)\n\t\t\t\t.sort((left, right) => left.task.createdAt.localeCompare(right.task.createdAt))\n\t\t\t\t.at(-1);\n\t\t\tif (!verifier) {\n\t\t\t\tconst verifierExecutionContract = implementationAttempt.dispatch.executionContract\n\t\t\t\t\t? verifierWorkerExecutionContract(implementationAttempt.dispatch.executionContract)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"dispatch\" as const,\n\t\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\t\timplementationProfileId: implementationAttempt.dispatch.profileId,\n\t\t\t\t\t\tsummary: implementationAttempt.result.summary,\n\t\t\t\t\t\tartifactUris: implementationAttempt.result.artifacts.map((artifact) => artifact.uri),\n\t\t\t\t\t\t...(verifierExecutionContract ? { verifierExecutionContract } : {}),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\tconst verifierAttempt = selectedWorkerAttempt(snapshot, verifier.task.taskId);\n\t\t\tif (!verifierAttempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(verifierAttempt.status)) return [];\n\t\t\tconst review = verifierAttempt.result?.evidence.find(\n\t\t\t\t(evidence) => evidence.kind === \"review\" && evidence.metadata?.subjectTaskId === subject.task.taskId,\n\t\t\t);\n\t\t\tconst verdictValue = review?.metadata?.verdict;\n\t\t\tconst verdict =\n\t\t\t\treview?.trusted && (verdictValue === \"accepted\" || verdictValue === \"rejected\")\n\t\t\t\t\t? verdictValue\n\t\t\t\t\t: \"inconclusive\";\n\t\t\tconst reasonCodesValue = review?.metadata?.reasonCodes;\n\t\t\tconst reasonCodes = Array.isArray(reasonCodesValue)\n\t\t\t\t? reasonCodesValue.filter((reasonCode): reasonCode is string => typeof reasonCode === \"string\")\n\t\t\t\t: [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\taction: \"reconcile\" as const,\n\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\tverifierTaskId: verifier.task.taskId,\n\t\t\t\t\tverifierAttemptId: verifierAttempt.attemptId,\n\t\t\t\t\tverdict,\n\t\t\t\t\treasonCode:\n\t\t\t\t\t\tverdict === \"accepted\"\n\t\t\t\t\t\t\t? \"independent_verification_accepted\"\n\t\t\t\t\t\t\t: verdict === \"rejected\"\n\t\t\t\t\t\t\t\t? `independent_verification_rejected:${reasonCodes.join(\",\") || \"unspecified\"}`\n\t\t\t\t\t\t\t\t: `independent_verification_inconclusive:${verifierAttempt.reasonCode ?? verifierAttempt.result?.reasonCode ?? \"interrupted\"}`,\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t}\n\n\tgetTask(taskId: string): TaskRuntimeProjection[\"tasks\"][string] | undefined {\n\t\treturn this.ledger.runtime.getSnapshot().tasks[taskId];\n\t}\n\n\tgetAgent(agentId: string): AgentBindingContract | undefined {\n\t\treturn this.ledger.runtime.getSnapshot().agents[agentId];\n\t}\n\n\tgetLatestAgentAttempt(agentId: string): AttemptRuntimeState | undefined {\n\t\treturn Object.values(this.ledger.runtime.getSnapshot().attempts)\n\t\t\t.filter((attempt) => attempt.agentId === agentId || attempt.dispatch.logicalLaneId === agentId)\n\t\t\t.sort((left, right) => left.createdAt.localeCompare(right.createdAt))\n\t\t\t.at(-1);\n\t}\n\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection {\n\t\treturn this.ledger.runtime.getSnapshot();\n\t}\n\n\tgetRecords(): LaneRecord[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).flatMap((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\tif (!attempt || isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\treturn record ? [record] : [];\n\t\t});\n\t}\n\n\tgetManagedRecords(): LaneRecord[] {\n\t\treturn projectManagedWorkerLaneRecords(this.ledger.runtime.getSnapshot());\n\t}\n\n\tgetAllRecords(): LaneRecord[] {\n\t\treturn [...this.getRecords(), ...this.getManagedRecords()];\n\t}\n\n\tgetRecord(laneId: string): LaneRecord | undefined {\n\t\treturn projectWorkerLaneRecord(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedRecord(laneId: string): LaneRecord | undefined {\n\t\treturn this.getManagedRecords().find((record) => record.laneId === laneId);\n\t}\n\n\tgetManagedAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedHandle(laneId: string): StartedDelegationAttempt | undefined {\n\t\tconst attempt = this.getManagedAttempt(laneId);\n\t\treturn attempt?.lease ? this.startedHandle(attempt) : undefined;\n\t}\n\n\tgetActiveAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetAttemptUsage(laneId: string): AttemptUsageSnapshot | undefined {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\treturn attempt ? this.ledger.getAttemptUsage(attempt.attemptId) : undefined;\n\t}\n\n\tgetRunningCount(profileId?: string): number {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).filter((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\treturn (\n\t\t\t\tattempt?.status === \"running\" &&\n\t\t\t\t!isManagedWorkerAttempt(attempt) &&\n\t\t\t\t(!profileId || attempt.dispatch.profileId === profileId)\n\t\t\t);\n\t\t}).length;\n\t}\n\n\tgetPendingTerminalNotifications(): Array<{ notificationId: string; record: LaneRecord }> {\n\t\tthis.ensureTerminalNotifications();\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.notifications).flatMap((notification) => {\n\t\t\tif (notification.status !== \"pending\" || !notification.attemptId) return [];\n\t\t\tconst attempt = snapshot.attempts[notification.attemptId];\n\t\t\tif (!attempt) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, attempt.taskId);\n\t\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return [];\n\t\t\treturn [{ notificationId: notification.notificationId, record }];\n\t\t});\n\t}\n\n\tgetTerminalNotification(\n\t\tlaneId: string,\n\t): { notificationId: string; status: \"pending\" | \"delivered\"; record: LaneRecord } | undefined {\n\t\tconst record = this.getRecord(laneId) ?? this.getManagedRecord(laneId);\n\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return undefined;\n\t\tthis.enqueueTerminalNotification(record);\n\t\tconst attempt = this.getActiveAttempt(laneId) ?? this.getManagedAttempt(laneId);\n\t\tif (!attempt) return undefined;\n\t\tconst notificationId = `worker-terminal:${attempt.attemptId}`;\n\t\tconst notification = this.ledger.runtime.getSnapshot().notifications[notificationId];\n\t\treturn notification ? { notificationId, status: notification.status, record } : undefined;\n\t}\n\n\tmarkNotificationsDelivered(notificationIds: readonly string[]): void {\n\t\tfor (const notificationId of notificationIds) this.ledger.runtime.markNotificationDelivered(notificationId);\n\t}\n\n\tprivate ensureTerminalNotifications(): void {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tfor (const taskId of Object.keys(snapshot.tasks)) {\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\tif (record && record.status !== \"queued\" && record.status !== \"running\") {\n\t\t\t\tthis.enqueueTerminalNotification(record);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate enqueueTerminalNotification(record: LaneRecord): void {\n\t\tconst attempt = this.getActiveAttempt(record.laneId) ?? this.getManagedAttempt(record.laneId);\n\t\tif (!attempt || ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status)) return;\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) return;\n\t\tif (attempt.result?.nextAction === \"independent_verification_required\" && !task.verification) return;\n\t\tthis.ledger.runtime.enqueueNotification({\n\t\t\tnotificationId: `worker-terminal:${attempt.attemptId}`,\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tmessage: `Worker ${record.laneId} reached ${record.status}.`,\n\t\t});\n\t}\n\n\tprivate requireActiveAttempt(laneId: string): AttemptRuntimeState {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt || !ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status)) {\n\t\t\tthrow new Error(`Durable worker '${laneId}' has no active attempt.`);\n\t\t}\n\t\treturn attempt;\n\t}\n\n\tprivate startedHandle(attempt: AttemptRuntimeState): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task || !attempt.lease) throw new Error(`Attempt '${attempt.attemptId}' has no started handle.`);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\texpiresAt: attempt.lease.expiresAt,\n\t\t};\n\t}\n\n\tprivate startPreparedManagedAttempt(\n\t\tattempt: AttemptRuntimeState,\n\t\tleaseTtlMs: number,\n\t\tcompileGrant: (target: { objectiveId: string; taskId: string; attemptId: string }) => ExecutionGrant,\n\t): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task) throw new Error(`Managed attempt '${attempt.attemptId}' has no durable task.`);\n\t\tconst grant = compileGrant({\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t});\n\t\tthis.bindGrant(attempt.attemptId, grant);\n\t\treturn this.ledger.start(\n\t\t\tattempt.attemptId,\n\t\t\tleaseTtlMs,\n\t\t\t`managed:${attempt.dispatch.logicalLaneId ?? attempt.taskId}`,\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"worker-lifecycle.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-lifecycle.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,MAAM,sCAAsC,CAAC;AAWxF,OAAO,EACN,6BAA6B,GAI7B,MAAM,uCAAuC,CAAC;AAM/C,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC;AAChG,OAAO,EACN,8BAA8B,EAC9B,sBAAsB,EACtB,mCAAmC,EACnC,+BAA+B,EAC/B,uBAAuB,EACvB,4BAA4B,EAC5B,qBAAqB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,mBAAmB,EAAE,mCAAmC,EAAE,MAAM,2BAA2B,CAAC;AAoBrG;;;GAGG;AACH,MAAM,OAAO,eAAe;IAK3B,YAAY,OAKX;QACA,IAAI,CAAC,MAAM,GAAG,IAAI,6BAA6B,CAAC,OAAO,CAAC,CAAC;QACzD,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,mBAAmB,CAAC;QACpE,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;QACnD,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtE,MAAM,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O;YACN,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW;YAClC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM;YACxB,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,YAAY,EAAE,OAAO,CAAC,KAAK,CAAC,YAAY;YACxC,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS;SAClC,CAAC;IACH,CAAC;IAEO,2BAA2B,CAClC,OAA4B,EAC5B,UAAkB,EAClB,YAAoG;QAEpG,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACrE,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,CAAC,SAAS,wBAAwB,CAAC,CAAC;QAC1F,MAAM,KAAK,GAAG,YAAY,CAAC;YAC1B,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW;YAClC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM;YACxB,SAAS,EAAE,OAAO,CAAC,SAAS;SAC5B,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QACzC,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CACvB,OAAO,CAAC,SAAS,EACjB,UAAU,EACV,WAAW,OAAO,CAAC,QAAQ,CAAC,aAAa,IAAI,OAAO,CAAC,MAAM,EAAE,CAC7D,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport { sameAgentResumeIdentity } from \"../orchestration/agent-resume.ts\";\nimport { latestAgentAttemptByDurableOrder } from \"../orchestration/attempt-ordering.ts\";\nimport type {\n\tAgentBindingContract,\n\tAgentResumeContext,\n\tAttemptRetryState,\n\tAttemptUsageSnapshot,\n\tExecutionGrant,\n\tWorkerExecutionContract,\n\tWorkerResultContract,\n\tWorkerRole,\n} from \"../orchestration/contracts.ts\";\nimport {\n\tDelegationOrchestrationLedger,\n\ttype PrepareDelegationInput,\n\ttype PrepareManagedDelegationInput,\n\ttype StartedDelegationAttempt,\n} from \"../orchestration/delegation-ledger.ts\";\nimport type {\n\tAttemptDispatchReadiness,\n\tAttemptRuntimeState,\n\tTaskRuntimeProjection,\n} from \"../orchestration/task-runtime.ts\";\nimport { verifierWorkerExecutionContract } from \"../orchestration/worker-execution-contract.ts\";\nimport {\n\tACTIVE_WORKER_ATTEMPT_STATUSES,\n\tisManagedWorkerAttempt,\n\tNONTERMINAL_WORKER_ATTEMPT_STATUSES,\n\tprojectManagedWorkerLaneRecords,\n\tprojectWorkerLaneRecord,\n\tselectedManagedWorkerAttempt,\n\tselectedWorkerAttempt,\n} from \"./worker-lane-projection.ts\";\nimport { isLocalProcessAlive, isLocalWorkerProcessOwnerProvenDead } from \"./worker-process-owner.ts\";\n\nexport type PendingVerificationRecovery =\n\t| {\n\t\t\taction: \"dispatch\";\n\t\t\tsubjectTaskId: string;\n\t\t\timplementationProfileId: string;\n\t\t\tsummary: string;\n\t\t\tartifactUris: readonly string[];\n\t\t\tverifierExecutionContract?: WorkerExecutionContract;\n\t }\n\t| {\n\t\t\taction: \"reconcile\";\n\t\t\tsubjectTaskId: string;\n\t\t\tverifierTaskId: string;\n\t\t\tverifierAttemptId: string;\n\t\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\t\treasonCode: string;\n\t };\n\n/**\n * Sole owner of in-process worker lifecycle state. LaneRecord is a compatibility/UI projection;\n * all transitions are committed through DurableTaskRuntime before the projection is returned.\n */\nexport class WorkerLifecycle {\n\treadonly ledger: DelegationOrchestrationLedger;\n\tprivate nextLaneNumber: number;\n\tprivate readonly isProcessAlive: (pid: number) => boolean;\n\n\tconstructor(options: {\n\t\tagentDir: string;\n\t\tsessionId: string;\n\t\tisProcessAlive?: (pid: number) => boolean;\n\t\tnow?: () => number;\n\t}) {\n\t\tthis.ledger = new DelegationOrchestrationLedger(options);\n\t\tthis.isProcessAlive = options.isProcessAlive ?? isLocalProcessAlive;\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst highest = Object.keys(snapshot.tasks).reduce((current, taskId) => {\n\t\t\tconst suffix = /^worker-(\\d+)$/.exec(taskId)?.[1];\n\t\t\treturn suffix ? Math.max(current, Number(suffix)) : current;\n\t\t}, 0);\n\t\tthis.nextLaneNumber = highest + 1;\n\t}\n\n\tprepare(\n\t\tinput: Omit<PrepareDelegationInput, \"laneId\">,\n\t\tlaneId?: string,\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t} {\n\t\tlet selectedLaneId = laneId;\n\t\tconst generatedLaneId = !selectedLaneId;\n\t\tif (!selectedLaneId) {\n\t\t\tselectedLaneId = this.getNextAvailableLaneIdCandidate();\n\t\t}\n\t\tconst attempt = this.ledger.prepare({ ...input, laneId: selectedLaneId });\n\t\tif (generatedLaneId) this.nextLaneNumber = Number(selectedLaneId.slice(\"worker-\".length)) + 1;\n\t\tconst record = this.getRecord(selectedLaneId);\n\t\tif (!record) throw new Error(`Durable worker '${selectedLaneId}' was not projected after enqueue.`);\n\t\treturn { record, attempt };\n\t}\n\n\t/** Return the next generated lane id without reserving it or changing lifecycle state. */\n\tgetNextAvailableLaneIdCandidate(): string {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tlet candidateNumber = this.nextLaneNumber;\n\t\twhile (snapshot.tasks[`worker-${candidateNumber}`]) candidateNumber += 1;\n\t\treturn `worker-${candidateNumber}`;\n\t}\n\n\t/** Queue the next distinct task/attempt for an idle logical agent. */\n\tprepareAgentTurn(input: {\n\t\tagentId: string;\n\t\tinstructions: string;\n\t\tcontrolMessageId?: string;\n\t\tdependsOnTaskIds?: readonly string[];\n\t}): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t} {\n\t\tconst attempt = this.ledger.prepareAgentTurn(input);\n\t\tconst record = this.getRecord(attempt.taskId);\n\t\tif (!record) throw new Error(`Logical worker '${input.agentId}' turn was not projected after enqueue.`);\n\t\treturn { record, attempt };\n\t}\n\n\tensureAgent(input: {\n\t\tagentId: string;\n\t\tparentAgentId?: string;\n\t\trole: WorkerRole;\n\t\tresumeContext: AgentResumeContext;\n\t}): AgentBindingContract {\n\t\tconst agentId = input.agentId.trim();\n\t\tconst existing = this.ledger.runtime.getSnapshot().agents[agentId];\n\t\tif (!existing) return this.ledger.runtime.registerAgent(input);\n\t\tif (\n\t\t\texisting.role !== input.role ||\n\t\t\texisting.parentAgentId !== input.parentAgentId ||\n\t\t\t!sameAgentResumeIdentity(existing.resumeContext, input.resumeContext)\n\t\t) {\n\t\t\tthrow new Error(`Agent '${agentId}' was re-registered with conflicting identity.`);\n\t\t}\n\t\treturn existing;\n\t}\n\n\t/** Retire one idle logical worker while retaining its durable binding and transcript identity. */\n\tretireAgent(agentId: string): AgentBindingContract {\n\t\treturn this.ledger.runtime.retireAgent(agentId);\n\t}\n\n\tprepareManaged(\n\t\tinput: PrepareManagedDelegationInput & {\n\t\t\tleaseTtlMs: number;\n\t\t\tcompileGrant(target: { objectiveId: string; taskId: string; attemptId: string }): ExecutionGrant;\n\t\t},\n\t): {\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\thandle: StartedDelegationAttempt;\n\t\tcreated: boolean;\n\t} {\n\t\tconst before = selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), input.laneId);\n\t\tif (before?.dispatch.dispatchSequence === input.dispatchSequence) {\n\t\t\tif (\n\t\t\t\tbefore.dispatch.provider !== \"legacy\" &&\n\t\t\t\t(before.dispatch.instructions !== input.instructions ||\n\t\t\t\t\tbefore.dispatch.profileId !== input.profileId ||\n\t\t\t\t\tbefore.dispatch.provider !== input.provider ||\n\t\t\t\t\tbefore.dispatch.worktreeLaneKey !== input.worktreeLaneKey ||\n\t\t\t\t\tbefore.dispatch.authorizationId !== input.authorizationId)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Managed worker '${input.laneId}' turn ${input.dispatchSequence} was re-reported with conflicting dispatch data.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (before.status === \"queued\") {\n\t\t\t\tconst handle = this.startPreparedManagedAttempt(before, input.leaseTtlMs, input.compileGrant);\n\t\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\t\treturn {\n\t\t\t\t\trecord,\n\t\t\t\t\tattempt: this.ledger.runtime.getSnapshot().attempts[before.attemptId]!,\n\t\t\t\t\thandle,\n\t\t\t\t\tcreated: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst record = this.getManagedRecord(input.laneId);\n\t\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected.`);\n\t\t\tif (!before.lease) throw new Error(`Managed worker '${input.laneId}' has no durable lease.`);\n\t\t\treturn {\n\t\t\t\trecord,\n\t\t\t\tattempt: before,\n\t\t\t\thandle: this.startedHandle(before),\n\t\t\t\tcreated: false,\n\t\t\t};\n\t\t}\n\t\tif (before && ACTIVE_WORKER_ATTEMPT_STATUSES.has(before.status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Managed worker '${input.laneId}' cannot dispatch turn ${input.dispatchSequence} while turn ${before.dispatch.dispatchSequence ?? 1} is active.`,\n\t\t\t);\n\t\t}\n\t\tconst attempt = this.ledger.prepareManaged(input);\n\t\tconst handle = this.startPreparedManagedAttempt(attempt, input.leaseTtlMs, input.compileGrant);\n\t\tconst record = this.getManagedRecord(input.laneId);\n\t\tif (!record) throw new Error(`Managed worker '${input.laneId}' was not projected after dispatch.`);\n\t\treturn { record, attempt: this.ledger.runtime.getSnapshot().attempts[attempt.attemptId]!, handle, created: true };\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): LaneRecord[] {\n\t\tconst before = new Map(this.getRecords().map((record) => [record.laneId, record.status]));\n\t\tthis.ledger.synchronizeGoalState(goal);\n\t\treturn this.getRecords().filter((record) => {\n\t\t\tconst previous = before.get(record.laneId);\n\t\t\treturn (\n\t\t\t\t(previous === \"queued\" || previous === \"running\") &&\n\t\t\t\trecord.status !== \"queued\" &&\n\t\t\t\trecord.status !== \"running\"\n\t\t\t);\n\t\t});\n\t}\n\n\tstart(laneId: string, leaseTtlMs: number): StartedDelegationAttempt {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\treturn this.ledger.start(attempt.attemptId, leaseTtlMs);\n\t}\n\n\tstartAgent(laneId: string, agentId: string, leaseTtlMs: number, ownerId = agentId): StartedDelegationAttempt {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\treturn this.ledger.start(attempt.attemptId, leaseTtlMs, ownerId, agentId);\n\t}\n\n\tcheckpoint(\n\t\tlaneId: string,\n\t\tinput: {\n\t\t\tsummary: string;\n\t\t\tartifactIds?: readonly string[];\n\t\t\tevidenceIds?: readonly string[];\n\t\t\tusage?: AttemptUsageSnapshot;\n\t\t},\n\t) {\n\t\tconst attempt = this.requireActiveAttempt(laneId);\n\t\tif (!attempt.lease) throw new Error(`Durable worker '${laneId}' has no live lease.`);\n\t\treturn this.ledger.runtime.checkpointAttempt({\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\tsummary: input.summary,\n\t\t\t...(input.artifactIds ? { artifactIds: input.artifactIds } : {}),\n\t\t\t...(input.evidenceIds ? { evidenceIds: input.evidenceIds } : {}),\n\t\t\t...(input.usage ? { usage: input.usage } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * Suspend only attempts whose exact controller owner is known (explicit shutdown) or whose\n\t * recorded local owner PID is proven gone (recovery). A live/unknown owner is never stolen.\n\t */\n\tsuspendBoundInProcessAttemptsForRestart(ownerId?: string): string[] {\n\t\tconst suspended: string[] = [];\n\t\tfor (const attempt of Object.values(this.ledger.runtime.getSnapshot().attempts)) {\n\t\t\tif (\n\t\t\t\t(attempt.status !== \"leased\" && attempt.status !== \"running\") ||\n\t\t\t\t!attempt.agentId ||\n\t\t\t\tattempt.dispatch.executionKind === \"managed-process\" ||\n\t\t\t\t!attempt.lease\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst ownsAttempt =\n\t\t\t\townerId !== undefined\n\t\t\t\t\t? attempt.lease.ownerId === ownerId\n\t\t\t\t\t: isLocalWorkerProcessOwnerProvenDead(attempt.lease.ownerId, this.isProcessAlive);\n\t\t\tif (!ownsAttempt) continue;\n\t\t\tthis.suspendBoundAttempt({\n\t\t\t\tlaneId: attempt.taskId,\n\t\t\t\townerId: attempt.lease.ownerId,\n\t\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\t\treasonCode:\n\t\t\t\t\townerId === undefined ? \"agent_process_recovered_after_owner_exit\" : \"agent_process_interrupted\",\n\t\t\t});\n\t\t\tsuspended.push(attempt.attemptId);\n\t\t}\n\t\treturn suspended;\n\t}\n\n\t/**\n\t * Applies an explicitly authorized restart suspension. The caller must identify both the logical\n\t * lane and the current lease fence; process liveness policy is intentionally kept by this class.\n\t */\n\tsuspendBoundAttempt(args: {\n\t\tlaneId: string;\n\t\townerId: string;\n\t\tleaseId: string;\n\t\tfencingToken: number;\n\t\treasonCode: string;\n\t\tretry?: AttemptRetryState;\n\t}): void {\n\t\tconst attempt = this.getActiveAttempt(args.laneId);\n\t\tif (!attempt || !attempt.agentId || !attempt.lease) {\n\t\t\tthrow new Error(`Durable worker '${args.laneId}' has no live agent-bound attempt for suspension.`);\n\t\t}\n\t\tthis.ledger.runtime.suspendBoundAttempt({\n\t\t\tattemptId: attempt.attemptId,\n\t\t\townerId: args.ownerId,\n\t\t\tleaseId: args.leaseId,\n\t\t\tfencingToken: args.fencingToken,\n\t\t\treasonCode: args.reasonCode,\n\t\t\t...(args.retry ? { retry: args.retry } : {}),\n\t\t});\n\t}\n\n\tresumeAgent(laneId: string, agentId: string, leaseTtlMs: number, ownerId = agentId): StartedDelegationAttempt {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt) throw new Error(`Durable worker '${laneId}' has no resumable attempt.`);\n\t\tthis.ledger.runtime.assertAttemptReadyForResume(attempt.attemptId);\n\t\tthis.ledger.runtime.requestAgentResume(agentId, attempt.attemptId);\n\t\tconst lease = this.ledger.runtime.resumeAttempt(attempt.attemptId, agentId, leaseTtlMs, ownerId);\n\t\treturn this.startedHandle(this.ledger.runtime.startAttempt(attempt.attemptId, lease.leaseId, lease.fencingToken));\n\t}\n\n\tsuspendAgent(\n\t\tlaneId: string,\n\t\tagentId: string,\n\t\townerId: string,\n\t\treasonCode = \"agent_interrupted\",\n\t\tretry?: AttemptRetryState,\n\t): void {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt || attempt.agentId !== agentId || !attempt.lease) {\n\t\t\tthrow new Error(`Logical worker '${agentId}' has no live attempt for interruption.`);\n\t\t}\n\t\tthis.suspendBoundAttempt({\n\t\t\tlaneId,\n\t\t\townerId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\treasonCode,\n\t\t\t...(retry ? { retry } : {}),\n\t\t});\n\t}\n\n\tscheduleAgentRetry(args: {\n\t\tlaneId: string;\n\t\tagentId: string;\n\t\townerId: string;\n\t\treasonCode: string;\n\t\tretry: AttemptRetryState;\n\t}): AttemptRuntimeState {\n\t\tthis.suspendAgent(args.laneId, args.agentId, args.ownerId, args.reasonCode, args.retry);\n\t\tconst attempt = this.getActiveAttempt(args.laneId);\n\t\tif (!attempt) throw new Error(`Durable worker '${args.laneId}' disappeared after retry suspension.`);\n\t\treturn attempt;\n\t}\n\n\tbindGrant(attemptId: string, grant: ExecutionGrant): void {\n\t\tthis.ledger.runtime.bindAttemptGrant(attemptId, grant);\n\t}\n\n\tfinish(result: WorkerResultContract, options: { notify?: boolean } = {}): LaneRecord {\n\t\tthis.ledger.runtime.finishAttempt(result);\n\t\tconst record = this.getRecord(result.taskId);\n\t\tif (!record) throw new Error(`Durable worker '${result.taskId}' was not projected after completion.`);\n\t\tif (options.notify !== false) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\treconcileVerification(args: {\n\t\tsubjectTaskId: string;\n\t\tverifierTaskId: string;\n\t\tverifierAttemptId: string;\n\t\tverdict: \"accepted\" | \"rejected\" | \"inconclusive\";\n\t\treasonCode: string;\n\t}): LaneRecord {\n\t\tthis.ledger.runtime.finishVerification({\n\t\t\ttaskId: args.subjectTaskId,\n\t\t\tverifierTaskId: args.verifierTaskId,\n\t\t\tverifierAttemptId: args.verifierAttemptId,\n\t\t\tverdict: args.verdict,\n\t\t\treasonCode: args.reasonCode,\n\t\t});\n\t\tconst subject = this.getRecord(args.subjectTaskId);\n\t\tif (!subject) throw new Error(`Verified worker '${args.subjectTaskId}' was not projected.`);\n\t\tthis.enqueueTerminalNotification(subject);\n\t\treturn subject;\n\t}\n\n\tcancel(laneId: string, reasonCode: string): LaneRecord | undefined {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt) return this.getRecord(laneId);\n\t\tthis.ledger.cancel(attempt.attemptId, reasonCode);\n\t\tconst record = this.getRecord(laneId);\n\t\tif (record) this.enqueueTerminalNotification(record);\n\t\treturn record;\n\t}\n\n\trecoverQueued(): Array<{\n\t\trecord: LaneRecord;\n\t\tattempt: AttemptRuntimeState;\n\t\tverificationOfTaskId?: string;\n\t}> {\n\t\treturn this.ledger.recoverQueuedDispatches().flatMap((attempt) => {\n\t\t\tif (isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = this.getRecord(attempt.taskId);\n\t\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId]?.task;\n\t\t\treturn record\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trecord,\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t...(task?.verificationOfTaskId ? { verificationOfTaskId: task.verificationOfTaskId } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [];\n\t\t});\n\t}\n\n\t/** Close crash windows between implementation completion, verifier dispatch, and reconciliation. */\n\tgetPendingVerificationRecoveries(): PendingVerificationRecovery[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.tasks).flatMap<PendingVerificationRecovery>((subject) => {\n\t\t\tif (subject.verification) return [];\n\t\t\tconst implementationAttempt = selectedWorkerAttempt(snapshot, subject.task.taskId);\n\t\t\tif (implementationAttempt?.result?.nextAction !== \"independent_verification_required\") return [];\n\t\t\tconst verifier = Object.values(snapshot.tasks)\n\t\t\t\t.filter((candidate) => candidate.task.verificationOfTaskId === subject.task.taskId)\n\t\t\t\t.at(-1);\n\t\t\tif (!verifier) {\n\t\t\t\tconst verifierExecutionContract = implementationAttempt.dispatch.executionContract\n\t\t\t\t\t? verifierWorkerExecutionContract(implementationAttempt.dispatch.executionContract)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"dispatch\" as const,\n\t\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\t\timplementationProfileId: implementationAttempt.dispatch.profileId,\n\t\t\t\t\t\tsummary: implementationAttempt.result.summary,\n\t\t\t\t\t\tartifactUris: implementationAttempt.result.artifacts.map((artifact) => artifact.uri),\n\t\t\t\t\t\t...(verifierExecutionContract ? { verifierExecutionContract } : {}),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\tconst verifierAttempt = selectedWorkerAttempt(snapshot, verifier.task.taskId);\n\t\t\tif (!verifierAttempt || NONTERMINAL_WORKER_ATTEMPT_STATUSES.has(verifierAttempt.status)) return [];\n\t\t\tconst review = verifierAttempt.result?.evidence.find(\n\t\t\t\t(evidence) =>\n\t\t\t\t\tevidence.trusted &&\n\t\t\t\t\tevidence.kind === \"review\" &&\n\t\t\t\t\tevidence.metadata?.subjectTaskId === subject.task.taskId &&\n\t\t\t\t\t(evidence.metadata.verdict === \"accepted\" || evidence.metadata.verdict === \"rejected\"),\n\t\t\t);\n\t\t\tconst verdictValue = review?.metadata?.verdict;\n\t\t\tconst verdict = verdictValue === \"accepted\" || verdictValue === \"rejected\" ? verdictValue : \"inconclusive\";\n\t\t\tconst reasonCodesValue = review?.metadata?.reasonCodes;\n\t\t\tconst reasonCodes = Array.isArray(reasonCodesValue)\n\t\t\t\t? reasonCodesValue.filter((reasonCode): reasonCode is string => typeof reasonCode === \"string\")\n\t\t\t\t: [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\taction: \"reconcile\" as const,\n\t\t\t\t\tsubjectTaskId: subject.task.taskId,\n\t\t\t\t\tverifierTaskId: verifier.task.taskId,\n\t\t\t\t\tverifierAttemptId: verifierAttempt.attemptId,\n\t\t\t\t\tverdict,\n\t\t\t\t\treasonCode:\n\t\t\t\t\t\tverdict === \"accepted\"\n\t\t\t\t\t\t\t? \"independent_verification_accepted\"\n\t\t\t\t\t\t\t: verdict === \"rejected\"\n\t\t\t\t\t\t\t\t? `independent_verification_rejected:${reasonCodes.join(\",\") || \"unspecified\"}`\n\t\t\t\t\t\t\t\t: `independent_verification_inconclusive:${verifierAttempt.reasonCode ?? verifierAttempt.result?.reasonCode ?? \"interrupted\"}`,\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t}\n\n\tgetTask(taskId: string): TaskRuntimeProjection[\"tasks\"][string] | undefined {\n\t\treturn this.ledger.runtime.getSnapshot().tasks[taskId];\n\t}\n\n\tgetAgent(agentId: string): AgentBindingContract | undefined {\n\t\treturn this.ledger.runtime.getSnapshot().agents[agentId];\n\t}\n\n\tgetLatestAgentAttempt(agentId: string): AttemptRuntimeState | undefined {\n\t\treturn latestAgentAttemptByDurableOrder(this.ledger.runtime.getSnapshot(), agentId);\n\t}\n\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection {\n\t\treturn this.ledger.runtime.getSnapshot();\n\t}\n\n\t/** Read-only dispatch gate for an already persisted queued worker attempt. */\n\tgetAttemptDispatchReadiness(attemptId: string): AttemptDispatchReadiness {\n\t\treturn this.ledger.runtime.getAttemptDispatchReadiness(attemptId);\n\t}\n\n\tgetRecords(): LaneRecord[] {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).flatMap((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\tif (!attempt || isManagedWorkerAttempt(attempt)) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\treturn record ? [record] : [];\n\t\t});\n\t}\n\n\tgetManagedRecords(): LaneRecord[] {\n\t\treturn projectManagedWorkerLaneRecords(this.ledger.runtime.getSnapshot());\n\t}\n\n\tgetAllRecords(): LaneRecord[] {\n\t\treturn [...this.getRecords(), ...this.getManagedRecords()];\n\t}\n\n\tgetRecord(laneId: string): LaneRecord | undefined {\n\t\treturn projectWorkerLaneRecord(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedRecord(laneId: string): LaneRecord | undefined {\n\t\treturn this.getManagedRecords().find((record) => record.laneId === laneId);\n\t}\n\n\tgetManagedAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedManagedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetManagedHandle(laneId: string): StartedDelegationAttempt | undefined {\n\t\tconst attempt = this.getManagedAttempt(laneId);\n\t\treturn attempt?.lease ? this.startedHandle(attempt) : undefined;\n\t}\n\n\tgetActiveAttempt(laneId: string): AttemptRuntimeState | undefined {\n\t\treturn selectedWorkerAttempt(this.ledger.runtime.getSnapshot(), laneId);\n\t}\n\n\tgetAttemptUsage(laneId: string): AttemptUsageSnapshot | undefined {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\treturn attempt ? this.ledger.getAttemptUsage(attempt.attemptId) : undefined;\n\t}\n\n\tgetRunningCount(profileId?: string): number {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.keys(snapshot.tasks).filter((taskId) => {\n\t\t\tconst attempt = selectedWorkerAttempt(snapshot, taskId);\n\t\t\treturn (\n\t\t\t\tattempt?.status === \"running\" &&\n\t\t\t\t!isManagedWorkerAttempt(attempt) &&\n\t\t\t\t(!profileId || attempt.dispatch.profileId === profileId)\n\t\t\t);\n\t\t}).length;\n\t}\n\n\tgetPendingTerminalNotifications(): Array<{ notificationId: string; record: LaneRecord }> {\n\t\tthis.ensureTerminalNotifications();\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\treturn Object.values(snapshot.notifications).flatMap((notification) => {\n\t\t\tif (notification.status !== \"pending\" || !notification.attemptId) return [];\n\t\t\tconst attempt = snapshot.attempts[notification.attemptId];\n\t\t\tif (!attempt) return [];\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, attempt.taskId);\n\t\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return [];\n\t\t\treturn [{ notificationId: notification.notificationId, record }];\n\t\t});\n\t}\n\n\tgetTerminalNotification(\n\t\tlaneId: string,\n\t): { notificationId: string; status: \"pending\" | \"delivered\"; record: LaneRecord } | undefined {\n\t\tconst record = this.getRecord(laneId) ?? this.getManagedRecord(laneId);\n\t\tif (!record || record.status === \"queued\" || record.status === \"running\") return undefined;\n\t\tthis.enqueueTerminalNotification(record);\n\t\tconst attempt = this.getActiveAttempt(laneId) ?? this.getManagedAttempt(laneId);\n\t\tif (!attempt) return undefined;\n\t\tconst notificationId = `worker-terminal:${attempt.attemptId}`;\n\t\tconst notification = this.ledger.runtime.getSnapshot().notifications[notificationId];\n\t\treturn notification ? { notificationId, status: notification.status, record } : undefined;\n\t}\n\n\tmarkNotificationsDelivered(notificationIds: readonly string[]): void {\n\t\tfor (const notificationId of notificationIds) this.ledger.runtime.markNotificationDelivered(notificationId);\n\t}\n\n\tprivate ensureTerminalNotifications(): void {\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tfor (const taskId of Object.keys(snapshot.tasks)) {\n\t\t\tconst record = projectWorkerLaneRecord(snapshot, taskId);\n\t\t\tif (record && record.status !== \"queued\" && record.status !== \"running\") {\n\t\t\t\tthis.enqueueTerminalNotification(record);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate enqueueTerminalNotification(record: LaneRecord): void {\n\t\tconst attempt = this.getActiveAttempt(record.laneId) ?? this.getManagedAttempt(record.laneId);\n\t\tif (!attempt || NONTERMINAL_WORKER_ATTEMPT_STATUSES.has(attempt.status)) return;\n\t\tconst snapshot = this.ledger.runtime.getSnapshot();\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) return;\n\t\tif (attempt.result?.nextAction === \"independent_verification_required\" && !task.verification) return;\n\t\tthis.ledger.runtime.enqueueNotification({\n\t\t\tnotificationId: `worker-terminal:${attempt.attemptId}`,\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tmessage: `Worker ${record.laneId} reached ${record.status}.`,\n\t\t});\n\t}\n\n\tprivate requireActiveAttempt(laneId: string): AttemptRuntimeState {\n\t\tconst attempt = this.getActiveAttempt(laneId);\n\t\tif (!attempt || !ACTIVE_WORKER_ATTEMPT_STATUSES.has(attempt.status)) {\n\t\t\tthrow new Error(`Durable worker '${laneId}' has no active attempt.`);\n\t\t}\n\t\treturn attempt;\n\t}\n\n\tprivate startedHandle(attempt: AttemptRuntimeState): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task || !attempt.lease) throw new Error(`Attempt '${attempt.attemptId}' has no started handle.`);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t\tleaseId: attempt.lease.leaseId,\n\t\t\tfencingToken: attempt.lease.fencingToken,\n\t\t\texpiresAt: attempt.lease.expiresAt,\n\t\t};\n\t}\n\n\tprivate startPreparedManagedAttempt(\n\t\tattempt: AttemptRuntimeState,\n\t\tleaseTtlMs: number,\n\t\tcompileGrant: (target: { objectiveId: string; taskId: string; attemptId: string }) => ExecutionGrant,\n\t): StartedDelegationAttempt {\n\t\tconst task = this.ledger.runtime.getSnapshot().tasks[attempt.taskId];\n\t\tif (!task) throw new Error(`Managed attempt '${attempt.attemptId}' has no durable task.`);\n\t\tconst grant = compileGrant({\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId: attempt.attemptId,\n\t\t});\n\t\tthis.bindGrant(attempt.attemptId, grant);\n\t\treturn this.ledger.start(\n\t\t\tattempt.attemptId,\n\t\t\tleaseTtlMs,\n\t\t\t`managed:${attempt.dispatch.logicalLaneId ?? attempt.taskId}`,\n\t\t);\n\t}\n}\n"]}
@@ -26,11 +26,15 @@ export declare class WorkerNotificationCoordinator {
26
26
  private scheduled;
27
27
  private disposed;
28
28
  private deliveryTail;
29
+ private retryTimer;
30
+ private retryCount;
29
31
  constructor(options: WorkerNotificationCoordinatorOptions);
30
32
  recordTerminal(record: LaneRecord, durableNotificationId?: string): void;
31
33
  statusChanged(): void;
32
34
  dispose(): void;
33
35
  private schedule;
36
+ private scheduleRetry;
37
+ private warnBestEffort;
34
38
  private flush;
35
39
  }
36
40
  //# sourceMappingURL=worker-notification-coordinator.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker-notification-coordinator.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-notification-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAIlF,MAAM,WAAW,2BAA2B;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,wBAAwB;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,gBAAgB,EAAE,MAAM,CAAC;IACzB,kBAAkB,EAAE,SAAS,2BAA2B,EAAE,CAAC;CAC3D;AAQD,MAAM,WAAW,oCAAoC;IACpD,gBAAgB,IAAI,SAAS,UAAU,EAAE,CAAC;IAC1C,UAAU,CAAC,MAAM,EAAE,wBAAwB,GAAG,IAAI,CAAC;IACnD,MAAM,CAAC,OAAO,EAAE,SAAS,2BAA2B,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvE,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,oBAAoB,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAAC;CAC/D;AAED,sGAAsG;AACtG,qBAAa,6BAA6B;IACzC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuC;IAC/D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgD;IACxE,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,YAAY,CAAqB;IAEzC,YAAY,OAAO,EAAE,oCAAoC,EAExD;IAED,cAAc,CAAC,MAAM,EAAE,UAAU,EAAE,qBAAqB,CAAC,EAAE,MAAM,GAAG,IAAI,CAavE;IAED,aAAa,IAAI,IAAI,CAEpB;IAED,OAAO,IAAI,IAAI,CAId;IAED,OAAO,CAAC,QAAQ;IAMhB,OAAO,CAAC,KAAK;CA+Cb"}
1
+ {"version":3,"file":"worker-notification-coordinator.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-notification-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EA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ED,OAAO,CAAC,QAAQ;IAQhB,OAAO,CAAC,aAAa;IAWrB,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,KAAK;CA+Db"}
@@ -6,6 +6,7 @@ export class WorkerNotificationCoordinator {
6
6
  this.scheduled = false;
7
7
  this.disposed = false;
8
8
  this.deliveryTail = Promise.resolve();
9
+ this.retryCount = 0;
9
10
  this.options = options;
10
11
  }
11
12
  recordTerminal(record, durableNotificationId) {
@@ -29,32 +30,70 @@ export class WorkerNotificationCoordinator {
29
30
  dispose() {
30
31
  this.disposed = true;
31
32
  this.scheduled = false;
33
+ if (this.retryTimer)
34
+ clearTimeout(this.retryTimer);
35
+ this.retryTimer = undefined;
32
36
  this.pending.clear();
33
37
  }
34
38
  schedule() {
35
39
  if (this.disposed || this.scheduled)
36
40
  return;
41
+ if (this.retryTimer)
42
+ clearTimeout(this.retryTimer);
43
+ this.retryTimer = undefined;
37
44
  this.scheduled = true;
38
45
  queueMicrotask(() => this.flush());
39
46
  }
47
+ scheduleRetry() {
48
+ if (this.disposed || this.scheduled || this.retryTimer)
49
+ return;
50
+ const delayMs = Math.min(100 * 2 ** Math.min(this.retryCount, 5), 5_000);
51
+ this.retryCount++;
52
+ this.retryTimer = setTimeout(() => {
53
+ this.retryTimer = undefined;
54
+ this.schedule();
55
+ }, delayMs);
56
+ if (typeof this.retryTimer === "object" && "unref" in this.retryTimer)
57
+ this.retryTimer.unref();
58
+ }
59
+ warnBestEffort(message) {
60
+ try {
61
+ this.options.warn(message);
62
+ }
63
+ catch {
64
+ // Diagnostics cannot consume or stop durable notification delivery.
65
+ }
66
+ }
40
67
  flush() {
41
68
  this.scheduled = false;
42
69
  if (this.disposed)
43
70
  return;
44
71
  const batch = [...this.pending.values()];
45
72
  this.pending.clear();
46
- const workerRecords = this.options.getWorkerRecords();
73
+ let workerRecords = [];
74
+ try {
75
+ workerRecords = this.options.getWorkerRecords();
76
+ }
77
+ catch (error) {
78
+ this.warnBestEffort(`Background worker status projection failed: ${error instanceof Error ? error.message : String(error)}`);
79
+ }
47
80
  const queued = workerRecords.filter((record) => record.status === "queued").length;
48
81
  const running = workerRecords.filter((record) => record.status === "running").length;
49
82
  const terminalSinceFlush = batch.map((notification) => notification.record);
50
- this.options.emitStatus({
83
+ const status = {
51
84
  active: queued + running,
52
85
  queued,
53
86
  running,
54
87
  completedSinceFlush: terminalSinceFlush.filter((record) => record.status === "succeeded").length,
55
88
  failedSinceFlush: terminalSinceFlush.filter((record) => record.status !== "succeeded").length,
56
89
  terminalSinceFlush,
57
- });
90
+ };
91
+ try {
92
+ this.options.emitStatus(status);
93
+ }
94
+ catch (error) {
95
+ this.warnBestEffort(`Background worker status observer failed: ${error instanceof Error ? error.message : String(error)}`);
96
+ }
58
97
  if (batch.length === 0)
59
98
  return;
60
99
  const delivery = this.deliveryTail.then(async () => {
@@ -70,6 +109,7 @@ export class WorkerNotificationCoordinator {
70
109
  timeout.unref();
71
110
  }),
72
111
  ]);
112
+ this.retryCount = 0;
73
113
  const durableIds = batch.flatMap((notification) => notification.durableNotificationId ? [notification.durableNotificationId] : []);
74
114
  if (durableIds.length > 0)
75
115
  this.options.markDurableDelivered(durableIds);
@@ -82,7 +122,8 @@ export class WorkerNotificationCoordinator {
82
122
  this.deliveryTail = delivery.catch((error) => {
83
123
  for (const notification of batch)
84
124
  this.pending.set(notification.key, notification);
85
- this.options.warn(`Background worker handoff failed: ${error instanceof Error ? error.message : String(error)}`);
125
+ this.warnBestEffort(`Background worker handoff failed: ${error instanceof Error ? error.message : String(error)}`);
126
+ this.scheduleRetry();
86
127
  });
87
128
  }
88
129
  }
@@ -1 +1 @@
1
- {"version":3,"file":"worker-notification-coordinator.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-notification-coordinator.ts"],"names":[],"mappings":"AAEA,MAAM,kBAAkB,GAAG,MAAM,CAAC;AA+BlC,sGAAsG;AACtG,MAAM,OAAO,6BAA6B;IAOzC,YAAY,OAA6C;QALxC,YAAO,GAAG,IAAI,GAAG,E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,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC7F,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { LaneRecord, LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\n\nconst HANDOFF_TIMEOUT_MS = 30_000;\n\nexport interface WorkerTerminalHandoffRecord {\n\tlaneId: string;\n\tstatus: LaneTerminalStatus;\n\treasonCode?: string;\n}\n\nexport interface WorkerNotificationStatus {\n\tactive: number;\n\tqueued: number;\n\trunning: number;\n\tcompletedSinceFlush: number;\n\tfailedSinceFlush: number;\n\tterminalSinceFlush: readonly WorkerTerminalHandoffRecord[];\n}\n\ninterface PendingWorkerNotification {\n\tkey: string;\n\trecord: WorkerTerminalHandoffRecord;\n\tdurableNotificationId?: string;\n}\n\nexport interface WorkerNotificationCoordinatorOptions {\n\tgetWorkerRecords(): readonly LaneRecord[];\n\temitStatus(status: WorkerNotificationStatus): void;\n\tnotify(records: readonly WorkerTerminalHandoffRecord[]): Promise<void>;\n\twarn(message: string): void;\n\tmarkDurableDelivered(notificationIds: readonly string[]): void;\n}\n\n/** Event-driven, bounded terminal outbox. Durable worker events can be replayed into it on resume. */\nexport class WorkerNotificationCoordinator {\n\tprivate readonly options: WorkerNotificationCoordinatorOptions;\n\tprivate readonly pending = new Map<string, PendingWorkerNotification>();\n\tprivate scheduled = false;\n\tprivate disposed = false;\n\tprivate deliveryTail = Promise.resolve();\n\n\tconstructor(options: WorkerNotificationCoordinatorOptions) {\n\t\tthis.options = options;\n\t}\n\n\trecordTerminal(record: LaneRecord, durableNotificationId?: string): void {\n\t\tif (record.status === \"queued\" || record.status === \"running\") return;\n\t\tconst key = durableNotificationId ?? `transient:${record.laneId}:${record.completedAt ?? record.status}`;\n\t\tthis.pending.set(key, {\n\t\t\tkey,\n\t\t\trecord: {\n\t\t\t\tlaneId: record.laneId,\n\t\t\t\tstatus: record.status,\n\t\t\t\t...(record.reasonCode ? { reasonCode: record.reasonCode } : {}),\n\t\t\t},\n\t\t\t...(durableNotificationId ? { durableNotificationId } : {}),\n\t\t});\n\t\tthis.schedule();\n\t}\n\n\tstatusChanged(): void {\n\t\tthis.schedule();\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.scheduled = false;\n\t\tthis.pending.clear();\n\t}\n\n\tprivate schedule(): void {\n\t\tif (this.disposed || this.scheduled) return;\n\t\tthis.scheduled = true;\n\t\tqueueMicrotask(() => this.flush());\n\t}\n\n\tprivate flush(): void {\n\t\tthis.scheduled = false;\n\t\tif (this.disposed) return;\n\t\tconst batch = [...this.pending.values()];\n\t\tthis.pending.clear();\n\t\tconst workerRecords = this.options.getWorkerRecords();\n\t\tconst queued = workerRecords.filter((record) => record.status === \"queued\").length;\n\t\tconst running = workerRecords.filter((record) => record.status === \"running\").length;\n\t\tconst terminalSinceFlush = batch.map((notification) => notification.record);\n\t\tthis.options.emitStatus({\n\t\t\tactive: queued + running,\n\t\t\tqueued,\n\t\t\trunning,\n\t\t\tcompletedSinceFlush: terminalSinceFlush.filter((record) => record.status === \"succeeded\").length,\n\t\t\tfailedSinceFlush: terminalSinceFlush.filter((record) => record.status !== \"succeeded\").length,\n\t\t\tterminalSinceFlush,\n\t\t});\n\t\tif (batch.length === 0) return;\n\t\tconst delivery = this.deliveryTail.then(async () => {\n\t\t\tif (this.disposed) return;\n\t\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\t\ttry {\n\t\t\t\tawait Promise.race([\n\t\t\t\t\tthis.options.notify(terminalSinceFlush),\n\t\t\t\t\tnew Promise<never>((_resolve, reject) => {\n\t\t\t\t\t\ttimeout = setTimeout(\n\t\t\t\t\t\t\t() => reject(new Error(`worker terminal handoff timed out after ${HANDOFF_TIMEOUT_MS}ms`)),\n\t\t\t\t\t\t\tHANDOFF_TIMEOUT_MS,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (typeof timeout === \"object\" && timeout && \"unref\" in timeout) timeout.unref();\n\t\t\t\t\t}),\n\t\t\t\t]);\n\t\t\t\tconst durableIds = batch.flatMap((notification) =>\n\t\t\t\t\tnotification.durableNotificationId ? [notification.durableNotificationId] : [],\n\t\t\t\t);\n\t\t\t\tif (durableIds.length > 0) this.options.markDurableDelivered(durableIds);\n\t\t\t} finally {\n\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t}\n\t\t});\n\t\tthis.deliveryTail = delivery.catch((error: unknown) => {\n\t\t\tfor (const notification of batch) this.pending.set(notification.key, notification);\n\t\t\tthis.options.warn(\n\t\t\t\t`Background worker handoff failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t});\n\t}\n}\n"]}
1
+ {"version":3,"file":"worker-notification-coordinator.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-notification-coordinator.ts"],"names":[],"mappings":"AAEA,MAAM,kBAAkB,GAAG,MAAM,CAAC;AA+BlC,sGAAsG;AACtG,MAAM,OAAO,6BAA6B;IASzC,YAAY,OAA6C;QAPxC,YAAO,GAAG,IAAI,GAAG,EAAqC,CAAC;QAChE,cAAS,GAAG,KAAK,CAAC;QAClB,aAAQ,GAAG,KAAK,CAAC;QACjB,iBAAY,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;QAEjC,eAAU,GAAG,CAAC,CAAC;QAGtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;IAED,cAAc,CAAC,MAAkB,EAAE,qBAA8B;QAChE,IAAI,MAAM,CAAC,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO;QACtE,MAAM,GAAG,GAAG,qBAAqB,IAAI,aAAa,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QACzG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE;YACrB,GAAG;YACH,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CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { LaneRecord, LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\n\nconst HANDOFF_TIMEOUT_MS = 30_000;\n\nexport interface WorkerTerminalHandoffRecord {\n\tlaneId: string;\n\tstatus: LaneTerminalStatus;\n\treasonCode?: string;\n}\n\nexport interface WorkerNotificationStatus {\n\tactive: number;\n\tqueued: number;\n\trunning: number;\n\tcompletedSinceFlush: number;\n\tfailedSinceFlush: number;\n\tterminalSinceFlush: readonly WorkerTerminalHandoffRecord[];\n}\n\ninterface PendingWorkerNotification {\n\tkey: string;\n\trecord: WorkerTerminalHandoffRecord;\n\tdurableNotificationId?: string;\n}\n\nexport interface WorkerNotificationCoordinatorOptions {\n\tgetWorkerRecords(): readonly LaneRecord[];\n\temitStatus(status: WorkerNotificationStatus): void;\n\tnotify(records: readonly WorkerTerminalHandoffRecord[]): Promise<void>;\n\twarn(message: string): void;\n\tmarkDurableDelivered(notificationIds: readonly string[]): void;\n}\n\n/** Event-driven, bounded terminal outbox. Durable worker events can be replayed into it on resume. */\nexport class WorkerNotificationCoordinator {\n\tprivate readonly options: WorkerNotificationCoordinatorOptions;\n\tprivate readonly pending = new Map<string, PendingWorkerNotification>();\n\tprivate scheduled = false;\n\tprivate disposed = false;\n\tprivate deliveryTail = Promise.resolve();\n\tprivate retryTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate retryCount = 0;\n\n\tconstructor(options: WorkerNotificationCoordinatorOptions) {\n\t\tthis.options = options;\n\t}\n\n\trecordTerminal(record: LaneRecord, durableNotificationId?: string): void {\n\t\tif (record.status === \"queued\" || record.status === \"running\") return;\n\t\tconst key = durableNotificationId ?? `transient:${record.laneId}:${record.completedAt ?? record.status}`;\n\t\tthis.pending.set(key, {\n\t\t\tkey,\n\t\t\trecord: {\n\t\t\t\tlaneId: record.laneId,\n\t\t\t\tstatus: record.status,\n\t\t\t\t...(record.reasonCode ? { reasonCode: record.reasonCode } : {}),\n\t\t\t},\n\t\t\t...(durableNotificationId ? { durableNotificationId } : {}),\n\t\t});\n\t\tthis.schedule();\n\t}\n\n\tstatusChanged(): void {\n\t\tthis.schedule();\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.scheduled = false;\n\t\tif (this.retryTimer) clearTimeout(this.retryTimer);\n\t\tthis.retryTimer = undefined;\n\t\tthis.pending.clear();\n\t}\n\n\tprivate schedule(): void {\n\t\tif (this.disposed || this.scheduled) return;\n\t\tif (this.retryTimer) clearTimeout(this.retryTimer);\n\t\tthis.retryTimer = undefined;\n\t\tthis.scheduled = true;\n\t\tqueueMicrotask(() => this.flush());\n\t}\n\n\tprivate scheduleRetry(): void {\n\t\tif (this.disposed || this.scheduled || this.retryTimer) return;\n\t\tconst delayMs = Math.min(100 * 2 ** Math.min(this.retryCount, 5), 5_000);\n\t\tthis.retryCount++;\n\t\tthis.retryTimer = setTimeout(() => {\n\t\t\tthis.retryTimer = undefined;\n\t\t\tthis.schedule();\n\t\t}, delayMs);\n\t\tif (typeof this.retryTimer === \"object\" && \"unref\" in this.retryTimer) this.retryTimer.unref();\n\t}\n\n\tprivate warnBestEffort(message: string): void {\n\t\ttry {\n\t\t\tthis.options.warn(message);\n\t\t} catch {\n\t\t\t// Diagnostics cannot consume or stop durable notification delivery.\n\t\t}\n\t}\n\n\tprivate flush(): void {\n\t\tthis.scheduled = false;\n\t\tif (this.disposed) return;\n\t\tconst batch = [...this.pending.values()];\n\t\tthis.pending.clear();\n\t\tlet workerRecords: readonly LaneRecord[] = [];\n\t\ttry {\n\t\t\tworkerRecords = this.options.getWorkerRecords();\n\t\t} catch (error) {\n\t\t\tthis.warnBestEffort(\n\t\t\t\t`Background worker status projection failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tconst queued = workerRecords.filter((record) => record.status === \"queued\").length;\n\t\tconst running = workerRecords.filter((record) => record.status === \"running\").length;\n\t\tconst terminalSinceFlush = batch.map((notification) => notification.record);\n\t\tconst status = {\n\t\t\tactive: queued + running,\n\t\t\tqueued,\n\t\t\trunning,\n\t\t\tcompletedSinceFlush: terminalSinceFlush.filter((record) => record.status === \"succeeded\").length,\n\t\t\tfailedSinceFlush: terminalSinceFlush.filter((record) => record.status !== \"succeeded\").length,\n\t\t\tterminalSinceFlush,\n\t\t};\n\t\ttry {\n\t\t\tthis.options.emitStatus(status);\n\t\t} catch (error) {\n\t\t\tthis.warnBestEffort(\n\t\t\t\t`Background worker status observer failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (batch.length === 0) return;\n\t\tconst delivery = this.deliveryTail.then(async () => {\n\t\t\tif (this.disposed) return;\n\t\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\t\ttry {\n\t\t\t\tawait Promise.race([\n\t\t\t\t\tthis.options.notify(terminalSinceFlush),\n\t\t\t\t\tnew Promise<never>((_resolve, reject) => {\n\t\t\t\t\t\ttimeout = setTimeout(\n\t\t\t\t\t\t\t() => reject(new Error(`worker terminal handoff timed out after ${HANDOFF_TIMEOUT_MS}ms`)),\n\t\t\t\t\t\t\tHANDOFF_TIMEOUT_MS,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (typeof timeout === \"object\" && timeout && \"unref\" in timeout) timeout.unref();\n\t\t\t\t\t}),\n\t\t\t\t]);\n\t\t\t\tthis.retryCount = 0;\n\t\t\t\tconst durableIds = batch.flatMap((notification) =>\n\t\t\t\t\tnotification.durableNotificationId ? [notification.durableNotificationId] : [],\n\t\t\t\t);\n\t\t\t\tif (durableIds.length > 0) this.options.markDurableDelivered(durableIds);\n\t\t\t} finally {\n\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t}\n\t\t});\n\t\tthis.deliveryTail = delivery.catch((error: unknown) => {\n\t\t\tfor (const notification of batch) this.pending.set(notification.key, notification);\n\t\t\tthis.warnBestEffort(\n\t\t\t\t`Background worker handoff failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\tthis.scheduleRetry();\n\t\t});\n\t}\n}\n"]}
@@ -0,0 +1,50 @@
1
+ import type { Usage } from "@caupulican/pi-ai";
2
+ import type { GatewayUsageDelta, ProviderBudgetReservation } from "../orchestration/capability-gateway.ts";
3
+ export declare class WorkerCompletionProtocolError extends Error {
4
+ constructor(message: string);
5
+ }
6
+ /**
7
+ * Owns one provider request's reservation epochs and usage evidence. The caller remains responsible
8
+ * for persisting the assistant and checkpoint between accounting and consuming an epoch.
9
+ */
10
+ export declare class WorkerProviderTurnProtocol {
11
+ private readonly acquireReservation;
12
+ private readonly recordUsage;
13
+ private readonly signal;
14
+ private readonly onFailure;
15
+ private readonly callbackAccountedUsage;
16
+ private held;
17
+ private heldConsumed;
18
+ private assistantUsageAccounted;
19
+ private inFlight;
20
+ private generation;
21
+ private closed;
22
+ private successfulPreflights;
23
+ private consumedPreflights;
24
+ constructor(options: {
25
+ acquireReservation(): Promise<ProviderBudgetReservation>;
26
+ recordUsage?(delta: GatewayUsageDelta): void;
27
+ signal: AbortSignal;
28
+ onFailure(error: unknown): void;
29
+ });
30
+ requestPreflight(): Promise<{
31
+ maxTokens: number;
32
+ }>;
33
+ accountAssistantUsage(usage: Usage): void;
34
+ /** Account usage before releasing a tool-request turn for nested or subsequent provider work. */
35
+ consumeToolAssistantAndRelease(): void;
36
+ /** Account usage while retaining a terminal turn's remaining capacity through result verification. */
37
+ consumeTerminalAssistantAndHold(): void;
38
+ assertEverySuccessfulPreflightConsumed(): void;
39
+ assertProviderOutputPreflight(kind?: "completion" | "compaction"): void;
40
+ hasSuccessfulPreflight(): boolean;
41
+ hasOutstandingAssistantReservation(): boolean;
42
+ /** Conservatively charge only provider-result usage not already evidenced by assistant callbacks. */
43
+ accountUnverifiedResultUsageDelta(reported: Usage): boolean;
44
+ close(): void;
45
+ private consumeAccountedAssistant;
46
+ private assertOutstandingReservation;
47
+ private releaseHeldReservation;
48
+ private fail;
49
+ }
50
+ //# sourceMappingURL=worker-provider-turn-protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-provider-turn-protocol.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-provider-turn-protocol.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,KAAK,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAE3G,qBAAa,6BAA8B,SAAQ,KAAK;IACvD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAmCD;;;GAGG;AACH,qBAAa,0BAA0B;IACtC,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAA2C;IAC9E,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAmD;IAC/E,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2B;IACrD,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAsB;IAC7D,OAAO,CAAC,IAAI,CAAwC;IACpD,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,uBAAuB,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,oBAAoB,CAAK;IACjC,OAAO,CAAC,kBAAkB,CAAK;IAE/B,YAAY,OAAO,EAAE;QACpB,kBAAkB,IAAI,OAAO,CAAC,yBAAyB,CAAC,CAAC;QACzD,WAAW,CAAC,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;QAC7C,MAAM,EAAE,WAAW,CAAC;QACpB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;KAChC,EAKA;IAEK,gBAAgB,IAAI,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CAsCvD;IAED,qBAAqB,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAiB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