@makaio/framework 1.0.0-dev-1787949057928 → 1.0.0-dev-1788511348215

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 (79) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/attempt-record-codec-dC9LSFUE.mjs +1 -0
  3. package/dist/authority-state-bootstrap-eitx6Ukn.mjs +1 -0
  4. package/dist/bus/index.mjs +1 -1
  5. package/dist/capabilities-DEvmD9VJ.mjs +1 -0
  6. package/dist/contracts/artifact/index.d.mts +1 -1
  7. package/dist/contracts/capabilities/index.d.mts +2 -2
  8. package/dist/contracts/capabilities/index.mjs +1 -1
  9. package/dist/contracts/client/index.d.mts +1 -1
  10. package/dist/contracts/extension/index.d.mts +2 -2
  11. package/dist/contracts/index.d.mts +12 -12
  12. package/dist/contracts/index.mjs +1 -1
  13. package/dist/contracts/worker/index.d.mts +2 -0
  14. package/dist/contracts/worker/index.mjs +1 -0
  15. package/dist/contracts/workflow/index.d.mts +1 -1
  16. package/dist/contracts/workflow/index.mjs +1 -1
  17. package/dist/{execution-attempt-repository-BJ2W6wwx.d.mts → execution-attempt-repository-DY4KTptE.d.mts} +359 -57
  18. package/dist/{index-8NdPPzUh2.d.mts → index-6trZYnUP2.d.mts} +12 -12
  19. package/dist/{index-CPi0UpRh.d.mts → index-B_8bA2JW.d.mts} +1 -1
  20. package/dist/{index-DfUpqwBa2.d.mts → index-BmilK-co2.d.mts} +53 -53
  21. package/dist/{index-CMekqu_D.d.mts → index-C6aSnO8m.d.mts} +42 -42
  22. package/dist/{index-BUwDmh1I.d.mts → index-CDud4NAm.d.mts} +10 -10
  23. package/dist/{index-CYjgoYeX.d.mts → index-DHH-93YD.d.mts} +1 -1
  24. package/dist/{index-B9io6JAL.d.mts → index-DI2lS7VT.d.mts} +1 -1
  25. package/dist/{index-cLB38AWX.d.mts → index-DNI6UF9h.d.mts} +60 -60
  26. package/dist/{index-NUByQvlg.d.mts → index-DXtQRehh.d.mts} +14 -14
  27. package/dist/{index-CVNbBtA-.d.mts → index-Wbd_syN2.d.mts} +112 -112
  28. package/dist/kernel/extension/index.d.mts +1 -1
  29. package/dist/kernel/index.d.mts +2 -2
  30. package/dist/kernel/observability/index.d.mts +1 -1
  31. package/dist/{namespace-C06lJSuj.d.mts → namespace-K23m4b0n.d.mts} +6 -6
  32. package/dist/package-Cgjpm9om.mjs +7 -0
  33. package/dist/{package-BNFTUFLB.d.mts → package-efR90JGe.d.mts} +59 -30
  34. package/dist/package.json +1 -1
  35. package/dist/runtime-node/index.d.mts +1 -1
  36. package/dist/runtime-node/index.mjs +1 -1
  37. package/dist/runtime-node/makaio-config.d.mts +2 -2
  38. package/dist/runtime-node/makaio-config.mjs +1 -1
  39. package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
  40. package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
  41. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  42. package/dist/{schemas-OWvBn7AH.d.mts → schemas-BCXvEWyF.d.mts} +4 -4
  43. package/dist/{schemas-BAv9RB9M.d.mts → schemas-D7EeKBDJ.d.mts} +3 -3
  44. package/dist/services/adapter-subsystem/index.d.mts +2 -2
  45. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  46. package/dist/services/filesystem/namespace.d.mts +6 -6
  47. package/dist/services/filesystem/schemas.d.mts +3 -3
  48. package/dist/services/index.d.mts +9 -9
  49. package/dist/services/provider-context/index.d.mts +1 -1
  50. package/dist/services/session/index.d.mts +1 -1
  51. package/dist/services/settings/namespace.d.mts +2 -2
  52. package/dist/services/subagent-template/index.d.mts +1 -1
  53. package/dist/services/subagent-template/schemas.d.mts +1 -1
  54. package/dist/worker-CARV52hT.mjs +1 -0
  55. package/dist/worker-CLsRbzpk.mjs +1 -0
  56. package/dist/workflow-BomH9DBB.mjs +1 -0
  57. package/dist/workflow-engine/execution-attempt-repository.d.mts +2 -2
  58. package/dist/workflow-engine/execution-attempt-repository.mjs +1 -1
  59. package/dist/workflow-engine/index.d.mts +178 -23
  60. package/dist/workflow-engine/index.mjs +1 -1
  61. package/dist/workflow-engine/package.d.mts +1 -1
  62. package/dist/workflow-engine/package.mjs +1 -1
  63. package/dist/workflow-engine/testing/index.d.mts +30 -9
  64. package/dist/workflow-engine/testing/index.mjs +1 -1
  65. package/dist/workflow-engine/testing/sqlite.d.mts +3 -2
  66. package/dist/workflow-engine/testing/sqlite.mjs +20 -20
  67. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  68. package/dist/workflow-worker-Dul-wcOR.mjs +1 -0
  69. package/package.json +4 -4
  70. package/dist/attempt-record-codec-BYfYkj4M.mjs +0 -1
  71. package/dist/authority-state-bootstrap-CLYus369.mjs +0 -1
  72. package/dist/capabilities-BUwuA7XX.mjs +0 -1
  73. package/dist/contracts/worker-node/index.d.mts +0 -2
  74. package/dist/contracts/worker-node/index.mjs +0 -1
  75. package/dist/package-B01gmu75.mjs +0 -7
  76. package/dist/worker-node-CjuQb9hl.mjs +0 -1
  77. package/dist/worker-node-Dtf9ilsR.mjs +0 -1
  78. package/dist/workflow-C4mck_NW.mjs +0 -1
  79. package/dist/workflow-worker-aNbdgqml.mjs +0 -1
@@ -1,5 +1,5 @@
1
1
  import { a as ProviderOperationClaim, i as ProcessBoundProvisionerLossProof, l as ProviderOperationOwnershipRecord } from "../../provider-operation-DbdyFwNm.mjs";
2
- import { C as ProvisioningClaimDecision, a as BeginProvisioningInput, h as ExecutionAttemptRepository, p as ExecutionAttemptRecord } from "../../execution-attempt-repository-BJ2W6wwx.mjs";
2
+ import { E as ProvisioningClaimDecision, S as OutcomeCodec, a as BeginProvisioningInput, g as ExecutionAttemptRepository, m as ExecutionAttemptRecord } from "../../execution-attempt-repository-DY4KTptE.mjs";
3
3
  import { BoundedRecoveryEvidence, ProviderAllocationRef, WorkflowRunResult } from "@makaio/framework/contracts";
4
4
 
5
5
  //#region subsystems/workflow-engine/src/testing/in-memory-attempt-repository.d.ts
@@ -7,17 +7,30 @@ import { BoundedRecoveryEvidence, ProviderAllocationRef, WorkflowRunResult } fro
7
7
  * Durable state the in-memory realization keeps.
8
8
  *
9
9
  * The four maps mirror the four durable facts the port owns: canonical attempt
10
- * state, fenced provider-operation ownership, committed workflow outcomes, and
11
- * which attempt is currently active for an execution. They are exposed so a
12
- * test can seed state before the first call and assert against it afterwards.
10
+ * state, fenced provider-operation ownership, committed outcomes, and which
11
+ * attempt is currently active for an owner. They are exposed so a test can
12
+ * seed state before the first call and assert against it afterwards.
13
+ *
14
+ * Not generic over the outcome type: the committed outcomes are held as the
15
+ * codec's durable text, the same representation a store's column holds, so
16
+ * none of the four maps carries an outcome-typed value.
13
17
  */
14
18
  interface InMemoryAttemptRepositoryState {
15
19
  /** Attempt records keyed by `executionAttemptId`. */
16
20
  readonly attempts: Map<string, ExecutionAttemptRecord>;
17
21
  /** Provider operation records keyed by `executionAttemptId`. */
18
22
  readonly operations: Map<string, ProviderOperationOwnershipRecord>;
19
- /** Committed canonical outcomes keyed by `executionAttemptId`. */
20
- readonly committedOutcomes: Map<string, WorkflowRunResult>;
23
+ /**
24
+ * Committed outcome texts keyed by `executionAttemptId`.
25
+ *
26
+ * The codec text and nothing else, exactly the `workflow_result` column a
27
+ * durable realization keeps: it is what a retry is compared against, and
28
+ * every outcome the port reports is a fresh decode of it. Keeping the
29
+ * decoded value here instead would hand every reader one shared instance,
30
+ * and a codec may reconstruct a mutable object — a `URL`, say — that no
31
+ * freeze can protect.
32
+ */
33
+ readonly committedOutcomes: Map<string, string>;
21
34
  /** Active attempt per `executionId`, the fence every bootstrap path reads. */
22
35
  readonly activeAttempts: Map<string, string>;
23
36
  }
