@caupulican/pi-adaptative 0.86.3 → 0.86.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/CHANGELOG.md +32 -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 +29 -2
  65. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  66. package/dist/core/delegation/worker-delegation-controller.js +625 -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-fleet-limits.d.ts +38 -0
  76. package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -0
  77. package/dist/core/delegation/worker-fleet-limits.js +113 -0
  78. package/dist/core/delegation/worker-fleet-limits.js.map +1 -0
  79. package/dist/core/delegation/worker-lane-projection.d.ts +1 -0
  80. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
  81. package/dist/core/delegation/worker-lane-projection.js +6 -2
  82. package/dist/core/delegation/worker-lane-projection.js.map +1 -1
  83. package/dist/core/delegation/worker-lifecycle.d.ts +20 -3
  84. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  85. package/dist/core/delegation/worker-lifecycle.js +42 -18
  86. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  87. package/dist/core/delegation/worker-notification-coordinator.d.ts +4 -0
  88. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  89. package/dist/core/delegation/worker-notification-coordinator.js +45 -4
  90. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  91. package/dist/core/delegation/worker-provider-turn-protocol.d.ts +50 -0
  92. package/dist/core/delegation/worker-provider-turn-protocol.d.ts.map +1 -0
  93. package/dist/core/delegation/worker-provider-turn-protocol.js +185 -0
  94. package/dist/core/delegation/worker-provider-turn-protocol.js.map +1 -0
  95. package/dist/core/delegation/worker-recovery-coordinator.d.ts +45 -4
  96. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  97. package/dist/core/delegation/worker-recovery-coordinator.js +223 -17
  98. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  99. package/dist/core/delegation/worker-retry-policy.d.ts +36 -0
  100. package/dist/core/delegation/worker-retry-policy.d.ts.map +1 -0
  101. package/dist/core/delegation/worker-retry-policy.js +41 -0
  102. package/dist/core/delegation/worker-retry-policy.js.map +1 -0
  103. package/dist/core/delegation/worker-runner.d.ts +3 -1
  104. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  105. package/dist/core/delegation/worker-runner.js +4 -2
  106. package/dist/core/delegation/worker-runner.js.map +1 -1
  107. package/dist/core/delegation/worker-task-view.d.ts +43 -0
  108. package/dist/core/delegation/worker-task-view.d.ts.map +1 -0
  109. package/dist/core/delegation/worker-task-view.js +194 -0
  110. package/dist/core/delegation/worker-task-view.js.map +1 -0
  111. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts +55 -0
  112. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts.map +1 -0
  113. package/dist/core/delegation/worker-terminal-handoff-coordinator.js +179 -0
  114. package/dist/core/delegation/worker-terminal-handoff-coordinator.js.map +1 -0
  115. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +2 -2
  116. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
  117. package/dist/core/delegation/worker-tree-budget-coordinator.js +12 -46
  118. package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
  119. package/dist/core/keybindings.d.ts +10 -0
  120. package/dist/core/keybindings.d.ts.map +1 -1
  121. package/dist/core/keybindings.js +2 -0
  122. package/dist/core/keybindings.js.map +1 -1
  123. package/dist/core/orchestration/attempt-ordering.d.ts +9 -0
  124. package/dist/core/orchestration/attempt-ordering.d.ts.map +1 -0
  125. package/dist/core/orchestration/attempt-ordering.js +29 -0
  126. package/dist/core/orchestration/attempt-ordering.js.map +1 -0
  127. package/dist/core/orchestration/capability-gateway.d.ts +19 -0
  128. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  129. package/dist/core/orchestration/capability-gateway.js +19 -2
  130. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  131. package/dist/core/orchestration/contracts.d.ts +43 -3
  132. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  133. package/dist/core/orchestration/contracts.js +24 -0
  134. package/dist/core/orchestration/contracts.js.map +1 -1
  135. package/dist/core/orchestration/delegation-ledger.d.ts +8 -3
  136. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  137. package/dist/core/orchestration/delegation-ledger.js +148 -55
  138. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  139. package/dist/core/orchestration/event-store.d.ts +6 -3
  140. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  141. package/dist/core/orchestration/event-store.js +228 -30
  142. package/dist/core/orchestration/event-store.js.map +1 -1
  143. package/dist/core/orchestration/task-runtime-codecs.d.ts +31 -0
  144. package/dist/core/orchestration/task-runtime-codecs.d.ts.map +1 -0
  145. package/dist/core/orchestration/task-runtime-codecs.js +1471 -0
  146. package/dist/core/orchestration/task-runtime-codecs.js.map +1 -0
  147. package/dist/core/orchestration/task-runtime-projection.d.ts +30 -0
  148. package/dist/core/orchestration/task-runtime-projection.d.ts.map +1 -0
  149. package/dist/core/orchestration/task-runtime-projection.js +340 -0
  150. package/dist/core/orchestration/task-runtime-projection.js.map +1 -0
  151. package/dist/core/orchestration/task-runtime-reducer.d.ts +38 -0
  152. package/dist/core/orchestration/task-runtime-reducer.d.ts.map +1 -0
  153. package/dist/core/orchestration/task-runtime-reducer.js +1270 -0
  154. package/dist/core/orchestration/task-runtime-reducer.js.map +1 -0
  155. package/dist/core/orchestration/task-runtime-state.d.ts +142 -0
  156. package/dist/core/orchestration/task-runtime-state.d.ts.map +1 -0
  157. package/dist/core/orchestration/task-runtime-state.js +14 -0
  158. package/dist/core/orchestration/task-runtime-state.js.map +1 -0
  159. package/dist/core/orchestration/task-runtime.d.ts +44 -98
  160. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  161. package/dist/core/orchestration/task-runtime.js +357 -1113
  162. package/dist/core/orchestration/task-runtime.js.map +1 -1
  163. package/dist/core/orchestration/worker-context-fork-reference.d.ts +20 -0
  164. package/dist/core/orchestration/worker-context-fork-reference.d.ts.map +1 -0
  165. package/dist/core/orchestration/worker-context-fork-reference.js +53 -0
  166. package/dist/core/orchestration/worker-context-fork-reference.js.map +1 -0
  167. package/dist/core/research/research-runner.d.ts +2 -0
  168. package/dist/core/research/research-runner.d.ts.map +1 -1
  169. package/dist/core/research/research-runner.js +1 -0
  170. package/dist/core/research/research-runner.js.map +1 -1
  171. package/dist/core/runtime-builder.d.ts.map +1 -1
  172. package/dist/core/runtime-builder.js +8 -0
  173. package/dist/core/runtime-builder.js.map +1 -1
  174. package/dist/core/secrets/credential-project.d.ts.map +1 -1
  175. package/dist/core/secrets/credential-project.js +24 -2
  176. package/dist/core/secrets/credential-project.js.map +1 -1
  177. package/dist/core/security/secret-text.d.ts +3 -0
  178. package/dist/core/security/secret-text.d.ts.map +1 -1
  179. package/dist/core/security/secret-text.js +15 -0
  180. package/dist/core/security/secret-text.js.map +1 -1
  181. package/dist/core/settings-manager.d.ts +3 -0
  182. package/dist/core/settings-manager.d.ts.map +1 -1
  183. package/dist/core/settings-manager.js +160 -8
  184. package/dist/core/settings-manager.js.map +1 -1
  185. package/dist/core/tools/delegate.d.ts +31 -4
  186. package/dist/core/tools/delegate.d.ts.map +1 -1
  187. package/dist/core/tools/delegate.js +749 -103
  188. package/dist/core/tools/delegate.js.map +1 -1
  189. package/dist/main.d.ts.map +1 -1
  190. package/dist/main.js +1 -0
  191. package/dist/main.js.map +1 -1
  192. package/dist/modes/interactive/components/activity-lane.d.ts +5 -0
  193. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  194. package/dist/modes/interactive/components/activity-lane.js +133 -49
  195. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  196. package/dist/modes/interactive/components/agents-overlay.d.ts +40 -0
  197. package/dist/modes/interactive/components/agents-overlay.d.ts.map +1 -0
  198. package/dist/modes/interactive/components/agents-overlay.js +153 -0
  199. package/dist/modes/interactive/components/agents-overlay.js.map +1 -0
  200. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  201. package/dist/modes/interactive/components/settings-selector.js +18 -13
  202. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  203. package/dist/modes/interactive/interactive-event-controller.d.ts +1 -1
  204. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -1
  205. package/dist/modes/interactive/interactive-event-controller.js +6 -3
  206. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  207. package/dist/modes/interactive/interactive-mode.d.ts +5 -0
  208. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  209. package/dist/modes/interactive/interactive-mode.js +51 -0
  210. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  211. package/dist/modes/interactive/key-handlers.d.ts +1 -0
  212. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  213. package/dist/modes/interactive/key-handlers.js +1 -0
  214. package/dist/modes/interactive/key-handlers.js.map +1 -1
  215. package/docs/harness-architecture.md +61 -17
  216. package/docs/settings.md +17 -9
  217. package/docs/worker-profiles.md +6 -2
  218. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  219. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  220. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  221. package/examples/extensions/sandbox/package-lock.json +2 -2
  222. package/examples/extensions/sandbox/package.json +1 -1
  223. package/examples/extensions/with-deps/package-lock.json +2 -2
  224. package/examples/extensions/with-deps/package.json +1 -1
  225. package/npm-shrinkwrap.json +12 -12
  226. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"delegation-ledger.js","sourceRoot":"","sources":["../../../src/core/orchestration/delegation-ledger.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAWxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAA4B,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC1G,OAAO,EAAE,eAAe,EAAE,6BAA6B,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AA+ClH,SAAS,aAAa,CAAC,OAA4B;IAClD,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC;AACnG,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,6BAA6B;IAIzC,YAAY,OAAgC;QAC3C,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,OAAO,GAAG,IAAI,kBAAkB,CAAC;YACrC,KAAK,EAAE,IAAI,uBAAuB,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;YAChG,GAAG,EAAE,OAAO,CAAC,GAAG;SAChB,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,CAAC,KAA6B;QACpC,MAAM,OAAO,GAAG,KAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC,OAAO,CAAC;QACvD,OAAO,IAAI,CAAC,iBAAiB,CAAC;YAC7B,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,YAAY,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AQ,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;QACvC,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,MAAM,CAC7C,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC,aAAa,KAAK,iBAAiB,CAChG,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { WorkerDelegationTaskContext } from \"../delegation/worker-delegation-request.ts\";\nimport { deriveWorkerTaskLabel } from \"../delegation/worker-task-label.ts\";\nimport { hasGoalAcceptanceOverride } from \"../goals/goal-acceptance.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport type {\n\tAgentBindingContract,\n\tAttemptUsageSnapshot,\n\tHarnessCapability,\n\tOrchestrationDispatchRequest,\n\tRiskBudget,\n\tWorkerExecutionContract,\n\tWorkerRole,\n} from \"./contracts.ts\";\nimport { OrchestrationEventStore } from \"./event-store.ts\";\nimport { type AttemptRuntimeState, DurableTaskRuntime, DurableTaskRuntimeError } from \"./task-runtime.ts\";\nimport { goalObjectiveId, projectGoalAcceptanceEvidence, projectGoalObjective } from \"./work-state-projection.ts\";\n\nexport interface DelegationLedgerOptions {\n\tagentDir: string;\n\tsessionId: string;\n\tnow?: () => number;\n}\n\nexport interface PrepareDelegationInput {\n\tlaneId: string;\n\tinstructions: string;\n\tparentAgentId?: string;\n\texecutionContract: WorkerExecutionContract;\n\trequiredCapabilities: readonly HarnessCapability[];\n\tgoal?: GoalState;\n\tverificationOfTaskId?: string;\n\ttaskContext?: WorkerDelegationTaskContext;\n}\n\nexport interface PrepareManagedDelegationInput {\n\tlaneId: string;\n\tdispatchSequence: number;\n\tinstructions: string;\n\tprofileId: string;\n\tprovider: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\triskBudget: RiskBudget;\n\tgoal?: GoalState;\n\tgoalId?: string;\n\tworktreeLaneKey?: string;\n}\n\nexport interface StartedDelegationAttempt {\n\tobjectiveId: string;\n\ttaskId: string;\n\tattemptId: string;\n\tleaseId: string;\n\tfencingToken: number;\n\texpiresAt: string;\n}\n\nexport interface PrepareAgentTurnInput {\n\tagentId: string;\n\tinstructions: string;\n}\n\nfunction activeAttempt(attempt: AttemptRuntimeState): boolean {\n\treturn attempt.status === \"queued\" || attempt.status === \"leased\" || attempt.status === \"running\";\n}\n\n/**\n * Durable adapter for in-process delegated completions. It records the dispatch before execution,\n * fences interrupted completions on restart, and returns queued work for event-driven re-dispatch.\n * It deliberately does not pretend an isolated completion has a resumable model transcript.\n */\nexport class DelegationOrchestrationLedger {\n\treadonly runtime: DurableTaskRuntime;\n\tprivate readonly sessionId: string;\n\n\tconstructor(options: DelegationLedgerOptions) {\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.runtime = new DurableTaskRuntime({\n\t\t\tstore: new OrchestrationEventStore({ agentDir: options.agentDir, sessionId: options.sessionId }),\n\t\t\tnow: options.now,\n\t\t});\n\t}\n\n\tprepare(input: PrepareDelegationInput): AttemptRuntimeState {\n\t\tconst profile = input.executionContract.worker.profile;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: input.laneId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: profile.profileId,\n\t\t\trole: profile.role,\n\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\triskBudget: profile.budget,\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\texecutionContract: input.executionContract,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.verificationOfTaskId ? { verificationOfTaskId: input.verificationOfTaskId } : {}),\n\t\t\t...(input.taskContext ? { taskContext: input.taskContext } : {}),\n\t\t\tdispatchMetadata: { logicalLaneId: input.laneId },\n\t\t});\n\t}\n\n\tprepareManaged(input: PrepareManagedDelegationInput): AttemptRuntimeState {\n\t\tif (!Number.isSafeInteger(input.dispatchSequence) || input.dispatchSequence < 1) {\n\t\t\tthrow new DurableTaskRuntimeError(\"Managed dispatch sequence must be a positive integer.\");\n\t\t}\n\t\tconst taskId = `${input.laneId}:turn:${input.dispatchSequence}`;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: input.profileId,\n\t\t\trole: input.role,\n\t\t\trequiredCapabilities: [],\n\t\t\triskBudget: input.riskBudget,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.goalId ? { goalId: input.goalId } : {}),\n\t\t\tdispatchMetadata: {\n\t\t\t\texecutionKind: \"managed-process\",\n\t\t\t\tlogicalLaneId: input.laneId,\n\t\t\t\tdispatchSequence: input.dispatchSequence,\n\t\t\t\tprovider: input.provider,\n\t\t\t\tauthorizationId: input.authorizationId,\n\t\t\t\t...(input.worktreeLaneKey ? { worktreeLaneKey: input.worktreeLaneKey } : {}),\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Queue one new turn for an existing logical agent. The agent identity and its immutable\n\t * execution contract are inherited from the last bound turn; the durable task and attempt ids\n\t * are intentionally new so retries, leases, and terminal evidence never collide across turns.\n\t */\n\tprepareAgentTurn(input: PrepareAgentTurnInput): AttemptRuntimeState {\n\t\tconst agentId = input.agentId.trim();\n\t\tconst instructions = input.instructions.trim();\n\t\tif (!agentId) throw new DurableTaskRuntimeError(\"Logical worker agent id is required.\");\n\t\tif (!instructions) throw new DurableTaskRuntimeError(\"Worker follow-up instructions are required.\");\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst agent = snapshot.agents[agentId];\n\t\tif (!agent) throw new DurableTaskRuntimeError(`Unknown logical worker agent '${agentId}'.`);\n\t\tif (agent.status !== \"registered\") {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' is not idle.`);\n\t\t}\n\t\tconst prior = this.latestAgentAttempt(snapshot, agent);\n\t\tconst contract = prior?.dispatch.executionContract;\n\t\tif (!prior || !contract) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no immutable execution contract.`);\n\t\t}\n\t\tconst priorTask = snapshot.tasks[prior.taskId]?.task;\n\t\tif (!priorTask) throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no prior durable task.`);\n\t\tconst sequence = Object.values(snapshot.attempts).filter((attempt) => attempt.agentId === agentId).length + 1;\n\t\tconst taskId = `${agentId}:turn:${sequence}`;\n\t\tif (snapshot.tasks[taskId]) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' already has turn ${sequence}.`);\n\t\t}\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions,\n\t\t\tprofileId: contract.worker.profile.profileId,\n\t\t\trole: agent.role,\n\t\t\trequiredCapabilities: contract.worker.authority.capabilities,\n\t\t\triskBudget: contract.worker.profile.budget,\n\t\t\ttaskContext: {\n\t\t\t\trequirementIds: prior.dispatch.requirementIds ?? [],\n\t\t\t\tdependsOnTaskIds: priorTask.dependsOn,\n\t\t\t\tacceptanceCriterionIds: priorTask.acceptanceCriterionIds,\n\t\t\t\tresourcePointerIds: prior.dispatch.resourcePointerIds,\n\t\t\t},\n\t\t\texecutionContract: contract,\n\t\t\tdispatchMetadata: {\n\t\t\t\tlogicalLaneId: agentId,\n\t\t\t\tdispatchSequence: sequence,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate latestAgentAttempt(\n\t\tsnapshot: ReturnType<DurableTaskRuntime[\"getSnapshot\"]>,\n\t\tagent: AgentBindingContract,\n\t): AttemptRuntimeState | undefined {\n\t\treturn Object.values(snapshot.attempts)\n\t\t\t.filter((attempt) => attempt.agentId === agent.agentId)\n\t\t\t.sort((left, right) => left.createdAt.localeCompare(right.createdAt))\n\t\t\t.at(-1);\n\t}\n\n\tprivate prepareNormalized(input: {\n\t\tlaneId: string;\n\t\tinstructions: string;\n\t\tprofileId: string;\n\t\trole: WorkerRole;\n\t\trequiredCapabilities: readonly HarnessCapability[];\n\t\triskBudget: RiskBudget;\n\t\tparentAgentId?: string;\n\t\tgoal?: GoalState;\n\t\tgoalId?: string;\n\t\tverificationOfTaskId?: string;\n\t\ttaskContext?: WorkerDelegationTaskContext;\n\t\texecutionContract?: WorkerExecutionContract;\n\t\tdispatchMetadata?: Pick<\n\t\t\tOrchestrationDispatchRequest,\n\t\t\t\"executionKind\" | \"logicalLaneId\" | \"dispatchSequence\" | \"provider\" | \"authorizationId\" | \"worktreeLaneKey\"\n\t\t>;\n\t}): AttemptRuntimeState {\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tconst existingVerificationSubject = input.verificationOfTaskId\n\t\t\t? snapshot.tasks[input.verificationOfTaskId]\n\t\t\t: undefined;\n\t\tif (input.verificationOfTaskId && !existingVerificationSubject) {\n\t\t\tthrow new DurableTaskRuntimeError(`Unknown verification subject '${input.verificationOfTaskId}'.`);\n\t\t}\n\t\tconst projectedGoal = input.goal ? projectGoalObjective(input.goal) : undefined;\n\t\tconst objectiveId =\n\t\t\texistingVerificationSubject?.task.objectiveId ??\n\t\t\tprojectedGoal?.objectiveId ??\n\t\t\t(input.goalId ? goalObjectiveId(input.goalId) : `session:${this.sessionId}`);\n\t\tif (input.goal && objectiveId === projectedGoal?.objectiveId) {\n\t\t\tthis.synchronizeGoalState(input.goal);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t} else if (!snapshot.objectives[objectiveId]) {\n\t\t\tthis.runtime.createObjective({\n\t\t\t\tobjectiveId,\n\t\t\t\ttitle: input.goalId ? `Goal ${input.goalId}` : `Session ${this.sessionId}`,\n\t\t\t\tdescription: input.goalId ? \"Externally managed goal work\" : \"Session-scoped delegated work\",\n\t\t\t});\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\n\t\tif (!snapshot.tasks[input.laneId]) {\n\t\t\tconst verificationSubject = input.verificationOfTaskId\n\t\t\t\t? snapshot.tasks[input.verificationOfTaskId]\n\t\t\t\t: undefined;\n\t\t\tthis.runtime.createTask({\n\t\t\t\ttaskId: input.laneId,\n\t\t\t\tobjectiveId,\n\t\t\t\ttitle: deriveWorkerTaskLabel(input.instructions, `Delegated ${input.role} work`),\n\t\t\t\tdescription: input.instructions,\n\t\t\t\trole: input.role,\n\t\t\t\tdependsOn: input.taskContext?.dependsOnTaskIds ?? [],\n\t\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\t\tacceptanceCriterionIds: input.taskContext?.acceptanceCriterionIds ?? [],\n\t\t\t\triskBudget: input.riskBudget,\n\t\t\t\t...(input.verificationOfTaskId\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tverificationOfTaskId: input.verificationOfTaskId,\n\t\t\t\t\t\t\tacceptanceCriterionIds: verificationSubject?.task.acceptanceCriterionIds ?? [],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\n\t\tconst task = snapshot.tasks[input.laneId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Failed to create task '${input.laneId}'.`);\n\t\tconst existing = [...task.attemptIds]\n\t\t\t.reverse()\n\t\t\t.map((attemptId) => snapshot.attempts[attemptId])\n\t\t\t.find((attempt): attempt is AttemptRuntimeState => attempt !== undefined && activeAttempt(attempt));\n\t\tif (existing) return existing;\n\n\t\treturn this.runtime.queueAttempt(input.laneId, {\n\t\t\ttaskId: input.laneId,\n\t\t\tprofileId: input.profileId,\n\t\t\tinstructions: input.instructions,\n\t\t\tresourcePointerIds: input.taskContext?.resourcePointerIds ?? [],\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\trequirementIds: input.taskContext?.requirementIds ?? [],\n\t\t\t...(input.executionContract ? { executionContract: input.executionContract } : {}),\n\t\t\t...input.dispatchMetadata,\n\t\t});\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tconst objective = projectGoalObjective(goal);\n\t\tthis.runtime.ensureObjective(objective);\n\t\tfor (const evidence of projectGoalAcceptanceEvidence(goal)) {\n\t\t\tthis.runtime.recordObjectiveEvidence(objective.objectiveId, evidence);\n\t\t}\n\t\tconst status = this.runtime.getSnapshot().objectives[goalObjectiveId(goal.goalId)]?.objective.status;\n\t\tswitch (goal.status) {\n\t\t\tcase \"active\":\n\t\t\t\tif (status === \"paused\") this.runtime.resumeObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"paused\":\n\t\t\tcase \"blocked\":\n\t\t\tcase \"usage_limited\":\n\t\t\tcase \"budget_limited\":\n\t\t\t\tif (status === \"active\") this.runtime.pauseObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"cancelled\":\n\t\t\t\tif (status !== \"cancelled\") this.runtime.cancelObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"completed\":\n\t\t\t\tif (status !== \"completed\") {\n\t\t\t\t\tthis.runtime.completeObjectiveFromOwner(objective.objectiveId, hasGoalAcceptanceOverride(goal));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tstart(\n\t\tattemptId: string,\n\t\tleaseTtlMs: number,\n\t\townerId = `in-process:${this.sessionId}`,\n\t\tagentId?: string,\n\t): StartedDelegationAttempt {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Unknown task '${attempt.taskId}'.`);\n\t\tconst lease = this.runtime.leaseAttempt(attemptId, ownerId, leaseTtlMs, agentId);\n\t\tthis.runtime.startAttempt(attemptId, lease.leaseId, lease.fencingToken);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId,\n\t\t\tleaseId: lease.leaseId,\n\t\t\tfencingToken: lease.fencingToken,\n\t\t\texpiresAt: lease.expiresAt,\n\t\t};\n\t}\n\n\tcancel(attemptId: string, reasonCode: string): void {\n\t\tthis.runtime.cancelAttempt(attemptId, reasonCode);\n\t}\n\n\t/** Latest fenced cumulative usage, if this attempt has crossed a durable checkpoint boundary. */\n\tgetAttemptUsage(attemptId: string): AttemptUsageSnapshot | undefined {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tfor (const checkpointId of [...attempt.checkpointIds].reverse()) {\n\t\t\tconst usage = snapshot.checkpoints[checkpointId]?.usage;\n\t\t\tif (usage) return structuredClone(usage);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Fence interrupted isolated completions and queue one replacement attempt per task. */\n\trecoverQueuedDispatches(): AttemptRuntimeState[] {\n\t\tthis.runtime.recoverInterruptedUnboundAttempts((attempt) => attempt.dispatch.executionKind !== \"managed-process\");\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tfor (const task of Object.values(snapshot.tasks)) {\n\t\t\tconst attempts = task.attemptIds.map((attemptId) => snapshot.attempts[attemptId]).filter(Boolean);\n\t\t\tif (attempts.some((attempt) => attempt && activeAttempt(attempt))) continue;\n\t\t\tconst interrupted = [...attempts].reverse().find((attempt) => attempt?.status === \"expired\");\n\t\t\tif (!interrupted || task.task.status !== \"ready\") continue;\n\t\t\tconst maxAttempts = task.task.riskBudget.maxAttempts;\n\t\t\tif (maxAttempts !== undefined && task.attemptIds.length >= maxAttempts) {\n\t\t\t\tthis.runtime.failTask(task.task.taskId, \"attempt_budget_exhausted\");\n\t\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.runtime.queueAttempt(task.task.taskId, interrupted.dispatch);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\t\treturn Object.values(snapshot.attempts).filter(\n\t\t\t(attempt) => attempt.status === \"queued\" && attempt.dispatch.executionKind !== \"managed-process\",\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"delegation-ledger.js","sourceRoot":"","sources":["../../../src/core/orchestration/delegation-ledger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAExE,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AASzE,OAAO,EAAE,mCAAmC,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAEN,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,eAAe,EAAE,6BAA6B,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClH,OAAO,EACN,mCAAmC,GAEnC,MAAM,oCAAoC,CAAC;AAmD5C,SAAS,aAAa,CAAC,OAA4B;IAClD,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC;AACnG,CAAC;AAED,SAAS,iBAAiB,CAAC,OAAe,EAAE,gBAAwB;IACnE,OAAO,gBAAgB,UAAU,CAAC,QAAQ,CAAC;SACzC,MAAM,CAAC,iCAAiC,CAAC;SACzC,MAAM,CAAC,IAAI,CAAC;SACZ,MAAM,CAAC,OAAO,CAAC;SACf,MAAM,CAAC,IAAI,CAAC;SACZ,MAAM,CAAC,gBAAgB,CAAC;SACxB,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,6BAA6B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,CAAC,CAAC;YAC7F,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,KAAK,OAAO;gBAAE,SAAS;YAC3D,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC;YACrD,IAAI,WAAW,KAAK,SAAS,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,IAAI,WAAW,EAAE,CAAC;gBACxE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,0BAA0B,CAAC,CAAC;gBACpE,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;gBACtC,SAAS;YACV,CAAC;YACD,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;YAClE,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;QACvC,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,MAAM,CAC7C,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC,aAAa,KAAK,iBAAiB,CAChG,CAAC;IACH,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { WorkerDelegationTaskContext } from \"../delegation/worker-delegation-request.ts\";\nimport { deriveWorkerTaskLabel } from \"../delegation/worker-task-label.ts\";\nimport { hasGoalAcceptanceOverride } from \"../goals/goal-acceptance.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport { latestAgentAttemptByDurableOrder } from \"./attempt-ordering.ts\";\nimport type {\n\tAttemptUsageSnapshot,\n\tHarnessCapability,\n\tOrchestrationDispatchRequest,\n\tRiskBudget,\n\tWorkerExecutionContract,\n\tWorkerRole,\n} from \"./contracts.ts\";\nimport { MAX_ORCHESTRATION_IDENTIFIER_LENGTH } from \"./contracts.ts\";\nimport { OrchestrationEventStore } from \"./event-store.ts\";\nimport {\n\ttype AttemptRuntimeState,\n\tDurableTaskRuntime,\n\tDurableTaskRuntimeError,\n\tvalidateTaskDependencyIds,\n} from \"./task-runtime.ts\";\nimport { goalObjectiveId, projectGoalAcceptanceEvidence, projectGoalObjective } from \"./work-state-projection.ts\";\nimport {\n\tnormalizeWorkerContextForkReference,\n\ttype WorkerContextForkReference,\n} from \"./worker-context-fork-reference.ts\";\n\nexport interface DelegationLedgerOptions {\n\tagentDir: string;\n\tsessionId: string;\n\tnow?: () => number;\n\tstore?: OrchestrationEventStore;\n}\n\nexport interface PrepareDelegationInput {\n\tlaneId: string;\n\tinstructions: string;\n\tparentAgentId?: string;\n\texecutionContract: WorkerExecutionContract;\n\trequiredCapabilities: readonly HarnessCapability[];\n\tgoal?: GoalState;\n\tverificationOfTaskId?: string;\n\ttaskContext?: WorkerDelegationTaskContext;\n\tbirthContextForkReference?: WorkerContextForkReference;\n}\n\nexport interface PrepareManagedDelegationInput {\n\tlaneId: string;\n\tdispatchSequence: number;\n\tinstructions: string;\n\tprofileId: string;\n\tprovider: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\triskBudget: RiskBudget;\n\tgoal?: GoalState;\n\tgoalId?: string;\n\tworktreeLaneKey?: string;\n}\n\nexport interface StartedDelegationAttempt {\n\tobjectiveId: string;\n\ttaskId: string;\n\tattemptId: string;\n\tleaseId: string;\n\tfencingToken: number;\n\texpiresAt: string;\n}\n\nexport interface PrepareAgentTurnInput {\n\tagentId: string;\n\tinstructions: string;\n\tcontrolMessageId?: string;\n\tdependsOnTaskIds?: readonly string[];\n}\n\nfunction activeAttempt(attempt: AttemptRuntimeState): boolean {\n\treturn attempt.status === \"queued\" || attempt.status === \"leased\" || attempt.status === \"running\";\n}\n\nfunction mailboxTurnTaskId(agentId: string, controlMessageId: string): string {\n\treturn `mailbox-turn-${createHash(\"sha256\")\n\t\t.update(\"pi-worker-agent-mailbox-turn-v1\")\n\t\t.update(\"\\0\")\n\t\t.update(agentId)\n\t\t.update(\"\\0\")\n\t\t.update(controlMessageId)\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Durable adapter for in-process delegated completions. It records the dispatch before execution,\n * fences interrupted completions on restart, and returns queued work for event-driven re-dispatch.\n * It deliberately does not pretend an isolated completion has a resumable model transcript.\n */\nexport class DelegationOrchestrationLedger {\n\treadonly runtime: DurableTaskRuntime;\n\tprivate readonly sessionId: string;\n\n\tconstructor(options: DelegationLedgerOptions) {\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.runtime = new DurableTaskRuntime({\n\t\t\tstore:\n\t\t\t\toptions.store ?? new OrchestrationEventStore({ agentDir: options.agentDir, sessionId: options.sessionId }),\n\t\t\tnow: options.now,\n\t\t});\n\t}\n\n\tprepare(input: PrepareDelegationInput): AttemptRuntimeState {\n\t\tconst profile = input.executionContract.worker.profile;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: input.laneId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: profile.profileId,\n\t\t\trole: profile.role,\n\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\triskBudget: profile.budget,\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\texecutionContract: input.executionContract,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.verificationOfTaskId ? { verificationOfTaskId: input.verificationOfTaskId } : {}),\n\t\t\t...(input.taskContext ? { taskContext: input.taskContext } : {}),\n\t\t\tdispatchMetadata: {\n\t\t\t\tlogicalLaneId: input.laneId,\n\t\t\t\t...(input.birthContextForkReference ? { birthContextForkReference: input.birthContextForkReference } : {}),\n\t\t\t},\n\t\t});\n\t}\n\n\tprepareManaged(input: PrepareManagedDelegationInput): AttemptRuntimeState {\n\t\tif (!Number.isSafeInteger(input.dispatchSequence) || input.dispatchSequence < 1) {\n\t\t\tthrow new DurableTaskRuntimeError(\"Managed dispatch sequence must be a positive integer.\");\n\t\t}\n\t\tconst taskId = `${input.laneId}:turn:${input.dispatchSequence}`;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: input.profileId,\n\t\t\trole: input.role,\n\t\t\trequiredCapabilities: [],\n\t\t\triskBudget: input.riskBudget,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.goalId ? { goalId: input.goalId } : {}),\n\t\t\tdispatchMetadata: {\n\t\t\t\texecutionKind: \"managed-process\",\n\t\t\t\tlogicalLaneId: input.laneId,\n\t\t\t\tdispatchSequence: input.dispatchSequence,\n\t\t\t\tprovider: input.provider,\n\t\t\t\tauthorizationId: input.authorizationId,\n\t\t\t\t...(input.worktreeLaneKey ? { worktreeLaneKey: input.worktreeLaneKey } : {}),\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Queue one new turn for an existing logical agent. The agent identity and its immutable\n\t * execution contract are inherited from the last bound turn. Each distinct control message owns\n\t * one deterministic task/attempt identity; exact retries adopt it instead of minting new work.\n\t */\n\tprepareAgentTurn(input: PrepareAgentTurnInput): AttemptRuntimeState {\n\t\tconst agentId = input.agentId.trim();\n\t\tconst instructions = input.instructions.trim();\n\t\tconst controlMessageId = input.controlMessageId?.trim();\n\t\tif (!agentId) throw new DurableTaskRuntimeError(\"Logical worker agent id is required.\");\n\t\tif (!instructions) throw new DurableTaskRuntimeError(\"Worker follow-up instructions are required.\");\n\t\tif (\n\t\t\tinput.controlMessageId !== undefined &&\n\t\t\t(!controlMessageId || controlMessageId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH)\n\t\t) {\n\t\t\tthrow new DurableTaskRuntimeError(\"Worker control message id is invalid.\");\n\t\t}\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst agent = snapshot.agents[agentId];\n\t\tif (!agent) throw new DurableTaskRuntimeError(`Unknown logical worker agent '${agentId}'.`);\n\t\tconst agentAttempts = Object.values(snapshot.attempts).filter(\n\t\t\t(attempt) => attempt.agentId === agentId || attempt.dispatch.logicalLaneId === agentId,\n\t\t);\n\t\tconst sequence = agentAttempts.length + 1;\n\t\tconst taskId = controlMessageId ? mailboxTurnTaskId(agentId, controlMessageId) : `${agentId}:turn:${sequence}`;\n\t\tconst existingTask = snapshot.tasks[taskId]?.task;\n\t\tconst prior = latestAgentAttemptByDurableOrder(snapshot, agent.agentId);\n\t\tconst contract = prior?.dispatch.executionContract;\n\t\tif (!prior || !contract) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no immutable execution contract.`);\n\t\t}\n\t\tconst priorTask = snapshot.tasks[prior.taskId]?.task;\n\t\tif (!priorTask) throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no prior durable task.`);\n\t\tconst dependencyTaskIds = validateTaskDependencyIds(\n\t\t\tsnapshot.tasks,\n\t\t\texistingTask?.objectiveId ?? priorTask.objectiveId,\n\t\t\tinput.dependsOnTaskIds,\n\t\t);\n\t\tif (existingTask && controlMessageId) {\n\t\t\tif (\n\t\t\t\texistingTask.description !== instructions ||\n\t\t\t\texistingTask.role !== agent.role ||\n\t\t\t\texistingTask.dependsOn.length !== dependencyTaskIds.length ||\n\t\t\t\texistingTask.dependsOn.some((dependencyId, index) => dependencyId !== dependencyTaskIds[index])\n\t\t\t) {\n\t\t\t\tthrow new DurableTaskRuntimeError(\n\t\t\t\t\t`Worker control message '${controlMessageId}' has conflicting task identity.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst existingAttempts = (snapshot.tasks[taskId]?.attemptIds ?? []).map(\n\t\t\t\t(attemptId) => snapshot.attempts[attemptId],\n\t\t\t);\n\t\t\tfor (const attempt of existingAttempts) {\n\t\t\t\tif (\n\t\t\t\t\t!attempt ||\n\t\t\t\t\tattempt.dispatch.logicalLaneId !== agentId ||\n\t\t\t\t\tattempt.dispatch.controlMessageId !== controlMessageId ||\n\t\t\t\t\tattempt.dispatch.instructions !== instructions\n\t\t\t\t) {\n\t\t\t\t\tthrow new DurableTaskRuntimeError(\n\t\t\t\t\t\t`Worker control message '${controlMessageId}' has conflicting dispatch evidence.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst existingAttempt = existingAttempts.at(-1);\n\t\t\tif (existingAttempt) return existingAttempt;\n\t\t}\n\t\tif (agent.status !== \"registered\") {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' is not idle.`);\n\t\t}\n\t\tif (existingTask && !controlMessageId) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' already has turn ${sequence}.`);\n\t\t}\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions,\n\t\t\tprofileId: contract.worker.profile.profileId,\n\t\t\trole: agent.role,\n\t\t\trequiredCapabilities: contract.worker.authority.capabilities,\n\t\t\triskBudget: contract.worker.profile.budget,\n\t\t\t...(priorTask.objectiveId.startsWith(\"goal:\") ? { goalId: priorTask.objectiveId.slice(\"goal:\".length) } : {}),\n\t\t\ttaskContext: {\n\t\t\t\trequirementIds: prior.dispatch.requirementIds ?? [],\n\t\t\t\tdependsOnTaskIds: dependencyTaskIds,\n\t\t\t\tacceptanceCriterionIds: priorTask.acceptanceCriterionIds,\n\t\t\t\tresourcePointerIds: prior.dispatch.resourcePointerIds,\n\t\t\t},\n\t\t\texecutionContract: contract,\n\t\t\tdispatchMetadata: {\n\t\t\t\tlogicalLaneId: agentId,\n\t\t\t\tdispatchSequence: sequence,\n\t\t\t\t...(controlMessageId ? { controlMessageId } : {}),\n\t\t\t\t...(prior.dispatch.birthContextForkReference\n\t\t\t\t\t? { birthContextForkReference: prior.dispatch.birthContextForkReference }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate prepareNormalized(input: {\n\t\tlaneId: string;\n\t\tinstructions: string;\n\t\tprofileId: string;\n\t\trole: WorkerRole;\n\t\trequiredCapabilities: readonly HarnessCapability[];\n\t\triskBudget: RiskBudget;\n\t\tparentAgentId?: string;\n\t\tgoal?: GoalState;\n\t\tgoalId?: string;\n\t\tverificationOfTaskId?: string;\n\t\ttaskContext?: WorkerDelegationTaskContext;\n\t\texecutionContract?: WorkerExecutionContract;\n\t\tdispatchMetadata?: Pick<\n\t\t\tOrchestrationDispatchRequest,\n\t\t\t| \"executionKind\"\n\t\t\t| \"logicalLaneId\"\n\t\t\t| \"dispatchSequence\"\n\t\t\t| \"controlMessageId\"\n\t\t\t| \"provider\"\n\t\t\t| \"authorizationId\"\n\t\t\t| \"worktreeLaneKey\"\n\t\t\t| \"birthContextForkReference\"\n\t\t>;\n\t}): AttemptRuntimeState {\n\t\tlet birthContextForkReference: WorkerContextForkReference | undefined;\n\t\ttry {\n\t\t\tbirthContextForkReference =\n\t\t\t\tinput.dispatchMetadata?.birthContextForkReference === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: normalizeWorkerContextForkReference(input.dispatchMetadata.birthContextForkReference);\n\t\t} catch (error) {\n\t\t\tthrow new DurableTaskRuntimeError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tconst existingVerificationSubject = input.verificationOfTaskId\n\t\t\t? snapshot.tasks[input.verificationOfTaskId]\n\t\t\t: undefined;\n\t\tif (input.verificationOfTaskId && !existingVerificationSubject) {\n\t\t\tthrow new DurableTaskRuntimeError(`Unknown verification subject '${input.verificationOfTaskId}'.`);\n\t\t}\n\t\tconst projectedGoal = input.goal ? projectGoalObjective(input.goal) : undefined;\n\t\tconst objectiveId =\n\t\t\texistingVerificationSubject?.task.objectiveId ??\n\t\t\tprojectedGoal?.objectiveId ??\n\t\t\t(input.goalId ? goalObjectiveId(input.goalId) : `session:${this.sessionId}`);\n\t\tconst dependencyTaskIds = validateTaskDependencyIds(\n\t\t\tsnapshot.tasks,\n\t\t\tobjectiveId,\n\t\t\tinput.taskContext?.dependsOnTaskIds,\n\t\t);\n\t\tconst existingTask = snapshot.tasks[input.laneId]?.task;\n\t\tif (\n\t\t\texistingTask &&\n\t\t\t(existingTask.objectiveId !== objectiveId ||\n\t\t\t\texistingTask.description !== input.instructions ||\n\t\t\t\texistingTask.role !== input.role ||\n\t\t\t\texistingTask.dependsOn.length !== dependencyTaskIds.length ||\n\t\t\t\texistingTask.dependsOn.some((dependencyId, index) => dependencyId !== dependencyTaskIds[index]))\n\t\t) {\n\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable dispatch identity.`);\n\t\t}\n\t\tconst taskStateBeforeWrites = snapshot.tasks[input.laneId];\n\t\tconst activeAttemptBeforeWrites = taskStateBeforeWrites?.attemptIds\n\t\t\t.map((attemptId) => snapshot.attempts[attemptId])\n\t\t\t.find((attempt): attempt is AttemptRuntimeState => attempt !== undefined && activeAttempt(attempt));\n\t\tfor (const attemptId of taskStateBeforeWrites?.attemptIds ?? []) {\n\t\t\tconst durableReference = snapshot.attempts[attemptId]?.dispatch.birthContextForkReference;\n\t\t\tif (!isDeepStrictEqual(durableReference, birthContextForkReference)) {\n\t\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has a conflicting birth context fork reference.`);\n\t\t\t}\n\t\t}\n\t\tconst projectedEvidence =\n\t\t\tinput.goal && objectiveId === projectedGoal?.objectiveId ? projectGoalAcceptanceEvidence(input.goal) : [];\n\t\tif (projectedGoal) this.runtime.assertObjectiveSynchronizationHeadroom(projectedGoal, projectedEvidence);\n\t\tthis.runtime.assertProjectionHeadroom({\n\t\t\tobjectives: snapshot.objectives[objectiveId] ? 0 : 1,\n\t\t\ttasks: taskStateBeforeWrites ? 0 : 1,\n\t\t\tattempts: activeAttemptBeforeWrites ? 0 : 1,\n\t\t});\n\t\tif (input.goal && objectiveId === projectedGoal?.objectiveId) {\n\t\t\tthis.synchronizeGoalState(input.goal);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t} else if (!snapshot.objectives[objectiveId]) {\n\t\t\tthis.runtime.createObjective({\n\t\t\t\tobjectiveId,\n\t\t\t\ttitle: input.goalId ? `Goal ${input.goalId}` : `Session ${this.sessionId}`,\n\t\t\t\tdescription: input.goalId ? \"Externally managed goal work\" : \"Session-scoped delegated work\",\n\t\t\t});\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\n\t\tconst verificationSubject = input.verificationOfTaskId ? snapshot.tasks[input.verificationOfTaskId] : undefined;\n\t\tconst taskInput = {\n\t\t\ttaskId: input.laneId,\n\t\t\tobjectiveId,\n\t\t\ttitle: deriveWorkerTaskLabel(input.instructions, `Delegated ${input.role} work`),\n\t\t\tdescription: input.instructions,\n\t\t\trole: input.role,\n\t\t\tdependsOn: dependencyTaskIds,\n\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\tacceptanceCriterionIds: input.taskContext?.acceptanceCriterionIds ?? [],\n\t\t\triskBudget: input.riskBudget,\n\t\t\t...(input.verificationOfTaskId\n\t\t\t\t? {\n\t\t\t\t\t\tverificationOfTaskId: input.verificationOfTaskId,\n\t\t\t\t\t\tacceptanceCriterionIds: verificationSubject?.task.acceptanceCriterionIds ?? [],\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t} as const;\n\t\tconst dispatch = {\n\t\t\ttaskId: input.laneId,\n\t\t\tprofileId: input.profileId,\n\t\t\tinstructions: input.instructions,\n\t\t\tresourcePointerIds: input.taskContext?.resourcePointerIds ?? [],\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\trequirementIds: input.taskContext?.requirementIds ?? [],\n\t\t\t...(input.executionContract ? { executionContract: input.executionContract } : {}),\n\t\t\t...input.dispatchMetadata,\n\t\t\t...(birthContextForkReference ? { birthContextForkReference } : {}),\n\t\t} as const;\n\t\tif (\n\t\t\texistingTask &&\n\t\t\t(existingTask.title !== taskInput.title ||\n\t\t\t\texistingTask.verificationOfTaskId !== taskInput.verificationOfTaskId ||\n\t\t\t\t!isDeepStrictEqual(existingTask.requiredCapabilities, [...new Set(taskInput.requiredCapabilities)]) ||\n\t\t\t\t!isDeepStrictEqual(existingTask.acceptanceCriterionIds, [...new Set(taskInput.acceptanceCriterionIds)]) ||\n\t\t\t\t!isDeepStrictEqual(existingTask.riskBudget, taskInput.riskBudget))\n\t\t) {\n\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable task identity.`);\n\t\t}\n\t\tif (activeAttemptBeforeWrites && !isDeepStrictEqual(activeAttemptBeforeWrites.dispatch, dispatch)) {\n\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable dispatch identity.`);\n\t\t}\n\t\tif (!snapshot.tasks[input.laneId]) {\n\t\t\treturn this.runtime.prepareTaskAttempt(\n\t\t\t\t{\n\t\t\t\t\t...taskInput,\n\t\t\t\t},\n\t\t\t\tdispatch,\n\t\t\t).attempt;\n\t\t}\n\n\t\tconst task = snapshot.tasks[input.laneId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Failed to create task '${input.laneId}'.`);\n\t\tif (activeAttemptBeforeWrites) return activeAttemptBeforeWrites;\n\n\t\treturn this.runtime.queueAttempt(input.laneId, dispatch);\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tconst objective = projectGoalObjective(goal);\n\t\tconst evidence = projectGoalAcceptanceEvidence(goal);\n\t\tthis.runtime.assertObjectiveSynchronizationHeadroom(objective, evidence);\n\t\tthis.runtime.ensureObjective(objective);\n\t\tfor (const item of evidence) {\n\t\t\tthis.runtime.recordObjectiveEvidence(objective.objectiveId, item);\n\t\t}\n\t\tconst status = this.runtime.getSnapshot().objectives[goalObjectiveId(goal.goalId)]?.objective.status;\n\t\tswitch (goal.status) {\n\t\t\tcase \"active\":\n\t\t\t\tif (status === \"paused\") this.runtime.resumeObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"paused\":\n\t\t\tcase \"blocked\":\n\t\t\tcase \"usage_limited\":\n\t\t\tcase \"budget_limited\":\n\t\t\t\tif (status === \"active\") this.runtime.pauseObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"cancelled\":\n\t\t\t\tif (status !== \"cancelled\") this.runtime.cancelObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"completed\":\n\t\t\t\tif (status !== \"completed\") {\n\t\t\t\t\tthis.runtime.completeObjectiveFromOwner(objective.objectiveId, hasGoalAcceptanceOverride(goal));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tstart(\n\t\tattemptId: string,\n\t\tleaseTtlMs: number,\n\t\townerId = `in-process:${this.sessionId}`,\n\t\tagentId?: string,\n\t): StartedDelegationAttempt {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Unknown task '${attempt.taskId}'.`);\n\t\tconst lease = this.runtime.leaseAttempt(attemptId, ownerId, leaseTtlMs, agentId);\n\t\tthis.runtime.startAttempt(attemptId, lease.leaseId, lease.fencingToken);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId,\n\t\t\tleaseId: lease.leaseId,\n\t\t\tfencingToken: lease.fencingToken,\n\t\t\texpiresAt: lease.expiresAt,\n\t\t};\n\t}\n\n\tcancel(attemptId: string, reasonCode: string): void {\n\t\tthis.runtime.cancelAttempt(attemptId, reasonCode);\n\t}\n\n\t/** Latest fenced cumulative usage, if this attempt has crossed a durable checkpoint boundary. */\n\tgetAttemptUsage(attemptId: string): AttemptUsageSnapshot | undefined {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tfor (const checkpointId of [...attempt.checkpointIds].reverse()) {\n\t\t\tconst usage = snapshot.checkpoints[checkpointId]?.usage;\n\t\t\tif (usage) return structuredClone(usage);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Fence interrupted isolated completions and queue one replacement attempt per task. */\n\trecoverQueuedDispatches(): AttemptRuntimeState[] {\n\t\tthis.runtime.recoverInterruptedUnboundAttempts((attempt) => attempt.dispatch.executionKind !== \"managed-process\");\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tfor (const task of Object.values(snapshot.tasks)) {\n\t\t\tconst attempts = task.attemptIds.map((attemptId) => snapshot.attempts[attemptId]).filter(Boolean);\n\t\t\tif (attempts.some((attempt) => attempt && activeAttempt(attempt))) continue;\n\t\t\tconst interrupted = [...attempts].reverse().find((attempt) => attempt?.status === \"expired\");\n\t\t\tif (!interrupted || task.task.status !== \"ready\") continue;\n\t\t\tconst maxAttempts = task.task.riskBudget.maxAttempts;\n\t\t\tif (maxAttempts !== undefined && task.attemptIds.length >= maxAttempts) {\n\t\t\t\tthis.runtime.failTask(task.task.taskId, \"attempt_budget_exhausted\");\n\t\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.runtime.queueAttempt(task.task.taskId, interrupted.dispatch);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\t\treturn Object.values(snapshot.attempts).filter(\n\t\t\t(attempt) => attempt.status === \"queued\" && attempt.dispatch.executionKind !== \"managed-process\",\n\t\t);\n\t}\n}\n"]}
