@makaio/framework 1.0.0-dev-1788963848381 → 1.0.0-dev-1788966380232
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.
- package/dist/.makaio-build.json +2 -2
- package/dist/{attempt-record-codec-62Ifw7fv.mjs → attempt-record-codec-D2Gb_epJ.mjs} +1 -1
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +1 -1
- package/dist/contracts/automation-trigger/index.d.mts +1 -1
- package/dist/contracts/capabilities/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +2 -2
- package/dist/contracts/extension/index.d.mts +4 -4
- package/dist/contracts/facet/index.d.mts +1 -1
- package/dist/contracts/harness/index.d.mts +1 -1
- package/dist/contracts/index.d.mts +71 -71
- package/dist/contracts/materialization/index.d.mts +2 -2
- package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
- package/dist/contracts/reaction/index.d.mts +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/workflow/index.d.mts +1 -1
- package/dist/{contribution-BexrtFLC.d.mts → contribution-BfEEQ8YZ.d.mts} +1 -1
- package/dist/{execution-attempt-owner-recovery-CwTiTnnR.mjs → execution-attempt-owner-recovery-D4APLAvt.mjs} +1 -1
- package/dist/{execution-attempt-repository-CE7UXmEi.d.mts → execution-attempt-repository--RVils5-.d.mts} +273 -189
- package/dist/execution-attempt-repository-CWbgCTwA.mjs +1 -0
- package/dist/{extension-context-DDfSMPat.d.mts → extension-context-Cpf_n5FH.d.mts} +3 -3
- package/dist/{hook-responses-CRQYe15-.d.mts → hook-responses-CpEfxEmG.d.mts} +1 -1
- package/dist/{index-Bq8JJ77a2.d.mts → index-09eal6WI2.d.mts} +11 -11
- package/dist/{index-B_gyAIAo.d.mts → index-B7wjmaev.d.mts} +23 -13
- package/dist/{index-DTadNB7U.d.mts → index-BKwYE1Qk.d.mts} +3 -3
- package/dist/{index-BsZu6i8H2.d.mts → index-BT5qcsEf2.d.mts} +15 -15
- package/dist/{index-CCYavCD92.d.mts → index-BfzuauBt2.d.mts} +1 -1
- package/dist/{index-DkviOBAT.d.mts → index-Bj2JCo9V.d.mts} +1 -1
- package/dist/{index-CpGf9W_u.d.mts → index-BkQlL0Pl.d.mts} +8 -8
- package/dist/{index-DsEwuqKE.d.mts → index-Bnm0QvJ4.d.mts} +32 -32
- package/dist/{index-dpaDWzUU.d.mts → index-BqR2xDu6.d.mts} +234 -234
- package/dist/{index-CR5OVrQJ.d.mts → index-Bxq_zO2E.d.mts} +4 -4
- package/dist/{index-ndFBIZvG2.d.mts → index-C75h1xHF2.d.mts} +1 -1
- package/dist/{index-BdGOOFbD.d.mts → index-CVh7ZP2I.d.mts} +6 -6
- package/dist/{index-Bk8WkSa_.d.mts → index-DO633_D-.d.mts} +45 -45
- package/dist/{index-CP96gudX2.d.mts → index-DU9Y9tes2.d.mts} +4 -4
- package/dist/{index-CX9F0vHE.d.mts → index-DY_0TRvM.d.mts} +7 -7
- package/dist/{index-DhhHzOUU.d.mts → index-DzlGAEws.d.mts} +1 -1
- package/dist/{index-BIlFSGnW.d.mts → index-LjLUr3Dm.d.mts} +10 -10
- package/dist/{index-E55FZQKt.d.mts → index-MtDz_goH.d.mts} +49 -49
- package/dist/{index-DCHdW5g-.d.mts → index-ud9i9pue.d.mts} +16 -16
- package/dist/{index-di-02yaB2.d.mts → index-v9TbeVee2.d.mts} +5 -5
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{namespace-CfA0C0JR.d.mts → namespace-B1sjokHd.d.mts} +2 -2
- package/dist/{namespace-BFZ4HTH-.d.mts → namespace-BYsKOw-g.d.mts} +2 -2
- package/dist/{namespace-Dmbm2JzV.d.mts → namespace-Cy62a3YP.d.mts} +2 -2
- package/dist/{namespace-De6ORL69.d.mts → namespace-KTRWfIPy.d.mts} +2 -2
- package/dist/package-B-xpYKe8.mjs +7 -0
- package/dist/{package-DjI3DSDe.d.mts → package-Bl0mcGb8.d.mts} +8 -1
- package/dist/package.json +1 -1
- package/dist/runtime-node/index.d.mts +1 -1
- package/dist/runtime-node/index.mjs +1 -1
- package/dist/runtime-node/workflow-worker/index.d.mts +1 -1
- package/dist/runtime-node/workflow-worker/index.mjs +1 -1
- package/dist/{schemas-a4aVR0WT.d.mts → schemas-BYyT43gX.d.mts} +13 -13
- package/dist/{schemas-CQe4xCRn.d.mts → schemas-DGKWi7mk.d.mts} +2 -2
- package/dist/{schemas-CikbhFMx.d.mts → schemas-DwqibWUL.d.mts} +2 -2
- package/dist/services/agent-runtime/index.d.mts +2 -2
- package/dist/services/agent-runtime/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/schemas.d.mts +1 -1
- package/dist/services/execution-target/index.d.mts +3 -3
- package/dist/services/execution-target/namespace.d.mts +1 -1
- package/dist/services/execution-target/schemas.d.mts +1 -1
- package/dist/services/filesystem/namespace.d.mts +6 -6
- package/dist/services/filesystem/schemas.d.mts +3 -3
- package/dist/services/index.d.mts +24 -24
- package/dist/services/log-import/browser.d.mts +2 -2
- package/dist/services/log-import/index.d.mts +2 -2
- package/dist/services/log-import/log-import.d.mts +1 -1
- package/dist/services/log-import/namespace.d.mts +2 -2
- package/dist/services/log-import/schemas.d.mts +1 -1
- package/dist/services/session/handlers/index.d.mts +1 -1
- package/dist/services/session/index.d.mts +3 -3
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +10 -10
- package/dist/services/subagent-template/index.d.mts +2 -2
- package/dist/services/subagent-template/namespace.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/{session-lineage-CLOlB9l_.d.mts → session-lineage-CEyJWg_J.d.mts} +1 -1
- package/dist/{types-Bs3Pm8rB2.d.mts → types-Bnc-pdB12.d.mts} +1 -1
- package/dist/{types-DoxPKNUW.d.mts → types-ZvPhKp3j.d.mts} +8 -8
- package/dist/{view-builder-BMpOHHlf.d.mts → view-builder-D54kvyf7.d.mts} +9 -9
- package/dist/workflow-engine/execution-attempt-repository.d.mts +2 -2
- package/dist/workflow-engine/execution-attempt-repository.mjs +1 -1
- package/dist/workflow-engine/index.d.mts +51 -51
- package/dist/workflow-engine/index.mjs +1 -1
- package/dist/workflow-engine/package.d.mts +1 -1
- package/dist/workflow-engine/package.mjs +1 -1
- package/dist/workflow-engine/provider-operation.d.mts +1 -1
- package/dist/workflow-engine/testing/conformance.d.mts +1 -1
- package/dist/workflow-engine/testing/conformance.mjs +2 -2
- package/dist/workflow-engine/testing/index.d.mts +3 -1
- package/dist/workflow-engine/testing/index.mjs +1 -1
- package/dist/workflow-engine/testing/sqlite.d.mts +1 -1
- package/dist/workflow-engine/testing/sqlite.mjs +66 -61
- package/dist/workflow-worker-CrnDwpkP.mjs +2 -0
- package/package.json +1 -1
- package/dist/execution-attempt-repository-Z7oEBcgp.mjs +0 -1
- package/dist/package-BESXccyx.mjs +0 -7
- package/dist/workflow-worker-Drf-skvM.mjs +0 -2
- package/dist/{index-BU9HQ1vJ2.d.mts → index-BBkJsViX2.d.mts} +6 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { I as RecordAllocationInput, Mt as AttemptOutcomeControlObservation, P as ProvisioningClaimDecision, Pt as ExecutionAttemptCancellationIntent, dt as ProviderOperationOwnershipRecord, it as ProviderOperationClaim, j as OutcomeCodec, r as AllocationRecordingDecision, rt as ProcessBoundProvisionerLossProof, s as AttemptControlState, u as BeginProvisioningInput, w as ExecutionOwnerId, x as ExecutionAttemptRepository, y as ExecutionAttemptRecord } from "../../execution-attempt-repository--RVils5-.mjs";
|
|
2
2
|
import { BoundedRecoveryEvidence, ExecutionAttemptInstruction, ExecutionAttemptPreparationResult, ProviderAllocationRef, WorkerAllocationLifetime, WorkflowRunResult } from "@makaio/framework/contracts";
|
|
3
3
|
|
|
4
4
|
//#region subsystems/workflow-engine/src/testing/attempt-record-codec.d.ts
|
|
@@ -43,6 +43,8 @@ interface InMemoryAttemptRepositoryState {
|
|
|
43
43
|
* freeze can protect.
|
|
44
44
|
*/
|
|
45
45
|
readonly committedOutcomes: Map<string, string>;
|
|
46
|
+
/** Commit-time control facts, absent only for outcomes created before this observation existed. */
|
|
47
|
+
readonly outcomeControlObservations: Map<string, AttemptOutcomeControlObservation>;
|
|
46
48
|
/** Active attempt per `executionId`, the fence every bootstrap path reads. */
|
|
47
49
|
readonly activeAttempts: Map<string, string>;
|
|
48
50
|
/** Request-to-attempt bindings, nested by owner and then opaque request key. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,c as t,d as n,f as r,g as i,h as a,l as o,m as s,n as c,o as l,p as u,s as d,u as f}from"../../execution-attempt-repository-Z7oEBcgp.mjs";import{a as p,i as m,n as h,o as g,t as _}from"../../execution-attempt-owner-recovery-CwTiTnnR.mjs";import{isProviderOperationResolved as v}from"../provider-operation.mjs";import{a as y,c as b,d as x,f as S,i as C,l as w,n as T,o as E,p as D,r as O,s as k,t as A,u as j}from"../../attempt-record-codec-62Ifw7fv.mjs";import{a as M,c as N,d as P,f as F,i as I,l as L,m as R,n as z,o as B,p as V,r as H,s as U,t as W,u as G}from"../../attempt-fixtures-CMx-2OlG.mjs";import{BoundedRecoveryEvidenceSchema as K}from"@makaio/framework/contracts";function q(e,t){return{...e,status:`settled`,settlementKind:t,claimable:!1,operationStartGate:`closed`}}function J(M,N={}){let P=N.attempts??new Map,F=N.operations??new Map,I=e=>F.get(e)?.obligation===`terminal-convergence`,L=N.committedOutcomes??new Map,R=N.activeAttempts??new Map,z=N.requestBindings??new Map,B=N.cancellations??new Map,V=e=>{let t=e.settlementKind!=null,r=!t&&R.get(e.executionId)===e.executionAttemptId;return n({matchesExecution:!0,settled:t,active:r,allocated:r&&e.allocationRef!==null&&!I(e.executionAttemptId)})},H=e=>{let t=P.get(e.executionAttemptId),n=F.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:v(t,n)?{kind:`resolved`,attempt:t}: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}},U=(e,t)=>{e.completionEvidence===null&&F.set(e.executionAttemptId,{...e,completionEvidence:t})},W=(e,t)=>{let n=k(e.allocationRef),r=H(e.claim);if(r.kind!==`not-found`&&x(r.attempt,n),r.kind===`resolved`)return{kind:`resolved`,allocationRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i,operation:a}=r;if(i.allocationRef!==null)return o(i.allocationRef,n)?{kind:`duplicate`,allocationRef:i.allocationRef}:{kind:`conflict`,allocationRef:i.allocationRef};let s=R.get(i.executionId)===i.executionAttemptId;return P.set(i.executionAttemptId,{...i,status:i.settlementKind===null?`allocated`:i.status,allocationRef:n,claimable:i.settlementKind===null&&t&&s}),F.set(a.executionAttemptId,{...a,obligation:`allocation-control`}),{kind:`recorded`}},G={async getAttemptWithAllocation(e){return P.get(e)??null},async recordDiscoveredAllocation(e){return W(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=b(e),r=H(e.claim);if(r.kind===`stale`)return{kind:`stale`,storedRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?{kind:`not-allocated`}:o(i.allocationRef,t)?(P.set(i.executionAttemptId,{...i,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:i.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=C(new Date().toISOString()),n=[];for(let r of P.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(D(r)));return n.sort(T)},async listOpenProviderOperations(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw RangeError(`limit must be a positive safe integer`);let t=C(e.observedAt),n=[];for(let e of F.values()){let r=P.get(e.executionAttemptId);!r||v(r,e)||e.ownerId!==null&&e.leaseExpiresAt!==null&&C(e.leaseExpiresAt)>t||n.push({attempt:r,operation:e})}return n.sort((e,t)=>T(e.attempt,t.attempt)).slice(0,e.limit)}},J=e=>{let t=O(e.bootstrapTimeoutMs);if(P.has(e.executionAttemptId))throw new c(e.executionAttemptId);let n={executionAttemptId:e.executionAttemptId,executionId:e.executionId,instruction:e.instruction,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,...t,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null,...A},r=R.get(e.executionId),i=r===void 0?void 0:P.get(r);return i!==void 0&&P.set(i.executionAttemptId,{...i,claimable:i.status===`allocated`?!1:i.claimable,operationStartGate:`closed`}),P.set(e.executionAttemptId,n),R.set(e.executionId,e.executionAttemptId),n};return{async createAttempt(e){return J({...e,instruction:g(e.instruction)})},async ensureAttempt(e){let t=m(e),n=z.get(t.executionId),r=n?.get(t.requestKey);if(r!==void 0)return h(t,P.get(r)??null);let i=J(t),a=n??new Map;return a.set(t.requestKey,i.executionAttemptId),z.set(t.executionId,a),{kind:`created`,attempt:structuredClone(i)}},async readAttemptSettlement(e){let t=p(e);return _(t,{attempt:P.get(t.executionAttemptId)??null,activeAttemptId:R.get(t.executionId)??null,outcomeText:L.get(t.executionAttemptId)??null},M)},async readBootstrapStartState(e){let t=P.get(e.executionAttemptId);return!t||t.executionId!==e.executionId?null:{settled:t.settlementKind!=null,active:R.get(e.executionId)===e.executionAttemptId,allocated:t.allocationRef!==null,allocationTerminated:I(e.executionAttemptId),operationStartGate:t.operationStartGate,bootstrapDeadlineAt:t.bootstrapDeadlineAt??null}},async beginProvisioning(e){let t=E(e.allocationLifetime),n=P.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(R.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.operationStartGate===`closed`)return{kind:`fenced`};if(n.status!==`pending`)return{kind:`already-provisioning`};P.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:y(e.leaseExpiresAt)};return F.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,completionEvidence:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return F.get(e)??null},async renewProviderOperationClaim(e){let t=H(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=y(e.leaseExpiresAt);return F.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=P.get(e.executionAttemptId),n=F.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(v(t,n))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:y(e.leaseExpiresAt)};return F.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:K.parse(e.evidence),n=H(e.claim);return n.kind===`authorized`?(F.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=K.parse(e.evidence),n=H(e.claim);return n.kind===`authorized`?(F.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async completeProviderOperation(e){let t=K.parse(e.evidence),n=P.get(e.claim.executionAttemptId),r=F.get(e.claim.executionAttemptId);return!n||!r?{kind:`not-found`}:r.token!==e.claim.token||r.generation!==e.claim.generation||r.ownerId!==e.claim.ownerId?{kind:`stale`}:v(n,r)?{kind:`already-completed`}:r.completionEvidence===null?(U(r,t),n.settlementKind===null?{kind:`evidence-recorded`}:{kind:`completed`}):{kind:`evidence-recorded`}},async recordAllocation(e){return W(e,!0)},async recordProvisioningAbsent(e){let t=K.parse(e.evidence),n=H(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?r.settlementKind===null?(P.set(r.executionAttemptId,q(r,`abandoned`)),U(i,t),{kind:`recorded`}):(U(i,t),{kind:`completed`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=K.parse(e.proof.evidence),n=H(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n,o=a(r,e);return o===null?r.settlementKind===null?(P.set(r.executionAttemptId,q(r,`abandoned`)),U(i,t),{kind:`recorded`}):(U(i,t),{kind:`completed`}):o},async recordAllocationTerminated(e){let t=K.parse(e.evidence),n=H(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(F.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=H(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.settlementKind===null?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(P.set(n.executionAttemptId,q(n,`infrastructure-failure`)),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`resolved`}:{kind:`not-found`}},async registerRuntime(t){let n=P.get(t.executionAttemptId);if(n===void 0||n.executionId!==t.executionId)return{kind:`not-found`};let r=V(n)??e(n,t);if(r!==null)return r;let i=n.runtimeGeneration+1;return P.set(n.executionAttemptId,{...n,runtimeGeneration:i,runtimeIncarnationId:t.runtimeIncarnationId,runtimeReadyAt:null,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null}),{kind:`registered`,runtimeGeneration:i}},async admitOperation(e){let t=P.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=V(t);if(n!==null)return n;let i=r(t,e,t.activeOperationId!==null&&t.activeOperationKey===e.admissionKey&&t.activeOperationAdmittedAt===null?y(new Date().toISOString()):``,t);if(i!==null)return i;let a=crypto.randomUUID(),o=y(new Date().toISOString());return P.set(t.executionAttemptId,{...t,activeOperationId:a,activeOperationKind:e.operationKind,activeOperationKey:e.admissionKey,activeOperationGeneration:t.runtimeGeneration,activeOperationAdmittedAt:o}),{kind:`admitted`,operationId:a,runtimeGeneration:t.runtimeGeneration,admittedAt:o}},async getInstruction(e){let t=P.get(e.executionAttemptId);return t?.executionId===e.executionId?t.instruction:null},async reportOperation(e){let t=j(e.result),n=P.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=s({matchesExecution:!0,settled:n.settlementKind!=null,active:R.get(e.executionId)===e.executionAttemptId,allocated:n.allocationRef!==null&&!I(e.executionAttemptId)},n,n,{...e,result:t});if(r!==null)return r;let i=w([...n.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return P.set(e.executionAttemptId,{...n,preparationReceipts:i,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`accepted`,binding:t.binding}},async completeOperation(e){let t=P.get(e.executionAttemptId);if(t===void 0)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};let n=u(t,e);return n===null?(P.set(t.executionAttemptId,{...t,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`completed`}):n},async markRuntimeReady(e){let t=y(e.readyAt),n=P.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=V(n)??i(n,e);return r===null?(P.set(n.executionAttemptId,{...n,runtimeReadyAt:t}),{kind:`ready`,acceptedAt:t}):r},async getAttemptControlState(e){let t=P.get(e);return t===void 0?null:S(t)},async requestCancellation(e){let t={requestedAt:new Date().toISOString(),...e.reason===void 0?{}:{reason:e.reason}};for(let[n,r]of P)r.executionId===e.executionId&&(B.has(n)||B.set(n,t),P.set(n,{...r,operationStartGate:`closed`}))},async readCancellation(e){let t=B.get(e);return t===void 0?null:{...t}},async getActiveAttempt(e,t){return R.get(e)===t?P.get(t)??null:null},canonicalizeOutcome(e){return t(M,e)},decodeOutcome(e){return d(M,e)},async commitOutcome(e){let t=e.result;if(R.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let n=P.get(e.executionAttemptId);if(n===void 0)return{kind:`fenced`};let r=L.get(e.executionAttemptId);if(r!==void 0){let e=d(M,r);return f(r,t.text)?{kind:`duplicate`,outcome:e,text:r}:{kind:`conflict`}}return n.settlementKind==null?(l(n,e.runtimeFence),L.set(e.executionAttemptId,t.text),P.set(e.executionAttemptId,q(n,`outcome`)),{kind:`accepted`,outcome:d(M,t.text),text:t.text}):{kind:`conflict`}},async abandonPendingAttempt(e,t){if(R.get(t)!==e)return{kind:`fenced`};let n=P.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`}:(P.set(e,q(n,`abandoned`)),{kind:`abandoned`}):{kind:`fenced`}},recovery:G,attempts:P,operations:F,committedOutcomes:L,activeAttempts:R,requestBindings:z,cancellations:B}}export{A as INITIAL_ATTEMPT_CONTROL_STATE,W as TEST_OWNER_ID,z as TEST_PROVIDER_ID,H as TEST_PROVISIONER_INCARNATION_ID,I as allocateTestAttempt,M as beginTestProvisioning,J as createInMemoryAttemptRepository,B as driveTestAttemptToAllocated,U as leaseAt,N as makeBeginProvisioningInput,L as makeEvidence,G as makeProcessLossProof,P as makeTestAllocationRef,F as makeTestInstruction,V as makeTestWorkflowResult,R as workflowRunResultOutcomeCodec};
|
|
1
|
+
import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,h as ee,l as s,m as c,n as l,o as u,s as d,u as f,v as p,x as m,y as h}from"../../execution-attempt-repository-CWbgCTwA.mjs";import{a as g,i as _,n as v,o as y,t as b}from"../../execution-attempt-owner-recovery-D4APLAvt.mjs";import{isProviderOperationResolved as x}from"../provider-operation.mjs";import{a as S,c as C,d as w,f as T,i as E,l as D,n as O,o as k,p as A,r as j,s as M,t as N,u as P}from"../../attempt-record-codec-D2Gb_epJ.mjs";import{a as F,c as I,d as L,f as R,i as z,l as B,m as V,n as H,o as U,p as W,r as G,s as K,t as q,u as J}from"../../attempt-fixtures-CMx-2OlG.mjs";import{randomUUID as Y}from"node:crypto";import{BoundedRecoveryEvidenceSchema as X}from"@makaio/framework/contracts";function Z(e,t){return{...e,status:`settled`,settlementKind:t,claimable:!1,operationStartGate:`closed`}}function Q(F,I={}){let L=I.attempts??new Map,R=I.operations??new Map,z=e=>R.get(e)?.obligation===`terminal-convergence`,B=I.committedOutcomes??new Map,V=I.outcomeControlObservations??new Map,H=I.activeAttempts??new Map,U=I.requestBindings??new Map,W=I.cancellations??new Map,G=e=>{let t=e.settlementKind!=null,n=!t&&H.get(e.executionId)===e.executionAttemptId;return ee({matchesExecution:!0,settled:t,active:n,allocated:n&&e.allocationRef!==null&&!z(e.executionAttemptId)})},K=e=>{let t=L.get(e.executionAttemptId),n=R.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:x(t,n)?{kind:`resolved`,attempt:t}: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}},q=(e,t)=>{e.completionEvidence===null&&R.set(e.executionAttemptId,{...e,completionEvidence:t})},J=(e,t)=>{let n=M(e.allocationRef),r=K(e.claim);if(r.kind!==`not-found`&&w(r.attempt,n),r.kind===`resolved`)return{kind:`resolved`,allocationRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i,operation:a}=r;if(i.allocationRef!==null)return d(i.allocationRef,n)?{kind:`duplicate`,allocationRef:i.allocationRef}:{kind:`conflict`,allocationRef:i.allocationRef};let o=H.get(i.executionId)===i.executionAttemptId;return L.set(i.executionAttemptId,{...i,status:i.settlementKind===null?`allocated`:i.status,allocationRef:n,claimable:i.settlementKind===null&&t&&o}),R.set(a.executionAttemptId,{...a,obligation:`allocation-control`}),{kind:`recorded`}},Q={async getAttemptWithAllocation(e){return L.get(e)??null},async recordDiscoveredAllocation(e){return J(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=C(e),r=K(e.claim);if(r.kind===`stale`)return{kind:`stale`,storedRef:r.attempt.allocationRef};if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?{kind:`not-allocated`}:d(i.allocationRef,t)?(L.set(i.executionAttemptId,{...i,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:i.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=E(new Date().toISOString()),n=[];for(let r of L.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&E(r.claimExpiresAt)<t||n.push(A(r)));return n.sort(O)},async listOpenProviderOperations(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw RangeError(`limit must be a positive safe integer`);let t=E(e.observedAt),n=[];for(let e of R.values()){let r=L.get(e.executionAttemptId);!r||x(r,e)||e.ownerId!==null&&e.leaseExpiresAt!==null&&E(e.leaseExpiresAt)>t||n.push({attempt:r,operation:e})}return n.sort((e,t)=>O(e.attempt,t.attempt)).slice(0,e.limit)}},$=e=>{let t=j(e.bootstrapTimeoutMs);if(L.has(e.executionAttemptId))throw new l(e.executionAttemptId);let n={executionAttemptId:e.executionAttemptId,executionId:e.executionId,instruction:e.instruction,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,...t,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null,...N},r=H.get(e.executionId),i=r===void 0?void 0:L.get(r);return i!==void 0&&L.set(i.executionAttemptId,{...i,claimable:i.status===`allocated`?!1:i.claimable,operationStartGate:`closed`}),L.set(e.executionAttemptId,n),H.set(e.executionId,e.executionAttemptId),n};return{async createAttempt(e){return $({...e,instruction:y(e.instruction)})},async ensureAttempt(e){let t=_(e),n=U.get(t.executionId),r=n?.get(t.requestKey);if(r!==void 0)return v(t,L.get(r)??null);let i=$(t),a=n??new Map;return a.set(t.requestKey,i.executionAttemptId),U.set(t.executionId,a),{kind:`created`,attempt:structuredClone(i)}},async readAttemptSettlement(e){let t=g(e);return b(t,{attempt:L.get(t.executionAttemptId)??null,activeAttemptId:H.get(t.executionId)??null,outcomeText:B.get(t.executionAttemptId)??null,controlObservation:V.get(t.executionAttemptId)??null},F)},async readBootstrapStartState(e){let t=L.get(e.executionAttemptId);return!t||t.executionId!==e.executionId?null:{settled:t.settlementKind!=null,active:H.get(e.executionId)===e.executionAttemptId,allocated:t.allocationRef!==null,allocationTerminated:z(e.executionAttemptId),operationStartGate:t.operationStartGate,bootstrapDeadlineAt:t.bootstrapDeadlineAt??null}},async beginProvisioning(e){let t=k(e.allocationLifetime),n=L.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(H.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.operationStartGate===`closed`)return{kind:`fenced`};if(n.status!==`pending`)return{kind:`already-provisioning`};L.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:S(e.leaseExpiresAt)};return R.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,completionEvidence:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return R.get(e)??null},async renewProviderOperationClaim(e){let t=K(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=S(e.leaseExpiresAt);return R.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=L.get(e.executionAttemptId),n=R.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(x(t,n))return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&E(n.leaseExpiresAt)>E(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:S(e.leaseExpiresAt)};return R.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:X.parse(e.evidence),n=K(e.claim);return n.kind===`authorized`?(R.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=X.parse(e.evidence),n=K(e.claim);return n.kind===`authorized`?(R.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async completeProviderOperation(e){let t=X.parse(e.evidence),n=L.get(e.claim.executionAttemptId),r=R.get(e.claim.executionAttemptId);return!n||!r?{kind:`not-found`}:r.token!==e.claim.token||r.generation!==e.claim.generation||r.ownerId!==e.claim.ownerId?{kind:`stale`}:x(n,r)?{kind:`already-completed`}:r.completionEvidence===null?(q(r,t),n.settlementKind===null?{kind:`evidence-recorded`}:{kind:`completed`}):{kind:`evidence-recorded`}},async recordAllocation(e){return J(e,!0)},async recordProvisioningAbsent(e){let t=X.parse(e.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?r.settlementKind===null?(L.set(r.executionAttemptId,Z(r,`abandoned`)),q(i,t),{kind:`recorded`}):(q(i,t),{kind:`completed`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=X.parse(e.proof.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n,a=h(r,e);return a===null?r.settlementKind===null?(L.set(r.executionAttemptId,Z(r,`abandoned`)),q(i,t),{kind:`recorded`}):(q(i,t),{kind:`completed`}):a},async recordAllocationTerminated(e){let t=X.parse(e.evidence),n=K(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(R.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=K(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.settlementKind===null?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(L.set(n.executionAttemptId,Z(n,`infrastructure-failure`)),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`resolved`}:{kind:`not-found`}},async registerRuntime(e){let t=L.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=G(t)??m(t,e);if(n!==null)return n;let r=t.runtimeGeneration+1;return L.set(t.executionAttemptId,{...t,runtimeGeneration:r,runtimeIncarnationId:e.runtimeIncarnationId,runtimeReadyAt:null,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null}),{kind:`registered`,runtimeGeneration:r}},async admitOperation(e){let t=L.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};let n=G(t);if(n!==null)return n;let r=o(t,e,t.activeOperationId!==null&&t.activeOperationKey===e.admissionKey&&t.activeOperationAdmittedAt===null?S(new Date().toISOString()):``,t);if(r!==null)return r;let i=crypto.randomUUID(),a=S(new Date().toISOString());return L.set(t.executionAttemptId,{...t,activeOperationId:i,activeOperationKind:e.operationKind,activeOperationKey:e.admissionKey,activeOperationGeneration:t.runtimeGeneration,activeOperationAdmittedAt:a}),{kind:`admitted`,operationId:i,runtimeGeneration:t.runtimeGeneration,admittedAt:a}},async getInstruction(e){let t=L.get(e.executionAttemptId);return t?.executionId===e.executionId?t.instruction:null},async reportOperation(e){let t=P(e.result),n=L.get(e.executionAttemptId);if(n===void 0||n.executionId!==e.executionId)return{kind:`not-found`};let r=p({matchesExecution:!0,settled:n.settlementKind!=null,active:H.get(e.executionId)===e.executionAttemptId,allocated:n.allocationRef!==null&&!z(e.executionAttemptId)},n,n,{...e,result:t});if(r!==null)return r;let i=D([...n.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return L.set(e.executionAttemptId,{...n,preparationReceipts:i,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`accepted`,binding:t.binding}},async completeOperation(t){let n=L.get(t.executionAttemptId);if(n===void 0)return{kind:`not-found`};if(n.settlementKind!=null)return{kind:`resolved`};let r=e(n,t);return r===null?(L.set(n.executionAttemptId,{...n,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:t.operationId}),{kind:`completed`}):r},async markRuntimeReady(e){let t=S(e.readyAt),r=L.get(e.executionAttemptId);if(r===void 0||r.executionId!==e.executionId)return{kind:`not-found`};let i=G(r)??n(r,e);return i===null?(L.set(r.executionAttemptId,{...r,runtimeReadyAt:t}),{kind:`ready`,acceptedAt:t}):i},async getAttemptControlState(e){let t=L.get(e);return t===void 0?null:T(t)},async requestAttemptCancellation(e){let t=i(e),n=L.get(t.executionAttemptId);if(n===void 0||n.executionId!==t.executionId)return{kind:`not-found`};let r=s(W.get(t.executionAttemptId)??null,t,new Date().toISOString());return r.kind===`conflict`?r:(W.set(t.executionAttemptId,{...r.intent}),L.set(t.executionAttemptId,{...n,operationStartGate:`closed`}),r)},async requestCancellation(e){let t=a(e),n={...t,requestKey:Y()},r=new Date().toISOString(),i=[...L].filter(([,e])=>e.executionId===t.executionId).map(([e,t])=>{let i=s(W.get(e)??null,n,r);if(i.kind===`conflict`)throw Error(`Conflicting generated cancellation request key`);return{id:e,attempt:t,intent:i.intent}});for(let{id:e,attempt:t,intent:n}of i)W.set(e,{...n}),L.set(e,{...t,operationStartGate:`closed`})},async readCancellation(e){let t=W.get(e);return t===void 0?null:{...t}},async getActiveAttempt(e,t){return H.get(e)===t?L.get(t)??null:null},canonicalizeOutcome(e){return u(F,e)},decodeOutcome(e){return t(F,e)},async commitOutcome(e){let n=e.result;if(H.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let i=L.get(e.executionAttemptId);if(i===void 0)return{kind:`fenced`};let a=B.get(e.executionAttemptId);if(a!==void 0){let i=t(F,a);return r(a,n.text)?{kind:`duplicate`,outcome:i,text:a,controlObservation:structuredClone(V.get(e.executionAttemptId)??null)}:{kind:`conflict`}}if(i.settlementKind!=null)return{kind:`conflict`};c(i,e.runtimeFence);let o=f(W.get(e.executionAttemptId)??null);return B.set(e.executionAttemptId,n.text),V.set(e.executionAttemptId,o),L.set(e.executionAttemptId,Z(i,`outcome`)),{kind:`accepted`,outcome:t(F,n.text),text:n.text,controlObservation:structuredClone(o)}},async abandonPendingAttempt(e,t){if(H.get(t)!==e)return{kind:`fenced`};let n=L.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`}:(L.set(e,Z(n,`abandoned`)),{kind:`abandoned`}):{kind:`fenced`}},recovery:Q,attempts:L,operations:R,committedOutcomes:B,outcomeControlObservations:V,activeAttempts:H,requestBindings:U,cancellations:W}}export{N as INITIAL_ATTEMPT_CONTROL_STATE,q as TEST_OWNER_ID,H as TEST_PROVIDER_ID,G as TEST_PROVISIONER_INCARNATION_ID,z as allocateTestAttempt,F as beginTestProvisioning,Q as createInMemoryAttemptRepository,U as driveTestAttemptToAllocated,K as leaseAt,I as makeBeginProvisioningInput,B as makeEvidence,J as makeProcessLossProof,L as makeTestAllocationRef,R as makeTestInstruction,W as makeTestWorkflowResult,V as workflowRunResultOutcomeCodec};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { j as OutcomeCodec, x as ExecutionAttemptRepository } from "../../execution-attempt-repository--RVils5-.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
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import{_ as e,
|
|
1
|
+
import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as ee,n as te,o as ne,r as u,s as d,t as f,u as re,v as ie,x as ae,y as oe}from"../../execution-attempt-repository-CWbgCTwA.mjs";import{a as se,i as ce,n as le,o as p,t as ue}from"../../execution-attempt-owner-recovery-D4APLAvt.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as m,isProviderOperationResolved as h}from"../provider-operation.mjs";import{a as g,c as de,d as fe,i as _,l as v,o as pe,p as me,r as y,s as he,t as ge,u as _e}from"../../attempt-record-codec-D2Gb_epJ.mjs";import{z as b}from"zod";import{BoundedRecoveryEvidenceSchema as x,ExecutionAttemptOperationKindSchema as S,ProviderAllocationRefSchema as C,WorkerAllocationLifetimeSchema as w}from"@makaio/framework/contracts";import{getRawSqlExecutor as ve,isSqliteUniqueViolationError as ye,serializeByKey as T,serializeDatabaseOperation as be}from"@makaio/framework/storage/drizzle";import{sql as E}from"drizzle-orm";const xe=[`CREATE TABLE IF NOT EXISTS test_execution_attempt_cancellation (
|
|
2
2
|
execution_attempt_id TEXT PRIMARY KEY,
|
|
3
|
+
request_key TEXT NOT NULL,
|
|
4
|
+
control_revision INTEGER NOT NULL,
|
|
3
5
|
requested_at TEXT NOT NULL,
|
|
4
6
|
reason TEXT
|
|
5
7
|
)`,`CREATE TABLE IF NOT EXISTS test_execution_attempt (
|
|
@@ -14,6 +16,7 @@ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o
|
|
|
14
16
|
allocation_ref TEXT,
|
|
15
17
|
settlement_kind TEXT,
|
|
16
18
|
workflow_result TEXT,
|
|
19
|
+
outcome_control_observation TEXT,
|
|
17
20
|
claimable INTEGER NOT NULL DEFAULT 0,
|
|
18
21
|
claim_expires_at TEXT,
|
|
19
22
|
created_at TEXT NOT NULL,
|
|
@@ -49,54 +52,60 @@ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o
|
|
|
49
52
|
failure_count INTEGER NOT NULL DEFAULT 0,
|
|
50
53
|
last_failure TEXT,
|
|
51
54
|
completion_evidence TEXT
|
|
52
|
-
)`];function
|
|
55
|
+
)`];function D(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 O(e,t){return e===null?null:t(JSON.parse(e))}const k=b.object({requestKey:b.string().min(1),controlRevision:b.number().int().positive(),requestedAt:b.string().datetime(),reason:b.string().optional()}),A=b.object({controlRevision:b.number().int().nonnegative(),cancellation:k.nullable()});function j(e){if(e===null)return null;let t=A.parse(JSON.parse(e));if(t.controlRevision!==(t.cancellation?.controlRevision??0))throw Error(`Stored outcome control revision does not match its cancellation receipt`);return t}function M(e){return{runtimeGeneration:e.runtime_generation,runtimeIncarnationId:e.runtime_incarnation_id,runtimeReadyAt:e.runtime_ready_at,operationStartGate:D(f,e.operation_start_gate,`operation_start_gate`),activeOperationId:e.active_operation_id,activeOperationKind:e.active_operation_kind===null?null:S.parse(e.active_operation_kind),activeOperationKey:e.active_operation_key,activeOperationGeneration:e.active_operation_generation,activeOperationAdmittedAt:e.active_operation_admitted_at,lastCompletedOperationId:e.last_completed_operation_id}}function N(e){return{...M(e),executionAttemptId:e.execution_attempt_id,executionId:e.execution_id,instruction:p(JSON.parse(e.instruction)),preparationReceipts:v(JSON.parse(e.preparation_receipts)),status:D(c,e.status,`status`),allocationRef:O(e.allocation_ref,e=>C.parse(e)),createdAt:e.created_at,bootstrapDeadlineAt:e.bootstrap_deadline_at,providerId:e.provider_id,allocationLifetime:e.allocation_lifetime===null?null:w.parse(e.allocation_lifetime),provisionerIncarnationId:e.provisioner_incarnation_id,settlementKind:e.settlement_kind===null?null:D(u,e.settlement_kind,`settlement_kind`),claimable:e.claimable!==0,claimExpiresAt:e.claim_expires_at}}function P(e){return{executionAttemptId:e.execution_attempt_id,generation:e.generation,ownerId:e.owner_id,token:e.token,leaseExpiresAt:e.lease_expires_at,obligation:D(m,e.obligation,`obligation`),failureCount:e.failure_count,lastFailure:O(e.last_failure,e=>x.parse(e)),completionEvidence:O(e.completion_evidence,e=>x.parse(e))}}const F=new Map,I=new Map;function L(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`)||L(t.cause)}function R(e){if(typeof e!=`object`||!e)return!1;let t=e;return(typeof t.message==`string`?t.message:``).includes(`no transaction is active`)||R(t.cause)}async function z(){await new Promise(e=>setImmediate(e))}async function Se(e){for(let t=0;;t+=1)try{await e.run(E.raw(`COMMIT`));return}catch(e){if(!L(e)||t===100)throw e;await z()}}async function Ce(e,t){return T(F,e,t)}async function we(e,t){return T(I,e,t)}const B=new WeakMap;async function Te(e,t){let n=(await t.all(E.raw(`PRAGMA database_list`))).find(e=>e.name===`main`)?.file??null;if(n!==null&&n!==``)return`file:${n}`;let r=B.get(e);if(r!==void 0)return r;let i=`connection:${crypto.randomUUID()}`;return B.set(e,i),i}async function V(e,t){let n=await e();if(typeof n!=`function`)return n;if((await n()).rowsAffected>0)return typeof t==`function`?t():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 H(e){return E`EXISTS (SELECT 1 FROM test_provider_operation
|
|
53
56
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
54
57
|
AND generation = ${e.generation}
|
|
55
58
|
AND owner_id = ${e.ownerId}
|
|
56
|
-
AND token = ${e.token})`}function U(e){return
|
|
59
|
+
AND token = ${e.token})`}function U(e){return E`(completion_evidence IS NULL
|
|
57
60
|
OR NOT EXISTS (SELECT 1 FROM test_execution_attempt
|
|
58
61
|
WHERE execution_attempt_id = ${e}
|
|
59
|
-
AND settlement_kind IS NOT NULL))`}function W(e){return
|
|
62
|
+
AND settlement_kind IS NOT NULL))`}function W(e){return E`EXISTS (SELECT 1 FROM test_provider_operation
|
|
60
63
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
61
64
|
AND generation = ${e.generation}
|
|
62
65
|
AND owner_id = ${e.ownerId}
|
|
63
66
|
AND token = ${e.token}
|
|
64
|
-
AND ${U(e.executionAttemptId)})`}function G(e){return
|
|
67
|
+
AND ${U(e.executionAttemptId)})`}function G(e){return E`EXISTS (SELECT 1 FROM test_provider_operation
|
|
65
68
|
WHERE execution_attempt_id = ${e}
|
|
66
|
-
AND obligation = ${`terminal-convergence`})`}function K(){return
|
|
69
|
+
AND obligation = ${`terminal-convergence`})`}function K(){return E`EXISTS (SELECT 1 FROM test_active_execution_attempt
|
|
67
70
|
WHERE execution_id = test_execution_attempt.execution_id
|
|
68
|
-
AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function q(
|
|
71
|
+
AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function q(c,u){let b=ve(c);await b.run(E.raw(`PRAGMA busy_timeout = 0`));let S=await Te(c,b);await Ce(S,async()=>{for(let e of xe)await b.run(E.raw(e));let e=await b.all(E.raw(`PRAGMA table_info(test_execution_attempt)`));e.some(e=>e.name===`bootstrap_deadline_at`)||await b.run(E.raw(`ALTER TABLE test_execution_attempt ADD COLUMN bootstrap_deadline_at TEXT`)),e.some(e=>e.name===`outcome_control_observation`)||await b.run(E.raw(`ALTER TABLE test_execution_attempt ADD COLUMN outcome_control_observation TEXT`));let t=await b.all(E.raw(`PRAGMA table_info(test_execution_attempt_cancellation)`));t.some(e=>e.name===`request_key`)||await b.run(E.raw(`ALTER TABLE test_execution_attempt_cancellation ADD COLUMN request_key TEXT`)),t.some(e=>e.name===`control_revision`)||await b.run(E.raw(`ALTER TABLE test_execution_attempt_cancellation ADD COLUMN control_revision INTEGER NOT NULL DEFAULT 1`));let n=await b.all(E`SELECT execution_attempt_id FROM test_execution_attempt_cancellation WHERE request_key IS NULL`);for(let e of n)await b.run(E`UPDATE test_execution_attempt_cancellation SET request_key = ${crypto.randomUUID()}
|
|
72
|
+
WHERE execution_attempt_id = ${e.execution_attempt_id} AND request_key IS NULL`);(await b.all(E.raw(`PRAGMA table_info(test_provider_operation)`))).some(e=>e.name===`completion_evidence`)||await b.run(E.raw(`ALTER TABLE test_provider_operation ADD COLUMN completion_evidence TEXT`))});let C,w=async e=>be(c,()=>we(S,async()=>{if(C!==void 0)throw Error(`This repository was retired by a failed transaction rollback`,{cause:C});for(let t=0;;t+=1)try{return await b.withSession(async t=>{let n=!1;try{await t.run(E.raw(`BEGIN IMMEDIATE`)),n=!0;let r=await e(t);return await Se(t),r}catch(e){try{await t.run(E.raw(`ROLLBACK`))}catch(t){throw!n&&R(t)?e:(C=AggregateError([e,t],`Transaction rollback failed`),C)}throw e}})}catch(e){if(!L(e)||t===100)throw e;await z()}})),T=async(e,t)=>{let[n]=await e.all(E`SELECT request_key, control_revision, requested_at, reason
|
|
73
|
+
FROM test_execution_attempt_cancellation WHERE execution_attempt_id = ${t}`);return n===void 0?null:k.parse({requestKey:n.request_key,controlRevision:n.control_revision,requestedAt:n.requested_at,...n.reason===null?{}:{reason:n.reason}})},O=async(e,t,n)=>{await e.run(E`INSERT INTO test_execution_attempt_cancellation
|
|
74
|
+
(execution_attempt_id, request_key, control_revision, requested_at, reason)
|
|
75
|
+
VALUES (${t}, ${n.requestKey}, ${n.controlRevision},
|
|
76
|
+
${n.requestedAt}, ${n.reason??null})`),await e.run(E`UPDATE test_execution_attempt SET operation_start_gate = 'closed'
|
|
77
|
+
WHERE execution_attempt_id = ${t}`)},A=async(e,t)=>(await e.all(E`SELECT * FROM test_execution_attempt WHERE execution_attempt_id = ${t}`))[0],F=async(e,t)=>(await e.all(E`SELECT * FROM test_provider_operation WHERE execution_attempt_id = ${t}`))[0],I=async(e,t)=>(await F(e,t))?.obligation===`terminal-convergence`,B=async(e,t)=>(await e.all(E`SELECT execution_attempt_id FROM test_active_execution_attempt WHERE execution_id = ${t}`))[0]?.execution_attempt_id??null,q=async(e,t)=>{let n=t.settlement_kind!==null,r=!n&&await B(e,t.execution_id)===t.execution_attempt_id;return s({matchesExecution:!0,settled:n,active:r,allocated:r&&t.allocation_ref!==null&&!await I(e,t.execution_attempt_id)})},J=async(e,t)=>{let n=await A(e,t.executionAttemptId),r=await F(e,t.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};let i=N(n);return h(i,P(r))?{kind:`resolved`,attempt:i}: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}},Y=async(e,t)=>{let n=await J(e,t);return n.kind===`authorized`?void 0:{kind:n.kind}},X=async(e,t,n,r)=>{let i=await e.run(E`UPDATE test_execution_attempt
|
|
69
78
|
SET status = ${`settled`}, settlement_kind = ${n}, claimable = ${0},
|
|
70
79
|
operation_start_gate = ${`closed`}
|
|
71
80
|
WHERE execution_attempt_id = ${t}
|
|
72
81
|
AND settlement_kind IS NULL
|
|
73
|
-
AND ${r}`);return i.rowsAffected,i},Z=async(e,t,n,r,i,a)=>{if(!a){let a=await X(e,t,`abandoned`,r);if(a.rowsAffected===0)return a;if((await e.run(
|
|
82
|
+
AND ${r}`);return i.rowsAffected,i},Z=async(e,t,n,r,i,a)=>{if(!a){let a=await X(e,t,`abandoned`,r);if(a.rowsAffected===0)return a;if((await e.run(E`UPDATE test_provider_operation
|
|
74
83
|
SET completion_evidence = ${JSON.stringify(i)}
|
|
75
84
|
WHERE execution_attempt_id = ${t}
|
|
76
85
|
AND ${H(n)}
|
|
77
|
-
AND completion_evidence IS NULL`)).rowsAffected===0&&(await F(e,t))?.completion_evidence===null)throw Error(`Pre-allocation settlement succeeded without provider completion evidence`);return a}return e.run(
|
|
86
|
+
AND completion_evidence IS NULL`)).rowsAffected===0&&(await F(e,t))?.completion_evidence===null)throw Error(`Pre-allocation settlement succeeded without provider completion evidence`);return a}return e.run(E`UPDATE test_provider_operation
|
|
78
87
|
SET completion_evidence = ${JSON.stringify(i)}
|
|
79
88
|
WHERE execution_attempt_id = ${t}
|
|
80
89
|
AND ${H(n)}
|
|
81
|
-
AND completion_evidence IS NULL`)},Q=(e,t)=>{let n=
|
|
90
|
+
AND completion_evidence IS NULL`)},Q=(e,t)=>{let n=he(e.allocationRef),r=t?E`CASE WHEN settlement_kind IS NULL AND ${K()} THEN 1 ELSE 0 END`:E`${0}`;return w(t=>V(async()=>{let i=await J(t,e.claim);if(i.kind!==`not-found`&&fe(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.allocationRef===null?async()=>{let i=await t.run(E`UPDATE test_execution_attempt
|
|
82
91
|
SET status = CASE WHEN settlement_kind IS NULL THEN ${`allocated`} ELSE status END,
|
|
83
92
|
allocation_ref = ${JSON.stringify(n)},
|
|
84
93
|
claimable = ${r}
|
|
85
94
|
WHERE execution_attempt_id = ${a.executionAttemptId}
|
|
86
95
|
AND allocation_ref IS NULL
|
|
87
|
-
AND ${W(e.claim)}`);return i.rowsAffected===0||await t.run(
|
|
88
|
-
WHERE execution_attempt_id = ${a.executionAttemptId}`),i}:
|
|
96
|
+
AND ${W(e.claim)}`);return i.rowsAffected===0||await t.run(E`UPDATE test_provider_operation SET obligation = ${`allocation-control`}
|
|
97
|
+
WHERE execution_attempt_id = ${a.executionAttemptId}`),i}:d(a.allocationRef,n)?{kind:`duplicate`,allocationRef:a.allocationRef}:{kind:`conflict`,allocationRef:a.allocationRef}},{kind:`recorded`}))},Ee={async getAttemptWithAllocation(e){return w(async t=>{let n=await A(t,e);return n===void 0?null:N(n)})},async recordDiscoveredAllocation(e){return Q(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=de(e);return w(r=>V(async()=>{let i=await J(r,e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a,attemptRow:o}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:d(a.allocationRef,t)?()=>r.run(E`UPDATE test_execution_attempt SET allocation_ref = ${JSON.stringify(n)}
|
|
89
98
|
WHERE execution_attempt_id = ${a.executionAttemptId}
|
|
90
99
|
AND execution_id = ${e.executionId}
|
|
91
100
|
AND allocation_ref = ${o.allocation_ref}
|
|
92
|
-
AND ${W(e.claim)}`):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},{kind:`evolved`}))},async getRecoverableAttempts(e){return
|
|
101
|
+
AND ${W(e.claim)}`):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},{kind:`evolved`}))},async getRecoverableAttempts(e){return w(async t=>{let n=new Date().toISOString();return(await t.all(E`SELECT * FROM test_execution_attempt
|
|
93
102
|
WHERE execution_id = ${e}
|
|
94
103
|
AND status = ${`allocated`}
|
|
95
104
|
AND settlement_kind IS NULL
|
|
96
105
|
AND allocation_ref IS NOT NULL
|
|
97
106
|
AND claimable = ${1}
|
|
98
107
|
AND (claim_expires_at IS NULL OR claim_expires_at >= ${n})
|
|
99
|
-
ORDER BY created_at ASC, execution_attempt_id ASC`)).map(e=>
|
|
108
|
+
ORDER BY created_at ASC, execution_attempt_id ASC`)).map(e=>me(N(e)))})},async listOpenProviderOperations(e){let t=g(e.observedAt);if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw RangeError(`Provider-operation recovery limit must be a positive safe integer`);return w(async n=>(await n.all(E`SELECT attempt.*, operation.generation, operation.owner_id, operation.token, operation.lease_expires_at,
|
|
100
109
|
operation.obligation, operation.failure_count, operation.last_failure, operation.completion_evidence
|
|
101
110
|
FROM test_execution_attempt AS attempt
|
|
102
111
|
INNER JOIN test_provider_operation AS operation
|
|
@@ -108,27 +117,27 @@ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o
|
|
|
108
117
|
OR operation.lease_expires_at <= ${t}
|
|
109
118
|
)
|
|
110
119
|
ORDER BY attempt.created_at ASC, attempt.execution_attempt_id ASC
|
|
111
|
-
LIMIT ${e.limit}`)).map(e=>({attempt:N(e),operation:P(e)})))}},$=async(e,t,n)=>{let{instruction:r}=t,{createdAt:i,bootstrapDeadlineAt:a}=n;try{await e.run(
|
|
120
|
+
LIMIT ${e.limit}`)).map(e=>({attempt:N(e),operation:P(e)})))}},$=async(e,t,n)=>{let{instruction:r}=t,{createdAt:i,bootstrapDeadlineAt:a}=n;try{await e.run(E`INSERT INTO test_execution_attempt
|
|
112
121
|
(execution_attempt_id, execution_id, instruction, status, claimable, created_at, bootstrap_deadline_at)
|
|
113
|
-
VALUES (${t.executionAttemptId}, ${t.executionId}, ${JSON.stringify(r)}, ${`pending`}, ${0}, ${i}, ${a})`)}catch(e){throw
|
|
122
|
+
VALUES (${t.executionAttemptId}, ${t.executionId}, ${JSON.stringify(r)}, ${`pending`}, ${0}, ${i}, ${a})`)}catch(e){throw ye(e)?new te(t.executionAttemptId,{cause:e}):e}return await e.run(E`UPDATE test_execution_attempt
|
|
114
123
|
SET claimable = ${0}
|
|
115
124
|
WHERE execution_attempt_id = (
|
|
116
125
|
SELECT execution_attempt_id
|
|
117
126
|
FROM test_active_execution_attempt
|
|
118
127
|
WHERE execution_id = ${t.executionId}
|
|
119
128
|
)
|
|
120
|
-
AND status = ${`allocated`}`),await e.run(
|
|
129
|
+
AND status = ${`allocated`}`),await e.run(E`UPDATE test_execution_attempt
|
|
121
130
|
SET operation_start_gate = ${`closed`}
|
|
122
131
|
WHERE execution_attempt_id = (
|
|
123
132
|
SELECT execution_attempt_id
|
|
124
133
|
FROM test_active_execution_attempt
|
|
125
134
|
WHERE execution_id = ${t.executionId}
|
|
126
|
-
)`),await e.run(
|
|
135
|
+
)`),await e.run(E`INSERT INTO test_active_execution_attempt (execution_id, execution_attempt_id)
|
|
127
136
|
VALUES (${t.executionId}, ${t.executionAttemptId})
|
|
128
137
|
ON CONFLICT(execution_id)
|
|
129
|
-
DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{...
|
|
130
|
-
WHERE execution_id = ${t.executionId} AND request_key = ${t.requestKey}`))[0];if(n!==void 0){let r=await
|
|
131
|
-
VALUES (${t.executionId}, ${t.requestKey}, ${r.executionAttemptId})`),{kind:`created`,attempt:structuredClone(r)}})},async readAttemptSettlement(e){let t=
|
|
138
|
+
DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{...ge,executionAttemptId:t.executionAttemptId,executionId:t.executionId,instruction:r,preparationReceipts:Object.freeze([]),status:`pending`,allocationRef:null,createdAt:i,bootstrapDeadlineAt:a,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null}};return{async createAttempt(e){let t={...e,instruction:p(e.instruction)},n=y(e.bootstrapTimeoutMs);return w(e=>$(e,t,n))},async ensureAttempt(e){let t=ce(e);return w(async e=>{let n=(await e.all(E`SELECT execution_attempt_id FROM test_execution_attempt_request
|
|
139
|
+
WHERE execution_id = ${t.executionId} AND request_key = ${t.requestKey}`))[0];if(n!==void 0){let r=await A(e,n.execution_attempt_id);return le(t,r===void 0?null:N(r))}let r=await $(e,t,y(t.bootstrapTimeoutMs));return await e.run(E`INSERT INTO test_execution_attempt_request (execution_id, request_key, execution_attempt_id)
|
|
140
|
+
VALUES (${t.executionId}, ${t.requestKey}, ${r.executionAttemptId})`),{kind:`created`,attempt:structuredClone(r)}})},async readAttemptSettlement(e){let t=se(e);return w(async e=>{let n=await A(e,t.executionAttemptId);return n===void 0||n.execution_id!==t.executionId?{kind:`not-found`}:ue(t,{attempt:N(n),activeAttemptId:await B(e,t.executionId),outcomeText:n.workflow_result,controlObservation:j(n.outcome_control_observation)},u)})},async readBootstrapStartState(e){return w(async t=>{let n=await A(t,e.executionAttemptId);return n===void 0||n.execution_id!==e.executionId?null:{settled:n.settlement_kind!==null,active:await B(t,e.executionId)===e.executionAttemptId,allocated:n.allocation_ref!==null,allocationTerminated:await I(t,e.executionAttemptId),operationStartGate:D(f,n.operation_start_gate,`operation_start_gate`),bootstrapDeadlineAt:n.bootstrap_deadline_at}})},async beginProvisioning(e){let t=pe(e.allocationLifetime),n={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:g(e.leaseExpiresAt)};return w(r=>V(async()=>{let i=await A(r,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=N(i);return await B(r,e.executionId)===e.executionAttemptId?a.settlementKind==null?a.allocationRef===null?a.operationStartGate===`closed`?{kind:`fenced`}:a.status===`pending`?async()=>{let i=await r.run(E`UPDATE test_execution_attempt
|
|
132
141
|
SET status = ${`provisioning`},
|
|
133
142
|
provider_id = ${e.providerId},
|
|
134
143
|
allocation_lifetime = ${t},
|
|
@@ -139,62 +148,62 @@ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o
|
|
|
139
148
|
AND operation_start_gate = 'open'
|
|
140
149
|
AND allocation_ref IS NULL
|
|
141
150
|
AND settlement_kind IS NULL
|
|
142
|
-
AND ${K()}`);return i.rowsAffected===0||await r.run(
|
|
151
|
+
AND ${K()}`);return i.rowsAffected===0||await r.run(E`INSERT INTO test_provider_operation
|
|
143
152
|
(execution_attempt_id, generation, owner_id, token, lease_expires_at, obligation, failure_count)
|
|
144
153
|
VALUES (${e.executionAttemptId}, ${n.generation}, ${n.ownerId}, ${n.token},
|
|
145
|
-
${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
|
|
154
|
+
${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 w(async t=>{let n=await F(t,e);return n===void 0?null:P(n)})},async renewProviderOperationClaim(e){let t=g(e.leaseExpiresAt);return w(n=>V(async()=>await Y(n,e.claim)??(()=>n.run(E`UPDATE test_provider_operation SET lease_expires_at = ${t}
|
|
146
155
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
147
|
-
AND ${W(e.claim)}`)),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:t}}))},async takeOverProviderOperation(e){return
|
|
156
|
+
AND ${W(e.claim)}`)),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:t}}))},async takeOverProviderOperation(e){return w(async t=>{let n=await A(t,e.executionAttemptId),r=await F(t,e.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};if(h(N(n),P(r)))return{kind:`resolved`};let i=g(e.observedAt);if(r.owner_id!==null&&r.lease_expires_at!==null&&_(r.lease_expires_at)>_(i))return{kind:`stale`};let a={executionAttemptId:e.executionAttemptId,generation:r.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:g(e.leaseExpiresAt)},{rowsAffected:o}=await t.run(E`UPDATE test_provider_operation
|
|
148
157
|
SET generation = ${a.generation}, owner_id = ${a.ownerId}, token = ${a.token},
|
|
149
158
|
lease_expires_at = ${a.leaseExpiresAt}
|
|
150
159
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
151
160
|
AND generation = ${r.generation}
|
|
152
|
-
AND ${U(e.executionAttemptId)}`);if(o===0){let n=await
|
|
161
|
+
AND ${U(e.executionAttemptId)}`);if(o===0){let n=await A(t,e.executionAttemptId),r=await F(t,e.executionAttemptId);return n!==void 0&&r!==void 0&&h(N(n),P(r))?{kind:`resolved`}:{kind:`stale`}}return{kind:`claimed`,claim:a}})},async handoffProviderOperation(e){let t=e.evidence===void 0?null:x.parse(e.evidence);return w(n=>V(async()=>await Y(n,e.claim)??(()=>n.run(t===null?E`UPDATE test_provider_operation
|
|
153
162
|
SET owner_id = NULL, token = NULL, lease_expires_at = NULL
|
|
154
163
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
155
|
-
AND ${W(e.claim)}`:
|
|
164
|
+
AND ${W(e.claim)}`:E`UPDATE test_provider_operation
|
|
156
165
|
SET owner_id = NULL, token = NULL, lease_expires_at = NULL,
|
|
157
166
|
last_failure = ${JSON.stringify(t)}
|
|
158
167
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
159
|
-
AND ${W(e.claim)}`)),{kind:`recorded`}))},async recordProviderOperationUncertainty(e){let t=
|
|
168
|
+
AND ${W(e.claim)}`)),{kind:`recorded`}))},async recordProviderOperationUncertainty(e){let t=x.parse(e.evidence);return w(n=>V(async()=>await Y(n,e.claim)??(()=>n.run(E`UPDATE test_provider_operation
|
|
160
169
|
SET failure_count = failure_count + 1, last_failure = ${JSON.stringify(t)}
|
|
161
170
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
162
|
-
AND ${W(e.claim)}`)),{kind:`recorded`}))},async completeProviderOperation(e){let t=
|
|
171
|
+
AND ${W(e.claim)}`)),{kind:`recorded`}))},async completeProviderOperation(e){let t=x.parse(e.evidence);return w(async n=>{let r=await A(n,e.claim.executionAttemptId),i=await F(n,e.claim.executionAttemptId);if(r===void 0||i===void 0)return{kind:`not-found`};if(!(i.generation===e.claim.generation&&i.owner_id===e.claim.ownerId&&i.token===e.claim.token))return{kind:`stale`};if(h(N(r),P(i)))return{kind:`already-completed`};if(i.completion_evidence!==null)return{kind:`evidence-recorded`};if((await n.run(E`UPDATE test_provider_operation
|
|
163
172
|
SET completion_evidence = ${JSON.stringify(t)}
|
|
164
173
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
165
174
|
AND ${H(e.claim)}
|
|
166
|
-
AND completion_evidence IS NULL`)).rowsAffected>0){let t=await
|
|
175
|
+
AND completion_evidence IS NULL`)).rowsAffected>0){let t=await A(n,e.claim.executionAttemptId);return t===void 0?{kind:`not-found`}:t.settlement_kind===null?{kind:`evidence-recorded`}:{kind:`completed`}}let a=await A(n,e.claim.executionAttemptId),o=await F(n,e.claim.executionAttemptId);return a===void 0||o===void 0?{kind:`not-found`}:o.generation===e.claim.generation&&o.owner_id===e.claim.ownerId&&o.token===e.claim.token?h(N(a),P(o))?{kind:`already-completed`}:o.completion_evidence===null?{kind:`stale`}:{kind:`evidence-recorded`}:{kind:`stale`}})},async recordAllocation(e){return Q(e,!0)},async recordProvisioningAbsent(e){let t=x.parse(e.evidence),n=!1;return w(r=>V(async()=>{let i=await J(r,e.claim);if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.executionId===e.executionId?a.allocationRef===null?(n=a.settlementKind!==null,()=>Z(r,a.executionAttemptId,e.claim,E`execution_id = ${e.executionId}
|
|
167
176
|
AND allocation_ref IS NULL
|
|
168
|
-
AND ${H(e.claim)}`,t,n)):{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`not-found`}},()=>n?{kind:`completed`}:{kind:`recorded`}))},async recordProvisionerIncarnationLost(e){let t=
|
|
177
|
+
AND ${H(e.claim)}`,t,n)):{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`not-found`}},()=>n?{kind:`completed`}:{kind:`recorded`}))},async recordProvisionerIncarnationLost(e){let t=x.parse(e.proof.evidence),n=!1;return w(r=>V(async()=>{let i=await J(r,e.claim);if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i,o=oe(a,e);return o===null?(n=a.settlementKind!==null,()=>Z(r,a.executionAttemptId,e.claim,E`execution_id = ${e.executionId}
|
|
169
178
|
AND allocation_ref IS NULL
|
|
170
179
|
AND allocation_lifetime = ${`provisioner-process-bound`}
|
|
171
180
|
AND provisioner_incarnation_id = ${e.proof.provisionerIncarnationId}
|
|
172
|
-
AND ${H(e.claim)}`,t,n)):
|
|
181
|
+
AND ${H(e.claim)}`,t,n)):o},()=>n?{kind:`completed`}:{kind:`recorded`}))},async recordAllocationTerminated(e){let t=x.parse(e.evidence);return w(n=>V(async()=>{let r=await J(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.allocationRef===null?{kind:`not-allocated`}:()=>n.run(E`UPDATE test_provider_operation
|
|
173
182
|
SET obligation = ${`terminal-convergence`}, last_failure = ${JSON.stringify(t)}
|
|
174
183
|
WHERE execution_attempt_id = ${i.executionAttemptId}
|
|
175
184
|
AND ${W(e.claim)}
|
|
176
185
|
AND EXISTS (SELECT 1 FROM test_execution_attempt
|
|
177
186
|
WHERE execution_attempt_id = ${i.executionAttemptId}
|
|
178
|
-
AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return
|
|
187
|
+
AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return w(t=>V(async()=>{let n=await J(t,e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.settlementKind===null?r.allocationRef===null?{kind:`not-allocated`}:D(m,i.obligation,`obligation`)===`terminal-convergence`?()=>X(t,r.executionAttemptId,`infrastructure-failure`,E`execution_id = ${e.executionId}
|
|
179
188
|
AND allocation_ref IS NOT NULL
|
|
180
189
|
AND ${G(r.executionAttemptId)}
|
|
181
|
-
AND ${H(e.claim)}`):{kind:`not-terminated`}:{kind:`resolved`}:{kind:`not-found`}},{kind:`recorded`}))},async registerRuntime(
|
|
182
|
-
SET runtime_generation = ${
|
|
183
|
-
runtime_incarnation_id = ${
|
|
190
|
+
AND ${H(e.claim)}`):{kind:`not-terminated`}:{kind:`resolved`}:{kind:`not-found`}},{kind:`recorded`}))},async registerRuntime(e){return w(async t=>{let n=0,r=await V(async()=>{let r=await A(t,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};let i=await q(t,r);if(i!==null)return i;let a=M(r),o=ae(a,e);return o===null?(n=a.runtimeGeneration+1,()=>t.run(E`UPDATE test_execution_attempt
|
|
191
|
+
SET runtime_generation = ${n},
|
|
192
|
+
runtime_incarnation_id = ${e.runtimeIncarnationId},
|
|
184
193
|
runtime_ready_at = NULL,
|
|
185
194
|
active_operation_id = NULL,
|
|
186
195
|
active_operation_kind = NULL,
|
|
187
196
|
active_operation_key = NULL,
|
|
188
197
|
active_operation_generation = NULL,
|
|
189
198
|
active_operation_admitted_at = NULL
|
|
190
|
-
WHERE execution_attempt_id = ${
|
|
191
|
-
AND execution_id = ${
|
|
192
|
-
AND runtime_generation = ${
|
|
199
|
+
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
200
|
+
AND execution_id = ${e.executionId}
|
|
201
|
+
AND runtime_generation = ${a.runtimeGeneration}
|
|
193
202
|
AND settlement_kind IS NULL
|
|
194
203
|
AND (active_operation_id IS NULL OR active_operation_kind = ${`runtime-probe`})
|
|
195
204
|
AND allocation_ref IS NOT NULL
|
|
196
|
-
AND NOT ${G(
|
|
197
|
-
AND ${K()}`)):
|
|
205
|
+
AND NOT ${G(e.executionAttemptId)}
|
|
206
|
+
AND ${K()}`)):o},{kind:`applied`});return r.kind===`applied`?{kind:`registered`,runtimeGeneration:n}:r})},async admitOperation(e){let t=crypto.randomUUID(),n=g(new Date().toISOString()),r=e.operationKind===`runtime-probe`?E`1 = 1`:E`runtime_ready_at IS NOT NULL`;return w(i=>V(async()=>{let a=await A(i,e.executionAttemptId);if(a===void 0||a.execution_id!==e.executionId)return{kind:`not-found`};let s=await q(i,a);if(s!==null)return s;let c=o(M(a),e,n,N(a));return c===null?()=>i.run(E`UPDATE test_execution_attempt
|
|
198
207
|
SET active_operation_id = ${t},
|
|
199
208
|
active_operation_kind = ${e.operationKind},
|
|
200
209
|
active_operation_key = ${e.admissionKey},
|
|
@@ -205,13 +214,13 @@ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o
|
|
|
205
214
|
AND active_operation_id IS NULL
|
|
206
215
|
AND operation_start_gate = ${`open`}
|
|
207
216
|
AND runtime_generation = ${e.runtimeGeneration}
|
|
208
|
-
AND instruction = ${
|
|
209
|
-
AND preparation_receipts = ${
|
|
217
|
+
AND instruction = ${a.instruction}
|
|
218
|
+
AND preparation_receipts = ${a.preparation_receipts}
|
|
210
219
|
AND settlement_kind IS NULL
|
|
211
220
|
AND allocation_ref IS NOT NULL
|
|
212
221
|
AND NOT ${G(e.executionAttemptId)}
|
|
213
|
-
AND ${
|
|
214
|
-
AND ${K()}`):c},{kind:`admitted`,operationId:t,runtimeGeneration:e.runtimeGeneration,admittedAt:n}))},async getInstruction(e){return
|
|
222
|
+
AND ${r}
|
|
223
|
+
AND ${K()}`):c},{kind:`admitted`,operationId:t,runtimeGeneration:e.runtimeGeneration,admittedAt:n}))},async getInstruction(e){return w(async t=>{let n=await A(t,e.executionAttemptId);return n?.execution_id===e.executionId?p(JSON.parse(n.instruction)):null})},async reportOperation(e){let t=_e(e.result);return w(n=>V(async()=>{let r=await A(n,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};let i=N(r),a=ie({matchesExecution:!0,settled:r.settlement_kind!==null,active:await B(n,e.executionId)===e.executionAttemptId,allocated:r.allocation_ref!==null&&!await I(n,e.executionAttemptId)},i,i,{...e,result:t});if(a!==null)return a;let o=v([...i.preparationReceipts,{operationId:e.operationId,runtimeGeneration:e.runtimeGeneration,result:t}]);return()=>n.run(E`UPDATE test_execution_attempt
|
|
215
224
|
SET preparation_receipts = ${JSON.stringify(o)},
|
|
216
225
|
active_operation_id = NULL,
|
|
217
226
|
active_operation_kind = NULL,
|
|
@@ -230,18 +239,18 @@ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o
|
|
|
230
239
|
AND preparation_receipts = ${r.preparation_receipts}
|
|
231
240
|
AND allocation_ref IS NOT NULL
|
|
232
241
|
AND NOT ${G(e.executionAttemptId)}
|
|
233
|
-
AND ${K()}`)},{kind:`accepted`,binding:t.binding}))},async completeOperation(
|
|
242
|
+
AND ${K()}`)},{kind:`accepted`,binding:t.binding}))},async completeOperation(t){return w(n=>V(async()=>{let r=await A(n,t.executionAttemptId);if(r===void 0)return{kind:`not-found`};if(r.settlement_kind!==null)return{kind:`resolved`};let i=e(M(r),t);return i===null?()=>n.run(E`UPDATE test_execution_attempt
|
|
234
243
|
SET active_operation_id = NULL,
|
|
235
244
|
active_operation_kind = NULL,
|
|
236
245
|
active_operation_key = NULL,
|
|
237
246
|
active_operation_generation = NULL,
|
|
238
247
|
active_operation_admitted_at = NULL,
|
|
239
|
-
last_completed_operation_id = ${
|
|
240
|
-
WHERE execution_attempt_id = ${
|
|
248
|
+
last_completed_operation_id = ${t.operationId}
|
|
249
|
+
WHERE execution_attempt_id = ${t.executionAttemptId}
|
|
241
250
|
AND settlement_kind IS NULL
|
|
242
|
-
AND active_operation_id = ${
|
|
251
|
+
AND active_operation_id = ${t.operationId}
|
|
243
252
|
AND active_operation_kind IN (${`runtime-probe`}, ${`workflow-run`})
|
|
244
|
-
AND active_operation_generation = ${
|
|
253
|
+
AND active_operation_generation = ${t.runtimeGeneration}`):i},{kind:`completed`}))},async markRuntimeReady(e){let t=g(e.readyAt);return w(r=>V(async()=>{let i=await A(r,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=await q(r,i);if(a!==null)return a;let o=n(M(i),e);return o===null?()=>r.run(E`UPDATE test_execution_attempt SET runtime_ready_at = ${t}
|
|
245
254
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
246
255
|
AND execution_id = ${e.executionId}
|
|
247
256
|
AND settlement_kind IS NULL
|
|
@@ -250,24 +259,20 @@ import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as ee,o
|
|
|
250
259
|
AND active_operation_id IS NULL
|
|
251
260
|
AND allocation_ref IS NOT NULL
|
|
252
261
|
AND NOT ${G(e.executionAttemptId)}
|
|
253
|
-
AND ${K()}`):o},{kind:`ready`,acceptedAt:t}))},async getAttemptControlState(e){return
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
WHERE execution_attempt_id = ${e}`);return n===void 0?null:{requestedAt:n.requested_at,...n.reason===null?{}:{reason:n.reason}}})},async getActiveAttempt(e,t){return D(async n=>{if(await B(n,e)!==t)return null;let r=await j(n,t);return r===void 0?null:N(r)})},canonicalizeOutcome(e){return t(u,e)},decodeOutcome(e){return d(u,e)},async commitOutcome(e){let t=e.result,n=e.runtimeFence,r=n===void 0?k`1 = 1`:k`
|
|
259
|
-
runtime_generation = ${n.runtimeGeneration}
|
|
260
|
-
AND ${n.operationId===null?k`active_operation_id IS NULL`:k`active_operation_id = ${n.operationId}
|
|
261
|
-
AND active_operation_generation = ${n.runtimeGeneration}`}`;return D(i=>V(async()=>{if(await B(i,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let a=await j(i,e.executionAttemptId);if(a===void 0)return{kind:`fenced`};let o=a.workflow_result;if(o!==null){let e=d(u,o);return p(o,t.text)?{kind:`duplicate`,outcome:e,text:o}:{kind:`conflict`}}return a.settlement_kind===null?(n!==void 0&&te(M(a),n),async()=>{let n=await i.run(k`UPDATE test_execution_attempt SET workflow_result = ${t.text}
|
|
262
|
+
AND ${K()}`):o},{kind:`ready`,acceptedAt:t}))},async getAttemptControlState(e){return w(async t=>{let n=await A(t,e);return n===void 0?null:M(n)})},async requestAttemptCancellation(e){let t=i(e);return w(async e=>{let n=await A(e,t.executionAttemptId);if(n===void 0||n.execution_id!==t.executionId)return{kind:`not-found`};let r=l(await T(e,t.executionAttemptId),t,new Date().toISOString());return r.kind===`accepted`&&await O(e,t.executionAttemptId,r.intent),r})},async requestCancellation(e){let t=a(e),n={requestKey:crypto.randomUUID(),reason:t.reason};await w(async e=>{let r=await e.all(E`SELECT execution_attempt_id FROM test_execution_attempt WHERE execution_id = ${t.executionId}`),i=new Date().toISOString(),a=[];for(let t of r){let r=l(await T(e,t.execution_attempt_id),n,i);if(r.kind===`conflict`)throw Error(`Generated cancellation request key conflicts with its receipt`);a.push({executionAttemptId:t.execution_attempt_id,decision:r})}for(let{executionAttemptId:t,decision:n}of a)n.kind===`accepted`&&await O(e,t,n.intent)})},async readCancellation(e){return w(t=>T(t,e))},async getActiveAttempt(e,t){return w(async n=>{if(await B(n,e)!==t)return null;let r=await A(n,t);return r===void 0?null:N(r)})},canonicalizeOutcome(e){return ne(u,e)},decodeOutcome(e){return t(u,e)},async commitOutcome(e){let n=e.result,i=e.runtimeFence,a=i===void 0?E`1 = 1`:E`
|
|
263
|
+
runtime_generation = ${i.runtimeGeneration}
|
|
264
|
+
AND ${i.operationId===null?E`active_operation_id IS NULL`:E`active_operation_id = ${i.operationId}
|
|
265
|
+
AND active_operation_generation = ${i.runtimeGeneration}`}`;return w(o=>{let s=null;return V(async()=>{if(await B(o,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let c=await A(o,e.executionAttemptId);if(c===void 0)return{kind:`fenced`};let l=c.workflow_result;if(l!==null){let e=t(u,l);return r(l,n.text)?{kind:`duplicate`,outcome:e,text:l,controlObservation:j(c.outcome_control_observation)}:{kind:`conflict`}}return c.settlement_kind===null?(i!==void 0&&ee(M(c),i),s=re(await T(o,e.executionAttemptId)),async()=>{let t=await o.run(E`UPDATE test_execution_attempt SET workflow_result = ${n.text},
|
|
266
|
+
outcome_control_observation = ${JSON.stringify(s)}
|
|
262
267
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
263
268
|
AND workflow_result IS NULL
|
|
264
269
|
AND settlement_kind IS NULL
|
|
265
|
-
AND ${
|
|
266
|
-
AND ${K()}`);return
|
|
270
|
+
AND ${a}
|
|
271
|
+
AND ${K()}`);return t.rowsAffected===0?t:X(o,e.executionAttemptId,`outcome`,E`workflow_result IS NOT NULL`)}):{kind:`conflict`}},()=>({kind:`accepted`,outcome:t(u,n.text),text:n.text,controlObservation:s}))})},async abandonPendingAttempt(e,t){return w(n=>V(async()=>{if(await B(n,t)!==e)return{kind:`fenced`};let r=await A(n,e);if(r===void 0)return{kind:`fenced`};let i=N(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(E`UPDATE test_execution_attempt
|
|
267
272
|
SET status = ${`settled`}, settlement_kind = ${`abandoned`}, claimable = ${0},
|
|
268
273
|
operation_start_gate = ${`closed`}
|
|
269
274
|
WHERE execution_attempt_id = ${e}
|
|
270
275
|
AND execution_id = ${t}
|
|
271
276
|
AND status = ${`pending`}
|
|
272
277
|
AND settlement_kind IS NULL
|
|
273
|
-
AND ${K()}`)},{kind:`abandoned`}))},recovery:
|
|
278
|
+
AND ${K()}`)},{kind:`abandoned`}))},recovery:Ee}}export{q as createSqliteAttemptRepository};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{resolveMakaioHome as e}from"./runtime-node/makaio-config.mjs";import{t}from"./extension-package-provenance-Dr7JXjLS.mjs";import{b as n,c as r,g as i,l as a,n as o,u as s,v as c}from"./bootstrap-start-client-rW55mDI-.mjs";import{mintOrRotateWorkflowExecutionBusSecret as l}from"./runtime-node/workflow-execution-bus-access.mjs";import{z as u}from"zod";import{execFile as d,spawn as f}from"node:child_process";import{promisify as p}from"node:util";import*as m from"node:fs/promises";import{access as ee}from"node:fs/promises";import*as h from"node:path";import{basename as te,isAbsolute as ne,join as g,relative as re}from"node:path";import*as _ from"node:crypto";import{randomUUID as v}from"node:crypto";import{constants as ie}from"node:fs";import{AdapterSubjects as ae,BoundedRecoveryEvidenceSchema as y,ExecutionAttemptSchemas as b,ExecutionAttemptSubjects as x,FrameworkContractNamespaces as oe,FrameworkStorageNamespaces as se,JsonValueSchema as ce,PRE_REQUEST_REJECTION_CODE as le,PROVIDER_ALLOCATION_REF_VERSION as ue,ProviderAllocationRefSchema as de,RECOVERY_EVIDENCE_LIMITS as S,WorkerCapabilitiesSchema as fe,WorkerSchemas as pe,WorkerSubjects as C,WorkflowRunContextSchema as me,WorkflowRunResultSchema as he,WorkflowWorkerConfigSchema as w,createWorkflowCancelSubject as ge}from"@makaio/framework/contracts";import{BusAbortError as _e,createBusInstance as ve,isRequestCancellation as T,waitForSubscriptionPropagation as ye}from"@makaio/framework/bus";import{ExtensionCoordinator as be,KernelSubjects as xe,coalesceExtensionOverrides as Se,filterEligibleExtensions as Ce}from"@makaio/framework/kernel";import{BaseService as we}from"@makaio/framework/service-base";import{AdapterRuntimeSubjects as Te,registerAdapterRuntimeIdentityHandlers as Ee}from"@makaio/framework/services/adapter-runtime";import{devNull as E}from"node:os";import{CLIDetectionNamespace as De,CLIDetectionSubjects as Oe}from"@makaio/framework/services/cli-detection/namespace";import{SessionOrchestratorToken as ke,ToolRegistryToken as Ae,canonicalModelPackage as je,createSubagentServicePackage as Me,createToolContributionProcessor as Ne,frameworkCorePackages as D,sessionBridgePackage as Pe,sessionOrchestratorPackage as Fe,sessionPackage as Ie,sessionStoragePackage as Le,toolRegistryPackage as Re}from"@makaio/framework/services";import{AdapterSubsystemSubjects as ze}from"@makaio/framework/services/adapter-subsystem";import{createClientsCorePackage as Be}from"@makaio/framework/clients";import{AdapterSubsystemToken as O,createAdapterSubsystemContributionProcessor as Ve,createAdapterSubsystemPackage as He,orderAfterAdapterSubsystem as Ue}from"@makaio/framework/adapter-subsystem";import{execa as We}from"execa";import Ge from"piscina";import{ExecutionAttemptAuthority as Ke,WORKFLOW_WORKLOAD_KIND as qe,WORKFLOW_WORKLOAD_VERSION as Je,WorkflowStorageSubjects as Ye,buildWorkflowAttemptInstruction as Xe,parseWorkflowAttemptInstruction as k,runAuthorityDispatchedAttempt as Ze,toCommittedWorkflowRunnerResult as Qe}from"@makaio/framework/workflow-engine";import{runWorkflowOrchestrator as $e}from"@makaio/framework/workflow-engine/workflow-orchestrator";import{setTimeout as et}from"node:timers/promises";function tt(e){return e.on(ae.getCapabilities,async t=>{let{adapterName:n,adapterId:r}=t.payload;if(r){await t.next();return}if(n){let r=await e.requestOptional(Te.resolveId,{adapterName:n}),i=r.handled?r.data.adapterId:void 0;i&&(t.payload.adapterId=i)}await t.next()},{priority:20})}function nt(e){let{coordinator:t,configRepository:n,platformDefaults:r,prepareAuthRuntime:i,runtimeSnapshotHandlerPriority:a,runtimeDefinitionHandlerPriority:o}=e,s=He({configRepository:n,coordinator:t,platformDefaults:r,...i!==void 0&&{prepareAuthRuntime:i},...a!==void 0&&{runtimeSnapshotHandlerPriority:a},...o!==void 0&&{runtimeDefinitionHandlerPriority:o}});return t.registerContributionProcessor(Ve({getAdapterSubsystemService:()=>t.getExtensionService(O)})),{adapterSubsystemPackage:s}}function rt(e){let{bus:t,currentMachineId:n}=e,r=Ee(t,{currentMachineId:n,listKnownAdapterNames:e.listKnownAdapterNames??(async()=>{let{configs:e}=await t.request(ze.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=tt(t);return{cleanup:()=>{r.cleanup(),i()}}}function it(e,t){if(!(e instanceof Error))return!1;let{rootPackageName:n,subpath:r}=ot(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"`)&&st(e.message,n)?!0:i.some(t=>e.message.includes(t))}async function at(e){try{return await import(e)}catch(t){if(it(t,e))return null;throw t}}function ot(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 st(e,t){let n=t,r=t.replaceAll(`/`,`\\`);return e.includes(`/${n}/package.json`)||e.includes(`\\${r}\\package.json`)}async function A(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`?h.extname(e)===``?i:[``,...i]:[``];for(let t of r.split(h.delimiter)){let n=t.replace(/^"|"$/gu,``),r=h.resolve(n||process.cwd());for(let t of a){let n=h.join(r,`${e}${t}`);try{return await ee(n,ie.X_OK),n}catch{}}}}async function j(e,t=5e3,n=1e3){let{stdout:r}=await We(e,[`--version`],{forceKillAfterDelay:n,timeout:t});return r}function ct(e){return e.match(/(\d+\.\d+\.\d+)/u)?.[1]??`unknown`}async function lt(e,t=A,n=j){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:ct(i)}}catch{return{binary:e,found:!1}}}async function ut(e,t=A,n=j){return Promise.all(e.map(e=>lt(e,t,n)))}var dt=class extends we{constructor(e){super(e)}onInit(){this.registerHandler(Oe.scan,async e=>{let t=await ut(e.payload.binaries);e.setResult({results:t})})}};const M={name:`makaio.cli-detection`,displayName:`CLI Detection`,version:`0.1.0`,critical:!0,surface:`any`,namespaces:[De],create:e=>new dt(e.bus)};function N(e,t){e.push(...ft(t))}function ft(e){return e===void 0?[]:typeof e==`function`?[e]:[...e]}function pt(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 mt(e=[]){return e.some(e=>typeof e==`string`&&e===`node`)?e:[`node`,...e]}function P(e){return Se(Ce(gt(e.packages,e.configProvider),e.surface,e.runtimeEnvironment))}function ht(e,n){let r=P(n),i=new Set(r.map(t));return e.filter(({ownerPackage:e})=>i.has(e)).map(({package:e})=>e)}function gt(e,t){return t?e.filter(e=>t.loadEnabled(e.name)!==!1):e}function F(e,t){return e.filter(e=>e.runtimeOwnership?.[t]===!0).map(e=>e.name)}function _t(e,t){let n=F(e,t);if(n.length>1)throw Error(`Multiple extensions own runtimeOwnership.${t}: ${n.join(`, `)}`)}function I(e){return _t(e,`sessionOrchestrator`),F(e,`sessionOrchestrator`).length===0}function vt(e){return e===!0||I(e)?D:D.filter(e=>e.name!==ke.name)}function L(e,t,n){let r=[];try{for(let i of e){let e=i.runtimeBoot;e&&N(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 yt(){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 R=class{pool;constructor(e){this.pool=new Ge({filename:e.workerEntry,maxThreads:e.maxConcurrency??4,idleTimeout:e.idleTimeoutMs??3e4})}async run(e,t,n){return this.pool.run(e,{signal:t,transferList:n})}onMessage(e){return this.pool.on(`message`,e),()=>this.pool.off(`message`,e)}async dispose(){await this.pool.destroy()}},z=class extends Error{code;constructor(e,t){super(e),this.code=t,this.name=`MaterializationError`}};function B(e,t,n){let r=h.resolve(t)+h.sep,i=h.resolve(e);if(i!==h.resolve(t)&&!i.startsWith(r))throw new z(`${n} escapes allowed root: ${e} is not within ${t}`,`containment-violation`)}async function V(e,t,n,r){let i=r??await m.realpath(t),a;try{a=await m.realpath(e)}catch{return e}let o=i+h.sep;if(a!==i&&!a.startsWith(o))throw new z(`${n} escapes allowed root via symlink: real path ${a} is not within ${i}`,`symlink-escape`);return a}function H(e){let t=e.indexOf(`-`);if(t===-1)throw new z(`Invalid SRI integrity format: ${e}`,`contribution-integrity-mismatch`);return{algorithm:e.slice(0,t),digest:e.slice(t+1)}}async function bt(e,t){let n=await m.readFile(e);return _.createHash(t).update(n).digest(`base64`)}const U=new Set([`.git`,`node_modules`]);function xt(e){return U.has(e.toLowerCase())}async function St(e,t){let n=t.toLowerCase();if(!U.has(n))return!1;if(t===n)return!0;try{let[r,i]=await Promise.all([m.lstat(h.join(e,t)),m.lstat(h.join(e,n))]);return r.dev===i.dev&&r.ino===i.ino}catch(e){if(e.code===`ENOENT`)return!1;throw e}}const Ct=U,wt=new Set([`.DS_Store`]);async function W(e,t){let n=_.createHash(t),r=[];async function i(t){let n=await m.readdir(t,{withFileTypes:!0});for(let a of n){let n=h.join(t,a.name);if(a.isSymbolicLink())throw new z(`Contribution package contains a symbolic link: ${h.relative(e,n)}`,`symlink-escape`);if(a.isDirectory()){Ct.has(a.name)||await i(n);continue}if(a.isFile()){wt.has(a.name)||r.push(h.relative(e,n));continue}throw new z(`Contribution package contains an unsupported filesystem entry: ${h.relative(e,n)}`,`contribution-integrity-mismatch`)}}await i(e),r.sort();for(let t of r)n.update(t.split(h.sep).join(`/`)),n.update(`\0`),n.update(await m.readFile(h.join(e,t))),n.update(`\0`);return`${t}-${n.digest(`base64`)}`}async function G(e,t=`sha256`){let n=_.createHash(t),r=[];async function i(t){let n=await m.readdir(t,{withFileTypes:!0});for(let a of n){let n=h.join(t,a.name);if(!await St(t,a.name)){if(a.isDirectory()){await i(n);continue}if(a.isFile()){r.push(h.relative(e,n));continue}throw a.isSymbolicLink()?new z(`Workspace root contains a symbolic link: ${h.relative(e,n)}`,`symlink-escape`):new z(`Workspace root contains an unsupported filesystem entry: ${h.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 m.readFile(h.join(e,t));n.update(r),n.update(`\0`)}return`${t}-${n.digest(`base64`)}`}async function K(e,t,n){let r=h.join(t,`node_modules`,e.packageName);B(r,t,`Contribution package directory`),await V(r,t,`Contribution package directory`,n);let i=h.join(r,`package.json`),a;try{a=await m.readFile(i,`utf-8`)}catch{throw new z(`Contribution package not found: ${e.packageName} (expected at ${r})`,`contribution-missing`)}let o=JSON.parse(a);if(o.name!==e.packageName)throw new z(`Contribution identity mismatch: expected ${e.packageName}, found ${o.name??`<none>`}`,`contribution-missing`);if(o.version!==e.version)throw new z(`Contribution version mismatch for ${e.packageName}: expected ${e.version}, found ${o.version??`<none>`}`,`contribution-version-mismatch`);let s=h.join(r,e.entrypoint);B(s,r,`Contribution entrypoint`),await V(s,t,`Contribution entrypoint`,n);try{await m.access(s)}catch{throw new z(`Contribution entrypoint not found for ${e.packageName}: ${e.entrypoint}`,`contribution-entrypoint-mismatch`)}let{algorithm:c}=H(e.integrity),l;try{l=await W(r,c)}catch(t){if(t instanceof z)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 z(`Contribution package cannot be read for ${e.packageName}`,`contribution-entrypoint-mismatch`):t}if(l!==e.integrity)throw new z(`Contribution integrity mismatch for ${e.packageName}: expected ${e.integrity}, computed ${l}`,`contribution-integrity-mismatch`);return s}async function Tt(e,t,n){let r=await n.resolveWorkspaceRoot(e.workspaceId);if(r===void 0)throw new z(`Unknown workspace ID: ${e.workspaceId}`,`unknown-workspace`);try{if(!(await m.stat(r)).isDirectory())throw new z(`Workspace root is not a directory: ${r}`,`containment-violation`)}catch(e){throw e instanceof z?e:new z(`Workspace root does not exist: ${r}`,`containment-violation`)}let i=await m.realpath(r),a=h.resolve(r,e.sourcePath);if(B(a,r,`Source path`),h.relative(r,a).split(h.sep).some(xt))throw new z(`Workflow source path selects excluded workspace content: ${e.sourcePath}`,`source-path-mismatch`);await V(a,r,`Source path`,i);let o=await G(r);if(o!==e.rootDigest)throw new z(`Workspace root digest mismatch: expected ${e.rootDigest}, computed ${o}`,`digest-mismatch`);try{await m.access(a)}catch{throw new z(`Workflow source file not found: ${a}`,`source-missing`)}return{workspaceRoot:r,sourcePath:a,contributionEntrypoints:await Promise.all(t.map(e=>K(e,r,i))),platform:process.platform,arch:process.arch}}var Et=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){this.pool??=new R(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,r,a){this.pool??=new R(this.options);let o=this.pool,s,c=!1,l,u=new Promise((t,r)=>{l=r,s=o.onMessage(r=>{n(r)&&r.executionAttemptId===a.executionAttemptId&&(r.executionId!==e.executionId||r.cancelSubject!==e.cancelSubject||(c=!0,s?.(),t(r)))})}),d=r??this.manifest,f=i(a.bootstrapDeadlineAt,t,async(t,n)=>{let r=await this.materializeTask(e,d,n);return o.run({...r,kind:`attempt-bound`,executionAttemptId:a.executionAttemptId,bootstrapDeadlineAt:a.bootstrapDeadlineAt,bootstrapPort:t},n,[t])});return f.then(()=>{c||(c=!0,s?.(),l(Error(`Workflow worker completed before ready signal: ${e.executionId}`)))},e=>{c||(c=!0,s?.(),l(e instanceof Error?e:Error(String(e))))}),{result:f,ready:u}}async dispose(){await this.pool?.dispose()}async materializeTask(e,t,n){if(n.throwIfAborted(),!(e.source.kind===`path`||t.contributionRefs.length>0))return{kind:`unbound`,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 Tt(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{kind:`unbound`,config:{...e,source:{kind:`path`,path:i.sourcePath}},manifest:t,contributionEntrypoints:i.contributionEntrypoints}}};function Dt(e){return e.mode===`source`?g(e.moduleDir,`workflow-worker`,`worker-entry.ts`):g(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}var Ot=class{options;terminalAuthority=`authority`;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;t.throwIfAborted();let c=e.source.kind===`path`?await this.options.readRunContext?.(e.executionId,t):void 0;t.throwIfAborted();let l=Xe({id:v(),revision:`1`,config:e,...c==null?{}:{runContext:c},preservation:{required:[]}});return{state:`authority-committed`,result:Qe(await Ze({authority:this.options.authority,executionId:e.executionId,instruction:l,withAttemptCreation:r?.withAttemptCreation,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)}),e)}}},kt=class{#e;constructor(e){this.#e=e.bus}async run(e,t,n){let r=w.parse(e),i=await s(r);return{state:`uncommitted`,result:await $e({config:await a(r,i,this.#e,t),loaded:i,bus:this.#e,signal:t})}}};function At(){return{contributionRefs:[]}}function jt(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;if(e.executionAttemptRepository){let n=e.executionAttemptBootstrapTimeoutMs;if(n===void 0)throw Error(`An ExecutionAttemptRepository requires executionAttemptBootstrapTimeoutMs`);t=new Ke(e.executionAttemptRepository,{bootstrapTimeoutMs:n})}let n=te(e.runtimeModuleDir)===`src`?`source`:`dist`,r=Mt({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 Mt(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 kt({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(C.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 Ot({dispatch:r,authority:e.authority,...n!==void 0&&{readRunContext:async(e,t)=>(await n.request(Ye.getRunContext,{executionId:e},{signal:t})).runContext},...t.manifest!==void 0&&{manifest:t.manifest},...t.requirements!==void 0&&{requirements:t.requirements}})}case`piscina`:return new Et({workerEntry:t.workerEntry??Dt({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??At(),...t.resolveWorkspaceRoot!==void 0&&{resolveWorkspaceRoot:t.resolveWorkspaceRoot},maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}const Nt=new Set([`accepted`,`duplicate`]);var q=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`}},J=class extends Error{decision;payload;reason;constructor(e,t,n=`authority-rejected`){super(`Attempt outcome delivery ${n===`deadline-exceeded`?`deadline exceeded`:`rejected by Authority`} (decision=${e}, executionAttemptId=${t.executionAttemptId}, outcome=${t.outcome.kind})`),this.decision=e,this.payload=t,this.reason=n,this.name=`AttemptOutcomeDeliveryError`}},Pt=class extends Error{reason;constructor(e=`deadline-exceeded`){super(`Authority request delivery deadline exceeded`),this.reason=e,this.name=`AuthorityRequestDeliveryError`}};function Ft(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 Lt(e,t,n,r){let i=Ft(n?.retry),a=n?.reconnect,o=Date.now()+i.deadlineMs,s;for(let n=0;n<=i.maxRetries;n++){if(o-Date.now()<=0||n>0&&!await It(n,i,o,a))throw t();try{let n=o-Date.now();if(n<=0)throw t();return await e(n)}catch(e){if(r(e))throw e;if(s=e,Date.now()>=o)throw t()}}throw s??t()}async function Rt(e,t){return await Lt(e,()=>new Pt,t,()=>!1)}async function zt(e,t,n){return await Lt(async n=>{let r=await e(n);if(Nt.has(r))return r;throw t(r)},()=>t(`deadline-exceeded`,`deadline-exceeded`),n,e=>e instanceof q||e instanceof J)}async function Bt(e,t,n){return await zt(async n=>(await e.request(C.control.outcome.submit,{executionAttemptId:t.executionAttemptId,executionId:t.executionId,result:t.result},{timeout:n})).decision,(e,n)=>n===void 0?new q(e,t.result):new q(e,t.result,n),n)}async function Vt(e,t,n){return await zt(async n=>(await e.request(x.outcome.submit,t,{timeout:n})).decision,(e,n)=>n===void 0?new J(e,t):new J(e,t,n),n)}const Ht={maxRetries:3,baseDelayMs:200,maxDelayMs:2e3,deadlineMs:1e4},Ut={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`,supportsRecovery:!1,materializationModes:[`local-directory`]},Wt={code:`outcome-acknowledged`,summary:`Piscina runner settled and the Authority acknowledged its workflow outcome`},Gt={code:`outcome-delivery-ended`,summary:`Piscina runner settled and its bounded workflow outcome delivery ended`};function Y(e){let t=new Set,n;return{publish:r=>{if(n!==void 0)return;let i=r();n=i;let a=[...t];t.clear();for(let t of a)try{t(i)}catch(t){console.error(`${e} observer failed:`,t)}},observe:e=>n===void 0?(t.add(e),()=>t.delete(e)):(e(n),()=>void 0)}}function Kt(e){let t=Y(`[PiscinaThinWorkflowProvider] Infrastructure-conclusion`);return{conclude:n=>{t.publish(()=>({evidence:y.parse({source:e.slice(0,S.source),summary:n.slice(0,S.summary),observedAt:new Date().toISOString()})}))},observe:t.observe}}function qt(e,t){let n=Y(`[PiscinaThinWorkflowProvider] Provider-completion`),r=Y(`[PiscinaThinWorkflowProvider] Local-observation-loss`),i;return{completion:{complete:r=>{i===void 0&&n.publish(()=>{let n=y.parse({source:e.slice(0,S.source),code:r.code,summary:r.summary,observedAt:new Date().toISOString()});return t(),i=`completion`,n})},observe:n.observe},localObservationLoss:{lose:()=>{i===void 0&&r.publish(()=>(i=`local-observation-loss`,{}))},observe:e=>r.observe(()=>e())}}}var Jt=class{executionAttemptId;controller;detachCallerAbort;infrastructure;completion;localObservationLoss;revokeBusIdentity;constructor(e,t,n,r,i,a,o){this.executionAttemptId=e,this.controller=t,this.detachCallerAbort=n,this.infrastructure=r,this.completion=i,this.localObservationLoss=a,this.revokeBusIdentity=o}cancel(e){return this.controller.abort(e??`Worker cancelled`),this.detachCallerAbort(),Promise.resolve()}terminate(){return this.controller.abort(`Worker terminated`),this.detachCallerAbort(),this.revokeBusIdentity(),Promise.resolve()}release(){return this.detachCallerAbort(),Promise.resolve()}observeInfrastructureConclusion(e){return this.infrastructure.observe(e)}observeProviderCompletion(e){return this.completion.observe(e)}observeLocalObservationLoss(e){return this.localObservationLoss.observe(e)}},Yt=class{options;environment=`piscina`;allocationLifetime=`provisioner-process-bound`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=fe.parse({...Ut,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??Ut.suspensionStrategy,supportsRecovery:!1})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e,t){t.throwIfAborted();let n=await this.resolveLaunchBeforeAllocation(e,t);if(t.throwIfAborted(),`kind`in n)return n;let r=n,i=new AbortController,a=Kt(this.id),o=()=>{i.abort(t.reason)};t.addEventListener(`abort`,o,{once:!0});let s=()=>t.removeEventListener(`abort`,o),c;try{let{executionAttemptId:n,executionId:o}=e,u=this.buildAllocationRef(n),d=l({executionAttemptId:n,executionId:o}),f=!1,p=()=>{f||(f=!0,d.cleanup())};c=p;let m=qt(this.id,p),ee=new Jt(n,i,s,a,m.completion,m.localObservationLoss,p);t.throwIfAborted();let h=this.options.runner.runWithReadiness({...r,busAuth:{kind:`hmac`,secret:d.secret}},i.signal,e.runtimeInputs.workerManifest,{executionAttemptId:n,bootstrapDeadlineAt:e.bootstrapDeadlineAt});return h.ready.then(()=>this.submitOutcomeOnSettlement(h.result,o,n,r.workflowId,a.conclude,m.completion.complete),e=>{i.abort(e),h.result.catch(()=>void 0),c?.(),a.conclude(`Piscina worker for attempt '${n}' was refused before its workflow run was admitted: `+(e instanceof Error?e.message:String(e))),m.localObservationLoss.lose()}),{kind:`allocated`,allocationRef:u,handle:ee}}catch(e){throw i.abort(e),s(),c?.(),e}}async resolveLaunchBeforeAllocation(e,t){try{let n=await this.options.launchResolver(e,t);return t.throwIfAborted(),n.busUrl?n:this.confirmedAbsent(`Piscina workflow configuration has no bus URL before local allocation setup`)}catch{return t.throwIfAborted(),this.confirmedAbsent(`Workflow launch resolution failed before Piscina local allocation setup`)}}confirmedAbsent(e){return{kind:`confirmed-absent`,evidence:y.parse({source:`piscina-thin-workflow-provider`,code:le,summary:e,observedAt:new Date().toISOString()})}}async submitOutcomeOnSettlement(e,t,n,r,i,a){let o;try{o=await e}catch(e){o={executionId:t,workflowId:r,status:`failed`,error:e instanceof Error?e.message:String(e)}}try{let e={...Ht,...this.options.outcomeRetry};await Bt(this.options.bus,{executionAttemptId:n,executionId:t,result:o},{retry:e})}catch(e){e instanceof q?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`),a(Gt);return}a(Wt)}buildAllocationRef(e){let t={version:ue,providerId:this.id,providerData:{executionAttemptId:e,allocatedAt:Date.now()}};return de.parse(t)}};function Xt(e){return async(t,n)=>{n.throwIfAborted();let r=await e({executionId:t.executionId,executionAttemptId:t.executionAttemptId});if(n.throwIfAborted(),r===null)throw Error(`Workflow launch instruction is unavailable for execution '${t.executionId}' attempt '${t.executionAttemptId}'`);let i=k(r);if(i.executionId!==t.executionId)throw Error(`Workflow instruction execution '${i.executionId}' does not match Worker request '${t.executionId}'`);return w.parse({source:i.source,...i.definitionSnapshot===void 0?{}:{definition:i.definitionSnapshot},executionId:i.executionId,workflowId:i.workflowId,triggerPayload:i.triggerPayload,...i.triggerMode===void 0?{}:{triggerMode:i.triggerMode},inputs:i.inputs,...i.config===void 0?{}:{config:i.config},...i.artifactRef===void 0?{}:{artifactRef:i.artifactRef},scope:i.scope,...t.connection.busUrl===void 0?{}:{busUrl:t.connection.busUrl},busAuth:t.connection.busAuth,...t.connection.env===void 0?{}:{env:t.connection.env},coordinatorSessionId:i.coordinatorSessionId,cancelSubject:i.cancelSubject,suspensionStrategy:t.runtimeInputs.suspensionStrategy,terminalAuthority:i.terminalAuthority,...i.materializationSpec===void 0?{}:{materializationSpec:i.materializationSpec}})}}const Zt=[Le,Pe,Ie];function Qt(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 $t(e,t,n){return rt({bus:e,currentMachineId:n,resolveLiveAdapterId:e=>t.getExtensionService(O)?.resolveLiveAdapterId(e),resolveLiveAdapterIdentity:e=>t.getExtensionService(O)?.resolveLiveAdapterIdentity(e),listLiveAdapterIdentities:()=>t.getExtensionService(O)?.getLiveAdapterIdentities()??[]})}async function en(e){let t=ve();t.registerNamespaces([...oe,...se]);let{context:n}=e,r=new be(t,{surface:`headless`,extensionContextBase:{cwd:n.cwd,platform:n.platform,homedir:n.homedir,makaioHome:n.makaioHome,username:n.username,machineId:n.machineId,tryImport:at}}),i,a=[()=>t.disconnect()],o=Qt(a);try{await e.connectAuthority(t);let s=[...e.contributedPackages,...await e.loadContributedPackages?.(t)??[]],{adapterSubsystemPackage:c}=nt({coordinator:r,configRepository:e.configRepository,platformDefaults:{cwd:n.cwd},runtimeSnapshotHandlerPriority:1,runtimeDefinitionHandlerPriority:1,...e.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:e.prepareAuthRuntime}}),l=Be({definitions:s.flatMap(e=>e.clients??[]),binaryResolutionPolicy:`global-only`});r.registerContributionProcessor(Ne());let u=[...Zt,c,je,...I(s)?[Fe]:[],Me(1),Re,M,l,...Ue(s)];r.load(u),a.push(...L(u,t,r)),a.push(()=>r.shutdown()),await r.startAll(),i=$t(t,r,n.machineId),a.push(()=>{i?.cleanup(),i=void 0});let d=r.getExtensionService(Ae);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(xe.ready,{machineId:n.machineId}),{bus:t,coordinator:r,machineId:n.machineId,shutdown:o}}catch(e){throw await o().catch(()=>void 0),e}}function tn(e){return Number.isInteger(e)&&e>=1&&e<=2147483647}function X(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function nn(e,t){try{process.kill(-e,0)}catch(e){if(e.code===`ESRCH`)return!1;if(e.code!==`EPERM`)throw e}let n;try{n=await rn(t)}catch{return!0}let r=!1;for(let t of n.trim().split(`
|
|
2
|
+
`)){let[n,i,a]=t.trim().split(/\s+/);if(n===``||i===void 0||a!==void 0||!/^\d+$/.test(n)||i===``||Number(n)===e&&(r=!0,!i.startsWith(`Z`)))return!0}return!r}function rn(e){return new Promise((t,n)=>{d(`ps`,[`-A`,`-o`,`pgid=,stat=`],{timeout:e,maxBuffer:1024*1024},(e,r)=>{if(e!==null){n(e);return}t(r)})})}async function an(e){if(e===void 0)return!0;try{try{X(e,`SIGKILL`)}catch(e){if(e.code!==`EPERM`)throw e}let t=Date.now()+2e3;for(;Date.now()<t;){let n=t-Date.now();if(n<=0)break;if(!await nn(e,Math.min(1e3,n)))return!0;await et(20)}}catch{}return!1}async function on(e){if(e.signal?.aborted)return{status:`cancelled`,exitCode:null};if(!tn(e.recipe.timeoutMs))return{status:`spawn-failed`,exitCode:null,message:`Setup timeout must be an integer between 1 and 2147483647 milliseconds`};if(process.platform===`win32`)return{status:`spawn-failed`,exitCode:null,message:`Setup process groups require a POSIX host`};try{return await sn(e)}catch{return{status:`spawn-failed`,exitCode:null,message:`Could not start the setup command`}}}function sn(e){return new Promise(t=>{let n=f(e.recipe.command,e.recipe.args,{cwd:e.workspaceRoot,env:{...process.env,...e.recipe.env,...e.env},shell:!1,detached:!0,stdio:`ignore`}),r,i,a=e=>{if(r===void 0&&(r=e,n.pid!==void 0)){try{X(n.pid,`SIGTERM`)}catch(e){if(e.code!==`EPERM`){r=`stop-failed`;return}}i=setTimeout(()=>{try{n.pid!==void 0&&X(n.pid,`SIGKILL`)}catch(e){e.code!==`EPERM`&&(r=`stop-failed`)}},200)}},o=()=>a(`cancelled`),s=setTimeout(()=>a(`timed-out`),e.recipe.timeoutMs);e.signal?.addEventListener(`abort`,o,{once:!0}),e.signal?.aborted&&o(),n.once(`error`,()=>{r=`spawn-failed`}),n.once(`close`,a=>{clearTimeout(s),clearTimeout(i),e.signal?.removeEventListener(`abort`,o),an(n.pid).then(e=>{t({status:e?r??(a===0?`completed`:`failed`):`stop-failed`,exitCode:a})})})})}async function cn(e,t,n){if(h.isAbsolute(t)||t.includes(`\\`)||t.split(`/`).includes(`..`))throw Error(`Source root must be workspace-relative`);let r=e;for(let i of t.split(`/`).filter(e=>e!==``&&e!==`.`))if(r=h.join(r,i),B(r,e,`Source root`),await V(r,e,`Source root`,e),n&&await m.mkdir(r).catch(e=>{if(e.code!==`EEXIST`)throw e}),!(await m.stat(r)).isDirectory())throw Error(`Source root must be a directory`);return V(r,e,`Source root`,e)}async function ln(e){e.signal?.throwIfAborted();let{requirement:t}=e,n=h.resolve(e.workspaceRoot);if(!h.isAbsolute(e.workspaceRoot)||n===h.parse(n).root)throw Error(`Workspace root must be an absolute, non-filesystem-root directory`);if(t.sourceRoots.length>1)throw Error(`Multiple source roots are not implemented`);if(t.sourceRoots.some(e=>e.source!==void 0)){if(e.realizeSource===void 0)throw Error(`Source acquisition requires an installed strategy`);if(t.provisioning!==`create`||t.custody!==`disposable`)throw Error(`Source acquisition currently requires a created disposable workspace`)}if(t.provisioning===`create`&&await m.mkdir(n),!(await m.lstat(n)).isDirectory())throw Error(`Workspace root must be a directory, not a symlink`);let r=await m.realpath(n),i=[];for(let n of t.sourceRoots){let a=await cn(r,n.path,t.provisioning===`create`);n.source!==void 0&&(await e.realizeSource({source:n.source,destination:a,signal:e.signal}),e.signal?.throwIfAborted()),i.push({id:n.id,path:a})}return un(t,{workspaceRoot:r,sourceRoots:i})}function un(e,t){let n=t.workspaceRoot,r=e.custody,i=!1,a=!0,o;return{binding:t,async runSetup(t={}){if(o!==void 0||i||!a)throw Error(`Workspace setup is unavailable`);if(t.signal?.aborted)return{status:`cancelled`,exitCode:null};i=!0;try{for(let[r,i]of e.setup.entries()){let e=await on({...t,recipe:i,workspaceRoot:n});if(a=e.status!==`stop-failed`,e.status!==`completed`)return{...e,commandIndex:r}}return{status:`completed`,exitCode:0}}finally{i=!1}},release(){return i||!a?Promise.reject(Error(`Workspace commands have not stopped`)):(o??=r===`external`?Promise.resolve():m.rm(n,{recursive:!0,force:!0}),o)}}}function Z(e,t){return e instanceof _e?T(e,t):t?.aborted===!0?e===t.reason||e instanceof DOMException&&e.name===`AbortError`?!0:e instanceof Error&&e.name===`AbortError`&&`code`in e&&e.code===`ABORT_ERR`&&Object.is(e.cause,t.reason):!1}async function dn(e,t,n,r){let i=b[`instruction.get`].response.parse(await e.request(x.instruction.get,{executionAttemptId:t,runtimeGeneration:n},{signal:r}));if(i.decision===`found`)return i.instruction;throw Error(`Attempt instruction read refused: ${i.refusalReason}`)}async function fn(e,t,n,r){let{executionAttemptId:i,runtimeGeneration:a}=t,o=b[`operation.admit`].response.parse(await Rt(async t=>await e.request(x.operation.admit,{executionAttemptId:i,runtimeGeneration:a,operationKind:n,admissionKey:r},{timeout:t}),{retry:t.retry,reconnect:t.reconnect}));if(o.decision===`refused`||o.operationId===void 0)throw Error(`Attempt ${n} admission refused: ${o.refusalReason??`missing-operation-id`}`);return o.operationId}function Q(e){return(e instanceof Error?e.message:String(e)).slice(0,8192)||`Local execution failed without a diagnostic message`}function pn(e,t){return e.find(e=>e.kind===t.workload.kind&&e.version===t.workload.version)}function mn(e){return{signal:e??new AbortController().signal,release:()=>{}}}async function $(e,t,n,r,i,a){let o=await Vt(e,{executionAttemptId:t.executionAttemptId,runtimeGeneration:t.runtimeGeneration,...i===void 0?{}:{operationId:i},outcome:r},{retry:t.retry,reconnect:t.reconnect});if(a!==void 0&&n!==void 0&&r.kind===`workload-result`&&n.preservation.required.length===0)try{await a.release()}catch{console.warn(`[makaio-worker] Acknowledged workspace cleanup failed.`)}return{outcome:r,decision:o}}async function hn(e,t,n,r){let i=b[`operation.report`].response.parse(await Rt(async i=>await e.request(x.operation.report,{executionAttemptId:t.executionAttemptId,runtimeGeneration:t.runtimeGeneration,operationId:n,result:{kind:`workspace-prepared`,binding:r.binding}},{timeout:i}),{retry:t.retry,reconnect:t.reconnect}));return i.decision===`refused`?void 0:i.binding}function gn(e){if(e.status!==`completed`)return e.status===`cancelled`?{kind:`cancelled`}:e.status===`stop-failed`?{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace setup stop-failed`}:{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace setup ${e.status}`}}async function _n(e,t,n,r){if(r.aborted)return await $(e,t,n,{kind:`cancelled`},void 0,void 0);let i=await fn(e,t,`workspace-preparation`,`workspace-preparation:${n.id}:${t.runtimeGeneration}`);if(r.aborted)return await $(e,t,n,{kind:`cancelled`},i,void 0);let a,o;try{if(t.workspaceRoot===void 0)throw Error(`Workspace preparation requires an explicit local root`);let e=await(t.preparation??{prepare:ln}).prepare({requirement:n.workspace,workspaceRoot:t.workspaceRoot,signal:r});a=e,o=await e.runSetup({signal:r,env:t.setupEnv})}catch(o){return await $(e,t,n,Z(o,r)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`workspace-preparation`,message:Q(o)},i,a)}let s=gn(o);if(s!==void 0)return await $(e,t,n,s,i,a);if(r.aborted)return await $(e,t,n,{kind:`cancelled`},i,a);let c=await hn(e,t,i,a);return c===void 0?await $(e,t,n,{kind:`technical-failure`,stage:`workspace-preparation`,message:`Workspace preparation report refused by the Authority`},i,a):r.aborted?await $(e,t,n,{kind:`cancelled`},void 0,a):{handle:a,binding:c}}async function vn(e,t,n,r,i){if(i.signal.aborted)return await $(e,t,n,{kind:`cancelled`},void 0,void 0);let a,o;if(n.workspace!==void 0){let r=await _n(e,t,n,i.signal);if(`outcome`in r)return r;a=r.handle,o=r.binding}if(i.signal.aborted)return await $(e,t,n,{kind:`cancelled`},void 0,a);let s=await fn(e,t,`workload-invocation`,`workload-invocation:${n.id}:${t.runtimeGeneration}`);if(i.signal.aborted)return await $(e,t,n,{kind:`cancelled`},s,a);let c;try{c={kind:`workload-result`,result:ce.parse(await r.invoke({instruction:n,...o===void 0?{}:{workspace:o},signal:i.signal}))}}catch(e){c=Z(e,i.signal)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`workload-invocation`,message:Q(e)}}return await $(e,t,n,c,s,a)}async function yn(e,t){let n;try{n=await dn(e,t.executionAttemptId,t.runtimeGeneration,t.signal)}catch(n){if(T(n,t.signal))return await $(e,t,void 0,{kind:`cancelled`},void 0,void 0);throw n}let r=pn(t.adapters,n);if(r===void 0)return await $(e,t,n,{kind:`technical-failure`,stage:`startup`,message:`Required adapter '${n.workload.kind}' version '${n.workload.version}' is unavailable`},void 0,void 0);let i;try{i=await(r.bindControl?.({instruction:n,signal:t.signal})??mn(t.signal))}catch(r){let i=Z(r,t.signal)?{kind:`cancelled`}:{kind:`technical-failure`,stage:`startup`,message:Q(r)};return await $(e,t,n,i,void 0,void 0)}try{return await vn(e,t,n,r,i)}finally{try{i.release()}catch{console.warn(`[makaio-worker] Workload control release failed.`)}}}async function bn(e,t,n,r,i){let a=pe[`runtime.inputs.get`].response.parse(await e.request(C.runtime.inputs.get,{executionAttemptId:t},{signal:i}));if(a.runtimeInputs===null)throw Error(`Selected Worker Runtime inputs are unavailable`);return me.parse({...n,...a.runtimeInputs,createdAt:0,env:r})}function xn(e,t){let n=(e,t)=>{let n=re(e,t);return n===``||!ne(n)&&n!==`..`&&!n.startsWith(`../`)&&!n.startsWith(`..\\`)};return n(e,t)||n(t,e)}async function Sn(t,n,r,i){let a=await t.loadContributions(r,i);i.throwIfAborted();let o=e();return await en({connectAuthority:e=>t.connectBus(e,n,i),contributedPackages:[...a],configRepository:t.configRepository,context:{cwd:r.workspaceRoot,platform:r.platform,homedir:o,makaioHome:o,username:`workflow-worker`,machineId:`headless-worker-${t.executionAttemptId}`},toolsets:[...t.toolsets],...t.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:t.prepareAuthRuntime}})}function Cn(e,t,n){let r={...e.workflowEnv},i,a=!0;return{adapter:{kind:qe,version:Je,async bindControl({instruction:t,signal:r}){let i=k(t);if(i.executionId!==e.executionId)throw Error(`Workflow instruction execution identity mismatch`);let a=new AbortController,o=n.on(ge(i.cancelSubject),()=>a.abort());try{return await ye(o),{signal:AbortSignal.any([...r===void 0?[]:[r],a.signal]),release:o}}catch(e){throw o(),e}},async invoke({instruction:o,workspace:s,signal:c}){let l=k(o);a=o.preservation.required.length!==0;let u=c??new AbortController().signal,d;try{u.throwIfAborted();let a=await bn(n,e.executionAttemptId,l,r,u),o=await e.materialize(a,u);(s===void 0||!xn(o.context.workspaceRoot,s.workspaceRoot))&&(i=o.cleanup);let c=wn(o.context,s);return u.throwIfAborted(),d=await Sn(e,t,c,u),u.throwIfAborted(),await e.execute(d.bus,a,c,u)}finally{await d?.shutdown()}}},async releaseExecutable(e){e===void 0||a||e.outcome.kind===`workload-result`&&(e.decision!==`accepted`&&e.decision!==`duplicate`||await i?.().catch(()=>void 0))}}}function wn(e,t){return t===void 0?e:{...e,workspaceRoot:t.workspaceRoot}}async function Tn(e,t){if(!(t.outcome.kind!==`workload-result`||e.onPostCommit===void 0))try{let n=he.parse(t.outcome.result);await e.onPostCommit(n,t.decision)}catch{}}async function En(e,t){t.throwIfAborted();let n={...e.workflowEnv},i=v(),a=await c(e.bootstrapDeadlineAt,t,t=>e.bootstrap(t)),{connection:s,endpoint:l}=await o({executionAttemptId:e.executionAttemptId,runtimeIncarnationId:i,bootstrapDeadlineAt:e.bootstrapDeadlineAt,signal:t,createConnection:()=>Dn(e,a)}),u=s.bus,d=Cn({...e,workflowEnv:n},a,u),f;try{let n=await r(u,{executionAttemptId:e.executionAttemptId,runtimeIncarnationId:i,signal:t});return l.bindGeneration(n),f=await yn(u,{executionAttemptId:e.executionAttemptId,runtimeGeneration:n,workspaceRoot:e.workspaceRoot,setupEnv:e.setupEnv,preparation:e.preparation,adapters:[d.adapter],signal:t,retry:e.outcomeRetry,reconnect:()=>u.reconnect()}),await Tn(e,f),f}finally{try{await d.releaseExecutable(f)}finally{l.cleanup(),await s.close()}}}function Dn(e,t){let n=ve();return n.registerNamespaces([...oe,...se]),{bus:n,async connect(r){try{await e.connectBus(n,t,r),r.throwIfAborted()}catch(e){throw n.disconnect(),e}},close:()=>n.disconnect()}}const On=p(d),kn=[`-c`,`core.attributesFile=${E}`],An=u.object({repositoryId:u.string().min(1),revision:u.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,`Git source revision must be a full commit object ID`)}).strict();async function jn(e,t,n){try{let r=await e.resolveRepository(t,n);if(!h.isAbsolute(r))throw Error(`Repository access did not return an absolute path`);return await m.realpath(r)}catch(e){throw Z(e,n)?e:Error(`Git source access failed`)}}async function Mn(e,t,n,r,i){let a;try{a=(await On(`git`,[...kn,`cat-file`,`-t`,t],{cwd:e,env:{...process.env,...n},signal:i,timeout:r,maxBuffer:1024,shell:!1,killSignal:`SIGKILL`,encoding:`utf8`})).stdout.trim()}catch(e){throw Z(e,i)?e:Error(`Git source object inspection failed`)}if(a!==`commit`)throw Error(`Git source revision must identify a commit object`)}function Nn(e){if(!tn(e.timeoutMs))throw Error(`Git command timeout must be an integer between 1 and 2147483647 milliseconds`);if(process.platform===`win32`)throw Error(`Local Git source preparation requires a POSIX host`);return async({source:t,destination:n,signal:r})=>{if(r?.throwIfAborted(),t.kind!==`git`)throw Error(`Unsupported local Git source kind`);let i=An.parse(t.input),a=await jn(e,i.repositoryId,r);r?.throwIfAborted();let o={...Object.fromEntries(Object.keys(process.env).filter(e=>/^git_/i.test(e)).map(e=>[e,void 0])),GIT_CONFIG_GLOBAL:E,GIT_CONFIG_SYSTEM:E,GIT_ATTR_NOSYSTEM:`1`},s=[[`init`,`--object-format=${i.revision.length===64?`sha256`:`sha1`}`],[`fetch`,`--no-tags`,`--no-write-fetch-head`,`--update-shallow`,`--`,a,i.revision],[`checkout`,`--detach`,i.revision,`--`]];for(let t of s){t[0]===`checkout`&&await Mn(n,i.revision,o,e.timeoutMs,r);let a=await on({workspaceRoot:n,signal:r,env:o,recipe:{command:`git`,args:[...kn,...t],env:{},timeoutMs:e.timeoutMs}});if(a.status===`cancelled`&&r?.throwIfAborted(),a.status!==`completed`)throw Error(`Git source ${t[0]} ${a.status}`)}}}function Pn(e){let t=Nn(e);return{prepare:e=>ln({...e,realizeSource:t})}}export{mt as A,nt as B,G as C,K as D,H as E,vt as F,M as I,it as L,L as M,P as N,pt as O,ht as P,at as R,W as S,Tt as T,tt as V,Dt as _,Xt as a,B as b,Pt as c,Vt as d,Bt as f,Ot as g,kt as h,en as i,yt as j,N as k,Nt as l,jt as m,En as n,Yt as o,Mt as p,yn as r,J as s,Pn as t,q as u,Et as v,bt as w,V as x,z as y,rt as z};
|