@@ -30,8 +43,9 @@ interface InMemoryAttemptRepositoryState {
30
43
  * a single failing durable write without losing the rest of the state machine.
31
44
  * Replacing a recovery operation means spreading `recovery` too, which is the
32
45
  * port's own rule that recovery is offered whole or not at all.
46
+ * @typeParam TOutcome - Owner-specific outcome type committed per attempt.
33
47
  */
34
- interface InMemoryAttemptRepository extends Required<ExecutionAttemptRepository>, InMemoryAttemptRepositoryState {}
48
+ interface InMemoryAttemptRepository<TOutcome> extends Required<ExecutionAttemptRepository<TOutcome>>, InMemoryAttemptRepositoryState {}
35
49
  /**
36
50
  * Create the in-memory reference realization of {@link ExecutionAttemptRepository}.
37
51
  *
@@ -55,10 +69,12 @@ interface InMemoryAttemptRepository extends Required<ExecutionAttemptRepository>
55
69
  * model transaction isolation. Use it wherever a test needs the port's
56
70
  * decisions without a database, and `createSqliteAttemptRepository` when the
57
71
  * test needs real transactional fencing between two independent connections.
72
+ * @param codec - Owner-injected codec that validates every submitted outcome.
58
73
  * @param seed - Pre-existing state to build on, shared with the caller.
59
74
  * @returns A repository exposing the full port surface, plus its backing state.
75
+ * @typeParam TOutcome - Owner-specific outcome type committed per attempt.
60
76
  */
61
- declare function createInMemoryAttemptRepository(seed?: Partial<InMemoryAttemptRepositoryState>): InMemoryAttemptRepository;
77
+ declare function createInMemoryAttemptRepository<TOutcome>(codec: OutcomeCodec<TOutcome>, seed?: Partial<InMemoryAttemptRepositoryState>): InMemoryAttemptRepository<TOutcome>;
62
78
  //#endregion
63
79
  //#region subsystems/workflow-engine/src/testing/attempt-fixtures.d.ts
64
80
  /** Controller process incarnation used by tests that need one fixed owner. */
@@ -135,6 +151,11 @@ declare function makeProcessLossProof(provisionerIncarnationId?: string, evidenc
135
151
  * @returns A versioned allocation reference.
136
152
  */
137
153
  declare function makeTestAllocationRef(providerId?: string, providerData?: Record<string, unknown>): ProviderAllocationRef;
154
+ /**
155
+ * Outcome codec for the workflow adapter: validates through
156
+ * {@link WorkflowRunResultSchema} and persists the canonical JSON text.
157
+ */
158
+ declare const workflowRunResultOutcomeCodec: OutcomeCodec<WorkflowRunResult>;
138
159
  /**
139
160
  * Build a terminal workflow result the port can commit.
140
161
  * @param executionId - Execution the result belongs to.
@@ -143,4 +164,4 @@ declare function makeTestAllocationRef(providerId?: string, providerData?: Recor
143
164
  */
144
165
  declare function makeTestWorkflowResult(executionId: string, status?: 'completed' | 'failed'): WorkflowRunResult;
145
166
  //#endregion
146
- export { type InMemoryAttemptRepository, type InMemoryAttemptRepositoryState, type ProvisioningClaimGrantor, TEST_OWNER_ID, TEST_PROVIDER_ID, TEST_PROVISIONER_INCARNATION_ID, beginTestProvisioning, createInMemoryAttemptRepository, leaseAt, makeBeginProvisioningInput, makeEvidence, makeProcessLossProof, makeTestAllocationRef, makeTestWorkflowResult };
167
+ export { type InMemoryAttemptRepository, type InMemoryAttemptRepositoryState, type ProvisioningClaimGrantor, TEST_OWNER_ID, TEST_PROVIDER_ID, TEST_PROVISIONER_INCARNATION_ID, beginTestProvisioning, createInMemoryAttemptRepository, leaseAt, makeBeginProvisioningInput, makeEvidence, makeProcessLossProof, makeTestAllocationRef, makeTestWorkflowResult, workflowRunResultOutcomeCodec };
@@ -1 +1 @@
1
- import{DuplicateExecutionAttemptError as e,sameAllocationRef as t,sameWorkflowResult as n}from"../execution-attempt-repository.mjs";import{a as r,c as i,i as a,l as o,n as s,o as c,r as l,s as u,t as d}from"../../attempt-record-codec-BYfYkj4M.mjs";import{BoundedRecoveryEvidenceSchema as f,PROVIDER_ALLOCATION_REF_VERSION as p}from"@makaio/framework/contracts";function m(p={}){let m=p.attempts??new Map,h=p.operations??new Map,g=p.committedOutcomes??new Map,_=p.activeAttempts??new Map,v=e=>{let t=m.get(e.executionAttemptId),n=h.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:t.settlementKind==null?n.token===null||n.token!==e.token||n.generation!==e.generation||n.ownerId!==e.ownerId?{kind:`stale`,attempt:t}:{kind:`authorized`,attempt:t,operation:n}:{kind:`resolved`,attempt:t}},y=(e,t)=>{h.set(e.executionAttemptId,{...e,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t})},b=(e,n)=>{let a=r(e.allocationRef),o=v(e.claim);if(o.kind!==`not-found`&&i(o.attempt,a),o.kind===`resolved`)return{kind:`resolved`,allocationRef:o.attempt.allocationRef};if(o.kind!==`authorized`)return{kind:o.kind};let{attempt:s,operation:c}=o;if(s.allocationRef!==null)return t(s.allocationRef,a)?{kind:`duplicate`,allocationRef:s.allocationRef}:{kind:`conflict`,allocationRef:s.allocationRef};let l=_.get(s.executionId)===s.executionAttemptId;return m.set(s.executionAttemptId,{...s,status:`allocated`,allocationRef:a,claimable:n&&l}),h.set(c.executionAttemptId,{...c,obligation:`allocation-control`}),{kind:`recorded`}};return{async createAttempt(t){if(m.has(t.executionAttemptId))throw new e(t.executionAttemptId);let n={executionAttemptId:t.executionAttemptId,executionId:t.executionId,status:`pending`,allocationRef:null,createdAt:new Date().toISOString(),providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null},r=_.get(t.executionId),i=r===void 0?void 0:m.get(r);return i?.status===`allocated`&&m.set(i.executionAttemptId,{...i,claimable:!1}),m.set(t.executionAttemptId,n),_.set(t.executionId,t.executionAttemptId),n},async beginProvisioning(e){let t=a(e.allocationLifetime),n=m.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(_.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(n.settlementKind!=null)return{kind:`resolved`,allocationRef:n.allocationRef};if(n.allocationRef!==null)return{kind:`allocated`,allocationRef:n.allocationRef};if(n.status!==`pending`)return{kind:`already-provisioning`};m.set(e.executionAttemptId,{...n,status:`provisioning`,providerId:e.providerId,allocationLifetime:t,provisionerIncarnationId:e.provisionerIncarnationId});let r={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:l(e.leaseExpiresAt)};return h.set(e.executionAttemptId,{executionAttemptId:e.executionAttemptId,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt,obligation:`provisioning-resolution`,failureCount:0,lastFailure:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return h.get(e)??null},async renewProviderOperationClaim(e){let t=v(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=l(e.leaseExpiresAt);return h.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=m.get(e.executionAttemptId),n=h.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&s(n.leaseExpiresAt)>s(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:l(e.leaseExpiresAt)};return h.set(e.executionAttemptId,{...n,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt}),{kind:`claimed`,claim:r}},async handoffProviderOperation(e){let t=e.evidence===void 0?void 0:f.parse(e.evidence),n=v(e.claim);return n.kind===`authorized`?(h.set(e.claim.executionAttemptId,{...n.operation,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t??n.operation.lastFailure}),{kind:`recorded`}):{kind:n.kind}},async recordProviderOperationUncertainty(e){let t=f.parse(e.evidence),n=v(e.claim);return n.kind===`authorized`?(h.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async recordAllocation(e){return b(e,!0)},async recordProvisioningAbsent(e){let t=f.parse(e.evidence),n=v(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?(m.set(r.executionAttemptId,{...r,status:`settled`,settlementKind:`abandoned`,claimable:!1}),y(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=f.parse(e.proof.evidence),n=v(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationLifetime===`provisioner-process-bound`?r.provisionerIncarnationId===null||r.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:r.provisionerIncarnationId}:r.allocationRef===null?(m.set(r.executionAttemptId,{...r,status:`settled`,settlementKind:`abandoned`,claimable:!1}),y(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-process-bound`,allocationLifetime:r.allocationLifetime}:{kind:`not-found`}},async recordAllocationTerminated(e){let t=f.parse(e.evidence),n=v(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(h.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=v(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(m.set(n.executionAttemptId,{...n,status:`settled`,settlementKind:`infrastructure-failure`,claimable:!1}),y(r,r.lastFailure),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`not-found`}},async getActiveAttempt(e,t){return _.get(e)===t?m.get(t)??null:null},async commitOutcome(e){let t=u(e.result);if(_.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let r=m.get(e.executionAttemptId);if(r===void 0)return{kind:`fenced`};let i=g.get(e.executionAttemptId);if(i)return n(i,t)?{kind:`duplicate`,outcome:i}:{kind:`conflict`};if(r.settlementKind!=null)return{kind:`conflict`};g.set(e.executionAttemptId,t),m.set(e.executionAttemptId,{...r,status:`settled`,settlementKind:`outcome`,claimable:!1});let a=h.get(e.executionAttemptId);return a&&y(a,a.lastFailure),{kind:`accepted`,outcome:t}},async abandonPendingAttempt(e,t){if(_.get(t)!==e)return{kind:`fenced`};let n=m.get(e);return n?n.status===`allocated`?{kind:`allocated`}:n.status===`provisioning`?{kind:`provisioning`}:n.status===`settled`?{kind:n.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:(m.set(e,{...n,status:`settled`,settlementKind:`abandoned`,claimable:!1}),{kind:`abandoned`}):{kind:`fenced`}},recovery:{async getAttemptWithAllocation(e){return m.get(e)??null},async recordDiscoveredAllocation(e){return b(e,!1)},async evolveAllocationRef(e){let{currentRef:n,nextRef:r}=c(e),i=v(e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:t(a.allocationRef,n)?(m.set(a.executionAttemptId,{...a,allocationRef:r}),{kind:`evolved`}):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=s(new Date().toISOString()),n=[];for(let r of m.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&s(r.claimExpiresAt)<t||n.push(o(r)));return n.sort(d)}},attempts:m,operations:h,committedOutcomes:g,activeAttempts:_}}const h=`controller-incarnation-1`,g=`provisioner-incarnation-1`,_=`test-provider`;function v(e){return new Date(Date.now()+e).toISOString()}function y(e,t,n={}){return{executionAttemptId:e,executionId:t,providerId:_,allocationLifetime:`provider-managed`,provisionerIncarnationId:g,ownerId:h,leaseExpiresAt:v(6e4),...n}}async function b(e,t,n,r={}){let i=await e.beginProvisioning(y(t,n,r));if(i.kind!==`started`)throw Error(`Expected provisioning to start, got '${i.kind}'`);return i.claim}function x(e={}){return{source:_,summary:`provider rejected the request before creating anything`,observedAt:new Date().toISOString(),...e}}function S(e=g,t=x({summary:`supervisor observed the provisioner process exit`})){return{kind:`provisioner-incarnation-lost`,provisionerIncarnationId:e,evidence:t}}function C(e=_,t={runId:1}){return{version:p,providerId:e,providerData:t}}function w(e,t=`completed`){let n={executionId:e,workflowId:`contract-workflow`};return t===`completed`?{...n,status:`completed`}:{...n,status:`failed`,error:`contract failure`}}export{h as TEST_OWNER_ID,_ as TEST_PROVIDER_ID,g as TEST_PROVISIONER_INCARNATION_ID,b as beginTestProvisioning,m as createInMemoryAttemptRepository,v as leaseAt,y as makeBeginProvisioningInput,x as makeEvidence,S as makeProcessLossProof,C as makeTestAllocationRef,w as makeTestWorkflowResult};
1
+ import{DuplicateExecutionAttemptError as e,decodeDurableOutcome as t,durableOutcome as n,sameAllocationRef as r,sameDurableOutcome as i}from"../execution-attempt-repository.mjs";import{a,c as o,i as s,n as c,o as l,r as u,s as d,t as f}from"../../attempt-record-codec-dC9LSFUE.mjs";import{BoundedRecoveryEvidenceSchema as p,PROVIDER_ALLOCATION_REF_VERSION as m,WorkflowRunResultSchema as h}from"@makaio/framework/contracts";function g(m,h={}){let g=h.attempts??new Map,_=h.operations??new Map,v=h.committedOutcomes??new Map,y=h.activeAttempts??new Map,b=e=>{let t=g.get(e.executionAttemptId),n=_.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:t.settlementKind==null?n.token===null||n.token!==e.token||n.generation!==e.generation||n.ownerId!==e.ownerId?{kind:`stale`,attempt:t}:{kind:`authorized`,attempt:t,operation:n}:{kind:`resolved`,attempt:t}},x=(e,t)=>{_.set(e.executionAttemptId,{...e,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t})},S=(e,t)=>{let n=a(e.allocationRef),i=b(e.claim);if(i.kind!==`not-found`&&d(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:o,operation:s}=i;if(o.allocationRef!==null)return r(o.allocationRef,n)?{kind:`duplicate`,allocationRef:o.allocationRef}:{kind:`conflict`,allocationRef:o.allocationRef};let c=y.get(o.executionId)===o.executionAttemptId;return g.set(o.executionAttemptId,{...o,status:`allocated`,allocationRef:n,claimable:t&&c}),_.set(s.executionAttemptId,{...s,obligation:`allocation-control`}),{kind:`recorded`}};return{async createAttempt(t){if(g.has(t.executionAttemptId))throw new e(t.executionAttemptId);let n={executionAttemptId:t.executionAttemptId,executionId:t.executionId,status:`pending`,allocationRef:null,createdAt:new Date().toISOString(),providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null},r=y.get(t.executionId),i=r===void 0?void 0:g.get(r);return i?.status===`allocated`&&g.set(i.executionAttemptId,{...i,claimable:!1}),g.set(t.executionAttemptId,n),y.set(t.executionId,t.executionAttemptId),n},async beginProvisioning(e){let t=s(e.allocationLifetime),n=g.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(y.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(n.settlementKind!=null)return{kind:`resolved`,allocationRef:n.allocationRef};if(n.allocationRef!==null)return{kind:`allocated`,allocationRef:n.allocationRef};if(n.status!==`pending`)return{kind:`already-provisioning`};g.set(e.executionAttemptId,{...n,status:`provisioning`,providerId:e.providerId,allocationLifetime:t,provisionerIncarnationId:e.provisionerIncarnationId});let r={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:u(e.leaseExpiresAt)};return _.set(e.executionAttemptId,{executionAttemptId:e.executionAttemptId,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt,obligation:`provisioning-resolution`,failureCount:0,lastFailure:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return _.get(e)??null},async renewProviderOperationClaim(e){let t=b(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=u(e.leaseExpiresAt);return _.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=g.get(e.executionAttemptId),n=_.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&c(n.leaseExpiresAt)>c(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:u(e.leaseExpiresAt)};return _.set(e.executionAttemptId,{...n,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt}),{kind:`claimed`,claim:r}},async handoffProviderOperation(e){let t=e.evidence===void 0?void 0:p.parse(e.evidence),n=b(e.claim);return n.kind===`authorized`?(_.set(e.claim.executionAttemptId,{...n.operation,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t??n.operation.lastFailure}),{kind:`recorded`}):{kind:n.kind}},async recordProviderOperationUncertainty(e){let t=p.parse(e.evidence),n=b(e.claim);return n.kind===`authorized`?(_.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async recordAllocation(e){return S(e,!0)},async recordProvisioningAbsent(e){let t=p.parse(e.evidence),n=b(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?(g.set(r.executionAttemptId,{...r,status:`settled`,settlementKind:`abandoned`,claimable:!1}),x(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=p.parse(e.proof.evidence),n=b(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationLifetime===`provisioner-process-bound`?r.provisionerIncarnationId===null||r.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:r.provisionerIncarnationId}:r.allocationRef===null?(g.set(r.executionAttemptId,{...r,status:`settled`,settlementKind:`abandoned`,claimable:!1}),x(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-process-bound`,allocationLifetime:r.allocationLifetime}:{kind:`not-found`}},async recordAllocationTerminated(e){let t=p.parse(e.evidence),n=b(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(_.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=b(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(g.set(n.executionAttemptId,{...n,status:`settled`,settlementKind:`infrastructure-failure`,claimable:!1}),x(r,r.lastFailure),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`not-found`}},async getActiveAttempt(e,t){return y.get(e)===t?g.get(t)??null:null},canonicalizeOutcome(e){return n(m,e)},decodeOutcome(e){return t(m,e)},async commitOutcome(e){let n=e.result;if(y.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let r=g.get(e.executionAttemptId);if(r===void 0)return{kind:`fenced`};let a=v.get(e.executionAttemptId);if(a!==void 0){let e=t(m,a);return i(a,n.text)?{kind:`duplicate`,outcome:e,text:a}:{kind:`conflict`}}if(r.settlementKind!=null)return{kind:`conflict`};v.set(e.executionAttemptId,n.text),g.set(e.executionAttemptId,{...r,status:`settled`,settlementKind:`outcome`,claimable:!1});let o=_.get(e.executionAttemptId);return o&&x(o,o.lastFailure),{kind:`accepted`,outcome:t(m,n.text),text:n.text}},async abandonPendingAttempt(e,t){if(y.get(t)!==e)return{kind:`fenced`};let n=g.get(e);return n?n.status===`allocated`?{kind:`allocated`}:n.status===`provisioning`?{kind:`provisioning`}:n.status===`settled`?{kind:n.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:(g.set(e,{...n,status:`settled`,settlementKind:`abandoned`,claimable:!1}),{kind:`abandoned`}):{kind:`fenced`}},recovery:{async getAttemptWithAllocation(e){return g.get(e)??null},async recordDiscoveredAllocation(e){return S(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=l(e),i=b(e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:r(a.allocationRef,t)?(g.set(a.executionAttemptId,{...a,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=c(new Date().toISOString()),n=[];for(let r of g.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&c(r.claimExpiresAt)<t||n.push(o(r)));return n.sort(f)}},attempts:g,operations:_,committedOutcomes:v,activeAttempts:y}}const _=`controller-incarnation-1`,v=`provisioner-incarnation-1`,y=`test-provider`;function b(e){return new Date(Date.now()+e).toISOString()}function x(e,t,n={}){return{executionAttemptId:e,executionId:t,providerId:y,allocationLifetime:`provider-managed`,provisionerIncarnationId:v,ownerId:_,leaseExpiresAt:b(6e4),...n}}async function S(e,t,n,r={}){let i=await e.beginProvisioning(x(t,n,r));if(i.kind!==`started`)throw Error(`Expected provisioning to start, got '${i.kind}'`);return i.claim}function C(e={}){return{source:y,summary:`provider rejected the request before creating anything`,observedAt:new Date().toISOString(),...e}}function w(e=v,t=C({summary:`supervisor observed the provisioner process exit`})){return{kind:`provisioner-incarnation-lost`,provisionerIncarnationId:e,evidence:t}}function T(e=y,t={runId:1}){return{version:m,providerId:e,providerData:t}}const E={parse:e=>h.parse(e),serialize:e=>JSON.stringify(e)};function D(e,t=`completed`){let n={executionId:e,workflowId:`contract-workflow`};return t===`completed`?{...n,status:`completed`}:{...n,status:`failed`,error:`contract failure`}}export{_ as TEST_OWNER_ID,y as TEST_PROVIDER_ID,v as TEST_PROVISIONER_INCARNATION_ID,S as beginTestProvisioning,g as createInMemoryAttemptRepository,b as leaseAt,x as makeBeginProvisioningInput,C as makeEvidence,w as makeProcessLossProof,T as makeTestAllocationRef,D as makeTestWorkflowResult,E as workflowRunResultOutcomeCodec};
@@ -1,4 +1,4 @@
1
- import { h as ExecutionAttemptRepository } from "../../execution-attempt-repository-BJ2W6wwx.mjs";
1
+ import { S as OutcomeCodec, g as ExecutionAttemptRepository } from "../../execution-attempt-repository-DY4KTptE.mjs";
2
2
  import { MakaioDatabase } from "@makaio/framework/storage/drizzle";
3
3
 
4
4
  //#region subsystems/workflow-engine/src/testing/sqlite-attempt-repository.d.ts
@@ -15,8 +15,9 @@ import { MakaioDatabase } from "@makaio/framework/storage/drizzle";
15
15
  * the storage migration chain. It is test support, not production
16
16
  * persistence.
17
17
  * @param db - Open database handle the repository reads and writes through.
18
+ * @param codec - Owner-injected codec that validates and serializes outcomes.
18
19
  * @returns A repository exposing the full port surface, backed by SQLite.
19
20
  */
20
- declare function createSqliteAttemptRepository(db: MakaioDatabase): Promise<Required<ExecutionAttemptRepository>>;
21
+ declare function createSqliteAttemptRepository<TOutcome>(db: MakaioDatabase, codec: OutcomeCodec<TOutcome>): Promise<Required<ExecutionAttemptRepository<TOutcome>>>;
21
22
  //#endregion
22
23
  export { createSqliteAttemptRepository };
@@ -1,4 +1,4 @@
1
- import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as t,EXECUTION_ATTEMPT_STATUSES as n,sameAllocationRef as r,sameWorkflowResult as i}from"../execution-attempt-repository.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as a}from"../provider-operation.mjs";import{a as o,c as s,i as c,l,n as u,o as d,r as f,s as p}from"../../attempt-record-codec-BYfYkj4M.mjs";import{BoundedRecoveryEvidenceSchema as m,ProviderAllocationRefSchema as h,WorkerNodeAllocationLifetimeSchema as g,WorkflowRunResultSchema as _}from"@makaio/framework/contracts";import{getRawSqlExecutor as v,isSqliteUniqueViolationError as y,serializeByKey as b,serializeDatabaseOperation as x}from"@makaio/framework/storage/drizzle";import{sql as S}from"drizzle-orm";const C=[`CREATE TABLE IF NOT EXISTS test_execution_attempt (
1
+ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as t,EXECUTION_ATTEMPT_STATUSES as n,decodeDurableOutcome as r,durableOutcome as i,sameAllocationRef as a,sameDurableOutcome as o}from"../execution-attempt-repository.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as s}from"../provider-operation.mjs";import{a as c,c as l,i as u,n as d,o as f,r as p,s as m}from"../../attempt-record-codec-dC9LSFUE.mjs";import{BoundedRecoveryEvidenceSchema as h,ProviderAllocationRefSchema as g,WorkerAllocationLifetimeSchema as _}from"@makaio/framework/contracts";import{getRawSqlExecutor as v,isSqliteUniqueViolationError as y,serializeByKey as b,serializeDatabaseOperation as x}from"@makaio/framework/storage/drizzle";import{sql as S}from"drizzle-orm";const C=[`CREATE TABLE IF NOT EXISTS test_execution_attempt (
2
2
  execution_attempt_id TEXT PRIMARY KEY,
3
3
  execution_id TEXT NOT NULL,
4
4
  status TEXT NOT NULL,
@@ -25,7 +25,7 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
25
25
  obligation TEXT NOT NULL,
26
26
  failure_count INTEGER NOT NULL DEFAULT 0,
27
27
  last_failure TEXT
28
- )`];function w(e,t,n){let r=e.find(e=>e===t);if(r===void 0)throw Error(`Stored '${n}' value '${t}' is not part of the port's vocabulary`);return r}function T(e,t){return e===null?null:t(JSON.parse(e))}function E(e){return{executionAttemptId:e.execution_attempt_id,executionId:e.execution_id,status:w(n,e.status,`status`),allocationRef:T(e.allocation_ref,e=>h.parse(e)),createdAt:e.created_at,providerId:e.provider_id,allocationLifetime:e.allocation_lifetime===null?null:g.parse(e.allocation_lifetime),provisionerIncarnationId:e.provisioner_incarnation_id,settlementKind:e.settlement_kind===null?null:w(t,e.settlement_kind,`settlement_kind`),claimable:e.claimable!==0,claimExpiresAt:e.claim_expires_at}}function D(e){return{executionAttemptId:e.execution_attempt_id,generation:e.generation,ownerId:e.owner_id,token:e.token,leaseExpiresAt:e.lease_expires_at,obligation:w(a,e.obligation,`obligation`),failureCount:e.failure_count,lastFailure:T(e.last_failure,e=>m.parse(e))}}const O=new Map,k=new Map;function A(e){if(typeof e!=`object`||!e)return!1;let t=e,n=typeof t.message==`string`?t.message:``;return n.includes(`SQLITE_BUSY`)||n.startsWith(`Failed query: BEGIN IMMEDIATE`)||n.startsWith(`Failed query: COMMIT`)||A(t.cause)}function j(e){if(typeof e!=`object`||!e)return!1;let t=e;return(typeof t.message==`string`?t.message:``).includes(`no transaction is active`)||j(t.cause)}async function M(){await new Promise(e=>setImmediate(e))}async function N(e){for(let t=0;;t+=1)try{await e.run(S.raw(`COMMIT`));return}catch(e){if(!A(e)||t===100)throw e;await M()}}async function P(e,t){return b(O,e,t)}async function F(e,t){return b(k,e,t)}const I=new WeakMap;async function L(e,t){let n=(await t.all(S.raw(`PRAGMA database_list`))).find(e=>e.name===`main`)?.file??null;if(n!==null&&n!==``)return`file:${n}`;let r=I.get(e);if(r!==void 0)return r;let i=`connection:${crypto.randomUUID()}`;return I.set(e,i),i}async function R(e,t){let n=await e();if(typeof n!=`function`)return n;if((await n()).rowsAffected>0)return t;let r=await e();if(typeof r!=`function`)return r;throw Error(`A guarded transition affected no rows while durable state still permitted it`)}function z(e){return S`EXISTS (SELECT 1 FROM test_provider_operation
28
+ )`];function w(e,t,n){let r=e.find(e=>e===t);if(r===void 0)throw Error(`Stored '${n}' value '${t}' is not part of the port's vocabulary`);return r}function T(e,t){return e===null?null:t(JSON.parse(e))}function E(e){return{executionAttemptId:e.execution_attempt_id,executionId:e.execution_id,status:w(n,e.status,`status`),allocationRef:T(e.allocation_ref,e=>g.parse(e)),createdAt:e.created_at,providerId:e.provider_id,allocationLifetime:e.allocation_lifetime===null?null:_.parse(e.allocation_lifetime),provisionerIncarnationId:e.provisioner_incarnation_id,settlementKind:e.settlement_kind===null?null:w(t,e.settlement_kind,`settlement_kind`),claimable:e.claimable!==0,claimExpiresAt:e.claim_expires_at}}function D(e){return{executionAttemptId:e.execution_attempt_id,generation:e.generation,ownerId:e.owner_id,token:e.token,leaseExpiresAt:e.lease_expires_at,obligation:w(s,e.obligation,`obligation`),failureCount:e.failure_count,lastFailure:T(e.last_failure,e=>h.parse(e))}}const O=new Map,k=new Map;function A(e){if(typeof e!=`object`||!e)return!1;let t=e,n=typeof t.message==`string`?t.message:``;return n.includes(`SQLITE_BUSY`)||n.startsWith(`Failed query: BEGIN IMMEDIATE`)||n.startsWith(`Failed query: COMMIT`)||A(t.cause)}function j(e){if(typeof e!=`object`||!e)return!1;let t=e;return(typeof t.message==`string`?t.message:``).includes(`no transaction is active`)||j(t.cause)}async function M(){await new Promise(e=>setImmediate(e))}async function N(e){for(let t=0;;t+=1)try{await e.run(S.raw(`COMMIT`));return}catch(e){if(!A(e)||t===100)throw e;await M()}}async function P(e,t){return b(O,e,t)}async function F(e,t){return b(k,e,t)}const I=new WeakMap;async function L(e,t){let n=(await t.all(S.raw(`PRAGMA database_list`))).find(e=>e.name===`main`)?.file??null;if(n!==null&&n!==``)return`file:${n}`;let r=I.get(e);if(r!==void 0)return r;let i=`connection:${crypto.randomUUID()}`;return I.set(e,i),i}async function R(e,t){let n=await e();if(typeof n!=`function`)return n;if((await n()).rowsAffected>0)return t;let r=await e();if(typeof r!=`function`)return r;throw Error(`A guarded transition affected no rows while durable state still permitted it`)}function z(e){return S`EXISTS (SELECT 1 FROM test_provider_operation
29
29
  WHERE execution_attempt_id = ${e.executionAttemptId}
30
30
  AND generation = ${e.generation}
31
31
  AND owner_id = ${e.ownerId}
@@ -34,7 +34,7 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
34
34
  WHERE execution_attempt_id = ${e}
35
35
  AND obligation = ${`terminal-convergence`})`}function U(){return S`EXISTS (SELECT 1 FROM test_active_execution_attempt
36
36
  WHERE execution_id = test_execution_attempt.execution_id
37
- AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function W(t){let n=v(t);await n.run(S.raw(`PRAGMA busy_timeout = 0`));let h=await L(t,n);await P(h,async()=>{for(let e of C)await n.run(S.raw(e))});let g,b=async e=>x(t,()=>F(h,async()=>{if(g!==void 0)throw Error(`This repository was retired by a failed transaction rollback`,{cause:g});for(let t=0;;t+=1)try{return await n.withSession(async t=>{let n=!1;try{await t.run(S.raw(`BEGIN IMMEDIATE`)),n=!0;let r=await e(t);return await N(t),r}catch(e){try{await t.run(S.raw(`ROLLBACK`))}catch(t){throw!n&&j(t)?e:(g=AggregateError([e,t],`Transaction rollback failed`),g)}throw e}})}catch(e){if(!A(e)||t===100)throw e;await M()}})),O=async(e,t)=>(await e.all(S`SELECT * FROM test_execution_attempt WHERE execution_attempt_id = ${t}`))[0],k=async(e,t)=>(await e.all(S`SELECT * FROM test_provider_operation WHERE execution_attempt_id = ${t}`))[0],I=async(e,t)=>(await e.all(S`SELECT execution_attempt_id FROM test_active_execution_attempt WHERE execution_id = ${t}`))[0]?.execution_attempt_id??null,W=async(e,t)=>{let n=await O(e,t.executionAttemptId),r=await k(e,t.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};let i=E(n);return i.settlementKind==null?r.token===null||r.token!==t.token||r.generation!==t.generation||r.owner_id!==t.ownerId?{kind:`stale`,attempt:i}:{kind:`authorized`,attempt:i,attemptRow:n,operation:r}:{kind:`resolved`,attempt:i}},G=async(e,t)=>{let n=await W(e,t);return n.kind===`authorized`?void 0:{kind:n.kind}},K=async(e,t,n,r,i)=>{let a=await e.run(S`UPDATE test_execution_attempt
37
+ AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function W(t,n){let g=v(t);await g.run(S.raw(`PRAGMA busy_timeout = 0`));let _=await L(t,g);await P(_,async()=>{for(let e of C)await g.run(S.raw(e))});let b,T=async e=>x(t,()=>F(_,async()=>{if(b!==void 0)throw Error(`This repository was retired by a failed transaction rollback`,{cause:b});for(let t=0;;t+=1)try{return await g.withSession(async t=>{let n=!1;try{await t.run(S.raw(`BEGIN IMMEDIATE`)),n=!0;let r=await e(t);return await N(t),r}catch(e){try{await t.run(S.raw(`ROLLBACK`))}catch(t){throw!n&&j(t)?e:(b=AggregateError([e,t],`Transaction rollback failed`),b)}throw e}})}catch(e){if(!A(e)||t===100)throw e;await M()}})),O=async(e,t)=>(await e.all(S`SELECT * FROM test_execution_attempt WHERE execution_attempt_id = ${t}`))[0],k=async(e,t)=>(await e.all(S`SELECT * FROM test_provider_operation WHERE execution_attempt_id = ${t}`))[0],I=async(e,t)=>(await e.all(S`SELECT execution_attempt_id FROM test_active_execution_attempt WHERE execution_id = ${t}`))[0]?.execution_attempt_id??null,W=async(e,t)=>{let n=await O(e,t.executionAttemptId),r=await k(e,t.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};let i=E(n);return i.settlementKind==null?r.token===null||r.token!==t.token||r.generation!==t.generation||r.owner_id!==t.ownerId?{kind:`stale`,attempt:i}:{kind:`authorized`,attempt:i,attemptRow:n,operation:r}:{kind:`resolved`,attempt:i}},G=async(e,t)=>{let n=await W(e,t);return n.kind===`authorized`?void 0:{kind:n.kind}},K=async(e,t,n,r,i)=>{let a=await e.run(S`UPDATE test_execution_attempt
38
38
  SET status = ${`settled`}, settlement_kind = ${n}, claimable = ${0}
39
39
  WHERE execution_attempt_id = ${t}
40
40
  AND settlement_kind IS NULL
@@ -42,14 +42,14 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
42
42
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL
43
43
  WHERE execution_attempt_id = ${t}`:S`UPDATE test_provider_operation
44
44
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL, last_failure = ${JSON.stringify(i)}
45
- WHERE execution_attempt_id = ${t}`),a},q=(e,t)=>{let n=o(e.allocationRef),i=t?S`CASE WHEN ${U()} THEN 1 ELSE 0 END`:S`${0}`;return b(t=>R(async()=>{let a=await W(t,e.claim);if(a.kind!==`not-found`&&s(a.attempt,n),a.kind===`resolved`)return{kind:`resolved`,allocationRef:a.attempt.allocationRef};if(a.kind!==`authorized`)return{kind:a.kind};let{attempt:o}=a;return o.allocationRef===null?async()=>{let r=await t.run(S`UPDATE test_execution_attempt
45
+ WHERE execution_attempt_id = ${t}`),a},q=(e,t)=>{let n=c(e.allocationRef),r=t?S`CASE WHEN ${U()} THEN 1 ELSE 0 END`:S`${0}`;return T(t=>R(async()=>{let i=await W(t,e.claim);if(i.kind!==`not-found`&&m(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:o}=i;return o.allocationRef===null?async()=>{let i=await t.run(S`UPDATE test_execution_attempt
46
46
  SET status = ${`allocated`},
47
47
  allocation_ref = ${JSON.stringify(n)},
48
- claimable = ${i}
48
+ claimable = ${r}
49
49
  WHERE execution_attempt_id = ${o.executionAttemptId}
50
50
  AND allocation_ref IS NULL
51
- AND ${V(e.claim)}`);return r.rowsAffected===0||await t.run(S`UPDATE test_provider_operation SET obligation = ${`allocation-control`}
52
- WHERE execution_attempt_id = ${o.executionAttemptId}`),r}:r(o.allocationRef,n)?{kind:`duplicate`,allocationRef:o.allocationRef}:{kind:`conflict`,allocationRef:o.allocationRef}},{kind:`recorded`}))};return{async createAttempt(t){return b(async n=>{let r=new Date().toISOString();try{await n.run(S`INSERT INTO test_execution_attempt
51
+ AND ${V(e.claim)}`);return i.rowsAffected===0||await t.run(S`UPDATE test_provider_operation SET obligation = ${`allocation-control`}
52
+ WHERE execution_attempt_id = ${o.executionAttemptId}`),i}:a(o.allocationRef,n)?{kind:`duplicate`,allocationRef:o.allocationRef}:{kind:`conflict`,allocationRef:o.allocationRef}},{kind:`recorded`}))};return{async createAttempt(t){return T(async n=>{let r=new Date().toISOString();try{await n.run(S`INSERT INTO test_execution_attempt
53
53
  (execution_attempt_id, execution_id, status, claimable, created_at)
54
54
  VALUES (${t.executionAttemptId}, ${t.executionId}, ${`pending`}, ${0}, ${r})`)}catch(n){throw y(n)?new e(t.executionAttemptId,{cause:n}):n}return await n.run(S`UPDATE test_execution_attempt
55
55
  SET claimable = ${0}
@@ -61,7 +61,7 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
61
61
  AND status = ${`allocated`}`),await n.run(S`INSERT INTO test_active_execution_attempt (execution_id, execution_attempt_id)
62
62
  VALUES (${t.executionId}, ${t.executionAttemptId})
63
63
  ON CONFLICT(execution_id)
64
- DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{executionAttemptId:t.executionAttemptId,executionId:t.executionId,status:`pending`,allocationRef:null,createdAt:r,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null}})},async beginProvisioning(e){let t=c(e.allocationLifetime),n={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:f(e.leaseExpiresAt)};return b(r=>R(async()=>{let i=await O(r,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=E(i);return await I(r,e.executionId)===e.executionAttemptId?a.settlementKind==null?a.allocationRef===null?a.status===`pending`?async()=>{let i=await r.run(S`UPDATE test_execution_attempt
64
+ DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{executionAttemptId:t.executionAttemptId,executionId:t.executionId,status:`pending`,allocationRef:null,createdAt:r,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null}})},async beginProvisioning(e){let t=u(e.allocationLifetime),n={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:p(e.leaseExpiresAt)};return T(r=>R(async()=>{let i=await O(r,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=E(i);return await I(r,e.executionId)===e.executionAttemptId?a.settlementKind==null?a.allocationRef===null?a.status===`pending`?async()=>{let i=await r.run(S`UPDATE test_execution_attempt
65
65
  SET status = ${`provisioning`},
66
66
  provider_id = ${e.providerId},
67
67
  allocation_lifetime = ${t},
@@ -74,53 +74,53 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
74
74
  AND ${U()}`);return i.rowsAffected===0||await r.run(S`INSERT INTO test_provider_operation
75
75
  (execution_attempt_id, generation, owner_id, token, lease_expires_at, obligation, failure_count)
76
76
  VALUES (${e.executionAttemptId}, ${n.generation}, ${n.ownerId}, ${n.token},
77
- ${n.leaseExpiresAt}, ${`provisioning-resolution`}, ${0})`),i}:{kind:`already-provisioning`}:{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`resolved`,allocationRef:a.allocationRef}:{kind:`fenced`}},{kind:`started`,claim:n}))},async getProviderOperation(e){return b(async t=>{let n=await k(t,e);return n===void 0?null:D(n)})},async renewProviderOperationClaim(e){let t=f(e.leaseExpiresAt);return b(n=>R(async()=>await G(n,e.claim)??(()=>n.run(S`UPDATE test_provider_operation SET lease_expires_at = ${t}
77
+ ${n.leaseExpiresAt}, ${`provisioning-resolution`}, ${0})`),i}:{kind:`already-provisioning`}:{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`resolved`,allocationRef:a.allocationRef}:{kind:`fenced`}},{kind:`started`,claim:n}))},async getProviderOperation(e){return T(async t=>{let n=await k(t,e);return n===void 0?null:D(n)})},async renewProviderOperationClaim(e){let t=p(e.leaseExpiresAt);return T(n=>R(async()=>await G(n,e.claim)??(()=>n.run(S`UPDATE test_provider_operation SET lease_expires_at = ${t}
78
78
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
79
- AND ${V(e.claim)}`)),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:t}}))},async takeOverProviderOperation(e){return b(async t=>{let n=await O(t,e.executionAttemptId),r=await k(t,e.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};if(r.owner_id!==null&&r.lease_expires_at!==null&&u(r.lease_expires_at)>u(e.observedAt))return{kind:`stale`};let i={executionAttemptId:e.executionAttemptId,generation:r.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:f(e.leaseExpiresAt)},{rowsAffected:a}=await t.run(S`UPDATE test_provider_operation
79
+ AND ${V(e.claim)}`)),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:t}}))},async takeOverProviderOperation(e){return T(async t=>{let n=await O(t,e.executionAttemptId),r=await k(t,e.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};if(r.owner_id!==null&&r.lease_expires_at!==null&&d(r.lease_expires_at)>d(e.observedAt))return{kind:`stale`};let i={executionAttemptId:e.executionAttemptId,generation:r.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:p(e.leaseExpiresAt)},{rowsAffected:a}=await t.run(S`UPDATE test_provider_operation
80
80
  SET generation = ${i.generation}, owner_id = ${i.ownerId}, token = ${i.token},
81
81
  lease_expires_at = ${i.leaseExpiresAt}
82
82
  WHERE execution_attempt_id = ${e.executionAttemptId}
83
83
  AND generation = ${r.generation}
84
- AND ${B(e.executionAttemptId)}`);return a===0?{kind:`stale`}:{kind:`claimed`,claim:i}})},async handoffProviderOperation(e){let t=e.evidence===void 0?null:m.parse(e.evidence);return b(n=>R(async()=>await G(n,e.claim)??(()=>n.run(t===null?S`UPDATE test_provider_operation
84
+ AND ${B(e.executionAttemptId)}`);return a===0?{kind:`stale`}:{kind:`claimed`,claim:i}})},async handoffProviderOperation(e){let t=e.evidence===void 0?null:h.parse(e.evidence);return T(n=>R(async()=>await G(n,e.claim)??(()=>n.run(t===null?S`UPDATE test_provider_operation
85
85
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL
86
86
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
87
87
  AND ${V(e.claim)}`:S`UPDATE test_provider_operation
88
88
  SET owner_id = NULL, token = NULL, lease_expires_at = NULL,
89
89
  last_failure = ${JSON.stringify(t)}
90
90
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
91
- AND ${V(e.claim)}`)),{kind:`recorded`}))},async recordProviderOperationUncertainty(e){let t=m.parse(e.evidence);return b(n=>R(async()=>await G(n,e.claim)??(()=>n.run(S`UPDATE test_provider_operation
91
+ AND ${V(e.claim)}`)),{kind:`recorded`}))},async recordProviderOperationUncertainty(e){let t=h.parse(e.evidence);return T(n=>R(async()=>await G(n,e.claim)??(()=>n.run(S`UPDATE test_provider_operation
92
92
  SET failure_count = failure_count + 1, last_failure = ${JSON.stringify(t)}
93
93
  WHERE execution_attempt_id = ${e.claim.executionAttemptId}
94
- AND ${V(e.claim)}`)),{kind:`recorded`}))},async recordAllocation(e){return q(e,!0)},async recordProvisioningAbsent(e){let t=m.parse(e.evidence);return b(n=>R(async()=>{let r=await W(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?()=>K(n,i.executionAttemptId,`abandoned`,S`execution_id = ${e.executionId}
94
+ AND ${V(e.claim)}`)),{kind:`recorded`}))},async recordAllocation(e){return q(e,!0)},async recordProvisioningAbsent(e){let t=h.parse(e.evidence);return T(n=>R(async()=>{let r=await W(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?()=>K(n,i.executionAttemptId,`abandoned`,S`execution_id = ${e.executionId}
95
95
  AND allocation_ref IS NULL
96
- AND ${z(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-found`}},{kind:`recorded`}))},async recordProvisionerIncarnationLost(e){let t=m.parse(e.proof.evidence);return b(n=>R(async()=>{let r=await W(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationLifetime===`provisioner-process-bound`?i.provisionerIncarnationId===null||i.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:i.provisionerIncarnationId}:i.allocationRef===null?()=>K(n,i.executionAttemptId,`abandoned`,S`execution_id = ${e.executionId}
96
+ AND ${z(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-found`}},{kind:`recorded`}))},async recordProvisionerIncarnationLost(e){let t=h.parse(e.proof.evidence);return T(n=>R(async()=>{let r=await W(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationLifetime===`provisioner-process-bound`?i.provisionerIncarnationId===null||i.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:i.provisionerIncarnationId}:i.allocationRef===null?()=>K(n,i.executionAttemptId,`abandoned`,S`execution_id = ${e.executionId}
97
97
  AND allocation_ref IS NULL
98
98
  AND allocation_lifetime = ${`provisioner-process-bound`}
99
99
  AND provisioner_incarnation_id = ${e.proof.provisionerIncarnationId}
100
- AND ${z(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-process-bound`,allocationLifetime:i.allocationLifetime}:{kind:`not-found`}},{kind:`recorded`}))},async recordAllocationTerminated(e){let t=m.parse(e.evidence);return b(n=>R(async()=>{let r=await W(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.allocationRef===null?{kind:`not-allocated`}:()=>n.run(S`UPDATE test_provider_operation
100
+ AND ${z(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-process-bound`,allocationLifetime:i.allocationLifetime}:{kind:`not-found`}},{kind:`recorded`}))},async recordAllocationTerminated(e){let t=h.parse(e.evidence);return T(n=>R(async()=>{let r=await W(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.allocationRef===null?{kind:`not-allocated`}:()=>n.run(S`UPDATE test_provider_operation
101
101
  SET obligation = ${`terminal-convergence`}, last_failure = ${JSON.stringify(t)}
102
102
  WHERE execution_attempt_id = ${i.executionAttemptId}
103
103
  AND ${V(e.claim)}
104
104
  AND EXISTS (SELECT 1 FROM test_execution_attempt
105
105
  WHERE execution_attempt_id = ${i.executionAttemptId}
106
- AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return b(t=>R(async()=>{let n=await W(t,e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?{kind:`not-allocated`}:w(a,i.obligation,`obligation`)===`terminal-convergence`?()=>K(t,r.executionAttemptId,`infrastructure-failure`,S`execution_id = ${e.executionId}
106
+ AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return T(t=>R(async()=>{let n=await W(t,e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?{kind:`not-allocated`}:w(s,i.obligation,`obligation`)===`terminal-convergence`?()=>K(t,r.executionAttemptId,`infrastructure-failure`,S`execution_id = ${e.executionId}
107
107
  AND allocation_ref IS NOT NULL
108
108
  AND ${H(r.executionAttemptId)}
109
- AND ${z(e.claim)}`):{kind:`not-terminated`}:{kind:`not-found`}},{kind:`recorded`}))},async getActiveAttempt(e,t){return b(async n=>{if(await I(n,e)!==t)return null;let r=await O(n,t);return r===void 0?null:E(r)})},async commitOutcome(e){let t=p(e.result);return b(n=>R(async()=>{if(await I(n,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let r=await O(n,e.executionAttemptId);if(r===void 0)return{kind:`fenced`};let a=T(r.workflow_result,e=>_.parse(e));return a===null?r.settlement_kind===null?async()=>{let r=await n.run(S`UPDATE test_execution_attempt SET workflow_result = ${JSON.stringify(t)}
109
+ AND ${z(e.claim)}`):{kind:`not-terminated`}:{kind:`not-found`}},{kind:`recorded`}))},async getActiveAttempt(e,t){return T(async n=>{if(await I(n,e)!==t)return null;let r=await O(n,t);return r===void 0?null:E(r)})},canonicalizeOutcome(e){return i(n,e)},decodeOutcome(e){return r(n,e)},async commitOutcome(e){let t=e.result;return T(i=>R(async()=>{if(await I(i,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let a=await O(i,e.executionAttemptId);if(a===void 0)return{kind:`fenced`};let s=a.workflow_result;if(s!==null){let e=r(n,s);return o(s,t.text)?{kind:`duplicate`,outcome:e,text:s}:{kind:`conflict`}}return a.settlement_kind===null?async()=>{let n=await i.run(S`UPDATE test_execution_attempt SET workflow_result = ${t.text}
110
110
  WHERE execution_attempt_id = ${e.executionAttemptId}
111
111
  AND workflow_result IS NULL
112
112
  AND settlement_kind IS NULL
113
- AND ${U()}`);return r.rowsAffected===0?r:K(n,e.executionAttemptId,`outcome`,S`workflow_result IS NOT NULL`)}:{kind:`conflict`}:i(a,t)?{kind:`duplicate`,outcome:a}:{kind:`conflict`}},{kind:`accepted`,outcome:t}))},async abandonPendingAttempt(e,t){return b(n=>R(async()=>{if(await I(n,t)!==e)return{kind:`fenced`};let r=await O(n,e);if(r===void 0)return{kind:`fenced`};let i=E(r);return i.status===`allocated`?{kind:`allocated`}:i.status===`provisioning`?{kind:`provisioning`}:i.status===`settled`?{kind:i.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:()=>n.run(S`UPDATE test_execution_attempt
113
+ AND ${U()}`);return n.rowsAffected===0?n:K(i,e.executionAttemptId,`outcome`,S`workflow_result IS NOT NULL`)}:{kind:`conflict`}},{kind:`accepted`,outcome:r(n,t.text),text:t.text}))},async abandonPendingAttempt(e,t){return T(n=>R(async()=>{if(await I(n,t)!==e)return{kind:`fenced`};let r=await O(n,e);if(r===void 0)return{kind:`fenced`};let i=E(r);return i.status===`allocated`?{kind:`allocated`}:i.status===`provisioning`?{kind:`provisioning`}:i.status===`settled`?{kind:i.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:()=>n.run(S`UPDATE test_execution_attempt
114
114
  SET status = ${`settled`}, settlement_kind = ${`abandoned`}, claimable = ${0}
115
115
  WHERE execution_attempt_id = ${e}
116
116
  AND execution_id = ${t}
117
117
  AND status = ${`pending`}
118
118
  AND settlement_kind IS NULL
119
- AND ${U()}`)},{kind:`abandoned`}))},recovery:{async getAttemptWithAllocation(e){return b(async t=>{let n=await O(t,e);return n===void 0?null:E(n)})},async recordDiscoveredAllocation(e){return q(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=d(e);return b(i=>R(async()=>{let a=await W(i,e.claim);if(a.kind===`stale`)return{kind:`stale`,storedRef:a.attempt.allocationRef};if(a.kind!==`authorized`)return{kind:a.kind};let{attempt:o,attemptRow:s}=a;return o.executionId===e.executionId?o.allocationRef===null?{kind:`not-allocated`}:r(o.allocationRef,t)?()=>i.run(S`UPDATE test_execution_attempt SET allocation_ref = ${JSON.stringify(n)}
119
+ AND ${U()}`)},{kind:`abandoned`}))},recovery:{async getAttemptWithAllocation(e){return T(async t=>{let n=await O(t,e);return n===void 0?null:E(n)})},async recordDiscoveredAllocation(e){return q(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=f(e);return T(r=>R(async()=>{let i=await W(r,e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:o,attemptRow:s}=i;return o.executionId===e.executionId?o.allocationRef===null?{kind:`not-allocated`}:a(o.allocationRef,t)?()=>r.run(S`UPDATE test_execution_attempt SET allocation_ref = ${JSON.stringify(n)}
120
120
  WHERE execution_attempt_id = ${o.executionAttemptId}
121
121
  AND execution_id = ${e.executionId}
122
122
  AND allocation_ref = ${s.allocation_ref}
123
- AND ${V(e.claim)}`):{kind:`stale`,storedRef:o.allocationRef}:{kind:`not-found`}},{kind:`evolved`}))},async getRecoverableAttempts(e){return b(async t=>{let n=new Date().toISOString();return(await t.all(S`SELECT * FROM test_execution_attempt
123
+ AND ${V(e.claim)}`):{kind:`stale`,storedRef:o.allocationRef}:{kind:`not-found`}},{kind:`evolved`}))},async getRecoverableAttempts(e){return T(async t=>{let n=new Date().toISOString();return(await t.all(S`SELECT * FROM test_execution_attempt
124
124
  WHERE execution_id = ${e}
125
125
  AND status = ${`allocated`}
126
126
  AND settlement_kind IS NULL
@@ -1 +1 @@
1
- import{D as e,M as t,c as n,ct as r,d as i,i as a,l as o,r as s,s as c,t as l,y as u}from"../authority-state-bootstrap-CLYus369.mjs";import{WORKFLOW_CANCELLED_REASON as d,WorkflowRunContextSchema as f}from"@makaio/framework/contracts";import*as p from"node:os";async function m(e,n,i,a){let o=await y(e,n,i);return await e.request(t.setExecution,{execution:o}),i===`completed`?await e.emit(r.execution.completed,{executionId:n.executionId,workflowId:n.workflowId,totalDuration:0,completedAt:o.completedAt}):await e.emit(r.execution.cancelled,{executionId:n.executionId,workflowId:n.workflowId,reason:a,completedAt:o.completedAt}),i===`cancelled`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,...a===void 0?{}:{reason:a}}:{executionId:n.executionId,workflowId:n.workflowId,status:`completed`}}function h(e,t){return t.status===`completed`?{executionId:e.executionId,workflowId:e.workflowId,status:`completed`,...t.artifact===void 0?{}:{artifact:t.artifact}}:t.status===`cancelled`?{executionId:e.executionId,workflowId:e.workflowId,status:`cancelled`,...t.reason===void 0?{}:{reason:t.reason}}:t.status===`paused`?{executionId:e.executionId,workflowId:e.workflowId,status:`paused`,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}:{executionId:e.executionId,workflowId:e.workflowId,status:`failed`,error:t.error}}function g(t){let n,r=()=>{n=u({bus:t.bus,activeExecutions:t.activeExecutions,shellAbortControllers:t.shellAbortControllers,activeRunnerSteps:t.activeRunnerSteps,durableLifecycleTransitions:t.durableLifecycleTransitions,lifecyclePublications:t.lifecyclePublications,publishingLifecycleExecutions:t.publishingLifecycleExecutions,cancelTimeoutMs:e.cancelTimeoutMs},t.executionId,d).catch(e=>(console.error(`[WorkflowOrchestrator] Failed to persist cancellation for ${t.executionId}:`,e),!1))};return t.signal.addEventListener(`abort`,r,{once:!0}),t.signal.aborted&&r(),async()=>(t.signal.removeEventListener(`abort`,r),n??!1)}async function _(e,n){let r=await e.requestOptional(t.getExecution,{executionId:n});return r.handled?r.data.execution?.startedAt??void 0:void 0}async function v(e,t){return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:`running`,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??Date.now(),triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function y(e,t,n){let r=Date.now();return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:n,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??r,completedAt:r,triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function b(e,t,r,i,s,c,l,u,f){let m=e.suspensionStrategy===`wait-in-process`?void 0:await x(e.executionId,l,{required:!0}),h=await n({definition:t,execution:r,runContext:i,zodSchema:f?.artifact,bus:l}),g=new o(e.executionId,e.workflowId,t,r,s,l,u,void 0,h,{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${p.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:e.env},{suspensionStrategy:e.suspensionStrategy,resumeFrames:m,runtimeLoopGates:c}),_=g.buildExpressionContext(),v=await a(t.root,g,_);return v.status===`failed`?{status:`failed`,error:v.error}:v.status===`paused`?{status:`paused`,pausedAtGateId:v.pausedAtGateId,pausedAtFrameId:v.pausedAtFrameId}:v.status===`cancelled`||u.aborted?{status:`cancelled`,reason:d}:{status:`completed`,artifact:h?.current}}async function x(e,n,r={}){try{let i=await n.requestOptional(t.listFrames,{executionId:e});if(!i.handled){if(r.required===!0)throw Error(`Frame storage handler is required to resume execution '${e}'.`);return}return i.data.frames.length===0?void 0:c(i.data.frames)}catch(e){if(r.required===!0)throw e;return}}function S(e,t){return f.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source.kind===`path`?{kind:`path`,path:e.materializationSpec?.sourcePath??``}:e.source,definitionSnapshot:e.source.kind===`definition`?e.definition??t:t,workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config??{},scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:e.cancelSubject,env:e.env,createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}async function C(e,n,i,a,o){i.status=`paused`,await e.request(t.setExecution,{execution:i}),await e.emit(r.execution.paused,{executionId:n.executionId,workflowId:n.workflowId,pausedAtGateId:a,pausedAtFrameId:o})}async function w(e,t,n,i,a,o){n===`completed`?await e.emit(r.execution.completed,{executionId:t.executionId,workflowId:t.workflowId,totalDuration:a-i.startedAt,completedAt:a}):n===`cancelled`?await e.emit(r.execution.cancelled,{executionId:t.executionId,workflowId:t.workflowId,reason:d,completedAt:a}):await e.emit(r.execution.failed,{executionId:t.executionId,workflowId:t.workflowId,error:o??`Workflow execution failed`,completedAt:a})}async function T(e){let{config:n,loaded:r,bus:a,signal:o}=e,{definition:c}=r;if(o.aborted)return n.terminalAuthority===`authority`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,reason:d}:m(a,n,`cancelled`,d);let u=await v(a,n),f=S(n,c);n.terminalAuthority===`authority`?await l(a,f,c):await i(a,u,f,c);let p=new Map(r.runtimeHandlers),_=r.runtimeLoopGates??new Map,y=new Map,x=new Map,T=new Map,E=new Map,D=new Map,O=new Set;y.set(n.executionId,{execution:u,workflow:c,runContext:f,runtimeHandlers:p,runtimeLoopGates:new Map(_)});let k=n.terminalAuthority===`authority`?async()=>!1:g({signal:o,executionId:n.executionId,bus:a,activeExecutions:y,shellAbortControllers:x,activeRunnerSteps:T,durableLifecycleTransitions:E,lifecyclePublications:D,publishingLifecycleExecutions:O}),A={status:`completed`},j=!1;try{c.root.nodes.length>0&&(s(c,_),A=await b(n,c,u,f,p,_,a,o,r.zodSchemas))}catch(e){A={status:`failed`,error:e instanceof Error?e.message:String(e)}}finally{j=await k(),y.clear()}if(j)return h(n,{status:`cancelled`,reason:d});if((o.aborted||u.status===`cancelled`)&&(A={status:`cancelled`,reason:d}),A.status===`paused`)return n.terminalAuthority!==`authority`&&await C(a,n,u,A.pausedAtGateId,A.pausedAtFrameId),h(n,A);if(n.terminalAuthority===`authority`)return h(n,A);let M=Date.now(),N=A.status===`failed`?A.error:void 0;return u.status=A.status,u.completedAt=M,u.error=N,await a.request(t.setExecution,{execution:u}),await w(a,n,A.status,u,M,N),h(n,A)}export{T as runWorkflowOrchestrator};
1
+ import{D as e,M as t,c as n,ct as r,d as i,i as a,l as o,r as s,s as c,t as l,y as u}from"../authority-state-bootstrap-eitx6Ukn.mjs";import{WORKFLOW_CANCELLED_REASON as d,WorkflowRunContextSchema as f}from"@makaio/framework/contracts";import*as p from"node:os";async function m(e,n,i,a){let o=await y(e,n,i);return await e.request(t.setExecution,{execution:o}),i===`completed`?await e.emit(r.execution.completed,{executionId:n.executionId,workflowId:n.workflowId,totalDuration:0,completedAt:o.completedAt}):await e.emit(r.execution.cancelled,{executionId:n.executionId,workflowId:n.workflowId,reason:a,completedAt:o.completedAt}),i===`cancelled`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,...a===void 0?{}:{reason:a}}:{executionId:n.executionId,workflowId:n.workflowId,status:`completed`}}function h(e,t){return t.status===`completed`?{executionId:e.executionId,workflowId:e.workflowId,status:`completed`,...t.artifact===void 0?{}:{artifact:t.artifact}}:t.status===`cancelled`?{executionId:e.executionId,workflowId:e.workflowId,status:`cancelled`,...t.reason===void 0?{}:{reason:t.reason}}:t.status===`paused`?{executionId:e.executionId,workflowId:e.workflowId,status:`paused`,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}:{executionId:e.executionId,workflowId:e.workflowId,status:`failed`,error:t.error}}function g(t){let n,r=()=>{n=u({bus:t.bus,activeExecutions:t.activeExecutions,shellAbortControllers:t.shellAbortControllers,activeRunnerSteps:t.activeRunnerSteps,durableLifecycleTransitions:t.durableLifecycleTransitions,lifecyclePublications:t.lifecyclePublications,publishingLifecycleExecutions:t.publishingLifecycleExecutions,cancelTimeoutMs:e.cancelTimeoutMs},t.executionId,d).catch(e=>(console.error(`[WorkflowOrchestrator] Failed to persist cancellation for ${t.executionId}:`,e),!1))};return t.signal.addEventListener(`abort`,r,{once:!0}),t.signal.aborted&&r(),async()=>(t.signal.removeEventListener(`abort`,r),n??!1)}async function _(e,n){let r=await e.requestOptional(t.getExecution,{executionId:n});return r.handled?r.data.execution?.startedAt??void 0:void 0}async function v(e,t){return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:`running`,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??Date.now(),triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function y(e,t,n){let r=Date.now();return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:n,inputs:t.inputs,config:t.config??{},startedAt:await _(e,t.executionId)??r,completedAt:r,triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function b(e,t,r,i,s,c,l,u,f){let m=e.suspensionStrategy===`wait-in-process`?void 0:await x(e.executionId,l,{required:!0}),h=await n({definition:t,execution:r,runContext:i,zodSchema:f?.artifact,bus:l}),g=new o(e.executionId,e.workflowId,t,r,s,l,u,void 0,h,{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${p.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:e.env},{suspensionStrategy:e.suspensionStrategy,resumeFrames:m,runtimeLoopGates:c}),_=g.buildExpressionContext(),v=await a(t.root,g,_);return v.status===`failed`?{status:`failed`,error:v.error}:v.status===`paused`?{status:`paused`,pausedAtGateId:v.pausedAtGateId,pausedAtFrameId:v.pausedAtFrameId}:v.status===`cancelled`||u.aborted?{status:`cancelled`,reason:d}:{status:`completed`,artifact:h?.current}}async function x(e,n,r={}){try{let i=await n.requestOptional(t.listFrames,{executionId:e});if(!i.handled){if(r.required===!0)throw Error(`Frame storage handler is required to resume execution '${e}'.`);return}return i.data.frames.length===0?void 0:c(i.data.frames)}catch(e){if(r.required===!0)throw e;return}}function S(e,t){return f.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source.kind===`path`?{kind:`path`,path:e.materializationSpec?.sourcePath??``}:e.source,definitionSnapshot:e.source.kind===`definition`?e.definition??t:t,workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config??{},scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:e.cancelSubject,env:e.env,createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}async function C(e,n,i,a,o){i.status=`paused`,await e.request(t.setExecution,{execution:i}),await e.emit(r.execution.paused,{executionId:n.executionId,workflowId:n.workflowId,pausedAtGateId:a,pausedAtFrameId:o})}async function w(e,t,n,i,a,o){n===`completed`?await e.emit(r.execution.completed,{executionId:t.executionId,workflowId:t.workflowId,totalDuration:a-i.startedAt,completedAt:a}):n===`cancelled`?await e.emit(r.execution.cancelled,{executionId:t.executionId,workflowId:t.workflowId,reason:d,completedAt:a}):await e.emit(r.execution.failed,{executionId:t.executionId,workflowId:t.workflowId,error:o??`Workflow execution failed`,completedAt:a})}async function T(e){let{config:n,loaded:r,bus:a,signal:o}=e,{definition:c}=r;if(o.aborted)return n.terminalAuthority===`authority`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,reason:d}:m(a,n,`cancelled`,d);let u=await v(a,n),f=S(n,c);n.terminalAuthority===`authority`?await l(a,f,c):await i(a,u,f,c);let p=new Map(r.runtimeHandlers),_=r.runtimeLoopGates??new Map,y=new Map,x=new Map,T=new Map,E=new Map,D=new Map,O=new Set;y.set(n.executionId,{execution:u,workflow:c,runContext:f,runtimeHandlers:p,runtimeLoopGates:new Map(_)});let k=n.terminalAuthority===`authority`?async()=>!1:g({signal:o,executionId:n.executionId,bus:a,activeExecutions:y,shellAbortControllers:x,activeRunnerSteps:T,durableLifecycleTransitions:E,lifecyclePublications:D,publishingLifecycleExecutions:O}),A={status:`completed`},j=!1;try{c.root.nodes.length>0&&(s(c,_),A=await b(n,c,u,f,p,_,a,o,r.zodSchemas))}catch(e){A={status:`failed`,error:e instanceof Error?e.message:String(e)}}finally{j=await k(),y.clear()}if(j)return h(n,{status:`cancelled`,reason:d});if((o.aborted||u.status===`cancelled`)&&(A={status:`cancelled`,reason:d}),A.status===`paused`)return n.terminalAuthority!==`authority`&&await C(a,n,u,A.pausedAtGateId,A.pausedAtFrameId),h(n,A);if(n.terminalAuthority===`authority`)return h(n,A);let M=Date.now(),N=A.status===`failed`?A.error:void 0;return u.status=A.status,u.completedAt=M,u.error=N,await a.request(t.setExecution,{execution:u}),await w(a,n,A.status,u,M,N),h(n,A)}export{T as runWorkflowOrchestrator};
@@ -0,0 +1 @@
1
+ import{resolveMakaioHome as e}from"./runtime-node/makaio-config.mjs";import{t}from"./extension-package-provenance-aYrZuS4W.mjs";import{n,o as r,t as i}from"./await-trigger-Bkg2BQfg.mjs";import*as a from"node:fs/promises";import{access as o}from"node:fs/promises";import*as s from"node:path";import{basename as c,join as l}from"node:path";import*as u from"node:crypto";import{constants as d}from"node:fs";import{createBusInstance as f,waitForSubscriptionPropagation as p}from"@makaio/framework/bus";import{AdapterSubjects as m,BoundedRecoveryEvidenceSchema as h,FrameworkContractNamespaces as g,FrameworkStorageNamespaces as _,PROVIDER_ALLOCATION_REF_VERSION as ee,ProviderAllocationRefSchema as te,RECOVERY_EVIDENCE_LIMITS as v,WorkerCapabilitiesSchema as ne,WorkerSubjects as y,WorkflowSubjects as re,WorkflowWorkerConfigSchema as ie,createWorkflowCancelSubject as ae}from"@makaio/framework/contracts";import{ExtensionCoordinator as oe,KernelSubjects as se,coalesceExtensionOverrides as ce,filterEligibleExtensions as le}from"@makaio/framework/kernel";import{BaseService as ue}from"@makaio/framework/service-base";import{AdapterRuntimeSubjects as de,registerAdapterRuntimeIdentityHandlers as fe}from"@makaio/framework/services/adapter-runtime";import{CLIDetectionNamespace as pe,CLIDetectionSubjects as me}from"@makaio/framework/services/cli-detection/namespace";import{SessionOrchestratorToken as he,ToolRegistryToken as ge,canonicalModelPackage as _e,createSubagentServicePackage as ve,createToolContributionProcessor as ye,frameworkCorePackages as b,sessionBridgePackage as be,sessionOrchestratorPackage as xe,sessionPackage as Se,sessionStoragePackage as Ce,toolRegistryPackage as we}from"@makaio/framework/services";import{AdapterSubsystemSubjects as x}from"@makaio/framework/services/adapter-subsystem";import{createClientsCorePackage as Te}from"@makaio/framework/clients";import{AdapterSubsystemToken as S,createAdapterSubsystemContributionProcessor as Ee,createAdapterSubsystemPackage as De,orderAfterAdapterSubsystem as Oe}from"@makaio/framework/adapter-subsystem";import{execa as ke}from"execa";import Ae from"piscina";import{ExecutionAttemptAuthority as je,runAuthorityDispatchedAttempt as Me}from"@makaio/framework/workflow-engine";import{runWorkflowOrchestrator as Ne}from"@makaio/framework/workflow-engine/workflow-orchestrator";function C(e){return e.on(m.getCapabilities,async t=>{let{adapterName:n,adapterId:r}=t.payload;if(r){await t.next();return}if(n){let r=await e.requestOptional(de.resolveId,{adapterName:n}),i=r.handled?r.data.adapterId:void 0;i&&(t.payload.adapterId=i)}await t.next()},{priority:20})}function w(e){let{coordinator:t,configRepository:n,platformDefaults:r,prepareAuthRuntime:i,runtimeSnapshotHandlerPriority:a,runtimeDefinitionHandlerPriority:o}=e,s=De({configRepository:n,coordinator:t,platformDefaults:r,...i!==void 0&&{prepareAuthRuntime:i},...a!==void 0&&{runtimeSnapshotHandlerPriority:a},...o!==void 0&&{runtimeDefinitionHandlerPriority:o}});return t.registerContributionProcessor(Ee({getAdapterSubsystemService:()=>t.getExtensionService(S)})),{adapterSubsystemPackage:s}}function T(e){let{bus:t,currentMachineId:n}=e,r=fe(t,{currentMachineId:n,listKnownAdapterNames:e.listKnownAdapterNames??(async()=>{let{configs:e}=await t.request(x.listAdapterConfigs,{});return e.map(e=>e.name)}),...e.resolveLiveAdapterId!==void 0&&{resolveLiveAdapterId:e.resolveLiveAdapterId},...e.resolveLiveAdapterIdentity!==void 0&&{resolveLiveAdapterIdentity:e.resolveLiveAdapterIdentity},...e.listLiveAdapterIdentities!==void 0&&{listLiveAdapterIdentities:e.listLiveAdapterIdentities}}),i=C(t);return{cleanup:()=>{r.cleanup(),i()}}}function E(e,t){if(!(e instanceof Error))return!1;let{rootPackageName:n,subpath:r}=Pe(t),i=(r===void 0?[t]:[t,n]).flatMap(e=>[`Cannot find package '${e}'`,`Cannot find module '${e}'`,`Cannot find package "${e}"`,`Cannot find module "${e}"`]),a=e;return(a.code===`ERR_MODULE_NOT_FOUND`||a.code===`MODULE_NOT_FOUND`)&&i.some(t=>e.message.includes(t))||a.code===`ERR_PACKAGE_PATH_NOT_EXPORTED`&&r!==void 0&&e.message.includes(`Package subpath '${r}' is not defined by "exports"`)&&Fe(e.message,n)?!0:i.some(t=>e.message.includes(t))}async function D(e){try{return await import(e)}catch(t){if(E(t,e))return null;throw t}}function Pe(e){let t=e.split(`/`);return e.startsWith(`@`)?{rootPackageName:t.slice(0,2).join(`/`),subpath:t.length>2?`./${t.slice(2).join(`/`)}`:void 0}:{rootPackageName:t[0]??e,subpath:t.length>1?`./${t.slice(1).join(`/`)}`:void 0}}function Fe(e,t){let n=t,r=t.replaceAll(`/`,`\\`);return e.includes(`/${n}/package.json`)||e.includes(`\\${r}\\package.json`)}async function O(e,t=process.env,n=process.platform){let r=t[Object.keys(t).find(e=>e.toUpperCase()===`PATH`)??`PATH`]??``,i=(t.PATHEXT??`.EXE;.CMD;.BAT;.COM`).split(`;`).filter(Boolean),a=n===`win32`?s.extname(e)===``?i:[``,...i]:[``];for(let t of r.split(s.delimiter)){let n=t.replace(/^"|"$/gu,``),r=s.resolve(n||process.cwd());for(let t of a){let n=s.join(r,`${e}${t}`);try{return await o(n,d.X_OK),n}catch{}}}}async function k(e,t=5e3,n=1e3){let{stdout:r}=await ke(e,[`--version`],{forceKillAfterDelay:n,timeout:t});return r}function Ie(e){return e.match(/(\d+\.\d+\.\d+)/u)?.[1]??`unknown`}async function Le(e,t=O,n=k){try{let r=await t(e);if(r===void 0)return{binary:e,found:!1};let i=await n(r);return i.length===0?{binary:e,found:!1}:{binary:e,found:!0,path:r,version:Ie(i)}}catch{return{binary:e,found:!1}}}async function Re(e,t=O,n=k){return Promise.all(e.map(e=>Le(e,t,n)))}var ze=class extends ue{constructor(e){super(e)}onInit(){this.registerHandler(me.scan,async e=>{let t=await Re(e.payload.binaries);e.setResult({results:t})})}};const A={name:`makaio.cli-detection`,displayName:`CLI Detection`,version:`0.1.0`,critical:!0,surface:`any`,namespaces:[pe],create:e=>new ze(e.bus)};function j(e,t){e.push(...Be(t))}function Be(e){return e===void 0?[]:typeof e==`function`?[e]:[...e]}function Ve(e,t=[]){let n=new Set([e]),r=new Set,i=new Map;for(let e of t)typeof e==`string`?n.add(e):(r.add(e.id),e.version!==void 0&&i.set(e.id,e.version));return{hosts:n,capabilities:r,...i.size>0?{capabilityVersions:i}:{}}}function He(e=[]){return e.some(e=>typeof e==`string`&&e===`node`)?e:[`node`,...e]}function M(e){return ce(le(We(e.packages,e.configProvider),e.surface,e.runtimeEnvironment))}function Ue(e,n){let r=M(n),i=new Set(r.map(t));return e.filter(({ownerPackage:e})=>i.has(e)).map(({package:e})=>e)}function We(e,t){return t?e.filter(e=>t.loadEnabled(e.name)!==!1):e}function N(e,t){return e.filter(e=>e.runtimeOwnership?.[t]===!0).map(e=>e.name)}function Ge(e,t){let n=N(e,t);if(n.length>1)throw Error(`Multiple extensions own runtimeOwnership.${t}: ${n.join(`, `)}`)}function P(e){return Ge(e,`sessionOrchestrator`),N(e,`sessionOrchestrator`).length===0}function Ke(e){return e===!0||P(e)?b:b.filter(e=>e.name!==he.name)}function F(e,t,n){let r=[];try{for(let i of e){let e=i.runtimeBoot;e&&j(r,e.configure({bus:t,registerContributionProcessor:e=>{r.push(n.registerContributionProcessor(e))},forEachActiveExtension:e=>{n.forEachActiveExtension(e)}}))}}catch(e){let t=[];for(let e of[...r].reverse())try{e()}catch(e){t.push(e)}throw t.length>0?AggregateError([e,...t],`Extension boot contribution failed and rollback cleanup reported additional errors`,{cause:e}):e}return r}function qe(){let e=process.env.MAKAIO_SKIP_EXTENSIONS;if(!e)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(t)}var Je=class{pool;constructor(e){this.pool=new Ae({filename:e.workerEntry,maxThreads:e.maxConcurrency??4,idleTimeout:e.idleTimeoutMs??3e4})}async run(e,t){return this.pool.run(e,{signal:t})}onMessage(e){return this.pool.on(`message`,e),()=>this.pool.off(`message`,e)}async dispose(){await this.pool.destroy()}},I=class extends Error{code;constructor(e,t){super(e),this.code=t,this.name=`MaterializationError`}};function L(e,t,n){let r=s.resolve(t)+s.sep,i=s.resolve(e);if(i!==s.resolve(t)&&!i.startsWith(r))throw new I(`${n} escapes allowed root: ${e} is not within ${t}`,`containment-violation`)}async function R(e,t,n,r){let i=r??await a.realpath(t),o;try{o=await a.realpath(e)}catch{return e}let c=i+s.sep;if(o!==i&&!o.startsWith(c))throw new I(`${n} escapes allowed root via symlink: real path ${o} is not within ${i}`,`symlink-escape`);return o}function z(e){let t=e.indexOf(`-`);if(t===-1)throw new I(`Invalid SRI integrity format: ${e}`,`contribution-integrity-mismatch`);return{algorithm:e.slice(0,t),digest:e.slice(t+1)}}async function Ye(e,t){let n=await a.readFile(e);return u.createHash(t).update(n).digest(`base64`)}const B=new Set([`.git`,`node_modules`]);function Xe(e){return B.has(e.toLowerCase())}async function Ze(e,t){let n=t.toLowerCase();if(!B.has(n))return!1;if(t===n)return!0;try{let[r,i]=await Promise.all([a.lstat(s.join(e,t)),a.lstat(s.join(e,n))]);return r.dev===i.dev&&r.ino===i.ino}catch(e){if(e.code===`ENOENT`)return!1;throw e}}const Qe=B,$e=new Set([`.DS_Store`]);async function V(e,t){let n=u.createHash(t),r=[];async function i(t){let n=await a.readdir(t,{withFileTypes:!0});for(let a of n){let n=s.join(t,a.name);if(a.isSymbolicLink())throw new I(`Contribution package contains a symbolic link: ${s.relative(e,n)}`,`symlink-escape`);if(a.isDirectory()){Qe.has(a.name)||await i(n);continue}if(a.isFile()){$e.has(a.name)||r.push(s.relative(e,n));continue}throw new I(`Contribution package contains an unsupported filesystem entry: ${s.relative(e,n)}`,`contribution-integrity-mismatch`)}}await i(e),r.sort();for(let t of r)n.update(t.split(s.sep).join(`/`)),n.update(`\0`),n.update(await a.readFile(s.join(e,t))),n.update(`\0`);return`${t}-${n.digest(`base64`)}`}async function H(e,t=`sha256`){let n=u.createHash(t),r=[];async function i(t){let n=await a.readdir(t,{withFileTypes:!0});for(let a of n){let n=s.join(t,a.name);if(!await Ze(t,a.name)){if(a.isDirectory()){await i(n);continue}if(a.isFile()){r.push(s.relative(e,n));continue}throw a.isSymbolicLink()?new I(`Workspace root contains a symbolic link: ${s.relative(e,n)}`,`symlink-escape`):new I(`Workspace root contains an unsupported filesystem entry: ${s.relative(e,n)}`,`unsupported-filesystem-entry`)}}}await i(e),r.sort();for(let t of r){n.update(t),n.update(`\0`);let r=await a.readFile(s.join(e,t));n.update(r),n.update(`\0`)}return`${t}-${n.digest(`base64`)}`}async function U(e,t,n){let r=s.join(t,`node_modules`,e.packageName);L(r,t,`Contribution package directory`),await R(r,t,`Contribution package directory`,n);let i=s.join(r,`package.json`),o;try{o=await a.readFile(i,`utf-8`)}catch{throw new I(`Contribution package not found: ${e.packageName} (expected at ${r})`,`contribution-missing`)}let c=JSON.parse(o);if(c.name!==e.packageName)throw new I(`Contribution identity mismatch: expected ${e.packageName}, found ${c.name??`<none>`}`,`contribution-missing`);if(c.version!==e.version)throw new I(`Contribution version mismatch for ${e.packageName}: expected ${e.version}, found ${c.version??`<none>`}`,`contribution-version-mismatch`);let l=s.join(r,e.entrypoint);L(l,r,`Contribution entrypoint`),await R(l,t,`Contribution entrypoint`,n);try{await a.access(l)}catch{throw new I(`Contribution entrypoint not found for ${e.packageName}: ${e.entrypoint}`,`contribution-entrypoint-mismatch`)}let{algorithm:u}=z(e.integrity),d;try{d=await V(r,u)}catch(t){if(t instanceof I)throw t;let n=typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`?t.code:void 0;throw n!==void 0&&!n.startsWith(`ERR_`)?new I(`Contribution package cannot be read for ${e.packageName}`,`contribution-entrypoint-mismatch`):t}if(d!==e.integrity)throw new I(`Contribution integrity mismatch for ${e.packageName}: expected ${e.integrity}, computed ${d}`,`contribution-integrity-mismatch`);return l}async function W(e,t,n){let r=await n.resolveWorkspaceRoot(e.workspaceId);if(r===void 0)throw new I(`Unknown workspace ID: ${e.workspaceId}`,`unknown-workspace`);try{if(!(await a.stat(r)).isDirectory())throw new I(`Workspace root is not a directory: ${r}`,`containment-violation`)}catch(e){throw e instanceof I?e:new I(`Workspace root does not exist: ${r}`,`containment-violation`)}let i=await a.realpath(r),o=s.resolve(r,e.sourcePath);if(L(o,r,`Source path`),s.relative(r,o).split(s.sep).some(Xe))throw new I(`Workflow source path selects excluded workspace content: ${e.sourcePath}`,`source-path-mismatch`);await R(o,r,`Source path`,i);let c=await H(r);if(c!==e.rootDigest)throw new I(`Workspace root digest mismatch: expected ${e.rootDigest}, computed ${c}`,`digest-mismatch`);try{await a.access(o)}catch{throw new I(`Workflow source file not found: ${o}`,`source-missing`)}return{workspaceRoot:r,sourcePath:o,contributionEntrypoints:await Promise.all(t.map(e=>U(e,r,i))),platform:process.platform,arch:process.arch}}var G=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){this.pool??=new Je(this.options);let r=n??this.manifest,i=await this.materializeTask(e,r,t);return{state:`uncommitted`,result:await this.pool.run(i,t)}}runWithReadiness(e,t,n){this.pool??=new Je(this.options);let i=this.pool,a,o=!1,s,c=new Promise((t,n)=>{s=n,a=i.onMessage(n=>{r(n)&&(n.executionId!==e.executionId||n.cancelSubject!==e.cancelSubject||(o=!0,a?.(),t(n)))})}),l=n??this.manifest,u=this.materializeTask(e,l,t).then(e=>i.run(e,t));return u.then(()=>{o||(o=!0,a?.(),s(Error(`Workflow worker completed before ready signal: ${e.executionId}`)))},e=>{o||(o=!0,a?.(),s(e instanceof Error?e:Error(String(e))))}),{result:u,ready:c}}async dispose(){await this.pool?.dispose()}async materializeTask(e,t,n){if(n.throwIfAborted(),!(e.source.kind===`path`||t.contributionRefs.length>0))return{config:e,manifest:t,contributionEntrypoints:[]};let r=e.materializationSpec;if(r?.kind!==`local-directory`)throw Error(`ThinWorkflowPiscinaRunner requires a local-directory materialization spec for path-backed workflows or declared contributions.`);if(this.options.resolveWorkspaceRoot===void 0)throw Error(`ThinWorkflowPiscinaRunner requires a host workspace-root resolver for local-directory materialization.`);let i=await W(r,t.contributionRefs,{resolveWorkspaceRoot:this.options.resolveWorkspaceRoot});if(n.throwIfAborted(),e.source.kind!==`path`)throw Error(`local-directory materialization requires a path-backed workflow source.`);return{config:{...e,source:{kind:`path`,path:i.sourcePath}},manifest:t,contributionEntrypoints:i.contributionEntrypoints}}};function K(e){return e.mode===`source`?l(e.moduleDir,`workflow-worker`,`worker-entry.ts`):l(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}var q=class{options;constructor(e){this.options=e}async run(e,t,n,r){let i={...e,terminalAuthority:`authority`},a=n??this.options.manifest,o=this.options.requirements,s=r?.dispatchMetadata;return{state:`authority-committed`,result:await Me({authority:this.options.authority,executionId:e.executionId,dispatch:e=>this.options.dispatch({executionAttemptId:e,config:i,...a!==void 0&&{manifest:a},...o!==void 0&&{requirements:o},...s!==void 0&&{metadata:s}},t)})}}},J=class{#e;constructor(e){this.#e=e.bus}async run(e,t,r){let a=ie.parse(e),o=await n(a);return{state:`uncommitted`,result:await Ne({config:await i(a,o,this.#e,t),loaded:o,bus:this.#e,signal:t})}}};function et(){return{contributionRefs:[]}}function tt(e){if(e.workflowRunner?.mode===`worker`&&!e.executionAttemptRepository)throw Error(`Worker dispatch mode requires an ExecutionAttemptRepository. Pass 'executionAttemptRepository' to createNodeWorkflowRunnerPackageOptions when workflowRunner.mode is 'worker'.`);let t=e.executionAttemptRepository?new je(e.executionAttemptRepository):void 0,n=c(e.runtimeModuleDir)===`src`?`source`:`dist`,r=Y({moduleDir:e.runtimeModuleDir,defaultWorkerEntryMode:n,runner:e.workflowRunner,bus:e.bus,authority:t});return{...r!==void 0&&{workflowRunner:r},executorConfig:{busUrl:e.busUrl,busAuth:{kind:`none`},platformDefaults:e.platformDefaults,makaioHome:e.makaioHome},...e.executionAttemptRepository!==void 0&&{executionAttemptRepository:e.executionAttemptRepository},...t!==void 0&&{executionAttemptAuthority:t},...e.workflowMaterializationSpecResolvers!==void 0&&{workflowMaterializationSpecResolvers:e.workflowMaterializationSpecResolvers}}}function Y(e){let{runner:t}=e;if(t)switch(t.mode){case void 0:case`in-process`:if(e.bus===void 0)throw Error(`InProcessWorkflowRunner requires a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'in-process'.`);return new J({bus:e.bus});case`worker`:{if(e.authority===void 0)throw Error(`WorkerRunner requires an ExecutionAttemptAuthority. Pass 'authority' to createNodeWorkflowRunner when runner.mode is 'worker'.`);let n=e.bus,r=t.dispatch??(n===void 0?void 0:(e,t)=>n.request(y.dispatch,{executionAttemptId:e.executionAttemptId,config:e.config,manifest:e.manifest,requirements:e.requirements,metadata:e.metadata},{signal:t}));if(r===void 0)throw Error(`WorkerRunner requires either a dispatch function or a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'worker'.`);return new q({dispatch:r,authority:e.authority,...t.manifest!==void 0&&{manifest:t.manifest},...t.requirements!==void 0&&{requirements:t.requirements}})}case`piscina`:return new G({workerEntry:t.workerEntry??K({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??et(),...t.resolveWorkspaceRoot!==void 0&&{resolveWorkspaceRoot:t.resolveWorkspaceRoot},maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}const nt=new Set([`accepted`,`duplicate`]);var X=class extends Error{decision;result;reason;constructor(e,t,n=`authority-rejected`){super(`Outcome delivery ${n===`deadline-exceeded`?`deadline exceeded`:`rejected by Authority`} (decision=${e}, executionId=${t.executionId}, status=${t.status})`),this.decision=e,this.result=t,this.reason=n,this.name=`OutcomeDeliveryError`}};function Z(e){return new X(`deadline-exceeded`,e,`deadline-exceeded`)}function rt(e){let t={maxRetries:e?.maxRetries??7,baseDelayMs:e?.baseDelayMs??1e3,maxDelayMs:e?.maxDelayMs??3e4,deadlineMs:e?.deadlineMs??12e4};if(!Number.isSafeInteger(t.maxRetries)||t.maxRetries<0)throw TypeError(`Outcome submission maxRetries must be a non-negative safe integer, got ${t.maxRetries}`);for(let[e,n]of Object.entries({baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,deadlineMs:t.deadlineMs}))if(!Number.isFinite(n)||n<=0)throw TypeError(`Outcome submission ${e} must be a positive finite number, got ${n}`);return t}async function it(e,t,n,r){let i=t.baseDelayMs*2**(e-1),a=n-Date.now(),o=Math.min(i,t.maxDelayMs,a);await new Promise(e=>setTimeout(e,o));let s=n-Date.now();if(s<=0)return!1;if(r!==void 0){let e;try{await Promise.race([r(),new Promise(t=>{e=setTimeout(t,s)})])}catch{}finally{e!==void 0&&clearTimeout(e)}}return Date.now()<n}async function Q(e,t,n){let r=rt(n?.retry),i=n?.reconnect,a=Date.now()+r.deadlineMs,o;for(let n=0;n<=r.maxRetries;n++){if(a-Date.now()<=0||n>0&&!await it(n,r,a,i))throw Z(t.result);try{let n=a-Date.now();if(n<=0)throw Z(t.result);let{decision:r}=await e.request(y.control.outcome.submit,{executionAttemptId:t.executionAttemptId,executionId:t.executionId,result:t.result},{timeout:n});if(nt.has(r))return r;throw new X(r,t.result)}catch(e){if(e instanceof X)throw e;if(o=e,Date.now()>=a)throw Z(t.result)}}throw o??Z(t.result)}const at={maxRetries:3,baseDelayMs:200,maxDelayMs:2e3,deadlineMs:1e4},ot={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`,supportsRecovery:!1,materializationModes:[`local-directory`]};function st(e){let t=new Set,n;return{conclude:r=>{if(n!==void 0)return;n={evidence:h.parse({source:e.slice(0,v.source),summary:r.slice(0,v.summary),observedAt:new Date().toISOString()})};let i=[...t];t.clear();for(let e of i)try{e(n)}catch(e){console.error(`[PiscinaThinWorkflowProvider] Infrastructure-conclusion observer failed:`,e)}},observe:e=>n===void 0?(t.add(e),()=>t.delete(e)):(e(n),()=>void 0)}}var ct=class{executionAttemptId;controller;detachCallerAbort;infrastructure;constructor(e,t,n,r){this.executionAttemptId=e,this.controller=t,this.detachCallerAbort=n,this.infrastructure=r}cancel(e){return this.controller.abort(e??`Worker cancelled`),this.detachCallerAbort(),Promise.resolve()}terminate(){return this.controller.abort(`Worker terminated`),this.detachCallerAbort(),Promise.resolve()}release(){return this.detachCallerAbort(),Promise.resolve()}observeInfrastructureConclusion(e){return this.infrastructure.observe(e)}},lt=class{options;environment=`piscina`;allocationLifetime=`provisioner-process-bound`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=ne.parse({...ot,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??ot.suspensionStrategy,supportsRecovery:!1})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e,t){t.throwIfAborted();let n=new AbortController,r=st(this.id),i=()=>{n.abort(t.reason)};t.addEventListener(`abort`,i,{once:!0});let a=()=>t.removeEventListener(`abort`,i);try{let{executionAttemptId:i,executionId:o,workerConfig:s}=e,c=this.buildAllocationRef(i),l=new ct(i,n,a,r);t.throwIfAborted();let u=this.options.runner.runWithReadiness(e.workerConfig,n.signal,e.workerManifest);return u.ready.then(async e=>{n.signal.aborted||await this.options.bus.emit(y.control[`attempt-ready`],{executionAttemptId:i,executionId:o,adapters:[...e.adapters]})},()=>void 0).catch(e=>n.abort(e)),this.submitOutcomeOnSettlement(u.result,o,i,s.workflowId,r.conclude),{kind:`allocated`,allocationRef:c,handle:l}}catch(e){throw n.abort(e),a(),e}}async submitOutcomeOnSettlement(e,t,n,r,i){let a;try{a=await e}catch(e){a={executionId:t,workflowId:r,status:`failed`,error:e instanceof Error?e.message:String(e)}}try{let e={...at,...this.options.outcomeRetry};await Q(this.options.bus,{executionAttemptId:n,executionId:t,result:a},{retry:e})}catch(e){e instanceof X?console.error(`[PiscinaThinWorkflowProvider] Outcome rejected for execution '${t}' attempt '${n}' (decision=${e.decision}):`,e):console.error(`[PiscinaThinWorkflowProvider] Failed to submit outcome for execution '${t}' attempt '${n}':`,e),i(`Piscina worker for attempt '${n}' ended without an acknowledged outcome because outcome submission could not be completed`)}}buildAllocationRef(e){let t={version:ee,providerId:this.id,providerData:{executionAttemptId:e,allocatedAt:Date.now()}};return te.parse(t)}};const ut=[Ce,be,Se];function dt(e){let t;return()=>(t??=(async()=>{let t=[];for(let n of[...e].reverse())try{await n()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Isolated workflow runtime shutdown reported errors`)})(),t)}function ft(e,t,n){return T({bus:e,currentMachineId:n,resolveLiveAdapterId:e=>t.getExtensionService(S)?.resolveLiveAdapterId(e),resolveLiveAdapterIdentity:e=>t.getExtensionService(S)?.resolveLiveAdapterIdentity(e),listLiveAdapterIdentities:()=>t.getExtensionService(S)?.getLiveAdapterIdentities()??[]})}async function pt(e){let t=f();t.registerNamespaces([...g,..._]);let{context:n}=e,r=new oe(t,{surface:`headless`,extensionContextBase:{cwd:n.cwd,platform:n.platform,homedir:n.homedir,makaioHome:n.makaioHome,username:n.username,machineId:n.machineId,tryImport:D}}),i,a=[()=>t.disconnect()],o=dt(a);try{await e.connectAuthority(t);let s=[...e.contributedPackages,...await e.loadContributedPackages?.(t)??[]],{adapterSubsystemPackage:c}=w({coordinator:r,configRepository:e.configRepository,platformDefaults:{cwd:n.cwd},runtimeSnapshotHandlerPriority:1,runtimeDefinitionHandlerPriority:1,...e.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:e.prepareAuthRuntime}}),l=Te({definitions:s.flatMap(e=>e.clients??[]),binaryResolutionPolicy:`global-only`});r.registerContributionProcessor(ye());let u=[...ut,c,_e,...P(s)?[xe]:[],ve(1),we,A,l,...Oe(s)];r.load(u),a.push(...F(u,t,r)),a.push(()=>r.shutdown()),await r.startAll(),i=ft(t,r,n.machineId),a.push(()=>{i?.cleanup(),i=void 0});let d=r.getExtensionService(ge);if(d===void 0)throw Error(`Isolated workflow tool registry did not start.`);for(let t of e.toolsets)await d.register(t);return await t.emit(se.ready,{machineId:n.machineId}),{bus:t,coordinator:r,machineId:n.machineId,shutdown:o}}catch(e){throw await o().catch(()=>void 0),e}}function mt(e,t){return{executionId:e,workflowId:t,status:`cancelled`,reason:`Execution cancelled`}}async function $(e,t,n){let r=new AbortController,i=e.on(ae(t),()=>{r.abort()}),a=()=>{r.abort()};return n?.addEventListener(`abort`,a,{once:!0}),n?.aborted&&r.abort(),await p(i),{signal:r.signal,cleanup:()=>{n?.removeEventListener(`abort`,a),i()}}}function ht(t,n){let r=e();return{cwd:t.workspaceRoot,platform:t.platform,homedir:r,makaioHome:r,username:`workflow-worker`,machineId:n}}async function gt(e,t,n,r,i,a){return await pt({connectAuthority:async n=>{await e.connectBus(n,t,i)},contributedPackages:[...r],configRepository:e.configRepository,context:ht(n,a),toolsets:[...e.toolsets],...e.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:e.prepareAuthRuntime}})}async function _t(e,t,n){let{executionId:r,executionAttemptId:i}=e,a=mt(r,n);return{result:a,decision:await Q(t,{executionAttemptId:i,executionId:r,result:a},{retry:e.outcomeRetry,reconnect:()=>t.reconnect()})}}async function vt(e,t,n,r,i){let{executionId:a,executionAttemptId:o}=e,s;try{s=await e.execute(t.bus,n,r,i)}catch(e){s=i.aborted&&e instanceof DOMException&&e.name===`AbortError`?mt(a,n.workflowId):{executionId:a,workflowId:n.workflowId,status:`failed`,error:e instanceof Error?e.message:String(e)}}let c=await Q(t.bus,{executionAttemptId:o,executionId:a,result:s},{retry:e.outcomeRetry,reconnect:()=>t.bus.reconnect()});if(e.onPostCommit!==void 0)try{await e.onPostCommit(s,c)}catch{}return{result:s,decision:c}}async function yt(e,t,n,r,i,a){let o=await $(n,r.cancelSubject),s=AbortSignal.any([i,o.signal]),c=s,l,u,d;try{s.throwIfAborted();let f=await e.materialize(r,s),p=f.context;d=f.cleanup,s.throwIfAborted();let m=await e.loadContributions(p,s);s.throwIfAborted(),l=await gt(e,t,p,m,s,a),u=await $(l.bus,r.cancelSubject,o.signal),o.cleanup(),n.disconnect();let h=AbortSignal.any([i,u.signal]);c=h,h.throwIfAborted();let{adapters:g}=await l.bus.request(x.listAdapters,{});return h.throwIfAborted(),await l.bus.emit(y.control[`attempt-ready`],{executionAttemptId:e.executionAttemptId,executionId:e.executionId,adapters:g.map(e=>e.name)}),await vt(e,l,r,p,h)}catch(t){if(!(c.aborted&&t instanceof DOMException&&t.name===`AbortError`))throw t;return await _t(e,l?.bus??n,r.workflowId)}finally{o.cleanup(),u?.cleanup(),l!==void 0&&await l.shutdown().catch(()=>void 0),d!==void 0&&await d().catch(()=>void 0)}}async function bt(e,t){t.throwIfAborted();let n=await e.bootstrap(t);t.throwIfAborted();let r=f();r.registerNamespaces([...g,..._]);try{return await e.connectBus(r,n,t),await yt(e,n,r,await r.request(re.getRunContext,{executionId:e.executionId},{signal:t}),t,`headless-worker-${e.executionAttemptId}`)}finally{try{r.disconnect()}catch{}}}export{A,j as C,M as D,F as E,C as F,D as M,T as N,Ue as O,w as P,Ve as S,qe as T,H as _,X as a,z as b,tt as c,K as d,G as f,V as g,R as h,nt as i,E as j,Ke as k,J as l,L as m,pt as n,Q as o,I as p,lt as r,Y as s,bt as t,q as u,Ye as v,He as w,U as x,W as y};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makaio/framework",
3
- "version": "1.0.0-dev-1787949057928",
3
+ "version": "1.0.0-dev-1788511348215",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/makaio-ai/makaio-framework.git",
@@ -188,9 +188,9 @@
188
188
  "types": "./dist/contracts/variant/index.d.mts",
189
189
  "default": "./dist/contracts/variant/index.mjs"
190
190
  },
191
- "./contracts/worker-node": {
192
- "types": "./dist/contracts/worker-node/index.d.mts",
193
- "default": "./dist/contracts/worker-node/index.mjs"
191
+ "./contracts/worker": {
192
+ "types": "./dist/contracts/worker/index.d.mts",
193
+ "default": "./dist/contracts/worker/index.mjs"
194
194
  },
195
195
  "./kernel": {
196
196
  "types": "./dist/kernel/index.d.mts",
@@ -1 +0,0 @@
1
- import{ProviderAllocationRefSchema as e,WorkerNodeAllocationLifetimeSchema as t,WorkflowRunResultSchema as n}from"@makaio/framework/contracts";function r(e){let t=Date.parse(e);if(Number.isNaN(t))throw Error(`Expected an ISO-8601 timestamp, received '${e}'`);return t}function i(e){return new Date(r(e)).toISOString()}function a(e){return typeof e==`object`&&!!e}function o(e){if(!(!a(e)||Object.isFrozen(e))){Object.freeze(e);for(let t of Object.values(e))o(t)}}function s(e,t){let n=t(structuredClone(e));return o(n),n}function c(t){return s(t,t=>e.parse(t))}function l(e){return s(e,e=>n.parse(e))}function u(e){return t.parse(e)}function d(t){let n=e.parse(t.currentRef),r=c(t.nextRef);if(n.providerId!==r.providerId)throw Error(`Allocation reference evolution must keep one provider, received '${n.providerId}' and '${r.providerId}'`);return{currentRef:n,nextRef:r}}function f(e,t){if(e.providerId!==t.providerId)throw Error(`Allocation reference for attempt '${e.executionAttemptId}' names provider '${t.providerId}' but the attempt is bound to '${e.providerId??`no provider`}'`)}function p(e,t){let n=r(e.createdAt)-r(t.createdAt);return n===0?e.executionAttemptId<t.executionAttemptId?-1:+(e.executionAttemptId>t.executionAttemptId):n}function m(e){let{status:t,claimable:n,settlementKind:r,allocationRef:i,providerId:a}=e,{allocationLifetime:o,provisionerIncarnationId:s}=e;if(t!==`allocated`||n!==!0||r!=null||i===null||a===null||o===null||s===null)throw Error(`Attempt '${e.executionAttemptId}' was selected as recoverable but is not: status '${t}', claimable '${String(n)}', settlement '${String(r)}', allocation '${i===null?`none`:`present`}', provider '${String(a)}', lifetime '${String(o)}', provisioner '${String(s)}'`);return{...e,status:t,claimable:!0,settlementKind:null,allocationRef:i,providerId:a,allocationLifetime:o,provisionerIncarnationId:s}}export{c as a,f as c,u as i,m as l,r as n,d as o,i as r,l as s,p as t};