@@ -9,6 +9,11 @@ export interface OrchestrationEventStoreOptions {
9
9
  maxTailBytes?: number;
10
10
  maxIdempotencyEvents?: number;
11
11
  }
12
+ export interface AppendOrchestrationEventOptions {
13
+ expectedLastOrdinal?: number;
14
+ /** Exact event admission under the append lock, before any durable file is written. */
15
+ validateBeforeCommit?: (event: OrchestrationEvent) => void;
16
+ }
12
17
  export declare class OrchestrationEventStoreError extends Error {
13
18
  constructor(message: string);
14
19
  }
@@ -44,9 +49,7 @@ export declare class OrchestrationEventStore {
44
49
  private verifiedSnapshotBaseline;
45
50
  private synchronizedIndexes;
46
51
  constructor(options: OrchestrationEventStoreOptions);
47
- append(input: AppendOrchestrationEventInput, options?: {
48
- expectedLastOrdinal?: number;
49
- }): OrchestrationEvent;
52
+ append(input: AppendOrchestrationEventInput, options?: AppendOrchestrationEventOptions): OrchestrationEvent;
50
53
  readAll(): OrchestrationEvent[];
51
54
  readAfter(ordinal: number): OrchestrationEvent[];
52
55
  readProjectionSnapshot(): {
@@ -1 +1 @@
1
- {"version":3,"file":"event-store.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/event-store.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAG3D,OAAO,EACN,KAAK,6BAA6B,EAGlC,KAAK,kBAAkB,EACvB,MAAM,gBAAgB,CAAC;AAgExB,MAAM,WAAW,8BAA8B;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,MAAM,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,qBAAa,4BAA6B,SAAQ,KAAK;IACtD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAED,qBAAa,6BAA8B,SAAQ,4BAA4B;IAC9E,YAAY,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAG3C;CACD;AAED,qBAAa,kCAAmC,SAAQ,4BAA4B;IACnF,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAEhC,YAAY,cAAc,EAAE,MAAM,EAIjC;CACD;AAkED;;;;;;;;GAQG;A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AAC,KAAK,EAAE,kBAAkB,KAAK,IAAI,GAAG,MAAM,IAAI,CAGnE;IAED,OAAO,CAAC,eAAe;IAqBvB,OAAO,CAAC,sBAAsB;IAe9B,OAAO,CAAC,4BAA4B;IAapC,OAAO,CAAC,yBAAyB;IAejC,kFAAkF;IAClF,OAAO,CAAC,oCAAoC;IAe5C,oGAAoG;IACpG,OAAO,CAAC,0BAA0B;IAYlC,OAAO,CAAC,oBAAoB;IAqC5B,OAAO,CAAC,8BAA8B;IA6DtC;;;;OAIG;IACH,OAAO,CAAC,oCAAoC;IAuC5C,OAAO,CAAC,6BAA6B;IAcrC,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,qBAAqB;IAiB7B;;;;;OAKG;IACH,OAAO,CAAC,0BAA0B;CAuDlC"}
@@ -1,10 +1,11 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { existsSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
4
5
  import { orchestrationEventStoreDir } from "../agent-paths.js";
5
6
  import { withFileLockSync, writeFileAtomicSync } from "../util/atomic-file.js";
6
7
  import { readBoundedDirectoryNamesSync, readBoundedTextFileSync } from "../util/bounded-file.js";
7
- import { isOrchestrationEvent, ORCHESTRATION_SCHEMA_VERSION, } from "./contracts.js";
8
+ import { isOrchestrationEvent, MAX_ORCHESTRATION_IDENTIFIER_LENGTH, MAX_ORCHESTRATION_PROJECTION_SNAPSHOT_BYTES, MAX_ORCHESTRATION_SNAPSHOT_IDEMPOTENCY_BYTES, ORCHESTRATION_EVENT_TYPES, ORCHESTRATION_SCHEMA_VERSION, toJsonObject, } from "./contracts.js";
8
9
  const EVENT_FILE_PATTERN = /^(\d{16})\.json$/;
9
10
  const SNAPSHOT_FILE_PATTERN = /^(\d{16})\.json$/;
10
11
  const DEFAULT_MAX_TAIL_EVENTS = 256;
@@ -18,8 +19,39 @@ const MAX_IDEMPOTENCY_DIRECTORY_ENTRIES = 2_048;
18
19
  const MAX_SNAPSHOT_DIRECTORY_ENTRIES = 8;
19
20
  const MAX_CURSOR_BYTES = 64 * 1024;
20
21
  const MAX_BASELINE_BYTES = 64 * 1024;
21
- /** Full current task state plus retained idempotency evidence; intentionally above the 16MiB tail cap. */
22
- const MAX_PROJECTION_SNAPSHOT_BYTES = 32 * 1024 * 1024;
22
+ const ORCHESTRATION_ACTORS = ["human", "kernel", "runtime", "policy", "router", "worker"];
23
+ const APPEND_INPUT_FIELDS = [
24
+ "type",
25
+ "aggregateId",
26
+ "actor",
27
+ "correlationId",
28
+ "causationId",
29
+ "idempotencyKey",
30
+ "payload",
31
+ ];
32
+ const EVENT_FIELDS = [
33
+ "schemaVersion",
34
+ "ordinal",
35
+ "eventId",
36
+ "type",
37
+ "aggregateId",
38
+ "actor",
39
+ "occurredAt",
40
+ "correlationId",
41
+ "causationId",
42
+ "idempotencyKey",
43
+ "payload",
44
+ ];
45
+ const SNAPSHOT_FIELDS = [
46
+ "version",
47
+ "schemaVersion",
48
+ "throughOrdinal",
49
+ "createdAt",
50
+ "projection",
51
+ "idempotencyEvents",
52
+ "digest",
53
+ ];
54
+ const BASELINE_FIELDS = ["version", "throughOrdinal", "digest", "snapshotFile"];
23
55
  export class OrchestrationEventStoreError extends Error {
24
56
  constructor(message) {
25
57
  super(message);
@@ -73,6 +105,9 @@ function parseCursor(filePath) {
73
105
  function serialize(value) {
74
106
  return `${JSON.stringify(value, null, "\t")}\n`;
75
107
  }
108
+ function serializeCompact(value) {
109
+ return `${JSON.stringify(value)}\n`;
110
+ }
76
111
  function serializeBounded(value, maxBytes, label, oversizedMessage = `${label} exceeds its byte limit.`) {
77
112
  const serialized = serialize(value);
78
113
  if (Buffer.byteLength(serialized, "utf-8") > maxBytes) {
@@ -80,6 +115,150 @@ function serializeBounded(value, maxBytes, label, oversizedMessage = `${label} e
80
115
  }
81
116
  return serialized;
82
117
  }
118
+ function serializeCompactBounded(value, maxBytes, label) {
119
+ const serialized = serializeCompact(value);
120
+ if (Buffer.byteLength(serialized, "utf8") > maxBytes) {
121
+ throw new OrchestrationEventStoreError(`${label} exceeds its byte limit.`);
122
+ }
123
+ return serialized;
124
+ }
125
+ function isCanonicalIdentifier(value) {
126
+ return (typeof value === "string" &&
127
+ value.length > 0 &&
128
+ value.length <= MAX_ORCHESTRATION_IDENTIFIER_LENGTH &&
129
+ value.trim() === value);
130
+ }
131
+ function canonicalIdentifier(value, label) {
132
+ if (!isCanonicalIdentifier(value)) {
133
+ throw new OrchestrationEventStoreError(`${label} must be a non-empty canonical identifier of at most ${MAX_ORCHESTRATION_IDENTIFIER_LENGTH} characters.`);
134
+ }
135
+ return value;
136
+ }
137
+ function isCanonicalIsoTimestamp(value) {
138
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value)
139
+ return false;
140
+ const milliseconds = Date.parse(value);
141
+ return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value;
142
+ }
143
+ function canonicalIsoTimestamp(value, label) {
144
+ if (!isCanonicalIsoTimestamp(value)) {
145
+ throw new OrchestrationEventStoreError(`${label} must be a canonical ISO-8601 timestamp.`);
146
+ }
147
+ return value;
148
+ }
149
+ function canonicalJsonObject(value, label) {
150
+ try {
151
+ return toJsonObject(value);
152
+ }
153
+ catch (error) {
154
+ throw new OrchestrationEventStoreError(`${label} must be a finite JSON object: ${error instanceof Error ? error.message : String(error)}`);
155
+ }
156
+ }
157
+ function hasExactFields(record, fields) {
158
+ const actualFields = Object.keys(record);
159
+ return actualFields.length === fields.length && fields.every((field) => Object.hasOwn(record, field));
160
+ }
161
+ function normalizeAppendInput(input) {
162
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
163
+ throw new OrchestrationEventStoreError("Orchestration append input must be an object.");
164
+ }
165
+ const raw = input;
166
+ const unsupportedField = Object.keys(raw).find((field) => !APPEND_INPUT_FIELDS.some((candidate) => candidate === field));
167
+ if (unsupportedField) {
168
+ throw new OrchestrationEventStoreError(`Orchestration append input field '${unsupportedField}' is unsupported.`);
169
+ }
170
+ const type = ORCHESTRATION_EVENT_TYPES.find((candidate) => candidate === raw.type);
171
+ if (!type) {
172
+ throw new OrchestrationEventStoreError(`Orchestration event type '${String(raw.type)}' is invalid.`);
173
+ }
174
+ const actor = ORCHESTRATION_ACTORS.find((candidate) => candidate === raw.actor);
175
+ if (!actor) {
176
+ throw new OrchestrationEventStoreError(`Orchestration event actor '${String(raw.actor)}' is invalid.`);
177
+ }
178
+ const correlationId = raw.correlationId === undefined
179
+ ? undefined
180
+ : canonicalIdentifier(raw.correlationId, "Orchestration correlation id");
181
+ const causationId = raw.causationId === undefined ? undefined : canonicalIdentifier(raw.causationId, "Orchestration causation id");
182
+ const idempotencyKey = raw.idempotencyKey === undefined
183
+ ? undefined
184
+ : canonicalIdentifier(raw.idempotencyKey, "Orchestration idempotency key");
185
+ return {
186
+ type,
187
+ aggregateId: canonicalIdentifier(raw.aggregateId, "Orchestration aggregate id"),
188
+ actor,
189
+ ...(correlationId ? { correlationId } : {}),
190
+ ...(causationId ? { causationId } : {}),
191
+ ...(idempotencyKey ? { idempotencyKey } : {}),
192
+ payload: canonicalJsonObject(raw.payload, "Orchestration event payload"),
193
+ };
194
+ }
195
+ function isCanonicalOrchestrationEvent(value) {
196
+ if (!isOrchestrationEvent(value))
197
+ return false;
198
+ if (Object.keys(value).some((field) => !EVENT_FIELDS.some((candidate) => candidate === field)))
199
+ return false;
200
+ if (!isCanonicalIdentifier(value.eventId) || !isCanonicalIdentifier(value.aggregateId))
201
+ return false;
202
+ if (!isCanonicalIsoTimestamp(value.occurredAt))
203
+ return false;
204
+ if (value.correlationId !== undefined && !isCanonicalIdentifier(value.correlationId))
205
+ return false;
206
+ if (value.causationId !== undefined && !isCanonicalIdentifier(value.causationId))
207
+ return false;
208
+ if (value.idempotencyKey !== undefined && !isCanonicalIdentifier(value.idempotencyKey))
209
+ return false;
210
+ try {
211
+ toJsonObject(value.payload);
212
+ return true;
213
+ }
214
+ catch {
215
+ return false;
216
+ }
217
+ }
218
+ function assertCanonicalOrchestrationEvent(value) {
219
+ if (!isCanonicalOrchestrationEvent(value)) {
220
+ throw new OrchestrationEventStoreError("Constructed orchestration event is not canonical.");
221
+ }
222
+ }
223
+ function observeListenerResult(value) {
224
+ if ((typeof value !== "object" || value === null) && typeof value !== "function")
225
+ return;
226
+ let then;
227
+ try {
228
+ then = value.then;
229
+ }
230
+ catch {
231
+ return;
232
+ }
233
+ if (typeof then === "function")
234
+ void Promise.resolve(value).catch(() => { });
235
+ }
236
+ function boundedIdempotencyEvents(events, maxEvents) {
237
+ const selectedNewestFirst = [];
238
+ let serializedBytes = 2;
239
+ for (const event of [...events].sort((left, right) => right.ordinal - left.ordinal)) {
240
+ if (selectedNewestFirst.length >= maxEvents)
241
+ break;
242
+ const eventBytes = Buffer.byteLength(JSON.stringify(event), "utf8");
243
+ const nextBytes = serializedBytes + (selectedNewestFirst.length > 0 ? 1 : 0) + eventBytes;
244
+ if (nextBytes > MAX_ORCHESTRATION_SNAPSHOT_IDEMPOTENCY_BYTES)
245
+ continue;
246
+ selectedNewestFirst.push(structuredClone(event));
247
+ serializedBytes = nextBytes;
248
+ }
249
+ return selectedNewestFirst.reverse();
250
+ }
251
+ function assertExactIdempotentReplay(existing, input) {
252
+ const matches = existing.type === input.type &&
253
+ existing.aggregateId === input.aggregateId &&
254
+ existing.actor === input.actor &&
255
+ existing.correlationId === (input.correlationId || undefined) &&
256
+ existing.causationId === (input.causationId || undefined) &&
257
+ isDeepStrictEqual(existing.payload, input.payload);
258
+ if (!matches) {
259
+ throw new OrchestrationEventStoreError(`Orchestration idempotency key '${input.idempotencyKey}' was reused with conflicting event content.`);
260
+ }
261
+ }
83
262
  function eventFileName(ordinal) {
84
263
  return `${String(ordinal).padStart(16, "0")}.json`;
85
264
  }
@@ -120,13 +299,20 @@ export class OrchestrationEventStore {
120
299
  this.maxIdempotencyEvents = positiveSafeInteger(options.maxIdempotencyEvents, DEFAULT_MAX_IDEMPOTENCY_EVENTS, MAX_CONFIGURED_IDEMPOTENCY_EVENTS, "maxIdempotencyEvents");
121
300
  }
122
301
  append(input, options = {}) {
302
+ const normalizedInput = normalizeAppendInput(input);
303
+ if (options.expectedLastOrdinal !== undefined &&
304
+ (!Number.isSafeInteger(options.expectedLastOrdinal) || options.expectedLastOrdinal < 0)) {
305
+ throw new OrchestrationEventStoreError("Expected orchestration ordinal must be a non-negative safe integer.");
306
+ }
123
307
  const committed = withFileLockSync(this.cursorPath, () => {
124
308
  const indexes = this.synchronizeIndexesUnlocked();
125
309
  const actual = indexes.lastOrdinal;
126
- if (input.idempotencyKey) {
127
- const existing = indexes.idempotencyEvents.get(input.idempotencyKey);
128
- if (existing)
310
+ if (normalizedInput.idempotencyKey) {
311
+ const existing = indexes.idempotencyEvents.get(normalizedInput.idempotencyKey);
312
+ if (existing) {
313
+ assertExactIdempotentReplay(existing, normalizedInput);
129
314
  return { event: existing, appended: false };
315
+ }
130
316
  }
131
317
  if (options.expectedLastOrdinal !== undefined) {
132
318
  if (actual !== options.expectedLastOrdinal) {
@@ -138,23 +324,25 @@ export class OrchestrationEventStore {
138
324
  schemaVersion: ORCHESTRATION_SCHEMA_VERSION,
139
325
  ordinal,
140
326
  eventId: this.createEventId(),
141
- type: input.type,
142
- aggregateId: input.aggregateId,
143
- actor: input.actor,
327
+ type: normalizedInput.type,
328
+ aggregateId: normalizedInput.aggregateId,
329
+ actor: normalizedInput.actor,
144
330
  occurredAt: this.now(),
145
- ...(input.correlationId ? { correlationId: input.correlationId } : {}),
146
- ...(input.causationId ? { causationId: input.causationId } : {}),
147
- ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),
148
- payload: structuredClone(input.payload),
331
+ ...(normalizedInput.correlationId ? { correlationId: normalizedInput.correlationId } : {}),
332
+ ...(normalizedInput.causationId ? { causationId: normalizedInput.causationId } : {}),
333
+ ...(normalizedInput.idempotencyKey ? { idempotencyKey: normalizedInput.idempotencyKey } : {}),
334
+ payload: normalizedInput.payload,
149
335
  };
336
+ assertCanonicalOrchestrationEvent(next);
150
337
  const serializedEvent = serializeBounded(next, this.maxTailBytes, "Orchestration event", "Orchestration event exceeds its configured tail byte limit.");
338
+ options.validateBeforeCommit?.(next);
151
339
  const nextTailBytes = indexes.tailBytes + Buffer.byteLength(serializedEvent);
152
340
  const serializedCursor = serializeBounded({ version: 1, lastOrdinal: ordinal, tailBytes: nextTailBytes }, MAX_CURSOR_BYTES, "Orchestration cursor");
153
341
  writeFileAtomicSync(join(this.eventsDir, eventFileName(ordinal)), serializedEvent);
154
342
  indexes.lastOrdinal = ordinal;
155
343
  indexes.tailBytes = nextTailBytes;
156
- if (input.idempotencyKey)
157
- indexes.idempotencyEvents.set(input.idempotencyKey, next);
344
+ if (normalizedInput.idempotencyKey)
345
+ indexes.idempotencyEvents.set(normalizedInput.idempotencyKey, next);
158
346
  // The immutable event is authoritative. The cursor is only a corruption high-water mark,
159
347
  // so a lock-protected direct overwrite avoids another tmp-file creation and rename on the
160
348
  // Windows scanner-sensitive path; a torn cursor is safely rebuilt from the event tail.
@@ -162,8 +350,14 @@ export class OrchestrationEventStore {
162
350
  return { event: next, appended: true };
163
351
  });
164
352
  if (committed.appended) {
165
- for (const listener of this.listeners)
166
- listener(structuredClone(committed.event));
353
+ for (const listener of [...this.listeners]) {
354
+ try {
355
+ observeListenerResult(listener(structuredClone(committed.event)));
356
+ }
357
+ catch {
358
+ // The event is already durable. Observer failures cannot turn a committed transition into a reported failure.
359
+ }
360
+ }
167
361
  }
168
362
  return structuredClone(committed.event);
169
363
  }
@@ -240,21 +434,19 @@ export class OrchestrationEventStore {
240
434
  retainedByKey.set(event.idempotencyKey, event);
241
435
  }
242
436
  }
243
- const idempotencyEvents = [...retainedByKey.values()]
244
- .sort((left, right) => left.ordinal - right.ordinal)
245
- .slice(-this.maxIdempotencyEvents)
246
- .map((event) => structuredClone(event));
437
+ const idempotencyEvents = boundedIdempotencyEvents([...retainedByKey.values()], this.maxIdempotencyEvents);
438
+ const canonicalProjection = canonicalJsonObject(projection(), "Orchestration projection snapshot");
247
439
  const content = {
248
440
  version: 1,
249
441
  schemaVersion: ORCHESTRATION_SCHEMA_VERSION,
250
442
  throughOrdinal,
251
- createdAt: this.now(),
252
- projection: structuredClone(projection()),
443
+ createdAt: canonicalIsoTimestamp(this.now(), "Orchestration projection snapshot creation time"),
444
+ projection: canonicalProjection,
253
445
  idempotencyEvents,
254
446
  };
255
447
  const digest = snapshotDigest(content);
256
448
  const snapshotFile = eventFileName(throughOrdinal);
257
- const serializedSnapshot = serializeBounded({ ...content, digest }, MAX_PROJECTION_SNAPSHOT_BYTES, "Orchestration projection snapshot");
449
+ const serializedSnapshot = serializeCompactBounded({ ...content, digest }, MAX_ORCHESTRATION_PROJECTION_SNAPSHOT_BYTES, "Orchestration projection snapshot");
258
450
  const serializedBaseline = serializeBounded({ version: 1, throughOrdinal, digest, snapshotFile }, MAX_BASELINE_BYTES, "Orchestration snapshot baseline");
259
451
  const serializedCursor = serializeBounded({ version: 1, lastOrdinal: throughOrdinal, tailBytes: 0 }, MAX_CURSOR_BYTES, "Orchestration cursor");
260
452
  writeFileAtomicSync(join(this.snapshotsDir, snapshotFile), serializedSnapshot);
@@ -381,7 +573,8 @@ export class OrchestrationEventStore {
381
573
  throw new OrchestrationEventStoreError("Invalid orchestration snapshot baseline.");
382
574
  }
383
575
  const baseline = parsed;
384
- if (baseline.version !== 1 ||
576
+ if (!hasExactFields(baseline, BASELINE_FIELDS) ||
577
+ baseline.version !== 1 ||
385
578
  !Number.isSafeInteger(baseline.throughOrdinal) ||
386
579
  Number(baseline.throughOrdinal) < 1 ||
387
580
  typeof baseline.digest !== "string" ||
@@ -404,7 +597,7 @@ export class OrchestrationEventStore {
404
597
  return undefined;
405
598
  let parsed;
406
599
  try {
407
- parsed = JSON.parse(readBoundedTextFileSync(join(this.snapshotsDir, baseline.snapshotFile), MAX_PROJECTION_SNAPSHOT_BYTES, "Orchestration projection snapshot"));
600
+ parsed = JSON.parse(readBoundedTextFileSync(join(this.snapshotsDir, baseline.snapshotFile), MAX_ORCHESTRATION_PROJECTION_SNAPSHOT_BYTES, "Orchestration projection snapshot"));
408
601
  }
409
602
  catch (error) {
410
603
  throw new OrchestrationEventStoreError(`Failed to parse orchestration projection snapshot: ${error instanceof Error ? error.message : String(error)}`);
@@ -413,7 +606,8 @@ export class OrchestrationEventStore {
413
606
  throw new OrchestrationEventStoreError("Invalid orchestration projection snapshot.");
414
607
  }
415
608
  const snapshot = parsed;
416
- if (snapshot.version !== 1 ||
609
+ if (!hasExactFields(snapshot, SNAPSHOT_FIELDS) ||
610
+ snapshot.version !== 1 ||
417
611
  snapshot.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION ||
418
612
  snapshot.throughOrdinal !== baseline.throughOrdinal ||
419
613
  typeof snapshot.createdAt !== "string" ||
@@ -422,7 +616,10 @@ export class OrchestrationEventStore {
422
616
  Array.isArray(snapshot.projection) ||
423
617
  !Array.isArray(snapshot.idempotencyEvents) ||
424
618
  snapshot.idempotencyEvents.length > this.maxIdempotencyEvents ||
425
- !snapshot.idempotencyEvents.every(isOrchestrationEvent) ||
619
+ Buffer.byteLength(JSON.stringify(snapshot.idempotencyEvents), "utf8") >
620
+ MAX_ORCHESTRATION_SNAPSHOT_IDEMPOTENCY_BYTES ||
621
+ !isCanonicalIsoTimestamp(snapshot.createdAt) ||
622
+ !snapshot.idempotencyEvents.every(isCanonicalOrchestrationEvent) ||
426
623
  !snapshot.idempotencyEvents.every((event) => event.ordinal <= baseline.throughOrdinal && event.idempotencyKey !== undefined) ||
427
624
  new Set(snapshot.idempotencyEvents.map((event) => event.idempotencyKey)).size !==
428
625
  snapshot.idempotencyEvents.length ||
@@ -430,12 +627,13 @@ export class OrchestrationEventStore {
430
627
  snapshot.digest !== baseline.digest) {
431
628
  throw new OrchestrationEventStoreError("Invalid orchestration projection snapshot.");
432
629
  }
630
+ const projection = canonicalJsonObject(snapshot.projection, "Orchestration projection snapshot state");
433
631
  const content = {
434
632
  version: 1,
435
633
  schemaVersion: ORCHESTRATION_SCHEMA_VERSION,
436
634
  throughOrdinal: baseline.throughOrdinal,
437
635
  createdAt: snapshot.createdAt,
438
- projection: structuredClone(snapshot.projection),
636
+ projection,
439
637
  idempotencyEvents: snapshot.idempotencyEvents.map((event) => structuredClone(event)),
440
638
  };
441
639
  if (snapshotDigest(content) !== baseline.digest) {
@@ -512,7 +710,7 @@ export class OrchestrationEventStore {
512
710
  catch (error) {
513
711
  throw new OrchestrationEventStoreError(`Failed to parse orchestration event ${name}: ${error instanceof Error ? error.message : String(error)}`);
514
712
  }
515
- if (!isOrchestrationEvent(parsed)) {
713
+ if (!isCanonicalOrchestrationEvent(parsed)) {
516
714
  throw new OrchestrationEventStoreError(`Invalid orchestration event record: ${name}`);
517
715
  }
518
716
  return parsed;