@makaio/framework 1.0.0-dev-1789234461336 → 1.0.0-dev-1789404058608
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/adapters/claude/index.d.mts +24 -24
- package/dist/authority-state-bootstrap-CvuWPywM.mjs +1 -0
- package/dist/bus/index.mjs +1 -1
- package/dist/{bus-BZB7jNes.mjs → bus-DlTN167w.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 +2 -2
- package/dist/contracts/capabilities/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +1 -1
- package/dist/contracts/extension/index.d.mts +3 -3
- package/dist/contracts/index.d.mts +61 -61
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +1 -1
- package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/shared/index.d.mts +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/worker/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/drizzle/0039_m_mtyn7x1q.sql +1 -0
- package/dist/drizzle/meta/_journal.json +7 -0
- package/dist/{index-Cplq28EL.d.mts → index-BArnbdj6.d.mts} +84 -67
- package/dist/{index-De_oh9M-2.d.mts → index-BEi6nx1S2.d.mts} +1 -1
- package/dist/{index-iVisrVdC2.d.mts → index-BUC9P6Q12.d.mts} +6 -6
- package/dist/{index-B6WkHnCQ.d.mts → index-C1nSuiG0.d.mts} +1 -1
- package/dist/{index-CA3Uzki8.d.mts → index-CGxjX4fw.d.mts} +5 -5
- package/dist/{index-nkix3hP7.d.mts → index-CWlvL7GB.d.mts} +6 -6
- package/dist/{index-DXZImst_2.d.mts → index-DH0m01hJ2.d.mts} +15 -11
- package/dist/{index-BmCm9R8_.d.mts → index-DaAWCLe9.d.mts} +25 -25
- package/dist/{index-ClKwF6LE.d.mts → index-DjQebquc.d.mts} +287 -287
- package/dist/{index-DMkzJCjS.d.mts → index-Du4wUv9q.d.mts} +7 -7
- package/dist/{index-CzUUoexw.d.mts → index-HJkz7i4E.d.mts} +70 -1
- package/dist/{index-mTaFX2HH2.d.mts → index-HMb0RcTG2.d.mts} +12 -12
- package/dist/{index-Bg3WVL8n.d.mts → index-N3f65Z_S.d.mts} +8 -8
- package/dist/{index-xsaaa85T.d.mts → index-T-aAKybB.d.mts} +8 -8
- package/dist/{index-BpQX136X.d.mts → index-U--ajOHy.d.mts} +1 -1
- package/dist/{index-D_j_T3nS.d.mts → index-gu4mzfTr.d.mts} +1 -1
- package/dist/{index-C6e9cwAl2.d.mts → index-n1hV8uFw2.d.mts} +7 -7
- 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-Phxf0Lep.d.mts → namespace-CPGTaFqO.d.mts} +2 -2
- package/dist/{namespace-UFcDEBJB.d.mts → namespace-D2RZfl0a.d.mts} +2 -2
- package/dist/{namespace-BsQPRiMd.d.mts → namespace-DM5vykb7.d.mts} +2 -2
- package/dist/{namespace-B5IFLQc-.d.mts → namespace-DQpBf2CK.d.mts} +6 -6
- package/dist/{namespace-rJ3ycPMg.d.mts → namespace-DSRoDmT6.d.mts} +2 -2
- package/dist/{package-CDj3F-L3.d.mts → package-D-oIvXJD.d.mts} +1 -1
- package/dist/{package-D2Erka-E.mjs → package-DYScYC0D.mjs} +2 -2
- package/dist/package.json +1 -1
- package/dist/runtime-node/index.d.mts +2 -2
- package/dist/runtime-node/index.mjs +22 -22
- package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
- package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
- package/dist/runtime-node/workflow-worker/index.mjs +1 -1
- package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
- package/dist/{schemas-COiUhOce.d.mts → schemas-BQsXr4FF.d.mts} +7 -7
- package/dist/{schemas-Cj6Gbqch.d.mts → schemas-BcynDWi-.d.mts} +7 -7
- package/dist/{schemas-CaBRbfhU.d.mts → schemas-CEJe8O6P.d.mts} +2 -2
- package/dist/{schemas-2_D4iVbb.d.mts → schemas-CJKDu4Kt.d.mts} +1 -1
- package/dist/{schemas-Cq1d5tid.d.mts → schemas-e8o4JGBu.d.mts} +2 -2
- package/dist/services/adapter-runtime/index.d.mts +3 -3
- package/dist/services/adapter-runtime/namespace.d.mts +1 -1
- package/dist/services/adapter-runtime/schemas.d.mts +1 -1
- 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 +29 -29
- package/dist/services/session/handlers/index.d.mts +1 -1
- package/dist/services/session/index.d.mts +2 -2
- package/dist/services/settings/namespace.d.mts +4 -4
- 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/services/tray-menu/index.d.mts +2 -2
- package/dist/services/tray-menu/namespace.d.mts +1 -1
- package/dist/services/tray-menu/schemas.d.mts +1 -1
- package/dist/{session-lineage-C3myyt5x.d.mts → session-lineage-BQimcKsh.d.mts} +1 -1
- package/dist/{transition-D-Lgbp1j.d.mts → transition-JmAdtcwW.d.mts} +1 -1
- package/dist/{types-DhbllltK.d.mts → types-C5MnkQv6.d.mts} +9 -9
- package/dist/{view-builder-CHUTXJDl.d.mts → view-builder-ByHQ4Oop.d.mts} +2 -2
- package/dist/{worker-4pqm147Q.mjs → worker-B72n8bse.mjs} +1 -1
- package/dist/workflow-D-X3rPsl.mjs +1 -0
- package/dist/workflow-engine/index.d.mts +67 -34
- 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/workflow-orchestrator.mjs +1 -1
- package/dist/workflow-worker-ChrMIcKm.mjs +2 -0
- package/package.json +1 -1
- package/dist/authority-state-bootstrap-BkI-zYRx.mjs +0 -1
- package/dist/workflow-C5cS1mgK.mjs +0 -1
- package/dist/workflow-worker-l-wflI6V.mjs +0 -2
- package/dist/{index-Htfr-K5U2.d.mts → index-CCH0Dnty2.d.mts} +6 -6
- package/dist/{schemas-JjyFxrC0.d.mts → schemas-lAb9QH1A.d.mts} +8 -8
|
@@ -37,9 +37,9 @@ declare const SubagentTemplateKernelNamespace: _$_makaio_core0.BusNamespaceDefin
|
|
|
37
37
|
status: _$zod.ZodEnum<{
|
|
38
38
|
completed: "completed";
|
|
39
39
|
cancelled: "cancelled";
|
|
40
|
-
failed: "failed";
|
|
41
40
|
running: "running";
|
|
42
41
|
waiting_input: "waiting_input";
|
|
42
|
+
failed: "failed";
|
|
43
43
|
}>;
|
|
44
44
|
result: _$zod.ZodOptional<_$zod.ZodString>;
|
|
45
45
|
error: _$zod.ZodOptional<_$zod.ZodString>;
|
|
@@ -101,9 +101,9 @@ declare const SubagentTemplateSubjects: _$_makaio_core0.BusSubjects<_$_makaio_co
|
|
|
101
101
|
status: _$zod.ZodEnum<{
|
|
102
102
|
completed: "completed";
|
|
103
103
|
cancelled: "cancelled";
|
|
104
|
-
failed: "failed";
|
|
105
104
|
running: "running";
|
|
106
105
|
waiting_input: "waiting_input";
|
|
106
|
+
failed: "failed";
|
|
107
107
|
}>;
|
|
108
108
|
result: _$zod.ZodOptional<_$zod.ZodString>;
|
|
109
109
|
error: _$zod.ZodOptional<_$zod.ZodString>;
|
|
@@ -865,9 +865,9 @@ declare const WorkflowAttemptOutcomeSchema: z.ZodUnion<readonly [z.ZodDiscrimina
|
|
|
865
865
|
confidence: z.ZodOptional<z.ZodObject<{
|
|
866
866
|
level: z.ZodEnum<{
|
|
867
867
|
inferred: "inferred";
|
|
868
|
-
confirmed: "confirmed";
|
|
869
868
|
assumed: "assumed";
|
|
870
869
|
stated: "stated";
|
|
870
|
+
confirmed: "confirmed";
|
|
871
871
|
verified: "verified";
|
|
872
872
|
}>;
|
|
873
873
|
basis: z.ZodArray<z.ZodObject<{
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{$ as e,A as t,At as n,Ct as r,Dt as i,Et as a,F as o,Ft as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,Mt as ee,N as te,Nt as ne,Ot as re,P as ie,Pt as ae,Q as oe,R as h,St as se,Tt as ce,U as le,V as ue,W as g,X as de,Y as fe,Z as pe,_ as me,_t as he,a as ge,at as _e,bt as ve,c as ye,ct as be,dt as xe,et as Se,f as Ce,ft as we,g as Te,gt as Ee,h as De,ht as Oe,i as ke,it as Ae,j as je,jt as Me,k as Ne,kt as Pe,l as Fe,lt as Ie,m as Le,mt as Re,n as ze,nt as Be,o as Ve,ot as He,p as Ue,pt as We,q as _,r as Ge,rt as Ke,st as qe,tt as Je,u as Ye,ut as Xe,vt as Ze,wt as Qe,xt as $e,y as et,yt as tt,z as nt}from"./authority-state-bootstrap-BkI-zYRx.mjs";import{d as rt,f as it,p as at}from"./execution-attempt-repository-aabFKcXN.mjs";import{assertWorkflowTriggerPayload as ot,compileWorkflowTriggerBindingFilter as st}from"./workflow-engine/workflow-trigger-binding-consumer.mjs";import{a as ct,r as lt}from"./execution-attempt-owner-recovery-CE_rvHKE.mjs";import{SerialLane as ut}from"@makaio/framework/utils";import{ArtifactSubjects as dt,AutomationTriggerSubjects as ft,CRON_AUTOMATION_TRIGGER_KIND as pt,EXECUTION_LIST_DEFAULT_LIMIT as mt,EXECUTION_LIST_MAX_LIMIT as v,EXECUTION_LIST_MIN_LIMIT as y,EXTERNAL_EXECUTION_ID_PREFIX as b,ExecutionAttemptSchemas as x,ExecutionAttemptSubjects as S,ExecutionsByArtifactRefsQuerySchema as ht,JsonPatchOperationSchema as gt,JsonValueSchema as _t,SessionSubjects as vt,WORKFLOW_CANCELLED_REASON as C,WorkLogFrameEntrySchema as yt,WorkerSubjects as bt,WorkflowAutomationTriggerBindingSchema as xt,WorkflowError as w,WorkflowErrorCode as St,WorkflowNamespace as Ct,WorkflowRunContextSchema as wt,WorkflowRunResultSchema as Tt,WorkflowStepTypeSchema as Et,WorkflowSubjects as T,createWorkflowCancelSubject as Dt,createWorkflowDelegateResultFinalizerNamespace as Ot,createWorkflowFinalizerNamespace as kt,dep as At,extensionToken as jt,serializeArtifactRef as Mt,walkWorkflowDefinition as Nt}from"@makaio/framework/contracts";import{BaseService as Pt}from"@makaio/framework/service-base";import{defineDialectSchema as Ft,executeTransaction as E,getDatabaseDialect as It,registerDrizzleHandlers as Lt,resolveSchema as D,serializeDatabaseOperation as O}from"@makaio/framework/storage/drizzle";import{and as k,asc as A,count as j,desc as M,eq as N,getTableColumns as Rt,gte as zt,isNotNull as Bt,isNull as P,lt as Vt,lte as Ht,notInArray as Ut,or as Wt,sql as F,sum as I}from"drizzle-orm";import{SessionToken as Gt}from"@makaio/framework/services";import{AutomationTriggerBindingRuntimeToken as Kt}from"@makaio/framework/services/automation-trigger";const qt=fe.postgres,Jt=_e.postgres,Yt=pe.postgres,Xt=qe.postgres,Zt=xe.postgres,Qt=e.postgres,$t=Ie.postgres,en=tt.postgres,tn=Oe.postgres,nn=We.postgres,rn=he.postgres,an=Je.postgres,on=Ke.postgres,sn=ne.postgres,cn=Pe.postgres,ln=$e.postgres,un=i.postgres,dn=Me.postgres,fn=r.postgres,pn=ce.postgres,L=Ft({workflowDefinitions:d,workflowExecutions:Ae,workflowExecutionFrames:de,workflowGateInstances:He,workflowStepSpans:Xe,workflowExecutionLinks:oe,workflowRunContexts:be,worklogSummaries:Ze,worklogFrameEntries:Re,worklogArtifactWrites:we,worklogGateEvents:Ee,workflowExecutionState:Se,workflowExecutionStateEvents:Be,workflowFinalizations:ee,executionAttempts:re,activeExecutionAttempts:ve,executionAttemptRequests:a,providerOperations:n,executionAttemptCancellations:se,executionAttemptControlEvidence:Qe},{workflowDefinitions:qt,workflowExecutions:Jt,workflowExecutionFrames:Yt,workflowGateInstances:Xt,workflowStepSpans:Zt,workflowExecutionLinks:Qt,workflowRunContexts:$t,worklogSummaries:en,worklogFrameEntries:tn,worklogArtifactWrites:nn,worklogGateEvents:rn,workflowExecutionState:an,workflowExecutionStateEvents:on,workflowFinalizations:sn,executionAttempts:cn,activeExecutionAttempts:ln,executionAttemptRequests:un,providerOperations:dn,executionAttemptCancellations:fn,executionAttemptControlEvidence:pn});function R(e){return e.type===`global`?{scopeType:`global`,scopeKind:``,scopeId:``}:e.type===`external`?{scopeType:`external`,scopeKind:e.kind,scopeId:e.id}:{scopeType:e.type,scopeKind:``,scopeId:e.id}}function z(e){switch(e.scopeType){case`global`:return{type:`global`};case`external`:if(!e.scopeKind||!e.scopeId)throw Error(`Invalid external workflow scope row: scopeKind and scopeId are required`);return{type:`external`,kind:e.scopeKind,id:e.scopeId};case`workspace`:case`session`:if(!e.scopeId)throw Error(`Invalid ${e.scopeType} workflow scope row: scopeId is required`);return{type:e.scopeType,id:e.scopeId};default:{let t=e.scopeType;throw Error(`Unknown scope type: ${String(t)}`)}}}function mn(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=R(t);return[N(e.scopeType,n),N(e.scopeKind,r),N(e.scopeId,i)]}function B(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,state:e.state??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:z(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executableSource:e.executableSource??void 0,requirements:e.requirements??void 0,successFinalizerId:e.successFinalizerId??void 0}}function hn(e,t){let n=R(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executableSource:e.executableSource??null,requirements:e.requirements??null,successFinalizerId:e.successFinalizerId??null,createdAt:t,updatedAt:t,...n}}function gn(e,t){let{workflowDefinitions:n}=D(t,L),r=Rt(n),i=e.on(_.get,async e=>{let r=await t.select().from(n).where(N(n.id,e.payload.id)).limit(1);e.setResult({workflow:r[0]?B(r[0]):null})}),a=e.on(_.set,async i=>{let a=i.payload.workflow,o=Date.now(),c=hn(a,o),l=await O(t,async()=>{let e=await t.insert(n).values(c).onConflictDoNothing({target:n.id}).returning();if(e.length>0)return{kind:`created`,row:e[0]};let[i]=await t.update(n).set({name:c.name,root:c.root,updatedAt:o,createdAt:F`COALESCE(${r.createdAt}, ${o})`,description:c.description===null?F`${r.description}`:c.description,inputSchema:c.inputSchema===null?F`${r.inputSchema}`:c.inputSchema,configSchema:c.configSchema===null?F`${r.configSchema}`:c.configSchema,outputSchema:c.outputSchema===null?F`${r.outputSchema}`:c.outputSchema,state:c.state,artifact:c.artifact===null?F`${r.artifact}`:c.artifact,triggers:c.triggers===null?F`${r.triggers}`:c.triggers,canvasLayout:c.canvasLayout===null?F`${r.canvasLayout}`:c.canvasLayout,source:c.source===null?F`${r.source}`:c.source,executableSource:c.executableSource,requirements:c.requirements,successFinalizerId:c.successFinalizerId,...R(a.scope)}).where(N(n.id,a.id)).returning();return i?{kind:`updated`,row:i}:void 0});l&&await e.emit(l.kind===`created`?s.definition.created:s.definition.updated,B(l.row)),i.setResult({id:a.id})}),o=e.on(_.delete,async r=>{let i=(await O(t,()=>t.delete(n).where(N(n.id,r.payload.id)).returning())).length>0;i&&await e.emit(s.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),c=e.on(_.list,async e=>{let r=e.payload,i=r.scope?mn(n,r.scope):[],a=i.length>0?await t.select().from(n).where(k(...i)):await t.select().from(n);e.setResult({workflows:a.map(B)})});return()=>{i(),a(),o(),c()}}function _n(e){return{frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId??void 0,status:e.status,attempt:e.attempt,iteration:e.iteration??void 0,branchKey:e.branchKey??void 0,...e.outputPresent?{output:e.output}:{},error:e.error??void 0,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0}}function vn(e,t){return{frameId:t.frameId,executionId:e,nodeId:t.nodeId,nodeType:t.nodeType,path:t.path,parentFrameId:t.parentFrameId??null,status:t.status,attempt:t.attempt,iteration:t.iteration??null,branchKey:t.branchKey??null,output:t.output===void 0?null:t.output,outputPresent:t.output!==void 0,error:t.error??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null}}function yn(e,t){let{workflowExecutionFrames:n}=D(t,L),r=e.on(_.setFrame,async e=>{let{executionId:r,frame:i}=e.payload;if(!g(e,r))throw Error(`Unauthorized: caller is not permitted to write frames for execution: ${r}`);let a=vn(r,i);await O(t,()=>t.insert(n).values(a).onConflictDoUpdate({target:n.frameId,set:a})),e.setResult({frameId:i.frameId})}),i=e.on(_.getFrame,async e=>{let r=await t.select().from(n).where(N(n.frameId,e.payload.frameId)).limit(1);e.setResult({frame:r[0]?_n(r[0]):null})}),a=e.on(_.listFrames,async e=>{if(!g(e,e.payload.executionId))throw Error(`Unauthorized: caller is not permitted to list frames for execution: ${e.payload.executionId}`);let r=await t.select().from(n).where(N(n.executionId,e.payload.executionId)).orderBy(A(n.startedAt),A(n.frameId));e.setResult({frames:r.map(_n)})});return()=>{r(),i(),a()}}function bn(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function V(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??void 0,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs??null,...e.resumeDataPresent?{resumeData:e.resumeData}:{},...e.reason===null?{}:{reason:e.reason},createdAt:e.createdAt,resolvedAt:e.resolvedAt??void 0}}function H(e){return{id:bn(e),executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??null,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs,resumeData:e.resumeData===void 0?null:e.resumeData,reason:e.reason??null,resumeDataPresent:e.resumeData!==void 0,createdAt:e.createdAt,resolvedAt:e.resolvedAt??null}}function xn(e,t,n,r){if(e===void 0&&t===void 0)throw Error(`Either executionId or status is required to list gate instances.`);let i=n??mt;if(!Number.isInteger(i)||i<y||i>v)throw Error(`Gate instance list limit must be an integer between ${y} and ${v}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[N(r.executionId,e)],...t===void 0?[]:[N(r.status,t)]]}}function Sn(e,t){let{workflowExecutions:n,workflowGateInstances:r}=D(t,L),i=e.on(_.setGateInstance,async e=>{let n=e.payload.gate;if(!g(e,n.executionId))throw Error(`Unauthorized: caller is not permitted to write gates for execution: ${n.executionId}`);let i=H(n);await O(t,()=>t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i})),e.setResult({id:i.id})}),a=e.on(_.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,i=H(n),a=await O(t,()=>t.update(r).set(i).where(k(N(r.id,i.id),N(r.status,`waiting`))).returning({id:r.id}));e.setResult({accepted:a.length===1})}),o=e.on(_.getGateInstance,async e=>{let{executionId:n,nodeId:i,frameId:a}=e.payload;if(!g(e,n))throw Error(`Unauthorized: caller is not permitted to read gates for execution: ${n}`);let o=[N(r.executionId,n),N(r.nodeId,i)];a!==void 0&&o.push(N(r.frameId,a));let s=await t.select().from(r).where(k(...o)).limit(1);e.setResult({gate:s[0]?V(s[0]):null})}),s=e.on(_.listGateInstances,async e=>{let{executionId:n,status:i,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=xn(n,i,a,r),c=await t.select().from(r).where(k(...s)).orderBy(M(r.createdAt),M(r.id)).limit(o);e.setResult({gates:c.map(V)})}),c=e.on(_.listPausedGateTimeouts,async e=>{let i=await t.select({gate:r}).from(r).innerJoin(n,N(r.executionId,n.id)).where(k(N(r.status,`waiting`),N(n.status,`paused`),Bt(r.timeoutMs)));e.setResult({gates:i.map(e=>V(e.gate))})});return()=>{i(),a(),o(),s(),c()}}function Cn(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function wn(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Tn(e,t){let{workflowStepSpans:n,workflowExecutionLinks:r}=D(t,L),i=e.on(_.setSpan,async e=>{let{span:r}=e.payload;if(!g(e,r.executionId))throw Error(`Unauthorized: caller is not permitted to write spans for execution: ${r.executionId}`);await O(t,()=>t.insert(n).values(r).onConflictDoUpdate({target:[n.executionId,n.frameId],set:r})),e.setResult({id:`${r.executionId}:${r.frameId}`})}),a=e.on(_.listSpans,async e=>{let r=await t.select().from(n).where(N(n.executionId,e.payload.executionId)).orderBy(A(n.startedAt),A(n.stepId),A(n.frameId));e.setResult({spans:r.map(Cn)})}),o=e.on(_.setExecutionLink,async e=>{let{link:n}=e.payload;await O(t,()=>t.insert(r).values(n).onConflictDoUpdate({target:[r.sourceExecutionId,r.targetExecutionId],set:n})),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),s=e.on(_.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:i}=e.payload;if(n===void 0&&i===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[N(r.sourceExecutionId,n)],...i===void 0?[]:[N(r.targetExecutionId,i)]],o=t.select().from(r).where(k(...a));e.setResult({links:(await o).map(wn)})});return()=>{i(),a(),o(),s()}}function U(e,t){return t===null?It(e)===`postgres`?F`'null'::jsonb`:F`'null'`:t}function En(e){switch(e.kind){case`path`:return{sourceKind:`path`,sourcePath:e.path,sourceFilename:null,sourceCode:null};case`source`:return{sourceKind:`source`,sourcePath:null,sourceFilename:e.filename,sourceCode:e.source};case`definition`:return{sourceKind:`definition`,sourcePath:null,sourceFilename:null,sourceCode:null}}}function Dn(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function On(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:Dn(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:z(e),...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===null?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===null?{}:{materializationSpec:e.materializationSpec}}}function kn(e){let t=En(e.source),n=R(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,artifactRef:e.artifactRef??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??null,materializationSpec:e.materializationSpec??null}}async function An(e,t,n){let r=kn(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function jn(e,t){let{workflowRunContexts:n,workflowExecutionState:r,workflowExecutionStateEvents:i}=D(t,L),a=e.on(_.setRunContext,async e=>{let a=e.payload.runContext,o=e.payload.initialState;await E(t,async e=>{if(await An(e,a,n),o===void 0)return;let s=Date.now(),c=U(t,o);await e.insert(r).values({executionId:a.executionId,sequence:0,value:c,updatedAt:s}).onConflictDoNothing(),await e.insert(i).values({executionId:a.executionId,sequence:0,patch:[],value:c,createdAt:s}).onConflictDoNothing()}),e.setResult({executionId:a.executionId})}),o=e.on(_.getRunContext,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(N(n.executionId,r)),a=i[0]?On(i[0]):null;e.setResult({runContext:a})});return()=>{a(),o()}}async function Mn(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=D(e,L),a=Date.now(),o=U(e,n);await E(e,async e=>{await e.insert(r).values({executionId:t,sequence:0,value:o,updatedAt:a}).onConflictDoNothing(),await e.insert(i).values({executionId:t,sequence:0,patch:[],value:o,createdAt:a}).onConflictDoNothing()})}async function Nn(e,t){let{workflowExecutionState:n}=D(e,L),r=(await e.select().from(n).where(N(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function Pn(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=D(e,L),i=Date.now(),a=U(e,t.nextValue);return E(e,async e=>{let o=(await e.select().from(n).where(N(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=le(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(k(N(n.executionId,t.executionId),N(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function Fn(e,t){let n=e.on(_.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await Mn(t,n,r),e.setResult({})}),r=e.on(_.getState,async e=>{let{executionId:n}=e.payload,r=await Nn(t,n);e.setResult({state:r})}),i=e.on(_.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await Pn(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{n(),r(),i()}}function In(e){return{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName??void 0,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,totalInputTokens:e.totalInputTokens??void 0,totalOutputTokens:e.totalOutputTokens??void 0,totalEstimatedCost:e.totalEstimatedCost??void 0,error:e.error??void 0,failedNodeId:e.failedNodeId??void 0}}async function Ln(e,t){let{worklogSummaries:n}=D(e,L);await e.insert(n).values(t).onConflictDoNothing()}async function Rn(e,t){let{worklogSummaries:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:zn(t),setWhere:Ut(n.status,[`completed`,`failed`,`cancelled`])})}function zn(e){return{workflowId:e.workflowId,workflowName:e.workflowName,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,error:e.error,failedNodeId:e.failedNodeId}}async function W(e,t){let{worklogSummaries:n}=D(e,L),r=await e.select().from(n).where(N(n.executionId,t)).limit(1);return r[0]?In(r[0]):null}async function Bn(e,t={}){let{worklogSummaries:n}=D(e,L),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[N(n.workflowId,r)],...i===void 0?[]:[N(n.status,i)]],c=s.length>0?k(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(M(n.startedAt)).limit(a).offset(o),e.select({count:j()}).from(n).where(c)]);return{items:l.map(In),total:u[0]?.count??0}}async function Vn(e,t){let{worklogFrameEntries:n}=D(e,L);await e.insert(n).values(t).onConflictDoNothing()}async function Hn(e,t){let{worklogFrameEntries:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:Ut(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function G(e,t){let{worklogFrameEntries:n}=D(e,L);return(await e.select().from(n).where(N(n.frameId,t)).limit(1))[0]??null}async function Un(e,t){let n=await G(e,t);return n===null?null:yt.parse({executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??void 0,branchKey:n.branchKey??void 0,startedAt:n.startedAt??void 0,completedAt:n.completedAt??void 0,durationMs:n.durationMs??void 0,inputTokens:n.inputTokens??void 0,outputTokens:n.outputTokens??void 0,estimatedCost:n.estimatedCost??void 0,error:n.error??void 0})}async function Wn(e,t){let{worklogArtifactWrites:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function Gn(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function Kn(e,t){let{worklogGateEvents:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function qn(e,t){let{worklogGateEvents:n}=D(e,L);return(await e.select().from(n).where(N(n.id,t)).limit(1))[0]??null}function Jn(e,t,n){return`${e}:${t}:${n}`}async function Yn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(N(t.executionId,n)).returning();return r}async function Xn(e,t,n){let[r]=await e.select({totalInputTokens:I(t.inputTokens),totalOutputTokens:I(t.outputTokens),totalEstimatedCost:I(t.estimatedCost),measuredInputTokens:j(t.inputTokens),measuredOutputTokens:j(t.outputTokens),measuredCosts:j(t.estimatedCost)}).from(t).where(N(t.executionId,n));return{totalInputTokens:Number(r?.totalInputTokens??0),totalOutputTokens:Number(r?.totalOutputTokens??0),totalEstimatedCost:Number(r?.totalEstimatedCost??0),hasMeasurements:Number(r?.measuredInputTokens??0)>0||Number(r?.measuredOutputTokens??0)>0||Number(r?.measuredCosts??0)>0}}function Zn(e){return e.hasMeasurements}async function Qn(e,t,n,r){await e.update(t).set({totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost}).where(N(t.executionId,n))}async function $n(e,t,n,r){let i=F`coalesce((select sum(${n.inputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,a=F`coalesce((select sum(${n.outputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,o=F`coalesce((select sum(${n.estimatedCost}) from ${n} where ${n.executionId} = ${r}), 0)`,s=F`exists(
|
|
1
|
+
import{$ as e,A as t,At as n,Ct as r,Dt as i,Et as a,F as o,Ft as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,Mt as ee,N as te,Nt as ne,Ot as re,P as ie,Pt as ae,Q as oe,R as h,St as se,Tt as ce,U as le,V as ue,W as g,X as de,Y as fe,Z as pe,_ as me,_t as he,a as ge,at as _e,bt as ve,c as ye,ct as be,dt as xe,et as Se,f as Ce,ft as we,g as Te,gt as Ee,h as De,ht as Oe,i as ke,it as Ae,j as je,jt as Me,k as Ne,kt as Pe,l as Fe,lt as Ie,m as Le,mt as Re,n as ze,nt as Be,o as Ve,ot as He,p as Ue,pt as We,q as _,r as Ge,rt as Ke,st as qe,tt as Je,u as Ye,ut as Xe,vt as Ze,wt as Qe,xt as $e,y as et,yt as tt,z as nt}from"./authority-state-bootstrap-CvuWPywM.mjs";import{d as rt,f as it,p as at}from"./execution-attempt-repository-aabFKcXN.mjs";import{assertWorkflowTriggerPayload as ot,compileWorkflowTriggerBindingFilter as st}from"./workflow-engine/workflow-trigger-binding-consumer.mjs";import{a as ct,r as lt}from"./execution-attempt-owner-recovery-CE_rvHKE.mjs";import{SerialLane as ut}from"@makaio/framework/utils";import{ArtifactSubjects as dt,AutomationTriggerSubjects as ft,CRON_AUTOMATION_TRIGGER_KIND as pt,EXECUTION_LIST_DEFAULT_LIMIT as mt,EXECUTION_LIST_MAX_LIMIT as v,EXECUTION_LIST_MIN_LIMIT as y,EXTERNAL_EXECUTION_ID_PREFIX as b,ExecutionAttemptSchemas as x,ExecutionAttemptSubjects as S,ExecutionsByArtifactRefsQuerySchema as ht,JsonPatchOperationSchema as gt,JsonValueSchema as _t,SessionSubjects as vt,WORKFLOW_CANCELLED_REASON as C,WorkLogFrameEntrySchema as yt,WorkerSubjects as bt,WorkflowAutomationTriggerBindingSchema as xt,WorkflowError as w,WorkflowErrorCode as St,WorkflowNamespace as Ct,WorkflowRunContextSchema as wt,WorkflowRunResultSchema as Tt,WorkflowStepTypeSchema as Et,WorkflowSubjects as T,createWorkflowCancelSubject as Dt,createWorkflowDelegateResultFinalizerNamespace as Ot,createWorkflowFinalizerNamespace as kt,dep as At,extensionToken as jt,serializeArtifactRef as Mt,walkWorkflowDefinition as Nt}from"@makaio/framework/contracts";import{BaseService as Pt}from"@makaio/framework/service-base";import{defineDialectSchema as Ft,executeTransaction as E,getDatabaseDialect as It,registerDrizzleHandlers as Lt,resolveSchema as D,serializeDatabaseOperation as O}from"@makaio/framework/storage/drizzle";import{and as k,asc as A,count as j,desc as M,eq as N,getTableColumns as Rt,gte as zt,isNotNull as Bt,isNull as P,lt as Vt,lte as Ht,notInArray as Ut,or as Wt,sql as F,sum as I}from"drizzle-orm";import{SessionToken as Gt}from"@makaio/framework/services";import{AutomationTriggerBindingRuntimeToken as Kt}from"@makaio/framework/services/automation-trigger";const qt=fe.postgres,Jt=_e.postgres,Yt=pe.postgres,Xt=qe.postgres,Zt=xe.postgres,Qt=e.postgres,$t=Ie.postgres,en=tt.postgres,tn=Oe.postgres,nn=We.postgres,rn=he.postgres,an=Je.postgres,on=Ke.postgres,sn=ne.postgres,cn=Pe.postgres,ln=$e.postgres,un=i.postgres,dn=Me.postgres,fn=r.postgres,pn=ce.postgres,L=Ft({workflowDefinitions:d,workflowExecutions:Ae,workflowExecutionFrames:de,workflowGateInstances:He,workflowStepSpans:Xe,workflowExecutionLinks:oe,workflowRunContexts:be,worklogSummaries:Ze,worklogFrameEntries:Re,worklogArtifactWrites:we,worklogGateEvents:Ee,workflowExecutionState:Se,workflowExecutionStateEvents:Be,workflowFinalizations:ee,executionAttempts:re,activeExecutionAttempts:ve,executionAttemptRequests:a,providerOperations:n,executionAttemptCancellations:se,executionAttemptControlEvidence:Qe},{workflowDefinitions:qt,workflowExecutions:Jt,workflowExecutionFrames:Yt,workflowGateInstances:Xt,workflowStepSpans:Zt,workflowExecutionLinks:Qt,workflowRunContexts:$t,worklogSummaries:en,worklogFrameEntries:tn,worklogArtifactWrites:nn,worklogGateEvents:rn,workflowExecutionState:an,workflowExecutionStateEvents:on,workflowFinalizations:sn,executionAttempts:cn,activeExecutionAttempts:ln,executionAttemptRequests:un,providerOperations:dn,executionAttemptCancellations:fn,executionAttemptControlEvidence:pn});function R(e){return e.type===`global`?{scopeType:`global`,scopeKind:``,scopeId:``}:e.type===`external`?{scopeType:`external`,scopeKind:e.kind,scopeId:e.id}:{scopeType:e.type,scopeKind:``,scopeId:e.id}}function z(e){switch(e.scopeType){case`global`:return{type:`global`};case`external`:if(!e.scopeKind||!e.scopeId)throw Error(`Invalid external workflow scope row: scopeKind and scopeId are required`);return{type:`external`,kind:e.scopeKind,id:e.scopeId};case`workspace`:case`session`:if(!e.scopeId)throw Error(`Invalid ${e.scopeType} workflow scope row: scopeId is required`);return{type:e.scopeType,id:e.scopeId};default:{let t=e.scopeType;throw Error(`Unknown scope type: ${String(t)}`)}}}function mn(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=R(t);return[N(e.scopeType,n),N(e.scopeKind,r),N(e.scopeId,i)]}function B(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,state:e.state??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:z(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executableSource:e.executableSource??void 0,requirements:e.requirements??void 0,successFinalizerId:e.successFinalizerId??void 0}}function hn(e,t){let n=R(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executableSource:e.executableSource??null,requirements:e.requirements??null,successFinalizerId:e.successFinalizerId??null,createdAt:t,updatedAt:t,...n}}function gn(e,t){let{workflowDefinitions:n}=D(t,L),r=Rt(n),i=e.on(_.get,async e=>{let r=await t.select().from(n).where(N(n.id,e.payload.id)).limit(1);e.setResult({workflow:r[0]?B(r[0]):null})}),a=e.on(_.set,async i=>{let a=i.payload.workflow,o=Date.now(),c=hn(a,o),l=await O(t,async()=>{let e=await t.insert(n).values(c).onConflictDoNothing({target:n.id}).returning();if(e.length>0)return{kind:`created`,row:e[0]};let[i]=await t.update(n).set({name:c.name,root:c.root,updatedAt:o,createdAt:F`COALESCE(${r.createdAt}, ${o})`,description:c.description===null?F`${r.description}`:c.description,inputSchema:c.inputSchema===null?F`${r.inputSchema}`:c.inputSchema,configSchema:c.configSchema===null?F`${r.configSchema}`:c.configSchema,outputSchema:c.outputSchema===null?F`${r.outputSchema}`:c.outputSchema,state:c.state,artifact:c.artifact===null?F`${r.artifact}`:c.artifact,triggers:c.triggers===null?F`${r.triggers}`:c.triggers,canvasLayout:c.canvasLayout===null?F`${r.canvasLayout}`:c.canvasLayout,source:c.source===null?F`${r.source}`:c.source,executableSource:c.executableSource,requirements:c.requirements,successFinalizerId:c.successFinalizerId,...R(a.scope)}).where(N(n.id,a.id)).returning();return i?{kind:`updated`,row:i}:void 0});l&&await e.emit(l.kind===`created`?s.definition.created:s.definition.updated,B(l.row)),i.setResult({id:a.id})}),o=e.on(_.delete,async r=>{let i=(await O(t,()=>t.delete(n).where(N(n.id,r.payload.id)).returning())).length>0;i&&await e.emit(s.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),c=e.on(_.list,async e=>{let r=e.payload,i=r.scope?mn(n,r.scope):[],a=i.length>0?await t.select().from(n).where(k(...i)):await t.select().from(n);e.setResult({workflows:a.map(B)})});return()=>{i(),a(),o(),c()}}function _n(e){return{frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId??void 0,status:e.status,attempt:e.attempt,iteration:e.iteration??void 0,branchKey:e.branchKey??void 0,...e.outputPresent?{output:e.output}:{},error:e.error??void 0,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0}}function vn(e,t){return{frameId:t.frameId,executionId:e,nodeId:t.nodeId,nodeType:t.nodeType,path:t.path,parentFrameId:t.parentFrameId??null,status:t.status,attempt:t.attempt,iteration:t.iteration??null,branchKey:t.branchKey??null,output:t.output===void 0?null:t.output,outputPresent:t.output!==void 0,error:t.error??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null}}function yn(e,t){let{workflowExecutionFrames:n}=D(t,L),r=e.on(_.setFrame,async e=>{let{executionId:r,frame:i}=e.payload;if(!g(e,r))throw Error(`Unauthorized: caller is not permitted to write frames for execution: ${r}`);let a=vn(r,i);await O(t,()=>t.insert(n).values(a).onConflictDoUpdate({target:n.frameId,set:a})),e.setResult({frameId:i.frameId})}),i=e.on(_.getFrame,async e=>{let r=await t.select().from(n).where(N(n.frameId,e.payload.frameId)).limit(1);e.setResult({frame:r[0]?_n(r[0]):null})}),a=e.on(_.listFrames,async e=>{if(!g(e,e.payload.executionId))throw Error(`Unauthorized: caller is not permitted to list frames for execution: ${e.payload.executionId}`);let r=await t.select().from(n).where(N(n.executionId,e.payload.executionId)).orderBy(A(n.startedAt),A(n.frameId));e.setResult({frames:r.map(_n)})});return()=>{r(),i(),a()}}function bn(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function V(e){return{executionId:e.executionId,...e.executionAttemptId===null?{}:{executionAttemptId:e.executionAttemptId},nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??void 0,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs??null,...e.resumeDataPresent?{resumeData:e.resumeData}:{},...e.reason===null?{}:{reason:e.reason},createdAt:e.createdAt,resolvedAt:e.resolvedAt??void 0}}function H(e){return{id:bn(e),executionId:e.executionId,executionAttemptId:e.executionAttemptId??null,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??null,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs,resumeData:e.resumeData===void 0?null:e.resumeData,reason:e.reason??null,resumeDataPresent:e.resumeData!==void 0,createdAt:e.createdAt,resolvedAt:e.resolvedAt??null}}function xn(e,t,n,r){if(e===void 0&&t===void 0)throw Error(`Either executionId or status is required to list gate instances.`);let i=n??mt;if(!Number.isInteger(i)||i<y||i>v)throw Error(`Gate instance list limit must be an integer between ${y} and ${v}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[N(r.executionId,e)],...t===void 0?[]:[N(r.status,t)]]}}function Sn(e,t){let{workflowGateInstances:n}=D(t,L);return e.on(_.resolveWaitingGateInstance,async e=>{let r=e.payload.gate,i=H(r),a=await O(t,()=>t.update(n).set(i).where(k(N(n.id,i.id),N(n.status,`waiting`),r.executionAttemptId===void 0?P(n.executionAttemptId):N(n.executionAttemptId,r.executionAttemptId))).returning({id:n.id}));e.setResult({accepted:a.length===1})})}function Cn(e,t){let{workflowExecutions:n,workflowGateInstances:r}=D(t,L),i=e.on(_.setGateInstance,async e=>{let n=e.payload.gate;if(!g(e,n.executionId))throw Error(`Unauthorized: caller is not permitted to write gates for execution: ${n.executionId}`);let i=H(n);await O(t,()=>t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i})),e.setResult({id:i.id})}),a=Sn(e,t),o=e.on(_.getGateInstance,async e=>{let{executionId:n,nodeId:i,frameId:a}=e.payload;if(!g(e,n))throw Error(`Unauthorized: caller is not permitted to read gates for execution: ${n}`);let o=[N(r.executionId,n),N(r.nodeId,i)];a!==void 0&&o.push(N(r.frameId,a));let s=await t.select().from(r).where(k(...o)).limit(1);e.setResult({gate:s[0]?V(s[0]):null})}),s=e.on(_.listGateInstances,async e=>{let{executionId:n,status:i,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=xn(n,i,a,r),c=await t.select().from(r).where(k(...s)).orderBy(M(r.createdAt),M(r.id)).limit(o);e.setResult({gates:c.map(V)})}),c=e.on(_.listPausedGateTimeouts,async e=>{let i=await t.select({gate:r}).from(r).innerJoin(n,N(r.executionId,n.id)).where(k(N(r.status,`waiting`),N(n.status,`paused`),Bt(r.timeoutMs)));e.setResult({gates:i.map(e=>V(e.gate))})});return()=>{i(),a(),o(),s(),c()}}function wn(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function Tn(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function En(e,t){let{workflowStepSpans:n,workflowExecutionLinks:r}=D(t,L),i=e.on(_.setSpan,async e=>{let{span:r}=e.payload;if(!g(e,r.executionId))throw Error(`Unauthorized: caller is not permitted to write spans for execution: ${r.executionId}`);await O(t,()=>t.insert(n).values(r).onConflictDoUpdate({target:[n.executionId,n.frameId],set:r})),e.setResult({id:`${r.executionId}:${r.frameId}`})}),a=e.on(_.listSpans,async e=>{let r=await t.select().from(n).where(N(n.executionId,e.payload.executionId)).orderBy(A(n.startedAt),A(n.stepId),A(n.frameId));e.setResult({spans:r.map(wn)})}),o=e.on(_.setExecutionLink,async e=>{let{link:n}=e.payload;await O(t,()=>t.insert(r).values(n).onConflictDoUpdate({target:[r.sourceExecutionId,r.targetExecutionId],set:n})),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),s=e.on(_.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:i}=e.payload;if(n===void 0&&i===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[N(r.sourceExecutionId,n)],...i===void 0?[]:[N(r.targetExecutionId,i)]],o=t.select().from(r).where(k(...a));e.setResult({links:(await o).map(Tn)})});return()=>{i(),a(),o(),s()}}function U(e,t){return t===null?It(e)===`postgres`?F`'null'::jsonb`:F`'null'`:t}function Dn(e){switch(e.kind){case`path`:return{sourceKind:`path`,sourcePath:e.path,sourceFilename:null,sourceCode:null};case`source`:return{sourceKind:`source`,sourcePath:null,sourceFilename:e.filename,sourceCode:e.source};case`definition`:return{sourceKind:`definition`,sourcePath:null,sourceFilename:null,sourceCode:null}}}function On(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function kn(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:On(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:z(e),...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===null?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===null?{}:{materializationSpec:e.materializationSpec}}}function An(e){let t=Dn(e.source),n=R(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,artifactRef:e.artifactRef??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??null,materializationSpec:e.materializationSpec??null}}async function jn(e,t,n){let r=An(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function Mn(e,t){let{workflowRunContexts:n,workflowExecutionState:r,workflowExecutionStateEvents:i}=D(t,L),a=e.on(_.setRunContext,async e=>{let a=e.payload.runContext,o=e.payload.initialState;await E(t,async e=>{if(await jn(e,a,n),o===void 0)return;let s=Date.now(),c=U(t,o);await e.insert(r).values({executionId:a.executionId,sequence:0,value:c,updatedAt:s}).onConflictDoNothing(),await e.insert(i).values({executionId:a.executionId,sequence:0,patch:[],value:c,createdAt:s}).onConflictDoNothing()}),e.setResult({executionId:a.executionId})}),o=e.on(_.getRunContext,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(N(n.executionId,r)),a=i[0]?kn(i[0]):null;e.setResult({runContext:a})});return()=>{a(),o()}}async function Nn(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=D(e,L),a=Date.now(),o=U(e,n);await E(e,async e=>{await e.insert(r).values({executionId:t,sequence:0,value:o,updatedAt:a}).onConflictDoNothing(),await e.insert(i).values({executionId:t,sequence:0,patch:[],value:o,createdAt:a}).onConflictDoNothing()})}async function Pn(e,t){let{workflowExecutionState:n}=D(e,L),r=(await e.select().from(n).where(N(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function Fn(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=D(e,L),i=Date.now(),a=U(e,t.nextValue);return E(e,async e=>{let o=(await e.select().from(n).where(N(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=le(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(k(N(n.executionId,t.executionId),N(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function In(e,t){let n=e.on(_.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await Nn(t,n,r),e.setResult({})}),r=e.on(_.getState,async e=>{let{executionId:n}=e.payload,r=await Pn(t,n);e.setResult({state:r})}),i=e.on(_.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await Fn(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{n(),r(),i()}}function Ln(e){return{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName??void 0,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,totalInputTokens:e.totalInputTokens??void 0,totalOutputTokens:e.totalOutputTokens??void 0,totalEstimatedCost:e.totalEstimatedCost??void 0,error:e.error??void 0,failedNodeId:e.failedNodeId??void 0}}async function Rn(e,t){let{worklogSummaries:n}=D(e,L);await e.insert(n).values(t).onConflictDoNothing()}async function zn(e,t){let{worklogSummaries:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:Bn(t),setWhere:Ut(n.status,[`completed`,`failed`,`cancelled`])})}function Bn(e){return{workflowId:e.workflowId,workflowName:e.workflowName,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,error:e.error,failedNodeId:e.failedNodeId}}async function W(e,t){let{worklogSummaries:n}=D(e,L),r=await e.select().from(n).where(N(n.executionId,t)).limit(1);return r[0]?Ln(r[0]):null}async function Vn(e,t={}){let{worklogSummaries:n}=D(e,L),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[N(n.workflowId,r)],...i===void 0?[]:[N(n.status,i)]],c=s.length>0?k(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(M(n.startedAt)).limit(a).offset(o),e.select({count:j()}).from(n).where(c)]);return{items:l.map(Ln),total:u[0]?.count??0}}async function Hn(e,t){let{worklogFrameEntries:n}=D(e,L);await e.insert(n).values(t).onConflictDoNothing()}async function Un(e,t){let{worklogFrameEntries:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:Ut(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function G(e,t){let{worklogFrameEntries:n}=D(e,L);return(await e.select().from(n).where(N(n.frameId,t)).limit(1))[0]??null}async function Wn(e,t){let n=await G(e,t);return n===null?null:yt.parse({executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??void 0,branchKey:n.branchKey??void 0,startedAt:n.startedAt??void 0,completedAt:n.completedAt??void 0,durationMs:n.durationMs??void 0,inputTokens:n.inputTokens??void 0,outputTokens:n.outputTokens??void 0,estimatedCost:n.estimatedCost??void 0,error:n.error??void 0})}async function Gn(e,t){let{worklogArtifactWrites:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function Kn(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function qn(e,t){let{worklogGateEvents:n}=D(e,L);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function Jn(e,t){let{worklogGateEvents:n}=D(e,L);return(await e.select().from(n).where(N(n.id,t)).limit(1))[0]??null}function Yn(e,t,n){return`${e}:${t}:${n}`}async function Xn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(N(t.executionId,n)).returning();return r}async function Zn(e,t,n){let[r]=await e.select({totalInputTokens:I(t.inputTokens),totalOutputTokens:I(t.outputTokens),totalEstimatedCost:I(t.estimatedCost),measuredInputTokens:j(t.inputTokens),measuredOutputTokens:j(t.outputTokens),measuredCosts:j(t.estimatedCost)}).from(t).where(N(t.executionId,n));return{totalInputTokens:Number(r?.totalInputTokens??0),totalOutputTokens:Number(r?.totalOutputTokens??0),totalEstimatedCost:Number(r?.totalEstimatedCost??0),hasMeasurements:Number(r?.measuredInputTokens??0)>0||Number(r?.measuredOutputTokens??0)>0||Number(r?.measuredCosts??0)>0}}function Qn(e){return e.hasMeasurements}async function $n(e,t,n,r){await e.update(t).set({totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost}).where(N(t.executionId,n))}async function er(e,t,n,r){let i=F`coalesce((select sum(${n.inputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,a=F`coalesce((select sum(${n.outputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,o=F`coalesce((select sum(${n.estimatedCost}) from ${n} where ${n.executionId} = ${r}), 0)`,s=F`exists(
|
|
2
2
|
select 1 from ${n}
|
|
3
3
|
where ${n.executionId} = ${r}
|
|
4
4
|
and (${n.inputTokens} is not null
|
|
5
5
|
or ${n.outputTokens} is not null
|
|
6
6
|
or ${n.estimatedCost} is not null)
|
|
7
|
-
)`;await e.update(t).set({totalInputTokens:i,totalOutputTokens:a,totalEstimatedCost:o}).where(k(N(t.executionId,r),s))}async function er(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=D(e,L);if(It(e)===`sqlite`){await $n(e,n,r,t);return}await E(e,async e=>{if(await Yn(e,n,t)===void 0)return;let i=await Xn(e,r,t);Zn(i)&&await Qn(e,n,t,i)})}async function tr(e,t={}){let{worklogSummaries:n}=D(e,L),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[N(n.workflowId,r)],...i===void 0?[]:[zt(n.startedAt,i)],...a===void 0?[]:[Ht(n.startedAt,a)]],s=o.length>0?k(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:j()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:I(n.durationMs),totalInputTokens:I(n.totalInputTokens),totalOutputTokens:I(n.totalOutputTokens),totalEstimatedCost:I(n.totalEstimatedCost)}).from(n).where(s)]),u={pending:0,running:0,paused:0,finalizing:0,completed:0,failed:0,cancelled:0},d=0;for(let e of c)u[e.status]=e.count,d+=e.count;let f=l[0];return{total:d,byStatus:u,totalDurationMs:Number(f?.totalDurationMs??0),totalInputTokens:Number(f?.totalInputTokens??0),totalOutputTokens:Number(f?.totalOutputTokens??0),totalEstimatedCost:Number(f?.totalEstimatedCost??0)}}async function nr(e,t,n,r,i){let a=await G(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(dt.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function K(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function q(e,t){try{await e.emit(s.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const rr=new Set([`completed`,`failed`,`cancelled`]);function ir(e){return rr.has(e)}async function ar(e,t){return await Ln(e,{executionId:t.executionId,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),!0}async function or(e,t){let n=t.completedAt??Date.now(),r=await W(e,t.executionId);return r!==null&&ir(r.status)?!1:(await Rn(e,{executionId:t.executionId,workflowId:r?.workflowId??t.executionId,workflowName:r?.workflowName??null,status:`completed`,startedAt:r?.startedAt??n-t.totalDuration,completedAt:n,durationMs:t.totalDuration,totalInputTokens:r?.totalInputTokens??null,totalOutputTokens:r?.totalOutputTokens??null,totalEstimatedCost:r?.totalEstimatedCost??null,error:null,failedNodeId:null}),!0)}async function sr(e,t,n,r,i,a){let o=await W(e,t);if(o!==null&&ir(o.status))return!1;let s=o?.startedAt??a;return await Rn(e,{executionId:t,workflowId:o?.workflowId??t,workflowName:o?.workflowName??null,status:n,startedAt:s,completedAt:a,durationMs:a-s,totalInputTokens:o?.totalInputTokens??null,totalOutputTokens:o?.totalOutputTokens??null,totalEstimatedCost:o?.totalEstimatedCost??null,error:r,failedNodeId:i}),!0}function cr(e,t){return[e.on(s.execution.started,async n=>{let{executionId:r}=n.payload;await K(`execution.started[${r}]`,async()=>{await O(t,()=>ar(t,n.payload))&&await q(e,r)})}),e.on(s.execution.completed,async n=>{let{executionId:r}=n.payload;await K(`execution.completed[${r}]`,async()=>{await O(t,()=>or(t,n.payload))&&await q(e,r)})}),e.on(s.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await K(`execution.failed[${r}]`,async()=>{await O(t,()=>sr(t,r,`failed`,i,a??null,o))&&await q(e,r)})}),e.on(s.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await K(`execution.cancelled[${r}]`,async()=>{await O(t,()=>sr(t,r,`cancelled`,null,null,i))&&await q(e,r)})})]}const lr=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function ur(e){return lr.has(e)}function dr(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function fr(e,t,n,r,i,a,o){let s=o??Date.now(),c=await G(t,r);c!==null&&ur(c.status)||(await Hn(t,{frameId:r,executionId:n,...dr(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await er(t,n),await q(e,n))}async function pr(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await G(t,r);l!==null&&ur(l.status)||(await Hn(t,{frameId:r,executionId:n,...dr(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await q(e,n))}function mr(e,t){return[e.on(s.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await K(`frame.started[${i}]`,async()=>{await Vn(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await q(e,r)})}),e.on(s.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await K(`frame.completed[${i}]`,()=>fr(e,t,r,i,a,o,s))}),e.on(s.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await K(`frame.failed[${i}]`,()=>pr(e,t,r,i,a,o,s,c))})]}const hr={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function gr(e,t){return[e.on(s.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await K(`gate.suspended[${i}]`,async()=>{await Kn(t,{id:Jn(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await q(e,r)})}),e.on(s.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await K(`gate.resumed[${i}]`,async()=>{let n=Jn(r,a,i),s=await qn(t,n),c=Date.now();await Kn(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await q(e,r)})}),e.on(s.gate.resolved,async n=>_r(n.payload,e,t)),e.on(s.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await K(`artifact.updated[${r}:${i}]`,async()=>{let n=await nr(e,t,i,a,o);if(n===null)return;let s=Date.now();await Wn(t,{id:Gn(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await q(e,r)})})]}async function _r(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await K(`gate.resolved[${i}]`,async()=>{let s=Jn(r,a,i),c=await qn(n,s),l=Date.now();await Kn(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:hr[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await q(t,r)})}function vr(e,t){let n=[...cr(e,t),...mr(e,t),...gr(e,t),e.on(s.worklog.get,async e=>{let{executionId:n}=e.payload,r=await W(t,n);e.setResult({summary:r})}),e.on(s.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await Un(t,n);e.setResult({frame:r})}),e.on(s.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await Bn(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(s.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await tr(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function J(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>J(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t,i=Object.keys(n).sort(),a=Object.keys(r).sort();return i.length===a.length&&i.every((e,t)=>e===a[t]&&J(n[e],r[e]))}function yr(e){return{executionId:e.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,status:e.status,attempt:e.attempt,iteration:e.iteration??null,branchKey:e.branchKey??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null,durationMs:e.durationMs??null,inputTokens:e.inputTokens??null,outputTokens:e.outputTokens??null,estimatedCost:e.estimatedCost??null,error:e.error??null}}function br(e,t){let n=e.frame;if(n!==void 0){let r=e.status===`failed`?e.error??null:null;if(n.executionId!==e.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);if(n.status!==e.status)throw Error(`settleExternalExecution requires frame.status to match status`);if(n.completedAt!==t)throw Error(`settleExternalExecution requires frame.completedAt to match completedAt`);if(n.durationMs!==t-n.startedAt)throw Error(`settleExternalExecution requires frame.durationMs to match its timestamps`);if((n.error??null)!==r)throw Error(`settleExternalExecution requires frame.error to match terminal error metadata`)}return JSON.stringify({version:1,status:e.status,completedAt:t,error:e.status===`failed`?e.error??null:null,reason:e.status===`cancelled`?e.reason??null:null,frame:n===void 0?null:{executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??null,branchKey:n.branchKey??null,startedAt:n.startedAt,completedAt:n.completedAt,durationMs:n.durationMs,error:n.status===`failed`?n.error??null:null}})}function xr(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function Sr(e,t,n,r,i){let a=br(r,i);if(n.externalSettlementFingerprint!==null){xr(n.externalSettlementFingerprint,a,r.executionId);return}if(r.frame!==void 0)throw Error(`settleExternalExecution: frame presence conflicts with the legacy frame-less settlement for execution "${r.executionId}"`);let o=r.status===`failed`?r.error??null:null,s=r.status===`cancelled`?r.reason??null:null;if((await e.update(t).set({externalSettlementFingerprint:a}).where(k(N(t.id,r.executionId),P(t.externalSettlementFingerprint),N(t.status,r.status),N(t.completedAt,i),o===null?P(t.error):N(t.error,o),s===null?P(t.reason):N(t.reason,s))).returning({fingerprint:t.externalSettlementFingerprint})).length>0)return;let[c]=await e.select().from(t).where(N(t.id,r.executionId)).limit(1);if(c===void 0)throw Error(`settleExternalExecution: execution "${r.executionId}" disappeared`);if(wr(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);xr(c.externalSettlementFingerprint,a,r.executionId)}function Cr(e,t){if(e.executionId!==t.executionId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`settleExternalExecution: frame "${t.frameId}" conflicts with its registered metadata`)}function wr(e,t,n){let r=t.status===`failed`?t.error??null:null,i=t.status===`cancelled`?t.reason??null:null;if(e.status!==t.status||e.completedAt!==n||e.error!==r||e.reason!==i)throw e.status===t.status?Error(`settleExternalExecution: execution "${t.executionId}" conflicts with an existing terminal settlement`):Error(`settleExternalExecution: execution "${t.executionId}" cannot transition from status "${e.status}"`)}async function Tr(e,t,n){let r=await e.select().from(t).where(N(t.executionId,n.executionId)),i=r.find(e=>e.frameId===n.frame.frameId);if(i!==void 0)return i;if(r.length>0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" conflicts with the registered frame identity`);let[a]=await e.select().from(t).where(N(t.frameId,n.frame.frameId)).limit(1);if(a!==void 0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" belongs to another execution`)}function Er(e,t,n,r){let i=Math.min(e.startedAt,r);return{executionId:e.id,workflowId:e.workflowId,workflowName:t?.workflowName??null,status:n.status,startedAt:i,completedAt:r,durationMs:r-i,totalInputTokens:t?.totalInputTokens??null,totalOutputTokens:t?.totalOutputTokens??null,totalEstimatedCost:t?.totalEstimatedCost??null,error:n.status===`failed`?n.error??null:null,failedNodeId:n.status===`failed`?n.frame?.nodeId??t?.failedNodeId??null:null}}function Dr(e,t){return yr({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function Or(e,t){if(e.externalRegistrationFrameId!==(t.externalRegistrationFrameId??null))throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);if(!(e.id===t.id&&e.workflowId===t.workflowId&&e.coordinatorSessionId===t.coordinatorSessionId&&e.startedAt===t.startedAt&&e.scopeType===t.scopeType&&e.scopeKind===t.scopeKind&&e.scopeId===t.scopeId&&e.artifactKind===t.artifactKind&&e.artifactId===t.artifactId&&J(e.inputs,t.inputs)&&J(e.triggerPayload,t.triggerPayload)))throw Error(`setExternalExecutionStart: registration conflicts for execution "${t.id}"`)}function kr(e,t){if(e.workflowId!==t.workflowId||e.startedAt!==t.startedAt||e.executionId!==t.executionId)throw Error(`setExternalExecutionStart: WorkLog summary conflicts for execution "${t.executionId}"`)}function Ar(e,t){if(e.executionId!==t.executionId||e.frameId!==t.frameId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`setExternalExecutionStart: WorkLog frame conflicts for frame "${t.frameId}"`)}async function jr(e,t,n,r){if(!t.id.startsWith(b))throw Error(`setExternalExecutionStart: execution "${t.id}" is not an external execution ID`);if(n!==void 0&&n.executionId!==t.id)throw Error(`setExternalExecutionStart requires frame.executionId to match execution.id`);let{workflowExecutions:i,worklogSummaries:a,worklogFrameEntries:o}=D(e,L),s={...r(t),externalRegistrationFrameId:n?.frameId??null},c={executionId:t.id,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt,completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null};await E(e,async e=>{let r=(await e.insert(i).values(s).onConflictDoNothing().returning({id:i.id})).length===0;if(r){let[n]=await e.select().from(i).where(N(i.id,t.id)).limit(1);if(n===void 0)throw Error(`setExternalExecutionStart: execution "${t.id}" disappeared`);Or(n,s)}let[l]=await e.select().from(a).where(N(a.executionId,t.id)).limit(1);if(l===void 0?await e.insert(a).values(c):kr(l,c),n!==void 0){let[i]=await e.select().from(o).where(N(o.frameId,n.frameId)).limit(1);if(i===void 0){if(r)throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);await e.insert(o).values(yr(n))}else Ar(i,n)}})}async function Mr(e,t,n,r,i){if(r.frame!==void 0){let n=await Tr(e,t,r);return n!==void 0&&Cr(n,r.frame),{frame:r.frame,existing:n}}if(n.externalRegistrationFrameId===null)return;let[a]=await e.select().from(t).where(N(t.frameId,n.externalRegistrationFrameId)).limit(1);if(a===void 0||a.executionId!==n.id)throw Error(`settleExternalExecution: registered frame "${n.externalRegistrationFrameId}" is unavailable for execution "${n.id}"`);if(a.startedAt===null)throw Error(`settleExternalExecution: registered frame "${a.frameId}" has no start timestamp`);if(i<a.startedAt)throw Error(`settleExternalExecution: completedAt must not precede the registered frame start timestamp`);let o=Et.parse(a.nodeType);return{frame:{executionId:a.executionId,frameId:a.frameId,nodeId:a.nodeId,nodeType:o,path:a.path,status:r.status,attempt:a.attempt,...a.iteration===null?{}:{iteration:a.iteration},...a.branchKey===null?{}:{branchKey:a.branchKey},startedAt:a.startedAt,completedAt:i,durationMs:i-a.startedAt,...r.status===`failed`&&r.error!==void 0?{error:r.error}:{}},existing:a}}async function Nr(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await Yn(e,a,n.id),c=await Mr(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=Dr(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await Xn(e,o,n.id),d=Zn(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...Er(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:zn(p)}),d&&await Qn(e,a,n.id,u)}async function Pr(e,t){if(!t.executionId.startsWith(b))throw Error(`settleExternalExecution: execution "${t.executionId}" is engine-owned and must use the engine finalizer`);if(t.frame!==void 0&&t.frame.executionId!==t.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);let{workflowExecutions:n,worklogSummaries:r,worklogFrameEntries:i}=D(e,L);return E(e,async e=>{let[a]=await e.select().from(n).where(N(n.id,t.executionId)).limit(1);if(a===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" was not registered`);let o=t.completedAt??a.completedAt??Date.now();if(a.status===`running`){let r=br(t,o);if((await e.update(n).set({status:t.status,completedAt:o,error:t.status===`failed`?t.error??null:null,reason:t.status===`cancelled`?t.reason??null:null,externalSettlementFingerprint:r}).where(k(N(n.id,t.executionId),N(n.status,`running`),P(n.externalSettlementFingerprint))).returning({id:n.id})).length===0){let[r]=await e.select().from(n).where(N(n.id,t.executionId)).limit(1);if(r===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" disappeared`);t.completedAt===void 0&&r.completedAt!==null&&(o=r.completedAt),wr(r,t,o),await Sr(e,n,r,t,o)}}else wr(a,t,o),await Sr(e,n,a,t,o);return await Nr(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function Fr(e,t,n){let r=e.on(_.setExternalExecutionStart,async r=>{let i=r.payload.execution,a=r.payload.frame;await jr(t,i,a,n),await q(e,i.id),r.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),i=e.on(_.settleExternalExecution,async n=>{let r=await Pr(t,n.payload);await q(e,n.payload.executionId),n.setResult({success:r})});return()=>{r(),i()}}function Y(e){return{executionId:e.executionId,workflowId:e.workflowId,finalizerId:e.finalizerId,transitionKey:e.transitionKey,claimToken:e.claimToken,intent:e.intent,claimedAt:e.claimedAt}}function Ir(e,t){return e.state===`claimed`&&e.executionId===t.executionId&&e.workflowId===t.workflowId&&e.finalizerId===t.finalizerId&&e.transitionKey===t.transitionKey&&e.claimToken===t.claimToken&&e.intent.status===t.intent.status&&e.intent.completedAt===t.intent.completedAt&&e.intent.error===t.intent.error&&e.intent.reason===t.intent.reason}function Lr(e,t){if(e.executionId!==t.executionId||e.workflowId!==t.workflowId||e.finalizerId!==t.finalizerId||e.transitionKey!==t.transitionKey||e.claimToken!==t.claimToken)throw Error(`workflow finalization publication claim does not match durable transition ${t.executionId}`)}async function Rr(e,t){let{workflowExecutions:n,workflowFinalizations:r}=D(e,L);return E(e,async e=>{let i=await e.select().from(r).where(N(r.executionId,t.executionId)).limit(1);return i[0]?Ir(i[0],t):(await e.update(n).set({status:`finalizing`}).where(k(N(n.id,t.executionId),N(n.workflowId,t.workflowId),N(n.status,`running`))).returning({id:n.id})).length===0?!1:(await e.insert(r).values({...t,state:`claimed`}),!0)})}function zr(e){return{status:e.status,completedAt:e.completedAt,error:e.status===`failed`?e.error??`Workflow finalization failed`:null,reason:e.status===`cancelled`?e.reason??null:null}}async function Br(e,t,n,r){let{workflowExecutions:i,workflowFinalizations:a}=D(e,L);return E(e,async e=>{let o=(await e.select().from(a).where(N(a.executionId,t)).limit(1))[0];return!o||o.claimToken!==n||o.state===`failed`?!1:o.state===`acknowledged`?!0:(await e.update(i).set(zr(o.intent)).where(k(N(i.id,t),N(i.status,`finalizing`))).returning({id:i.id})).length===0?!1:(await e.update(a).set({state:`acknowledged`,settledAt:r}).where(k(N(a.executionId,t),N(a.claimToken,n),N(a.state,`claimed`))),!0)})}async function Vr(e,t,n,r,i){let{workflowExecutions:a,workflowFinalizations:o}=D(e,L);return E(e,async e=>{let s=(await e.select().from(o).where(N(o.executionId,t)).limit(1))[0];return!s||s.claimToken!==n||s.state===`acknowledged`?!1:s.state===`failed`?!0:(await e.update(a).set({status:`failed`,error:r,reason:null,completedAt:i}).where(k(N(a.id,t),N(a.status,`finalizing`))).returning({id:a.id})).length===0?!1:(await e.update(o).set({state:`failed`,failure:r,settledAt:i}).where(k(N(o.executionId,t),N(o.claimToken,n),N(o.state,`claimed`))),!0)})}async function Hr(e,t,n){let{workflowExecutions:r,workflowFinalizations:i}=D(t,L),a=(await t.select().from(i).where(N(i.executionId,n.executionId)).limit(1))[0];if(!a||(Lr(a,n),a.state===`claimed`||a.publishedAt!==null))return;let o=(await t.select({startedAt:r.startedAt,status:r.status,error:r.error,reason:r.reason,completedAt:r.completedAt}).from(r).where(N(r.id,a.executionId)).limit(1))[0];if(!(!o||o.completedAt==null)){if(o.status===`completed`)await e.emit(s.execution.completed,{executionId:a.executionId,workflowId:a.workflowId,totalDuration:o.completedAt-o.startedAt,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`failed`)await e.emit(s.execution.failed,{executionId:a.executionId,workflowId:a.workflowId,error:o.error??`Workflow finalization failed`,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`cancelled`)await e.emit(s.execution.cancelled,{executionId:a.executionId,workflowId:a.workflowId,reason:o.reason??void 0,completedAt:o.completedAt,transitionKey:a.transitionKey});else return;await O(t,()=>t.update(i).set({publishedAt:Date.now()}).where(k(N(i.executionId,a.executionId),P(i.publishedAt))))}}function Ur(e,t){let n=new Map;return async r=>{let i=(n.get(r.executionId)??Promise.resolve()).catch(()=>void 0).then(()=>Hr(e,t,r));n.set(r.executionId,i);try{await i}finally{n.get(r.executionId)===i&&n.delete(r.executionId)}}}function Wr(e,t){let n=Ur(e,t),r=e.on(_.claimFinalization,async e=>{e.setResult({claimed:await Rr(t,e.payload.claim)})}),i=e.on(_.listClaimedFinalizations,async e=>{let{workflowFinalizations:n}=D(t,L),r=await t.select().from(n).where(k(N(n.finalizerId,e.payload.finalizerId),N(n.state,`claimed`)));e.setResult({claims:r.map(Y)})}),a=e.on(_.listUnpublishedFinalizations,async e=>{let{workflowFinalizations:n}=D(t,L),r=await t.select().from(n).where(k(Wt(N(n.state,`acknowledged`),N(n.state,`failed`)),N(n.finalizerId,e.payload.finalizerId),P(n.publishedAt)));e.setResult({claims:r.map(Y)})}),o=e.on(_.publishFinalization,async e=>{await n(e.payload.claim),e.setResult({})}),s=e.on(_.acknowledgeFinalization,async e=>{let{executionId:r,claimToken:i,settledAt:a}=e.payload,o=await Br(t,r,i,a);if(e.setResult({acknowledged:o}),!o)return;let{workflowFinalizations:s}=D(t,L),c=await t.select().from(s).where(N(s.executionId,r)).limit(1);c[0]&&await n(Y(c[0]))}),c=e.on(_.failFinalization,async e=>{let{executionId:r,claimToken:i,error:a,settledAt:o}=e.payload,s=await Vr(t,r,i,a,o);if(e.setResult({failed:s}),!s)return;let{workflowFinalizations:c}=D(t,L),l=await t.select().from(c).where(N(c.executionId,r)).limit(1);l[0]&&await n(Y(l[0]))});return()=>{r(),i(),a(),o(),s(),c()}}function Gr(e){return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??void 0,status:e.status,inputs:e.inputs,config:{},error:e.error??void 0,reason:e.reason??void 0,startedAt:e.startedAt,completedAt:e.completedAt??void 0,triggerPayload:e.triggerPayload??void 0,...e.artifactKind!==null&&e.artifactId!==null?{artifactRef:{kind:e.artifactKind,id:e.artifactId}}:{},scope:z(e)}}function X(e){let t=R(e.scope);return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??null,status:e.status,inputs:e.inputs,error:e.error??null,reason:e.reason??null,startedAt:e.startedAt,completedAt:e.completedAt??null,triggerPayload:e.triggerPayload??null,artifactKind:e.artifactRef?.kind??null,artifactId:e.artifactRef?.id??null,...t}}function Kr(e,t,n,r,i,a){let o=[...e?[N(a.workflowId,e)]:[],...n?[N(a.status,n)]:[],...i===void 0?[]:[N(a.artifactKind,i.kind),N(a.artifactId,i.id)]];if(t&&o.push(...mn(a,t)),r){let e=Wt(Vt(a.startedAt,r.startedAt),k(N(a.startedAt,r.startedAt),Vt(a.id,r.id)));e&&o.push(e)}return o}async function qr(e,t,n,r,i){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);for(let e of i??[])if(e.targetExecutionId!==t.id)throw Error(`setExecutionStart requires executionLinks.targetExecutionId to match execution.id`);let{workflowExecutions:a,workflowRunContexts:o,workflowExecutionState:s,workflowExecutionStateEvents:c,workflowExecutionLinks:l}=D(e,L),u=X(t);await E(e,async d=>{await d.insert(a).values(u).onConflictDoUpdate({target:a.id,set:u});let f=(n.dispatchMetadata===void 0?await d.select({dispatchMetadata:o.dispatchMetadata}).from(o).where(N(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await An(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=U(e,r);await d.insert(s).values({executionId:t.id,sequence:0,value:i,updatedAt:n}).onConflictDoNothing(),await d.insert(c).values({executionId:t.id,sequence:0,patch:[],value:i,createdAt:n}).onConflictDoNothing()}for(let e of i??[])await d.insert(l).values(e).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:e})})}async function Jr(e,t,n){if(n.executionId!==t.id)throw Error(`restorePausedGateResumeState requires execution.id to match gate.executionId`);if(t.status!==`paused`||n.status!==`waiting`)throw Error(`restorePausedGateResumeState requires a paused execution and waiting gate`);let{workflowExecutions:r,workflowGateInstances:i}=D(e,L),a=X(t),o=H(n);await E(e,async e=>{await e.insert(r).values(a).onConflictDoUpdate({target:r.id,set:a}),await e.insert(i).values(o).onConflictDoUpdate({target:i.id,set:o})})}async function Yr(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=D(e,L);return E(e,async e=>{if((await e.select().from(i).where(N(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(k(N(a.executionId,t),N(a.status,`waiting`)))).map(e=>({...V(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(N(i.id,t));for(let t of o){let n=H(t);await e.update(a).set(n).where(N(a.id,n.id))}return{cancelled:!0,gates:o}})}async function Xr(e,t,n,r,i,a){let{workflowExecutions:o}=D(e,L);return E(e,async e=>{if((await e.select({id:o.id}).from(o).where(N(o.id,t)).limit(1))[0]===void 0)return!1;let s={};return n!==void 0&&(s.status=n),r!==void 0&&(s.error=r),i!==void 0&&(s.reason=i),a!==void 0&&(s.completedAt=a),Object.keys(s).length>0&&await e.update(o).set(s).where(N(o.id,t)),!0})}function Zr(e,t){let{workflowExecutions:n}=D(t,L),r=e.on(_.getExecution,async e=>{let{executionId:r}=e.payload;if(!g(e,r))throw Error(`Unauthorized execution read: ${r}`);let i=await t.select().from(n).where(N(n.id,r));e.setResult({execution:i[0]?Gr(i[0]):null})}),i=e.on(_.setExecution,async e=>{let r=e.payload.execution,i=X(r);await O(t,()=>t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:i})),e.setResult({id:r.id})}),a=e.on(_.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await qr(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),o=e.on(_.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await Jr(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),s=e.on(_.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await Xr(t,n,r,i,a,o);e.setResult({success:s})}),c=e.on(_.pauseRunningExecution,async e=>{let{workflowExecutions:n}=D(t,L),r=await O(t,()=>t.update(n).set({status:`paused`}).where(k(N(n.id,e.payload.executionId),N(n.status,`running`))).returning({id:n.id}));e.setResult({paused:r.length===1})}),l=e.on(_.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await Yr(t,n,r,i))});return()=>{r(),i(),a(),o(),s(),c(),l()}}function Qr(e,t){let{workflowExecutions:n}=D(t,L),r=e.on(_.listExecutions,async e=>{let{workflowId:r,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(r===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=Kr(r,i,a,s,c,n),u=o??mt;if(!Number.isInteger(u)||u<y||u>v)throw Error(`Execution list limit must be an integer between ${y} and ${v}.`);let d=await t.select().from(n).where(k(...l)).orderBy(M(n.startedAt),M(n.id)).limit(u);e.setResult({executions:d.map(Gr)})}),i=e.on(_.listExecutionsByArtifactRefs,async e=>{let r=ht.safeParse(e.payload);if(!r.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${r.error.message}`);let{refs:i,limitPerRef:a}=r.data,o={};for(let e of i){let r=await t.select().from(n).where(k(N(n.artifactKind,e.kind),N(n.artifactId,e.id))).orderBy(M(n.startedAt),M(n.id)).limit(a);r.length>0&&(o[Mt(e)]=r.map(Gr))}e.setResult({executionsByRef:o})});return()=>{r(),i()}}function $r(e,t){let n=gn(e,t),r=Zr(e,t),i=Qr(e,t),a=yn(e,t),o=Sn(e,t),s=Tn(e,t),c=jn(e,t),l=Fn(e,t),u=vr(e,t),d=Fr(e,t,X),f=Wr(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d(),f()}}function ei(e){return e.startsWith(b)}function ti(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function ni(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}async function ri(e,t){let{runContext:n}=await e.request(_.getRunContext,{executionId:t});if(n===null)throw Error(`Run context not found for execution: ${t}`);if(n.definitionSnapshot!==void 0)return n.definitionSnapshot;let{workflow:r}=await e.request(_.get,{id:n.workflowId});return r??void 0}function ii(e){return[e.on(s.getDefinition,async t=>{let n=await e.request(_.get,{id:t.payload.id});t.setResult(n)}),e.on(s.setDefinition,async t=>{let n=await e.request(_.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(s.deleteDefinition,async t=>{let n=await e.request(_.delete,{id:t.payload.id});t.setResult(n)}),e.on(s.listDefinitions,async t=>{let n=await e.request(_.list,t.payload);t.setResult(n)}),e.on(s.getExecution,async t=>{let n=await e.request(_.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(s.listExecutions,async t=>{let n=await e.request(_.listExecutions,t.payload);t.setResult(n)}),e.on(s.listExecutionsByArtifactRefs,async t=>{let n=await e.request(_.listExecutionsByArtifactRefs,t.payload);t.setResult(n)}),e.on(s.listSpans,async t=>{let n=await e.request(_.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(s.listFrames,async t=>{let n=await e.request(_.listFrames,{executionId:t.payload.executionId});t.setResult(n)}),e.on(s.listGateInstances,async t=>{let n=await e.request(_.listGateInstances,t.payload);t.setResult(n)}),e.on(s.setExecutionLink,async t=>{let n=await e.request(_.setExecutionLink,{link:t.payload.link});t.setResult(n)}),e.on(s.listExecutionLinks,async t=>{let n=await e.request(_.listExecutionLinks,t.payload);t.setResult(n)}),e.on(s.getRunContext,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(_.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)}),...ai(e)]}function ai(e){return[e.on(s.registerExternalExecution,async t=>{let n=ae.registerExternalExecution.request.parse(t.payload),{name:r,scope:i,input:a}=n;if(n.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let o=n.executionId??nt(`wfx-ext`);if(!ei(o))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let s=n.startedAt??Date.now(),c={id:o,workflowId:r,status:`running`,inputs:a===void 0?{}:a,startedAt:s,scope:i??{type:`global`},...ti(n)},l=oi(o,s,n.frame),u=await e.request(_.setExternalExecutionStart,{execution:c,...l===void 0?{}:{frame:l}});t.setResult(u)}),e.on(s.completeExternalExecution,async t=>{let n=ae.completeExternalExecution.request.parse(t.payload),{executionId:r,status:i}=n;if(!g(t,r))throw Error(`Unauthorized: caller is not permitted to settle execution: ${r}`);if(!ei(r))throw Error(`completeExternalExecution: execution "${r}" is engine-owned and must be completed through the engine finalizer, not this API`);let a=si(n),o=await e.request(_.settleExternalExecution,{executionId:r,status:i,...ni(n),...n.completedAt===void 0?{}:{completedAt:n.completedAt},...a===void 0?{}:{frame:a}});t.setResult({success:o.success})})]}function oi(e,t,n){if(n===void 0)return;let r=n.frameId??`${e}:${n.nodeId}`;return{executionId:e,frameId:r,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path??[r],status:`running`,attempt:n.attempt,...n.iteration===void 0?{}:{iteration:n.iteration},...n.branchKey===void 0?{}:{branchKey:n.branchKey},startedAt:n.startedAt??t}}function si(e){if(e.frame===void 0)return;if(e.completedAt===void 0)throw Error(`completedAt is required when frame metadata is supplied`);let t=e.completedAt-e.frame.startedAt;if(t<0)throw Error(`completedAt must not precede frame.startedAt`);if(e.frame.durationMs!==void 0&&e.frame.durationMs!==t)throw Error(`frame.durationMs must equal completedAt - frame.startedAt`);return{executionId:e.executionId,frameId:e.frame.frameId,nodeId:e.frame.nodeId,nodeType:e.frame.nodeType,path:e.frame.path,status:e.status,attempt:e.frame.attempt,...e.frame.iteration===void 0?{}:{iteration:e.frame.iteration},...e.frame.branchKey===void 0?{}:{branchKey:e.frame.branchKey},startedAt:e.frame.startedAt,completedAt:e.completedAt,durationMs:t,...e.status===`failed`&&e.error!==void 0?{error:e.error}:{}}}function ci(e){return[e.on(s.state.get,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${n}`);let{state:r}=await e.request(_.getState,{executionId:n});if(r===null)throw Error(`no workflow state for execution ${n}`);t.setResult(r)}),e.on(s.state.patch,async t=>{let{executionId:n,expectedSequence:r,patch:i,nextValue:a}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${n}`);if(r===void 0)throw Error(`expectedSequence is required to patch workflow state`);let o=await ri(e,n);o!==void 0&&ue(o,a,`next`),gt.array().parse(i);let c=await e.request(_.patchState,{executionId:n,expectedSequence:r,nextValue:a});e.emit(s.state.updated,{executionId:c.executionId,sequence:c.sequence,patch:c.patch,value:c.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:c.executionId,sequence:c.sequence,value:c.value})})]}async function li(e,t){let{runContext:n}=await e.bus.request(_.getRunContext,{executionId:t});if(n===null)throw new w(St.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return n}function ui(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function di(e,t){let n=await li(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.scopeOverride??n.scope,c={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,scopeOverride:s,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:ui(t.mode,t.reason)}]};return t.mode===`snapshot`?await hi(e,n,c):pi(n)?await gi(e,n,c):await Ce(e,n.workflowId,c)}function fi(e,t){return pi(e)?t.id:e.workflowId}function pi(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function mi(e){let t=e.definitionSnapshot;if(t===void 0)throw new w(St.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function hi(e,t,n){let r=mi(t);return Le(e,fi(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}async function gi(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`){let{materializationSpec:r}=t;if(r===void 0)throw Error(`Invalid persisted path-backed run context: materializationSpec is required`);return Ue(e,t.source.path,{...n,materializationSpec:r})}let r=mi(t);return Le(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}var _i=class{bus;resumePausedExecution;handles=new Map;constructor(e,t){this.bus=e,this.resumePausedExecution=t}dispose(){for(let e of this.handles.values())clearTimeout(e);this.handles.clear()}clear(e,t,n){let r=this.makeKey(e,t,n),i=this.handles.get(r);i!==void 0&&(clearTimeout(i),this.handles.delete(r))}schedule(e){e.timeoutMs!==null&&(this.clear(e.executionId,e.nodeId,e.frameId),this.scheduleNextWakeup({...e,timeoutMs:e.timeoutMs}))}scheduleNextWakeup(e){let t=this.makeKey(e.executionId,e.nodeId,e.frameId),n=Math.max(0,e.openedAt+e.timeoutMs-Date.now()),r=setTimeout(()=>{if(this.handles.delete(t),Date.now()<e.openedAt+e.timeoutMs){this.scheduleNextWakeup(e);return}this.handleExpiredWakeup(e)},Math.min(n,2147483647));this.handles.set(t,r)}scheduleNextWakeupAfterDelay(e,t){let n=this.makeKey(e.executionId,e.nodeId,e.frameId),r=setTimeout(()=>{this.handles.delete(n),this.handleExpiredWakeup(e)},t);this.handles.set(n,r)}async handleExpiredWakeup(e){try{await this.resumeTimedOutPausedGate(e)===`retry`&&this.scheduleNextWakeupAfterDelay(e,25)}catch(t){this.scheduleFailedWakeupRetry(e,t)}}scheduleFailedWakeupRetry(e,t){let n=(e.failedWakeupAttempts??0)+1;if(n>4){console.error(`[WorkflowExecutor] Giving up on timed-out gate '${e.nodeId}' after 4 failed wakeup retries:`,t);return}let r=Math.min(250*2**(n-1),2e3);console.error(`[WorkflowExecutor] Failed to resume timed-out gate '${e.nodeId}', retrying in ${r} ms:`,t),this.scheduleNextWakeupAfterDelay({...e,failedWakeupAttempts:n},r)}makeKey(e,t,n){return`${e}:${t}:${n}`}async resumeTimedOutPausedGate(e){this.clear(e.executionId,e.nodeId,e.frameId);let{gate:t}=await this.bus.request(_.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:n}=await this.bus.request(_.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function vi(e){if(e!==void 0)return yi(e)?e:{}}function yi(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bi(e){if(e!==void 0)return _t.parse(e)}function xi(e,t){return wt.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}function Si(e){return e?.status===`paused`}function Ci(e){return e?.status===`waiting`}async function wi(e,t,n,r,i,a,o){try{await h(e,i.id,async()=>{let o=await e.bus.request(_.getExecution,{executionId:i.id});o.execution?.status!==`paused`&&o.execution?.status!==`running`||(t.delete(i.id),n.delete(i.id),r.delete(i.id),await e.bus.request(_.restorePausedGateResumeState,{execution:i,gate:a}))})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${o}' after resume launch failure:`,e)}}async function Ti(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(_.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Ei(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Di(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(_.getGateInstance,t);return Ci(n)?n:null}let{gates:n}=await e.request(_.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}async function Oi(e,t){let n=e.authority.canonicalizeOutcome(t.outcome),r=t.runtimeFence===void 0?void 0:{...t.runtimeFence};await e.validation?.validate(t.executionId,n.outcome);let i=await e.authority.commitOutcome(t.executionAttemptId,t.executionId,n,r);if(i.kind===`accepted`||i.kind===`duplicate`){let n=await e.convergence.converge({executionId:t.executionId,executionAttemptId:t.executionAttemptId,outcome:i.outcome,decision:i.kind,controlObservation:structuredClone(i.controlObservation)});e.authority.settleOutcome(t.executionAttemptId,{kind:i.kind,outcome:e.authority.decodeOutcome(i.text),text:i.text,controlObservation:i.controlObservation,acceptance:n})}return i.kind}function Z(e,t){let n=c(e);if(n===null)throw Error(`Attempt requests require an authenticated workflow-execution-attempt peer`);if(n.executionAttemptId!==t)throw Error(`Request executionAttemptId does not match authenticated peer identity`);return n}function ki(e,t){if(e===null||e.runtimeGeneration!==t.runtimeGeneration)return!1;if(t.outcome.kind===`cancelled`&&t.operationId===void 0)return e.activeOperationId===null;let n=t.outcome.kind===`technical-failure`?t.outcome.stage:t.outcome.kind===`cancelled`?e.activeOperationKind:`workload-invocation`;return n===`startup`?t.operationId===void 0&&e.activeOperationId===null:!(e.activeOperationId!==t.operationId||e.activeOperationGeneration!==t.runtimeGeneration||e.activeOperationKind!==n||n!==`workspace-preparation`&&n!==`workload-invocation`)}function Ai(e,t){return e.on(S.instruction.get,async e=>{let n=x[`instruction.get`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.getInstruction(r);if(i===null){e.setResult({decision:`refused`,refusalReason:`not-found`});return}if((await t.getAttemptControlState(r.executionAttemptId))?.runtimeGeneration!==n.runtimeGeneration){e.setResult({decision:`refused`,refusalReason:`stale-generation`});return}e.setResult({decision:`found`,instruction:i})})}function ji(e,t){let n=[Ai(e,t.authority),e.on(S.control.report,async e=>{let n=x[`control.report`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.authority.reportAttemptControl({...n,executionId:r.executionId});i.kind===`accepted`||i.kind===`duplicate`?e.setResult({decision:i.kind}):e.setResult({decision:`refused`,reason:i.kind})}),e.on(S.operation.report,async e=>{let n=x[`operation.report`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.authority.reportOperation({...n,executionId:r.executionId});i.kind===`accepted`||i.kind===`duplicate`?e.setResult({decision:i.kind,binding:i.binding}):e.setResult({decision:`refused`,refusalReason:i.kind})}),e.on(S.outcome.submit,async e=>{let n=x[`outcome.submit`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.authority.getInstruction(r);if(i===null)throw Error(`No instruction belongs to this authenticated Attempt`);if(!ki(await t.authority.getAttemptControlState(r.executionAttemptId),n)){e.setResult({decision:`fenced`});return}let a={runtimeGeneration:n.runtimeGeneration,operationId:n.operationId??null},o=await t.decodeOutcome({instruction:i,outcome:n.outcome});try{let n=await Oi(t,{...r,outcome:o,runtimeFence:a});e.setResult({decision:n})}catch(t){if(!(t instanceof at))throw t;e.setResult({decision:`fenced`})}})];return()=>{for(let e of n)e()}}function Mi(e,t){return e.origin.local?{executionAttemptId:t.executionAttemptId,executionId:t.executionId}:c(e)}var Ni=class{acceptOutcome;constructor(e){this.acceptOutcome=e}converge(e){return this.acceptOutcome(e)}};function Pi(e){return{authority:e.authority,decodeOutcome:et,convergence:new Ni(e.acceptOutcome)}}function Fi(e,t){let n=Pi(t),r=ji(e,n),i=e.on(bt.control.outcome.submit,async e=>{let r=Mi(e,e.payload);if(r===null)throw Error(`Outcome submission requires an authenticated workflow-execution-attempt peer`);let{result:i}=e.payload;if(!e.origin.local){if(e.payload.executionId!==r.executionId)throw Error(`Outcome payload executionId '${e.payload.executionId}' does not match authenticated peer claim '${r.executionId}'`);if(e.payload.executionAttemptId!==r.executionAttemptId)throw Error(`Outcome payload executionAttemptId '${e.payload.executionAttemptId}' does not match authenticated peer identity '${r.executionAttemptId}'`)}if(i.executionId!==r.executionId)throw Error(`Nested result.executionId '${i.executionId}' does not match trusted identity '${r.executionId}'`);let a=Tt.parse(i),o=await t.authority.getInstruction(r);if(o===null)throw Error(`No instruction belongs to this workflow Attempt`);let s=await n.decodeOutcome({instruction:o,outcome:{kind:`workload-result`,result:a}}),c=await Oi(n,{executionId:r.executionId,executionAttemptId:r.executionAttemptId,outcome:s});e.setResult({decision:Ii(c)})});return()=>{i(),r()}}function Ii(e){return e}function Li(e,t){return e.on(S.operation.admit,async e=>{let n=c(e);if(n===null)throw Error(`Operation admission requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:r,operationKind:i,admissionKey:a,runtimeGeneration:o}=x[`operation.admit`].request.parse(e.payload);if(r!==n.executionAttemptId)throw Error(`Admission payload executionAttemptId '${r}' does not match authenticated peer identity '${n.executionAttemptId}'`);if(i===`runtime-probe`)throw Error(`Operation admission does not accept 'runtime-probe' (executionAttemptId='${r}'): the bounded probe is admitted only by runtime registration`);let s=await t.authority.admitOperation({executionAttemptId:r,executionId:n.executionId,operationKind:i,admissionKey:a,runtimeGeneration:o});if(s.kind===`admitted`||s.kind===`duplicate`){await t.bus.emit(S.operation.admitted,{executionAttemptId:r,operationId:s.operationId,operationKind:i,runtimeGeneration:s.runtimeGeneration,admittedAt:s.admittedAt}),e.setResult({decision:s.kind,operationId:s.operationId});return}e.setResult({decision:`refused`,refusalReason:s.kind})})}const Ri=1e4;function zi(e,t){let n=t.probeDeliveryTimeoutMs??1e4;return e.on(S.runtime.register,async e=>{let r=c(e);if(r===null)throw Error(`Runtime registration requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:i,runtimeIncarnationId:a}=x[`runtime.register`].request.parse(e.payload);if(i!==r.executionAttemptId)throw Error(`Registration payload executionAttemptId '${i}' does not match authenticated peer identity '${r.executionAttemptId}'`);let o=await t.authority.registerRuntime({executionAttemptId:i,executionId:r.executionId,runtimeIncarnationId:a});if(o.kind===`duplicate`&&o.runtimeReadyAt!==null){await Bi(t,i,o.runtimeGeneration),e.setResult({decision:`duplicate`,runtimeGeneration:o.runtimeGeneration});return}if(o.kind!==`registered`&&o.kind!==`duplicate`){e.setResult(Ui(o.kind));return}let s=o.runtimeGeneration;if(await Vi(t,n,{executionAttemptId:i,executionId:r.executionId,runtimeIncarnationId:a,runtimeGeneration:s})===null){e.setResult(Ui(`probe-failed`));return}await Bi(t,i,s),e.setResult({decision:`ready`,runtimeGeneration:s})})}async function Bi(e,t,n){let r=await e.authority.getAttemptControlState(t);r===null||r.runtimeGeneration!==n||r.runtimeReadyAt===null||await e.bus.emit(S.runtime.ready,{executionAttemptId:t,runtimeGeneration:n,acceptedAt:r.runtimeReadyAt})}async function Vi(e,t,n){let{executionAttemptId:r,executionId:i,runtimeIncarnationId:a,runtimeGeneration:o}=n,s=await e.authority.admitOperation({executionAttemptId:r,executionId:i,operationKind:`runtime-probe`,admissionKey:`probe:${a}`,runtimeGeneration:o});if(s.kind!==`admitted`&&s.kind!==`duplicate`)return null;let c=s.operationId,l=()=>Hi(e,{executionAttemptId:r,operationId:c,runtimeGeneration:o}),u;try{u=(await e.bus.request(S.operation.deliver,{executionAttemptId:r,runtimeIncarnationId:a,operationId:c,operationKind:`runtime-probe`,runtimeGeneration:o},{timeout:t})).receipt}catch{return await l(),null}if(u!==`completed`&&u!==`duplicate`)return await l(),null;let d=await e.authority.completeOperation({executionAttemptId:r,operationId:c,runtimeGeneration:o});if(d.kind!==`completed`&&d.kind!==`duplicate`)return null;let f=await e.authority.markRuntimeReady({executionAttemptId:r,executionId:i,runtimeGeneration:o,readyAt:new Date().toISOString()});return f.kind!==`ready`&&f.kind!==`duplicate`?null:{kind:f.kind,acceptedAt:f.acceptedAt}}async function Hi(e,t){try{await e.authority.completeOperation(t)}catch{}}function Ui(e){return{decision:`refused`,runtimeGeneration:0,refusalReason:e}}function Wi(e,t,n){n(zi(e,{bus:e,authority:t})),n(Li(e,{bus:e,authority:t}))}function Gi(e,t){let n=new AbortController,r=e.on(S.bootstrap.awaitStart,async e=>{let r=c(e);if(r===null)throw Error(`Bootstrap start requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:i}=x[`bootstrap.awaitStart`].request.parse(e.payload);if(i!==r.executionAttemptId)throw Error(`Bootstrap start executionAttemptId does not match authenticated peer identity`);let a=e.signal?AbortSignal.any([e.signal,n.signal]):n.signal;e.setResult(await t.awaitBootstrapStart({executionAttemptId:i,executionId:r.executionId},{signal:a,deadline:e.deadline??Date.now()+31e3}))});return()=>{n.signal.aborted||(n.abort(Error(`Bootstrap start handler shut down`)),r())}}function Ki(e){return e.on(s.finalizeDelegateResult,async t=>{let n=t.payload;qi(t,n.executionId);let{execution:r}=await e.request(_.getExecution,{executionId:n.executionId});if(r===null||r.workflowId!==n.workflowId)throw Error(`delegate result finalization execution does not own the requested workflow`);let{runContext:i}=await e.request(_.getRunContext,{executionId:n.executionId});if(i===null||i.executionId!==n.executionId||i.workflowId!==n.workflowId)throw Error(`delegate result finalization run context does not own the requested workflow execution`);if(i.definitionSnapshot===void 0)throw Error(`delegate result finalization requires an Authority-owned definition snapshot`);Ji(i.definitionSnapshot,n.nodeId,n.nodeType,n.finalizerId);let{subjects:a}=Ot(n.finalizerId),o=await e.request(a.finalize,{executionId:n.executionId,workflowId:n.workflowId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,rawResult:n.rawResult,toolObservations:n.toolObservations,...n.economics===void 0?{}:{economics:n.economics}});t.setResult(o)})}function qi(e,t){if(!g(e,t))throw Error(`delegate result finalization requires its authenticated workflow-execution-attempt peer`)}function Ji(e,t,n,r){let i=!1;if(Nt(e.root,{enter(e){if(!(e.type!==`delegate-agent`&&e.type!==`delegate-role`||e.id!==t||e.type!==n))return e.resultFinalizerId===r&&(i=!0),!1}}),!i)throw Error(`delegate result finalizer is not selected by the requested durable delegate node`)}async function Yi(e,t,n){let[{execution:r},{runContext:i}]=await Promise.all([e.bus.request(_.getExecution,{executionId:t}),e.bus.request(_.getRunContext,{executionId:t})]);if(!r)throw Error(`Authority execution not found: ${t}`);if(i?.executionId!==t||i.workflowId!==r.workflowId)throw Error(`authority technical failure run context identity mismatch`);if(i.terminalAuthority!==`authority`)throw Error(`authority technical failure requires terminalAuthority=authority`);if(r.status===`failed`||r.status===`cancelled`)return{accepted:!0,status:r.status};if(r.status!==`running`)throw Error(`Authority technical failure conflicts with execution status: ${r.status}`);await te(e,r,t,`${n.stage}: ${n.message}`);let a=await e.bus.request(_.getExecution,{executionId:t});if(a.execution?.status!==`failed`&&a.execution?.status!==`cancelled`)throw Error(`Authority technical failure did not settle as failed or cancelled`);return{accepted:!0,status:a.execution.status}}async function Xi(e,t,n){let[{execution:r},{runContext:i}]=await Promise.all([e.bus.request(_.getExecution,{executionId:t}),e.bus.request(_.getRunContext,{executionId:t})]);if(!r)throw Error(`Authority execution not found: ${t}`);if(i?.executionId!==t||i.workflowId!==r.workflowId)throw Error(`authority cancellation run context identity mismatch`);if(i.terminalAuthority!==`authority`)throw Error(`authority cancellation requires terminalAuthority=authority`);if(r.status===`cancelled`)return{accepted:!0,status:`cancelled`};if(r.status!==`running`)throw Error(`Authority cancellation conflicts with execution status: ${r.status}`);if(await m(e,t,n.reason),(await e.bus.request(_.getExecution,{executionId:t})).execution?.status!==`cancelled`)throw Error(`Authority cancellation did not settle as cancelled`);return{accepted:!0,status:`cancelled`}}async function Zi(e,t,n){if(t.status===`finalizing`){if(n.status!==`completed`)throw Error(`authority runner result conflicts with terminal execution`);await u(e);let r=await e.bus.request(_.getExecution,{executionId:t.id});if(!r.execution)throw Error(`Authority runner success finalization execution is missing`);if(!o(r.execution.status,n.status))throw Error(`authority runner result conflicts with terminal execution`);return r.execution.status}if(!(t.status!==`completed`&&t.status!==`failed`&&t.status!==`cancelled`)){if(!o(t.status,n.status))throw Error(`authority runner result conflicts with terminal execution`);return t.status}}async function Qi(e,t){return h(e,t.executionId,async()=>{let{execution:n}=await e.bus.request(_.getExecution,{executionId:t.executionId});if(!n)throw Error(`Authority execution not found: ${t.executionId}`);if(!(`kind`in t.outcome)&&(t.outcome.executionId!==n.id||t.outcome.workflowId!==n.workflowId))throw Error(`authority outcome execution or workflow identity mismatch`);return n})}async function $i(e,t){let n=await Qi(e.lifecycle,t),r=`kind`in t.outcome?t.outcome.kind===`cancelled`:t.outcome.status===`cancelled`;if(n.status===`cancelled`&&!r)return`recorded-only`;if(!r&&t.controlObservation!==null&&t.controlObservation.controlRevision>0&&(n.status===`running`||n.status===`paused`))throw Error(`Workflow owner cancellation is not durably settled for '${t.executionId}'`);let i=await ea(e,t);if((await Qi(e.lifecycle,t)).status===`cancelled`&&!r)return`recorded-only`;if(!i)throw Error(`Workflow outcome did not converge execution '${t.executionId}'`);return`projected`}async function ea(e,t){if(`kind`in t.outcome){let n=t.outcome.kind===`cancelled`?await e.acceptCancellation(t.executionId,t.outcome):await e.acceptTechnicalFailure(t.executionId,t.outcome);return n.accepted&&(t.outcome.kind===`cancelled`?n.status===`cancelled`:n.status===`failed`||n.status===`cancelled`)}if(t.outcome.status===`paused`)return je(e.lifecycle,t.outcome);let n=await e.acceptTerminalResult(t.executionId,t.outcome);return n.accepted&&o(n.status,t.outcome.status)}var ta=class extends Pt{workflowRunner;executionAttemptAuthority;static storage={drizzle:$r};config;stopBootstrapWaits;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;workflowAbortControllers=new Map;successFinalizers=new Map;durableLifecycleTransitions=new Map;lifecyclePublications=new Map;publishingLifecycleExecutions=new Set;materializationSpecResolvers=new Set;constructor(e,t,n,r){super(e),this.workflowRunner=n,this.executionAttemptAuthority=r,this.config={...l,...t},this.gateTimeoutScheduler=new _i(e,e=>this.resumePausedExecution(e))}registerWorkflowMaterializationSpecResolver(e){return this.materializationSpecResolvers.add(e),()=>this.materializationSpecResolvers.delete(e)}async registerSuccessFinalizer(e){if(!this.initialized)throw Error(`[WorkflowExecutor] Initialize the executor before registering success finalizers`);if(this.successFinalizers.has(e))throw Error(`[WorkflowExecutor] Success finalizer already registered: ${e}`);let{namespace:t,subjects:n}=kt(e);this.bus.registerNamespace(t);let r={finalizerId:e,finalizeSubject:n.finalize};this.successFinalizers.set(e,r);try{await u(this.buildFinalizerDeps())}catch(t){throw this.successFinalizers.get(e)===r&&this.successFinalizers.delete(e),t}let i=!1;return()=>{i||(i=!0,this.successFinalizers.get(e)===r&&this.successFinalizers.delete(e))}}async acceptAuthorityRunnerResult(e,n){if(n.status===`paused`)throw Error(`authority runner result must be terminal`);if(n.executionId!==e)throw Error(`authority runner result execution identity mismatch`);let{execution:r}=await this.bus.request(_.getExecution,{executionId:e});if(!r)throw Error(`Authority runner execution not found: ${e}`);if(r.workflowId!==n.workflowId)throw Error(`authority runner result workflow identity mismatch`);if(r.status===`cancelled`&&n.status!==`cancelled`)return{accepted:!1,status:r.status};let i;if(r.status===`finalizing`){let{workflow:t}=await this.loadAuthorityRunnerContext(e,n.workflowId);i=await this.registerAuthorityResultFinalizer(t)}let a=await Zi(this.buildFinalizerDeps(),r,n).finally(()=>i?.());if(a!==void 0)return{accepted:!0,status:a};if(r.status!==`running`)throw Error(`Authority runner execution is ${r.status}`);let{runContext:s,workflow:c}=await this.loadAuthorityRunnerContext(e,n.workflowId),l=await this.registerAuthorityResultFinalizer(c),u=this.activeExecutions.get(e),d=!1;if(!u)this.activeExecutions.set(e,{execution:r,workflow:c,runContext:s,runtimeHandlers:new Map,runtimeLoopGates:new Map}),d=!0;else if(u.execution.workflowId!==n.workflowId)throw Error(`authority runner active execution identity mismatch`);try{await t({activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps()},n)}finally{d&&this.activeExecutions.delete(e),l?.()}let f=await this.bus.request(_.getExecution,{executionId:e});if(f.execution?.status===`cancelled`&&n.status!==`cancelled`)return{accepted:!1,status:f.execution.status};if(!f.execution||!o(f.execution.status,n.status))throw Error(`Authority runner result did not settle compatibly with ${n.status}`);return{accepted:!0,status:f.execution.status}}acceptAuthorityTechnicalFailure=(e,t)=>Yi(this.buildFinalizerDeps(),e,t);acceptAuthorityCancellation=(e,t)=>Xi(this.buildFinalizerDeps(),e,t);acceptAuthorityOutcome=e=>$i({lifecycle:this.buildFinalizerDeps(),acceptTerminalResult:(e,t)=>this.acceptAuthorityRunnerResult(e,t),acceptTechnicalFailure:this.acceptAuthorityTechnicalFailure,acceptCancellation:this.acceptAuthorityCancellation},e);async loadAuthorityRunnerContext(e,t){let{runContext:n}=await this.bus.request(_.getRunContext,{executionId:e});if(!n)throw Error(`Authority runner run context not found: ${e}`);if(n.executionId!==e||n.workflowId!==t)throw Error(`authority runner run context identity mismatch`);if(n.terminalAuthority!==`authority`)throw Error(`authority runner result requires terminalAuthority=authority`);let r=n.definitionSnapshot??(await this.bus.request(_.get,{id:n.workflowId})).workflow;if(!r||r.id!==t)throw Error(`authority runner workflow definition is unavailable or mismatched`);return{runContext:n,workflow:r}}registerAuthorityResultFinalizer(e){return!e.successFinalizerId||this.successFinalizers.has(e.successFinalizerId)?Promise.resolve(void 0):this.registerSuccessFinalizer(e.successFinalizerId)}async onInit(){this.registerExecutionHandlers(),this.addCleanup(ze(this.bus,(e,t)=>{let n=this.activeExecutions.get(e);n!==void 0&&(n.workflow=t)})),this.addCleanup(Ki(this.bus)),this.executionAttemptAuthority!==void 0&&(this.stopBootstrapWaits=Gi(this.bus,this.executionAttemptAuthority),this.addCleanup(this.stopBootstrapWaits),this.addCleanup(Fi(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority,acceptOutcome:this.acceptAuthorityOutcome})),Wi(this.bus,this.executionAttemptAuthority,e=>this.addCleanup(e))),ii(this.bus).forEach(e=>this.addCleanup(e)),ci(this.bus).forEach(e=>this.addCleanup(e)),await this.rehydratePausedGateTimeouts()}async onDestroy(){this.stopBootstrapWaits?.();let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await p(e,t,`Workflow engine shutdown`)&&(this.workflowAbortControllers.get(t)?.abort(),this.workflowAbortControllers.delete(t))}));for(let e of this.workflowAbortControllers.values())e.abort();this.workflowAbortControllers.clear(),await Promise.allSettled(this.executionTasks.values()),await Promise.allSettled(this.durableLifecycleTransitions.values()),await Promise.allSettled(this.lifecyclePublications.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){let e=this.executionAttemptAuthority;return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs,requestAttemptCancellation:e===void 0?void 0:(t,n)=>e.requestCancellation({executionId:t,reason:n}),notifyAttemptCancellation:(e,t)=>this.notifyAttemptCancellation(e,t),successFinalizers:this.successFinalizers,resolveSuccessFinalizerId:e=>this.activeExecutions.get(e)?.workflow.successFinalizerId,durableLifecycleTransitions:this.durableLifecycleTransitions,lifecyclePublications:this.lifecyclePublications,publishingLifecycleExecutions:this.publishingLifecycleExecutions}}async notifyAttemptCancellation(e,t){this.workflowAbortControllers.get(e)?.abort(t??C),await this.bus.emit(Dt(`workflow.${e}.cancel`),{executionId:e,reason:t}).catch(t=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${e}:`,t)})}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(vt.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${e}`);return t.targetWorkingDirectory??this.config.platformDefaults.cwd}resolveEphemeralPlatformFields(){return Ye(this.config.platformDefaults.cwd,this.config.makaioHome)}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>xi(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e),executionAttemptAuthority:this.executionAttemptAuthority,materializationSpecResolvers:this.materializationSpecResolvers}}registerExecutionHandlers(){this.registerHandler(s.acceptAuthorityRunnerResult,async e=>{if(!e.origin.local)throw Error(`authority runner result acceptance is local-authority only`);let{executionId:t,result:n}=e.payload;e.setResult(await this.acceptAuthorityRunnerResult(t,n))}),this.registerHandler(s.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s}=e.payload;try{let c=await Ce(this.buildStartDeps(),t,{input:bi(n),config:vi(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,scopeOverride:s});e.setResult({executionId:c})}catch(e){if(e instanceof w)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(s.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,reason:l}=e.payload;try{let u=await di(this.buildStartDeps(),{executionId:t,mode:n,input:bi(r),config:vi(i),parentSessionId:a,triggerPayload:o,artifactRef:s,scopeOverride:c,reason:l});e.setResult({executionId:u})}catch(e){if(e instanceof w)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(s.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,materializationSpec:n,triggerPayload:r,triggerMode:i,scope:a}=e.payload;try{let o=await Ue(this.buildStartDeps(),t,{...n===void 0?{}:{materializationSpec:n},triggerPayload:r,triggerMode:i,scopeOverride:a});e.setResult({executionId:o})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(s.cancel,async e=>{let{executionId:t,reason:n}=e.payload,r=await p(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:r})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(s.gate.respond,async e=>{let{executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o}=e.payload,s=await this.respondToPausedGate({executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o});e.setResult({accepted:s})},{priority:-100}))}registerGateTimeoutHandlers(){this.addCleanup(this.bus.on(s.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(s.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(_.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Ei(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let n=new AbortController;this.workflowAbortControllers.set(e,n);try{let r;try{let i=await ye({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new Fe(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,n.signal,void 0,i,{context:this.resolveEphemeralPlatformFields(),env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});Ge(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();r=await ke(t.workflow.root,a,o)}catch(r){if(n.signal.aborted||t.execution.status===`cancelled`){await m(this.buildFinalizerDeps(),e,C);return}let i=r instanceof Error?r.message:String(r);await te(this.buildFinalizerDeps(),t.execution,e,i);return}let i=this.buildFinalizerDeps();r.status===`cancelled`||n.signal.aborted||t.execution.status===`cancelled`?await m(i,e,C):r.status===`failed`?await te(i,t.execution,e,r.error):r.status===`paused`?(t.execution.status=`paused`,await this.bus.request(_.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await ie(i,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:n,frameId:r,resumeData:i,reason:a}=e,{execution:o}=await this.bus.request(_.getExecution,{executionId:t});if(!Si(o))return!1;let s=await Di(this.bus,{executionId:t,nodeId:n,frameId:r});if(s===null||!Ve(n,s.schema,i).valid)return!1;let{runContext:c}=await this.bus.request(_.getRunContext,{executionId:t});if(c===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Ti(this.bus,c);let{accepted:l}=await this.bus.request(_.resolveWaitingGateInstance,{gate:{...s,status:e.action===`reject`?`rejected`:`resumed`,resumeData:i,...a===void 0?{}:{reason:a},resolvedAt:Date.now()}});if(!l)return!1;try{await this.resumePausedExecution(o.id)}catch(e){throw await wi(this.buildFinalizerDeps(),this.activeExecutions,this.executionTasks,this.workflowAbortControllers,o,s,n),e}return this.gateTimeoutScheduler.clear(t,n,s.frameId),!0}async resumePausedExecution(e){let{runContext:t}=await this.bus.request(_.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let n=t.definitionSnapshot??(await this.bus.request(_.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})();await Ti(this.bus,t);let r=Ne(t,n,{resume:!0}),i=me(this.buildStartDeps(),r);await h(this.buildFinalizerDeps(),e,async()=>{let{execution:a}=await this.bus.request(_.getExecution,{executionId:e});if(a===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(a.status!==`paused`)return;await this.bus.request(_.setExecution,{execution:{...a,status:`running`}}),this.activeExecutions.set(e,{execution:{...a,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let o=Te(this.buildStartDeps(),r,i);De(this.executionTasks,e,o)})}};const Q=`[WorkflowTriggerReconciler]`;function na(e){return e.map(ra)}function ra(e){let t=xt.parse(e);return{binding:t,matches:st(t),subscription:void 0}}function ia(e,t,n){let r=e.triggers??[];try{return n===void 0?na(r):r.map(e=>n.has(e.kind)?ra(e):void 0)}catch(i){if(t){console.error(`${Q} keeping last-good triggers for workflow "${e.id}": its trigger bindings are invalid`,i);return}return r.map((t,r)=>{if(!(n!==void 0&&!n.has(t.kind)))try{return ra(t)}catch(t){console.error(`${Q} leaving invalid trigger ${r} of workflow "${e.id}" inactive`,t);return}})}}function aa(e,t){return e.scope.type!==`global`||t.kind!==pt}async function oa(e,t,n,r){if(r!==void 0)for(let[i,a]of Array.from(r)){let o=e.triggers?.[i];if(o!==void 0&&n!==void 0&&!n.has(o.kind))continue;let s=t[i];s!==void 0&&aa(e,s.binding)||(r.delete(i),await $(a.subscription))}}async function $(e){if(e!==void 0)try{await e.detach()}catch(t){console.error(`${Q} detach failed for '${e.bindingKey}':`,t)}}var sa=class{bus;resolveRuntime;consumers=new Map;cleanupFns=[];initialized=!1;initialization;lane=new ut;pendingChanges=[];constructor(e,t){this.bus=e,this.resolveRuntime=t}async init(){if(this.initialized)return;if(this.initialization!==void 0)return this.initialization;let e=this.initialize();return this.initialization=e,e.then(()=>this.clearInitialization(e),()=>this.clearInitialization(e)),e}clearInitialization(e){this.initialization===e&&(this.initialization=void 0)}async initialize(){try{let e=({payload:e})=>{this.onSignal(`refresh of workflow "${e.id}"`,()=>this.refreshDefinition(e.id))};this.cleanupFns.push(this.bus.on(T.definition.created,e),this.bus.on(T.definition.updated,e),this.bus.on(T.definition.deleted,e),this.bus.on(ft.changed,e=>{this.scheduleRegistryReconcile(e.payload)})),await this.reconcileStored(`keep-last-good`),this.initialized=!0}catch(e){throw await this.teardown(),e}}async destroy(){await this.teardown(),this.initialized=!1}activeConsumerCount(){let e=0;for(let t of this.consumers.values())e+=t.size;return e}onSignal(e,t){t().catch(t=>{console.error(`${Q} ${e} failed:`,t)})}scheduleRegistryReconcile(e){let t=this.pendingChanges.length>0;this.pendingChanges.push(e),!t&&queueMicrotask(()=>{if(this.pendingChanges.length===0)return;let e=this.pendingChanges.splice(0),t=new Set(e.flatMap(({kinds:e})=>e)),n=e.map(({owner:e,revision:t})=>`${e}@${t}`).join(`, `);this.onSignal(`reconciliation after trigger registry changes (${n})`,()=>this.reconcileStored(`drop-unavailable`,t))})}async reconcileStored(e,t){await this.lane.run(async()=>{let{workflows:n}=await this.bus.request(_.list,{}),r=new Set(n.map(e=>e.id));for(let r of n){let n=r.triggers??[];t!==void 0&&!n.some(e=>t.has(e.kind))||await this.applyDefinitionWithinLane(r,e,t)}for(let e of Array.from(this.consumers.keys()))r.has(e)||await this.forgetWorkflowWithinLane(e)})}async refreshDefinition(e){await this.lane.run(async()=>{let{workflow:t}=await this.bus.request(_.get,{id:e});if(t===null){await this.forgetWorkflowWithinLane(e);return}await this.applyDefinitionWithinLane(t,`keep-last-good`)})}async applyDefinitionWithinLane(e,t,n){let r=ia(e,(this.consumers.get(e.id)?.size??0)>0,n);if(r===void 0)return;let i=this.consumers.get(e.id);if(await oa(e,r,n,i),i?.size===0&&this.consumers.delete(e.id),!r.some(t=>t!==void 0&&aa(e,t.binding)&&(n===void 0||n.has(t.binding.kind))))return;let a=this.resolveRuntime();if(a===void 0){r.length>0&&console.warn(`${Q} no automation trigger binding runtime is available; declarative triggers of workflow "${e.id}" stay inactive`);return}let o=this.consumers.get(e.id);o===void 0&&(o=new Map,this.consumers.set(e.id,o));for(let[i,s]of r.entries())s!==void 0&&aa(e,s.binding)&&(n!==void 0&&!n.has(s.binding.kind)||await this.refreshConsumerWithinLane(a,e.id,i,s,o,t));o.size===0&&this.consumers.delete(e.id)}async refreshConsumerWithinLane(e,t,n,r,i,a){let o=i.get(n),s=this.createListener(t,n,r);try{let t=o?.subscription?.bindingKey,a=e.prepareBinding(r.binding);if(a===void 0)throw Error(`Automation trigger kind '${r.binding.kind}' is not registered`);if(!a.workflowCompatible)throw Error(`Automation trigger kind '${r.binding.kind}' does not emit an object-root payload`);(t===void 0||t!==a.bindingKey)&&i.set(n,r),r.subscription=await a.subscribe(s),i.set(n,r),await $(o?.subscription);return}catch(e){if(o===void 0?i.delete(n):i.set(n,o),a===`keep-last-good`){console.error(`${Q} keeping last-good trigger ${n} of workflow "${t}": binding '${r.binding.kind}' could not be activated`,e);return}console.warn(`${Q} dropping trigger ${n} of workflow "${t}": binding '${r.binding.kind}' is no longer available`,e),i.delete(n),await $(o?.subscription)}}async forgetWorkflowWithinLane(e){let t=this.consumers.get(e);if(t!==void 0){this.consumers.delete(e);for(let e of t.values())await $(e.subscription)}}createListener(e,t,n){let r=`trigger ${t} ('${n.binding.kind}') of workflow "${e}"`;return async i=>{if(this.consumers.get(e)?.get(t)!==n)return;let a;try{a=n.matches(i.payload)}catch(e){console.error(`${Q} filter evaluation failed for ${r}:`,e);return}if(a)try{await this.bus.request(T.start,{workflowId:e,triggerPayload:ot(i.payload)})}catch(t){console.error(`${Q} failed to start workflow "${e}" from ${r}:`,t)}}}async teardown(){this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.pendingChanges.length=0,await this.lane.run(async()=>{for(let e of Array.from(this.consumers.keys()))await this.forgetWorkflowWithinLane(e)})}};const ca=1e3;function la(e){if(e===null)return{status:`refused`,reason:`not-found`};if(e.settled)return{status:`refused`,reason:`resolved`};if(!e.active)return{status:`refused`,reason:`fenced`};if(e.allocationTerminated)return{status:`refused`,reason:`allocation-terminated`};if(e.operationStartGate===`closed`)return{status:`refused`,reason:`gate-closed`};let t=e.bootstrapDeadlineAt===null?NaN:Date.parse(e.bootstrapDeadlineAt);return!Number.isFinite(t)||t<=Date.now()?{status:`refused`,reason:`bootstrap-expired`}:{status:e.allocated?`permitted`:`pending`}}function ua(e,t){return new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),t.aborted&&i(),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function da(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),n()},a=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),r(t.reason)},o=setTimeout(i,e);t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}function fa(e,t){return setTimeout(()=>e.abort(Error(`Bootstrap start observation timed out`)),Math.max(0,t-Date.now()))}async function pa(e,t,n){if(n.signal.throwIfAborted(),!Number.isFinite(n.deadline))throw Error(`Bootstrap start request requires a finite deadline`);let r=Math.min(Date.now()+3e4,n.deadline-ca),i=new AbortController,a=AbortSignal.any([n.signal,i.signal]),o=Math.min(n.deadline,r+ca),s=fa(i,o);try{for(;;){a.throwIfAborted();let n=await ua(e.readBootstrapStartState(t),a);a.throwIfAborted();let c=la(n);if(c.status!==`pending`)return c;let l=Date.parse(n?.bootstrapDeadlineAt??``);clearTimeout(s),s=fa(i,Math.min(o,l+ca));let u=Math.min(r,l)-Date.now();if(u<=0)return c;await da(Math.min(100,u),a)}}finally{clearTimeout(s)}}var ma=class{repository;bootstrapTimeoutMs;waiters=new Map;constructor(e,t){if(!Number.isSafeInteger(t?.bootstrapTimeoutMs)||t.bootstrapTimeoutMs<=0)throw Error(`ExecutionAttemptAuthority requires an explicit positive safe-integer bootstrapTimeoutMs`);this.repository=e,this.bootstrapTimeoutMs=t.bootstrapTimeoutMs}awaitBootstrapStart(e,t){return pa(this.repository,e,t)}async createAttempt(e,t){let n=crypto.randomUUID(),r=await this.repository.createAttempt({executionAttemptId:n,executionId:e,instruction:t,bootstrapTimeoutMs:this.bootstrapTimeoutMs});return this.installWaiter(n),r}async ensureAttempt(e){let t=lt(e);return this.repository.ensureAttempt({...t,executionAttemptId:crypto.randomUUID(),bootstrapTimeoutMs:this.bootstrapTimeoutMs})}async readAttemptSettlement(e){return this.repository.readAttemptSettlement(ct(e))}async getInstruction(e){return this.repository.getInstruction(e)}async requestAttemptCancellation(e){return this.repository.requestAttemptCancellation(rt(e))}async requestCancellation(e){return this.repository.requestCancellation(it(e))}async readCancellation(e){return this.repository.readCancellation(e)}async reportOperation(e){return this.repository.reportOperation(e)}async beginProvisioning(e){return this.repository.beginProvisioning(e)}async getProviderOperation(e){return this.repository.getProviderOperation(e)}async renewProviderOperationClaim(e){return this.repository.renewProviderOperationClaim(e)}async takeOverProviderOperation(e){return this.repository.takeOverProviderOperation(e)}async handoffProviderOperation(e){return this.repository.handoffProviderOperation(e)}async recordProviderOperationUncertainty(e){return this.repository.recordProviderOperationUncertainty(e)}async completeProviderOperation(e){return this.repository.completeProviderOperation(e)}async recordAllocation(e){return this.repository.recordAllocation(e)}async recordProvisioningAbsent(e){let t=await this.repository.recordProvisioningAbsent(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' provisioning produced no allocation: ${e.evidence.source} reported '${e.evidence.summary}'`)),t}async recordProvisionerIncarnationLost(e){let t=await this.repository.recordProvisionerIncarnationLost(e);if(t.kind===`recorded`){let{evidence:t,provisionerIncarnationId:n}=e.proof;this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' lost the provisioner incarnation '${n}' its allocation was bound to: ${t.source} reported '${t.summary}'`))}return t}async recordAllocationTerminated(e){return this.repository.recordAllocationTerminated(e)}async registerRuntime(e){return this.repository.registerRuntime(e)}async admitOperation(e){return this.repository.admitOperation(e)}async completeOperation(e){return this.repository.completeOperation(e)}async markRuntimeReady(e){return this.repository.markRuntimeReady(e)}async getAttemptControlState(e){return this.repository.getAttemptControlState(e)}async readAttemptCancellationControl(e){return this.repository.readAttemptCancellationControl(e)}async recordAttemptControlReceipt(e){return this.repository.recordAttemptControlReceipt(e)}async reportAttemptControl(e){return this.repository.reportAttemptControl(e)}async getActiveAttempt(e,t){return this.repository.getActiveAttempt(e,t)}canonicalizeOutcome(e){return this.repository.canonicalizeOutcome(e)}decodeOutcome(e){return this.repository.decodeOutcome(e)}async commitOutcome(e,t,n,r){let i=await this.repository.commitOutcome({executionAttemptId:e,executionId:t,result:n,...r===void 0?{}:{runtimeFence:r}});return(i.kind===`conflict`||i.kind===`fenced`)&&this.settleWaiterInternal(e,i),i}waitForOutcome(e){return this.waiters.get(e)?.promise}settleOutcome(e,t){this.settleWaiterInternal(e,t)}discardWaiter(e){this.waiters.delete(e)}rejectAndDiscardWaiter(e,t){this.rejectWaiterWith(e,()=>t)}rejectWaiterWith(e,t){let n=this.waiters.get(e);n!==void 0&&(n.promise.catch(()=>void 0),n.reject(t()),this.waiters.delete(e))}get supportsRecovery(){return this.repository.recovery!==void 0}async getAttemptWithAllocation(e){return this.requireRecovery(`getAttemptWithAllocation`).getAttemptWithAllocation(e)}async recordDiscoveredAllocation(e){return this.requireRecovery(`recordDiscoveredAllocation`).recordDiscoveredAllocation(e)}async evolveAllocationRef(e){let t=this.requireRecovery(`evolveAllocationRef`);if(e.currentRef.providerId!==e.nextRef.providerId)throw Error(`Provider identity mismatch in allocation ref evolution: currentRef.providerId '${e.currentRef.providerId}' !== nextRef.providerId '${e.nextRef.providerId}'. Provider identity must not change during correlation.`);return t.evolveAllocationRef(e)}async getRecoverableAttempts(e){return this.requireRecovery(`getRecoverableAttempts`).getRecoverableAttempts(e)}async listOpenProviderOperations(e){return this.requireRecovery(`listOpenProviderOperations`).listOpenProviderOperations(e)}async recordInfrastructureFailure(e){let t=await this.repository.recordInfrastructureFailure(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' suffered infrastructure failure: the provider allocation terminated without an acknowledged outcome`)),t}async abandonPendingAttempt(e,t){let n=await this.repository.abandonPendingAttempt(e,t);return(n.kind===`abandoned`||n.kind===`already-abandoned`)&&this.waiters.delete(e),n}requireRecovery(e){let{recovery:t}=this.repository;if(t===void 0)throw Error(`Recovery operation '${e}' requires a repository that exposes recovery operations. The injected repository does not support recovery.`);return t}installWaiter(e){this.waiters.set(e,ge())}settleWaiterInternal(e,t){let n=this.waiters.get(e);if(n){switch(t.kind){case`accepted`:case`duplicate`:n.resolve({outcome:t.outcome,controlObservation:t.controlObservation,acceptance:t.acceptance});break;case`conflict`:n.reject(Error(`Outcome conflict for attempt '${e}': a different outcome was already committed`));break;case`fenced`:n.reject(Error(`Attempt '${e}' has been fenced: it is no longer the active attempt for this execution`));break}this.waiters.delete(e)}}},ha=class extends Pt{workflowExecutor;triggerReconcilerInstance;attemptAuthority;workspaceRootResolvers=new Set;constructor(e,t){super(e);let n=t?.executionAttemptAuthority;if(!n&&t?.executionAttemptRepository){let e=t.executionAttemptBootstrapTimeoutMs;if(e===void 0)throw Error(`An ExecutionAttemptRepository requires executionAttemptBootstrapTimeoutMs`);n=new ma(t.executionAttemptRepository,{bootstrapTimeoutMs:e})}this.attemptAuthority=n,this.workflowExecutor=new ta(e,t?.executorConfig,t?.workflowRunner,this.attemptAuthority);for(let e of t?.workflowMaterializationSpecResolvers??[])this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e);let r=t?.automationTriggerBindingRuntime;this.triggerReconcilerInstance=new sa(e,()=>r?.())}get executor(){return this.workflowExecutor}get executionAttemptAuthority(){return this.attemptAuthority}registerSuccessFinalizer(e){return this.workflowExecutor.registerSuccessFinalizer(e)}acceptAuthorityRunnerResult(e,t){return this.workflowExecutor.acceptAuthorityRunnerResult(e,t)}get triggerReconciler(){return this.triggerReconcilerInstance}registerWorkflowMaterializationSpecResolver(e){return this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e)}registerWorkspaceRootResolver(e){return this.workspaceRootResolvers.add(e),()=>{this.workspaceRootResolvers.delete(e)}}async resolveWorkspaceRoot(e){for(let t of this.workspaceRootResolvers){let n=await t(e);if(n!==void 0)return n}}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.triggerReconcilerInstance.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.triggerReconcilerInstance.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const ga=jt(`makaio.workflow-engine`);function _a(e){return{name:ga.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[At(Gt.name),At(Kt.name,void 0,!0)],critical:!0,namespaces:[Ct,f],storage:{registerHandlers:Lt($r)},create:t=>new ha(t.bus,{...e,automationTriggerBindingRuntime:()=>t.getService(Kt)})}}const va=_a();export{Pn as _,ma as a,Gi as c,Li as d,ji as f,Mn as g,Nn as h,ha as i,Ri as l,$r as m,_a as n,sa as o,Oi as p,va as r,ta as s,ga as t,zi as u};
|
|
7
|
+
)`;await e.update(t).set({totalInputTokens:i,totalOutputTokens:a,totalEstimatedCost:o}).where(k(N(t.executionId,r),s))}async function tr(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=D(e,L);if(It(e)===`sqlite`){await er(e,n,r,t);return}await E(e,async e=>{if(await Xn(e,n,t)===void 0)return;let i=await Zn(e,r,t);Qn(i)&&await $n(e,n,t,i)})}async function nr(e,t={}){let{worklogSummaries:n}=D(e,L),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[N(n.workflowId,r)],...i===void 0?[]:[zt(n.startedAt,i)],...a===void 0?[]:[Ht(n.startedAt,a)]],s=o.length>0?k(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:j()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:I(n.durationMs),totalInputTokens:I(n.totalInputTokens),totalOutputTokens:I(n.totalOutputTokens),totalEstimatedCost:I(n.totalEstimatedCost)}).from(n).where(s)]),u={pending:0,running:0,paused:0,finalizing:0,completed:0,failed:0,cancelled:0},d=0;for(let e of c)u[e.status]=e.count,d+=e.count;let f=l[0];return{total:d,byStatus:u,totalDurationMs:Number(f?.totalDurationMs??0),totalInputTokens:Number(f?.totalInputTokens??0),totalOutputTokens:Number(f?.totalOutputTokens??0),totalEstimatedCost:Number(f?.totalEstimatedCost??0)}}async function rr(e,t,n,r,i){let a=await G(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(dt.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function K(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function q(e,t){try{await e.emit(s.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const ir=new Set([`completed`,`failed`,`cancelled`]);function ar(e){return ir.has(e)}async function or(e,t){return await Rn(e,{executionId:t.executionId,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),!0}async function sr(e,t){let n=t.completedAt??Date.now(),r=await W(e,t.executionId);return r!==null&&ar(r.status)?!1:(await zn(e,{executionId:t.executionId,workflowId:r?.workflowId??t.executionId,workflowName:r?.workflowName??null,status:`completed`,startedAt:r?.startedAt??n-t.totalDuration,completedAt:n,durationMs:t.totalDuration,totalInputTokens:r?.totalInputTokens??null,totalOutputTokens:r?.totalOutputTokens??null,totalEstimatedCost:r?.totalEstimatedCost??null,error:null,failedNodeId:null}),!0)}async function cr(e,t,n,r,i,a){let o=await W(e,t);if(o!==null&&ar(o.status))return!1;let s=o?.startedAt??a;return await zn(e,{executionId:t,workflowId:o?.workflowId??t,workflowName:o?.workflowName??null,status:n,startedAt:s,completedAt:a,durationMs:a-s,totalInputTokens:o?.totalInputTokens??null,totalOutputTokens:o?.totalOutputTokens??null,totalEstimatedCost:o?.totalEstimatedCost??null,error:r,failedNodeId:i}),!0}function lr(e,t){return[e.on(s.execution.started,async n=>{let{executionId:r}=n.payload;await K(`execution.started[${r}]`,async()=>{await O(t,()=>or(t,n.payload))&&await q(e,r)})}),e.on(s.execution.completed,async n=>{let{executionId:r}=n.payload;await K(`execution.completed[${r}]`,async()=>{await O(t,()=>sr(t,n.payload))&&await q(e,r)})}),e.on(s.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await K(`execution.failed[${r}]`,async()=>{await O(t,()=>cr(t,r,`failed`,i,a??null,o))&&await q(e,r)})}),e.on(s.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await K(`execution.cancelled[${r}]`,async()=>{await O(t,()=>cr(t,r,`cancelled`,null,null,i))&&await q(e,r)})})]}const ur=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function dr(e){return ur.has(e)}function fr(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function pr(e,t,n,r,i,a,o){let s=o??Date.now(),c=await G(t,r);c!==null&&dr(c.status)||(await Un(t,{frameId:r,executionId:n,...fr(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await tr(t,n),await q(e,n))}async function mr(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await G(t,r);l!==null&&dr(l.status)||(await Un(t,{frameId:r,executionId:n,...fr(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await q(e,n))}function hr(e,t){return[e.on(s.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await K(`frame.started[${i}]`,async()=>{await Hn(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await q(e,r)})}),e.on(s.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await K(`frame.completed[${i}]`,()=>pr(e,t,r,i,a,o,s))}),e.on(s.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await K(`frame.failed[${i}]`,()=>mr(e,t,r,i,a,o,s,c))})]}const gr={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function _r(e,t){return[e.on(s.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await K(`gate.suspended[${i}]`,async()=>{await qn(t,{id:Yn(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await q(e,r)})}),e.on(s.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await K(`gate.resumed[${i}]`,async()=>{let n=Yn(r,a,i),s=await Jn(t,n),c=Date.now();await qn(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await q(e,r)})}),e.on(s.gate.resolved,async n=>vr(n.payload,e,t)),e.on(s.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await K(`artifact.updated[${r}:${i}]`,async()=>{let n=await rr(e,t,i,a,o);if(n===null)return;let s=Date.now();await Gn(t,{id:Kn(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await q(e,r)})})]}async function vr(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await K(`gate.resolved[${i}]`,async()=>{let s=Yn(r,a,i),c=await Jn(n,s),l=Date.now();await qn(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:gr[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await q(t,r)})}function yr(e,t){let n=[...lr(e,t),...hr(e,t),..._r(e,t),e.on(s.worklog.get,async e=>{let{executionId:n}=e.payload,r=await W(t,n);e.setResult({summary:r})}),e.on(s.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await Wn(t,n);e.setResult({frame:r})}),e.on(s.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await Vn(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(s.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await nr(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function J(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>J(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t,i=Object.keys(n).sort(),a=Object.keys(r).sort();return i.length===a.length&&i.every((e,t)=>e===a[t]&&J(n[e],r[e]))}function br(e){return{executionId:e.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,status:e.status,attempt:e.attempt,iteration:e.iteration??null,branchKey:e.branchKey??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null,durationMs:e.durationMs??null,inputTokens:e.inputTokens??null,outputTokens:e.outputTokens??null,estimatedCost:e.estimatedCost??null,error:e.error??null}}function xr(e,t){let n=e.frame;if(n!==void 0){let r=e.status===`failed`?e.error??null:null;if(n.executionId!==e.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);if(n.status!==e.status)throw Error(`settleExternalExecution requires frame.status to match status`);if(n.completedAt!==t)throw Error(`settleExternalExecution requires frame.completedAt to match completedAt`);if(n.durationMs!==t-n.startedAt)throw Error(`settleExternalExecution requires frame.durationMs to match its timestamps`);if((n.error??null)!==r)throw Error(`settleExternalExecution requires frame.error to match terminal error metadata`)}return JSON.stringify({version:1,status:e.status,completedAt:t,error:e.status===`failed`?e.error??null:null,reason:e.status===`cancelled`?e.reason??null:null,frame:n===void 0?null:{executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??null,branchKey:n.branchKey??null,startedAt:n.startedAt,completedAt:n.completedAt,durationMs:n.durationMs,error:n.status===`failed`?n.error??null:null}})}function Sr(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function Cr(e,t,n,r,i){let a=xr(r,i);if(n.externalSettlementFingerprint!==null){Sr(n.externalSettlementFingerprint,a,r.executionId);return}if(r.frame!==void 0)throw Error(`settleExternalExecution: frame presence conflicts with the legacy frame-less settlement for execution "${r.executionId}"`);let o=r.status===`failed`?r.error??null:null,s=r.status===`cancelled`?r.reason??null:null;if((await e.update(t).set({externalSettlementFingerprint:a}).where(k(N(t.id,r.executionId),P(t.externalSettlementFingerprint),N(t.status,r.status),N(t.completedAt,i),o===null?P(t.error):N(t.error,o),s===null?P(t.reason):N(t.reason,s))).returning({fingerprint:t.externalSettlementFingerprint})).length>0)return;let[c]=await e.select().from(t).where(N(t.id,r.executionId)).limit(1);if(c===void 0)throw Error(`settleExternalExecution: execution "${r.executionId}" disappeared`);if(Tr(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);Sr(c.externalSettlementFingerprint,a,r.executionId)}function wr(e,t){if(e.executionId!==t.executionId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`settleExternalExecution: frame "${t.frameId}" conflicts with its registered metadata`)}function Tr(e,t,n){let r=t.status===`failed`?t.error??null:null,i=t.status===`cancelled`?t.reason??null:null;if(e.status!==t.status||e.completedAt!==n||e.error!==r||e.reason!==i)throw e.status===t.status?Error(`settleExternalExecution: execution "${t.executionId}" conflicts with an existing terminal settlement`):Error(`settleExternalExecution: execution "${t.executionId}" cannot transition from status "${e.status}"`)}async function Er(e,t,n){let r=await e.select().from(t).where(N(t.executionId,n.executionId)),i=r.find(e=>e.frameId===n.frame.frameId);if(i!==void 0)return i;if(r.length>0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" conflicts with the registered frame identity`);let[a]=await e.select().from(t).where(N(t.frameId,n.frame.frameId)).limit(1);if(a!==void 0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" belongs to another execution`)}function Dr(e,t,n,r){let i=Math.min(e.startedAt,r);return{executionId:e.id,workflowId:e.workflowId,workflowName:t?.workflowName??null,status:n.status,startedAt:i,completedAt:r,durationMs:r-i,totalInputTokens:t?.totalInputTokens??null,totalOutputTokens:t?.totalOutputTokens??null,totalEstimatedCost:t?.totalEstimatedCost??null,error:n.status===`failed`?n.error??null:null,failedNodeId:n.status===`failed`?n.frame?.nodeId??t?.failedNodeId??null:null}}function Or(e,t){return br({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function kr(e,t){if(e.externalRegistrationFrameId!==(t.externalRegistrationFrameId??null))throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);if(!(e.id===t.id&&e.workflowId===t.workflowId&&e.coordinatorSessionId===t.coordinatorSessionId&&e.startedAt===t.startedAt&&e.scopeType===t.scopeType&&e.scopeKind===t.scopeKind&&e.scopeId===t.scopeId&&e.artifactKind===t.artifactKind&&e.artifactId===t.artifactId&&J(e.inputs,t.inputs)&&J(e.triggerPayload,t.triggerPayload)))throw Error(`setExternalExecutionStart: registration conflicts for execution "${t.id}"`)}function Ar(e,t){if(e.workflowId!==t.workflowId||e.startedAt!==t.startedAt||e.executionId!==t.executionId)throw Error(`setExternalExecutionStart: WorkLog summary conflicts for execution "${t.executionId}"`)}function jr(e,t){if(e.executionId!==t.executionId||e.frameId!==t.frameId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`setExternalExecutionStart: WorkLog frame conflicts for frame "${t.frameId}"`)}async function Mr(e,t,n,r){if(!t.id.startsWith(b))throw Error(`setExternalExecutionStart: execution "${t.id}" is not an external execution ID`);if(n!==void 0&&n.executionId!==t.id)throw Error(`setExternalExecutionStart requires frame.executionId to match execution.id`);let{workflowExecutions:i,worklogSummaries:a,worklogFrameEntries:o}=D(e,L),s={...r(t),externalRegistrationFrameId:n?.frameId??null},c={executionId:t.id,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt,completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null};await E(e,async e=>{let r=(await e.insert(i).values(s).onConflictDoNothing().returning({id:i.id})).length===0;if(r){let[n]=await e.select().from(i).where(N(i.id,t.id)).limit(1);if(n===void 0)throw Error(`setExternalExecutionStart: execution "${t.id}" disappeared`);kr(n,s)}let[l]=await e.select().from(a).where(N(a.executionId,t.id)).limit(1);if(l===void 0?await e.insert(a).values(c):Ar(l,c),n!==void 0){let[i]=await e.select().from(o).where(N(o.frameId,n.frameId)).limit(1);if(i===void 0){if(r)throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);await e.insert(o).values(br(n))}else jr(i,n)}})}async function Nr(e,t,n,r,i){if(r.frame!==void 0){let n=await Er(e,t,r);return n!==void 0&&wr(n,r.frame),{frame:r.frame,existing:n}}if(n.externalRegistrationFrameId===null)return;let[a]=await e.select().from(t).where(N(t.frameId,n.externalRegistrationFrameId)).limit(1);if(a===void 0||a.executionId!==n.id)throw Error(`settleExternalExecution: registered frame "${n.externalRegistrationFrameId}" is unavailable for execution "${n.id}"`);if(a.startedAt===null)throw Error(`settleExternalExecution: registered frame "${a.frameId}" has no start timestamp`);if(i<a.startedAt)throw Error(`settleExternalExecution: completedAt must not precede the registered frame start timestamp`);let o=Et.parse(a.nodeType);return{frame:{executionId:a.executionId,frameId:a.frameId,nodeId:a.nodeId,nodeType:o,path:a.path,status:r.status,attempt:a.attempt,...a.iteration===null?{}:{iteration:a.iteration},...a.branchKey===null?{}:{branchKey:a.branchKey},startedAt:a.startedAt,completedAt:i,durationMs:i-a.startedAt,...r.status===`failed`&&r.error!==void 0?{error:r.error}:{}},existing:a}}async function Pr(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await Xn(e,a,n.id),c=await Nr(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=Or(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await Zn(e,o,n.id),d=Qn(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...Dr(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:Bn(p)}),d&&await $n(e,a,n.id,u)}async function Fr(e,t){if(!t.executionId.startsWith(b))throw Error(`settleExternalExecution: execution "${t.executionId}" is engine-owned and must use the engine finalizer`);if(t.frame!==void 0&&t.frame.executionId!==t.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);let{workflowExecutions:n,worklogSummaries:r,worklogFrameEntries:i}=D(e,L);return E(e,async e=>{let[a]=await e.select().from(n).where(N(n.id,t.executionId)).limit(1);if(a===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" was not registered`);let o=t.completedAt??a.completedAt??Date.now();if(a.status===`running`){let r=xr(t,o);if((await e.update(n).set({status:t.status,completedAt:o,error:t.status===`failed`?t.error??null:null,reason:t.status===`cancelled`?t.reason??null:null,externalSettlementFingerprint:r}).where(k(N(n.id,t.executionId),N(n.status,`running`),P(n.externalSettlementFingerprint))).returning({id:n.id})).length===0){let[r]=await e.select().from(n).where(N(n.id,t.executionId)).limit(1);if(r===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" disappeared`);t.completedAt===void 0&&r.completedAt!==null&&(o=r.completedAt),Tr(r,t,o),await Cr(e,n,r,t,o)}}else Tr(a,t,o),await Cr(e,n,a,t,o);return await Pr(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function Ir(e,t,n){let r=e.on(_.setExternalExecutionStart,async r=>{let i=r.payload.execution,a=r.payload.frame;await Mr(t,i,a,n),await q(e,i.id),r.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),i=e.on(_.settleExternalExecution,async n=>{let r=await Fr(t,n.payload);await q(e,n.payload.executionId),n.setResult({success:r})});return()=>{r(),i()}}function Y(e){return{executionId:e.executionId,workflowId:e.workflowId,finalizerId:e.finalizerId,transitionKey:e.transitionKey,claimToken:e.claimToken,intent:e.intent,claimedAt:e.claimedAt}}function Lr(e,t){return e.state===`claimed`&&e.executionId===t.executionId&&e.workflowId===t.workflowId&&e.finalizerId===t.finalizerId&&e.transitionKey===t.transitionKey&&e.claimToken===t.claimToken&&e.intent.status===t.intent.status&&e.intent.completedAt===t.intent.completedAt&&e.intent.error===t.intent.error&&e.intent.reason===t.intent.reason}function Rr(e,t){if(e.executionId!==t.executionId||e.workflowId!==t.workflowId||e.finalizerId!==t.finalizerId||e.transitionKey!==t.transitionKey||e.claimToken!==t.claimToken)throw Error(`workflow finalization publication claim does not match durable transition ${t.executionId}`)}async function zr(e,t){let{workflowExecutions:n,workflowFinalizations:r}=D(e,L);return E(e,async e=>{let i=await e.select().from(r).where(N(r.executionId,t.executionId)).limit(1);return i[0]?Lr(i[0],t):(await e.update(n).set({status:`finalizing`}).where(k(N(n.id,t.executionId),N(n.workflowId,t.workflowId),N(n.status,`running`))).returning({id:n.id})).length===0?!1:(await e.insert(r).values({...t,state:`claimed`}),!0)})}function Br(e){return{status:e.status,completedAt:e.completedAt,error:e.status===`failed`?e.error??`Workflow finalization failed`:null,reason:e.status===`cancelled`?e.reason??null:null}}async function Vr(e,t,n,r){let{workflowExecutions:i,workflowFinalizations:a}=D(e,L);return E(e,async e=>{let o=(await e.select().from(a).where(N(a.executionId,t)).limit(1))[0];return!o||o.claimToken!==n||o.state===`failed`?!1:o.state===`acknowledged`?!0:(await e.update(i).set(Br(o.intent)).where(k(N(i.id,t),N(i.status,`finalizing`))).returning({id:i.id})).length===0?!1:(await e.update(a).set({state:`acknowledged`,settledAt:r}).where(k(N(a.executionId,t),N(a.claimToken,n),N(a.state,`claimed`))),!0)})}async function Hr(e,t,n,r,i){let{workflowExecutions:a,workflowFinalizations:o}=D(e,L);return E(e,async e=>{let s=(await e.select().from(o).where(N(o.executionId,t)).limit(1))[0];return!s||s.claimToken!==n||s.state===`acknowledged`?!1:s.state===`failed`?!0:(await e.update(a).set({status:`failed`,error:r,reason:null,completedAt:i}).where(k(N(a.id,t),N(a.status,`finalizing`))).returning({id:a.id})).length===0?!1:(await e.update(o).set({state:`failed`,failure:r,settledAt:i}).where(k(N(o.executionId,t),N(o.claimToken,n),N(o.state,`claimed`))),!0)})}async function Ur(e,t,n){let{workflowExecutions:r,workflowFinalizations:i}=D(t,L),a=(await t.select().from(i).where(N(i.executionId,n.executionId)).limit(1))[0];if(!a||(Rr(a,n),a.state===`claimed`||a.publishedAt!==null))return;let o=(await t.select({startedAt:r.startedAt,status:r.status,error:r.error,reason:r.reason,completedAt:r.completedAt}).from(r).where(N(r.id,a.executionId)).limit(1))[0];if(!(!o||o.completedAt==null)){if(o.status===`completed`)await e.emit(s.execution.completed,{executionId:a.executionId,workflowId:a.workflowId,totalDuration:o.completedAt-o.startedAt,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`failed`)await e.emit(s.execution.failed,{executionId:a.executionId,workflowId:a.workflowId,error:o.error??`Workflow finalization failed`,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`cancelled`)await e.emit(s.execution.cancelled,{executionId:a.executionId,workflowId:a.workflowId,reason:o.reason??void 0,completedAt:o.completedAt,transitionKey:a.transitionKey});else return;await O(t,()=>t.update(i).set({publishedAt:Date.now()}).where(k(N(i.executionId,a.executionId),P(i.publishedAt))))}}function Wr(e,t){let n=new Map;return async r=>{let i=(n.get(r.executionId)??Promise.resolve()).catch(()=>void 0).then(()=>Ur(e,t,r));n.set(r.executionId,i);try{await i}finally{n.get(r.executionId)===i&&n.delete(r.executionId)}}}function Gr(e,t){let n=Wr(e,t),r=e.on(_.claimFinalization,async e=>{e.setResult({claimed:await zr(t,e.payload.claim)})}),i=e.on(_.listClaimedFinalizations,async e=>{let{workflowFinalizations:n}=D(t,L),r=await t.select().from(n).where(k(N(n.finalizerId,e.payload.finalizerId),N(n.state,`claimed`)));e.setResult({claims:r.map(Y)})}),a=e.on(_.listUnpublishedFinalizations,async e=>{let{workflowFinalizations:n}=D(t,L),r=await t.select().from(n).where(k(Wt(N(n.state,`acknowledged`),N(n.state,`failed`)),N(n.finalizerId,e.payload.finalizerId),P(n.publishedAt)));e.setResult({claims:r.map(Y)})}),o=e.on(_.publishFinalization,async e=>{await n(e.payload.claim),e.setResult({})}),s=e.on(_.acknowledgeFinalization,async e=>{let{executionId:r,claimToken:i,settledAt:a}=e.payload,o=await Vr(t,r,i,a);if(e.setResult({acknowledged:o}),!o)return;let{workflowFinalizations:s}=D(t,L),c=await t.select().from(s).where(N(s.executionId,r)).limit(1);c[0]&&await n(Y(c[0]))}),c=e.on(_.failFinalization,async e=>{let{executionId:r,claimToken:i,error:a,settledAt:o}=e.payload,s=await Hr(t,r,i,a,o);if(e.setResult({failed:s}),!s)return;let{workflowFinalizations:c}=D(t,L),l=await t.select().from(c).where(N(c.executionId,r)).limit(1);l[0]&&await n(Y(l[0]))});return()=>{r(),i(),a(),o(),s(),c()}}function Kr(e){return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??void 0,status:e.status,inputs:e.inputs,config:{},error:e.error??void 0,reason:e.reason??void 0,startedAt:e.startedAt,completedAt:e.completedAt??void 0,triggerPayload:e.triggerPayload??void 0,...e.artifactKind!==null&&e.artifactId!==null?{artifactRef:{kind:e.artifactKind,id:e.artifactId}}:{},scope:z(e)}}function X(e){let t=R(e.scope);return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??null,status:e.status,inputs:e.inputs,error:e.error??null,reason:e.reason??null,startedAt:e.startedAt,completedAt:e.completedAt??null,triggerPayload:e.triggerPayload??null,artifactKind:e.artifactRef?.kind??null,artifactId:e.artifactRef?.id??null,...t}}function qr(e,t,n,r,i,a){let o=[...e?[N(a.workflowId,e)]:[],...n?[N(a.status,n)]:[],...i===void 0?[]:[N(a.artifactKind,i.kind),N(a.artifactId,i.id)]];if(t&&o.push(...mn(a,t)),r){let e=Wt(Vt(a.startedAt,r.startedAt),k(N(a.startedAt,r.startedAt),Vt(a.id,r.id)));e&&o.push(e)}return o}async function Jr(e,t,n,r,i){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);for(let e of i??[])if(e.targetExecutionId!==t.id)throw Error(`setExecutionStart requires executionLinks.targetExecutionId to match execution.id`);let{workflowExecutions:a,workflowRunContexts:o,workflowExecutionState:s,workflowExecutionStateEvents:c,workflowExecutionLinks:l}=D(e,L),u=X(t);await E(e,async d=>{await d.insert(a).values(u).onConflictDoUpdate({target:a.id,set:u});let f=(n.dispatchMetadata===void 0?await d.select({dispatchMetadata:o.dispatchMetadata}).from(o).where(N(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await jn(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=U(e,r);await d.insert(s).values({executionId:t.id,sequence:0,value:i,updatedAt:n}).onConflictDoNothing(),await d.insert(c).values({executionId:t.id,sequence:0,patch:[],value:i,createdAt:n}).onConflictDoNothing()}for(let e of i??[])await d.insert(l).values(e).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:e})})}async function Yr(e,t,n){if(n.executionId!==t.id)throw Error(`restorePausedGateResumeState requires execution.id to match gate.executionId`);if(t.status!==`paused`||n.status!==`waiting`)throw Error(`restorePausedGateResumeState requires a paused execution and waiting gate`);let{workflowExecutions:r,workflowGateInstances:i}=D(e,L),a=X(t),o=H(n);await E(e,async e=>{await e.insert(r).values(a).onConflictDoUpdate({target:r.id,set:a}),await e.insert(i).values(o).onConflictDoUpdate({target:i.id,set:o})})}async function Xr(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=D(e,L);return E(e,async e=>{if((await e.select().from(i).where(N(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(k(N(a.executionId,t),N(a.status,`waiting`)))).map(e=>({...V(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(N(i.id,t));for(let t of o){let n=H(t);await e.update(a).set(n).where(N(a.id,n.id))}return{cancelled:!0,gates:o}})}async function Zr(e,t,n,r,i,a){let{workflowExecutions:o}=D(e,L);return E(e,async e=>{if((await e.select({id:o.id}).from(o).where(N(o.id,t)).limit(1))[0]===void 0)return!1;let s={};return n!==void 0&&(s.status=n),r!==void 0&&(s.error=r),i!==void 0&&(s.reason=i),a!==void 0&&(s.completedAt=a),Object.keys(s).length>0&&await e.update(o).set(s).where(N(o.id,t)),!0})}function Qr(e,t){let{workflowExecutions:n}=D(t,L),r=e.on(_.getExecution,async e=>{let{executionId:r}=e.payload;if(!g(e,r))throw Error(`Unauthorized execution read: ${r}`);let i=await t.select().from(n).where(N(n.id,r));e.setResult({execution:i[0]?Kr(i[0]):null})}),i=e.on(_.setExecution,async e=>{let r=e.payload.execution,i=X(r);await O(t,()=>t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:i})),e.setResult({id:r.id})}),a=e.on(_.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await Jr(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),o=e.on(_.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await Yr(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),s=e.on(_.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await Zr(t,n,r,i,a,o);e.setResult({success:s})}),c=e.on(_.pauseRunningExecution,async e=>{let{workflowExecutions:n}=D(t,L),r=await O(t,()=>t.update(n).set({status:`paused`}).where(k(N(n.id,e.payload.executionId),N(n.status,`running`))).returning({id:n.id}));e.setResult({paused:r.length===1})}),l=e.on(_.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await Xr(t,n,r,i))});return()=>{r(),i(),a(),o(),s(),c(),l()}}function $r(e,t){let{workflowExecutions:n}=D(t,L),r=e.on(_.listExecutions,async e=>{let{workflowId:r,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(r===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=qr(r,i,a,s,c,n),u=o??mt;if(!Number.isInteger(u)||u<y||u>v)throw Error(`Execution list limit must be an integer between ${y} and ${v}.`);let d=await t.select().from(n).where(k(...l)).orderBy(M(n.startedAt),M(n.id)).limit(u);e.setResult({executions:d.map(Kr)})}),i=e.on(_.listExecutionsByArtifactRefs,async e=>{let r=ht.safeParse(e.payload);if(!r.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${r.error.message}`);let{refs:i,limitPerRef:a}=r.data,o={};for(let e of i){let r=await t.select().from(n).where(k(N(n.artifactKind,e.kind),N(n.artifactId,e.id))).orderBy(M(n.startedAt),M(n.id)).limit(a);r.length>0&&(o[Mt(e)]=r.map(Kr))}e.setResult({executionsByRef:o})});return()=>{r(),i()}}function ei(e,t){let n=gn(e,t),r=Qr(e,t),i=$r(e,t),a=yn(e,t),o=Cn(e,t),s=En(e,t),c=Mn(e,t),l=In(e,t),u=yr(e,t),d=Ir(e,t,X),f=Gr(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d(),f()}}function ti(e){return e.startsWith(b)}function ni(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function ri(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}async function ii(e,t){let{runContext:n}=await e.request(_.getRunContext,{executionId:t});if(n===null)throw Error(`Run context not found for execution: ${t}`);if(n.definitionSnapshot!==void 0)return n.definitionSnapshot;let{workflow:r}=await e.request(_.get,{id:n.workflowId});return r??void 0}function ai(e){return[e.on(s.getDefinition,async t=>{let n=await e.request(_.get,{id:t.payload.id});t.setResult(n)}),e.on(s.setDefinition,async t=>{let n=await e.request(_.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(s.deleteDefinition,async t=>{let n=await e.request(_.delete,{id:t.payload.id});t.setResult(n)}),e.on(s.listDefinitions,async t=>{let n=await e.request(_.list,t.payload);t.setResult(n)}),e.on(s.getExecution,async t=>{let n=await e.request(_.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(s.listExecutions,async t=>{let n=await e.request(_.listExecutions,t.payload);t.setResult(n)}),e.on(s.listExecutionsByArtifactRefs,async t=>{let n=await e.request(_.listExecutionsByArtifactRefs,t.payload);t.setResult(n)}),e.on(s.listSpans,async t=>{let n=await e.request(_.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(s.listFrames,async t=>{let n=await e.request(_.listFrames,{executionId:t.payload.executionId});t.setResult(n)}),e.on(s.listGateInstances,async t=>{let n=await e.request(_.listGateInstances,t.payload);t.setResult(n)}),e.on(s.setExecutionLink,async t=>{let n=await e.request(_.setExecutionLink,{link:t.payload.link});t.setResult(n)}),e.on(s.listExecutionLinks,async t=>{let n=await e.request(_.listExecutionLinks,t.payload);t.setResult(n)}),e.on(s.getRunContext,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(_.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)}),...oi(e)]}function oi(e){return[e.on(s.registerExternalExecution,async t=>{let n=ae.registerExternalExecution.request.parse(t.payload),{name:r,scope:i,input:a}=n;if(n.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let o=n.executionId??nt(`wfx-ext`);if(!ti(o))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let s=n.startedAt??Date.now(),c={id:o,workflowId:r,status:`running`,inputs:a===void 0?{}:a,startedAt:s,scope:i??{type:`global`},...ni(n)},l=si(o,s,n.frame),u=await e.request(_.setExternalExecutionStart,{execution:c,...l===void 0?{}:{frame:l}});t.setResult(u)}),e.on(s.completeExternalExecution,async t=>{let n=ae.completeExternalExecution.request.parse(t.payload),{executionId:r,status:i}=n;if(!g(t,r))throw Error(`Unauthorized: caller is not permitted to settle execution: ${r}`);if(!ti(r))throw Error(`completeExternalExecution: execution "${r}" is engine-owned and must be completed through the engine finalizer, not this API`);let a=ci(n),o=await e.request(_.settleExternalExecution,{executionId:r,status:i,...ri(n),...n.completedAt===void 0?{}:{completedAt:n.completedAt},...a===void 0?{}:{frame:a}});t.setResult({success:o.success})})]}function si(e,t,n){if(n===void 0)return;let r=n.frameId??`${e}:${n.nodeId}`;return{executionId:e,frameId:r,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path??[r],status:`running`,attempt:n.attempt,...n.iteration===void 0?{}:{iteration:n.iteration},...n.branchKey===void 0?{}:{branchKey:n.branchKey},startedAt:n.startedAt??t}}function ci(e){if(e.frame===void 0)return;if(e.completedAt===void 0)throw Error(`completedAt is required when frame metadata is supplied`);let t=e.completedAt-e.frame.startedAt;if(t<0)throw Error(`completedAt must not precede frame.startedAt`);if(e.frame.durationMs!==void 0&&e.frame.durationMs!==t)throw Error(`frame.durationMs must equal completedAt - frame.startedAt`);return{executionId:e.executionId,frameId:e.frame.frameId,nodeId:e.frame.nodeId,nodeType:e.frame.nodeType,path:e.frame.path,status:e.status,attempt:e.frame.attempt,...e.frame.iteration===void 0?{}:{iteration:e.frame.iteration},...e.frame.branchKey===void 0?{}:{branchKey:e.frame.branchKey},startedAt:e.frame.startedAt,completedAt:e.completedAt,durationMs:t,...e.status===`failed`&&e.error!==void 0?{error:e.error}:{}}}function li(e){return[e.on(s.state.get,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${n}`);let{state:r}=await e.request(_.getState,{executionId:n});if(r===null)throw Error(`no workflow state for execution ${n}`);t.setResult(r)}),e.on(s.state.patch,async t=>{let{executionId:n,expectedSequence:r,patch:i,nextValue:a}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${n}`);if(r===void 0)throw Error(`expectedSequence is required to patch workflow state`);let o=await ii(e,n);o!==void 0&&ue(o,a,`next`),gt.array().parse(i);let c=await e.request(_.patchState,{executionId:n,expectedSequence:r,nextValue:a});e.emit(s.state.updated,{executionId:c.executionId,sequence:c.sequence,patch:c.patch,value:c.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:c.executionId,sequence:c.sequence,value:c.value})})]}async function ui(e,t){let{runContext:n}=await e.bus.request(_.getRunContext,{executionId:t});if(n===null)throw new w(St.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return n}function di(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function fi(e,t){let n=await ui(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.scopeOverride??n.scope,c={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,scopeOverride:s,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:di(t.mode,t.reason)}]};return t.mode===`snapshot`?await gi(e,n,c):mi(n)?await _i(e,n,c):await Ce(e,n.workflowId,c)}function pi(e,t){return mi(e)?t.id:e.workflowId}function mi(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function hi(e){let t=e.definitionSnapshot;if(t===void 0)throw new w(St.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function gi(e,t,n){let r=hi(t);return Le(e,pi(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}async function _i(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`){let{materializationSpec:r}=t;if(r===void 0)throw Error(`Invalid persisted path-backed run context: materializationSpec is required`);return Ue(e,t.source.path,{...n,materializationSpec:r})}let r=hi(t);return Le(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}var vi=class{bus;resumePausedExecution;handles=new Map;constructor(e,t){this.bus=e,this.resumePausedExecution=t}dispose(){for(let e of this.handles.values())clearTimeout(e);this.handles.clear()}clear(e,t,n){let r=this.makeKey(e,t,n),i=this.handles.get(r);i!==void 0&&(clearTimeout(i),this.handles.delete(r))}schedule(e){e.timeoutMs!==null&&(this.clear(e.executionId,e.nodeId,e.frameId),this.scheduleNextWakeup({...e,timeoutMs:e.timeoutMs}))}scheduleNextWakeup(e){let t=this.makeKey(e.executionId,e.nodeId,e.frameId),n=Math.max(0,e.openedAt+e.timeoutMs-Date.now()),r=setTimeout(()=>{if(this.handles.delete(t),Date.now()<e.openedAt+e.timeoutMs){this.scheduleNextWakeup(e);return}this.handleExpiredWakeup(e)},Math.min(n,2147483647));this.handles.set(t,r)}scheduleNextWakeupAfterDelay(e,t){let n=this.makeKey(e.executionId,e.nodeId,e.frameId),r=setTimeout(()=>{this.handles.delete(n),this.handleExpiredWakeup(e)},t);this.handles.set(n,r)}async handleExpiredWakeup(e){try{await this.resumeTimedOutPausedGate(e)===`retry`&&this.scheduleNextWakeupAfterDelay(e,25)}catch(t){this.scheduleFailedWakeupRetry(e,t)}}scheduleFailedWakeupRetry(e,t){let n=(e.failedWakeupAttempts??0)+1;if(n>4){console.error(`[WorkflowExecutor] Giving up on timed-out gate '${e.nodeId}' after 4 failed wakeup retries:`,t);return}let r=Math.min(250*2**(n-1),2e3);console.error(`[WorkflowExecutor] Failed to resume timed-out gate '${e.nodeId}', retrying in ${r} ms:`,t),this.scheduleNextWakeupAfterDelay({...e,failedWakeupAttempts:n},r)}makeKey(e,t,n){return`${e}:${t}:${n}`}async resumeTimedOutPausedGate(e){this.clear(e.executionId,e.nodeId,e.frameId);let{gate:t}=await this.bus.request(_.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:n}=await this.bus.request(_.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function yi(e){if(e!==void 0)return bi(e)?e:{}}function bi(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function xi(e){if(e!==void 0)return _t.parse(e)}function Si(e,t){return wt.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}function Ci(e){return e?.status===`paused`}function wi(e){return e?.status===`waiting`}async function Ti(e,t,n,r,i,a,o){try{await h(e,i.id,async()=>{let o=await e.bus.request(_.getExecution,{executionId:i.id});o.execution?.status!==`paused`&&o.execution?.status!==`running`||(t.delete(i.id),n.delete(i.id),r.delete(i.id),await e.bus.request(_.restorePausedGateResumeState,{execution:i,gate:a}))})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${o}' after resume launch failure:`,e)}}async function Ei(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(_.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Di(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Oi(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(_.getGateInstance,t);return wi(n)?n:null}let{gates:n}=await e.request(_.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}async function ki(e,t){let n=e.authority.canonicalizeOutcome(t.outcome),r=t.runtimeFence===void 0?void 0:{...t.runtimeFence};await e.validation?.validate(t.executionId,n.outcome);let i=await e.authority.commitOutcome(t.executionAttemptId,t.executionId,n,r);if(i.kind===`accepted`||i.kind===`duplicate`){let n=await e.convergence.converge({executionId:t.executionId,executionAttemptId:t.executionAttemptId,outcome:i.outcome,decision:i.kind,controlObservation:structuredClone(i.controlObservation)});e.authority.settleOutcome(t.executionAttemptId,{kind:i.kind,outcome:e.authority.decodeOutcome(i.text),text:i.text,controlObservation:i.controlObservation,acceptance:n})}return i.kind}function Z(e,t){let n=c(e);if(n===null)throw Error(`Attempt requests require an authenticated workflow-execution-attempt peer`);if(n.executionAttemptId!==t)throw Error(`Request executionAttemptId does not match authenticated peer identity`);return n}function Ai(e,t){if(e===null||e.runtimeGeneration!==t.runtimeGeneration)return!1;if(t.outcome.kind===`cancelled`&&t.operationId===void 0)return e.activeOperationId===null;let n=t.outcome.kind===`technical-failure`?t.outcome.stage:t.outcome.kind===`cancelled`?e.activeOperationKind:`workload-invocation`;return n===`startup`?t.operationId===void 0&&e.activeOperationId===null:!(e.activeOperationId!==t.operationId||e.activeOperationGeneration!==t.runtimeGeneration||e.activeOperationKind!==n||n!==`workspace-preparation`&&n!==`workload-invocation`)}function ji(e,t){return e.on(S.instruction.get,async e=>{let n=x[`instruction.get`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.getInstruction(r);if(i===null){e.setResult({decision:`refused`,refusalReason:`not-found`});return}if((await t.getAttemptControlState(r.executionAttemptId))?.runtimeGeneration!==n.runtimeGeneration){e.setResult({decision:`refused`,refusalReason:`stale-generation`});return}e.setResult({decision:`found`,instruction:i})})}function Mi(e,t){let n=[ji(e,t.authority),e.on(S.control.report,async e=>{let n=x[`control.report`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.authority.reportAttemptControl({...n,executionId:r.executionId});i.kind===`accepted`||i.kind===`duplicate`?e.setResult({decision:i.kind}):e.setResult({decision:`refused`,reason:i.kind})}),e.on(S.operation.report,async e=>{let n=x[`operation.report`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.authority.reportOperation({...n,executionId:r.executionId});i.kind===`accepted`||i.kind===`duplicate`?e.setResult({decision:i.kind,binding:i.binding}):e.setResult({decision:`refused`,refusalReason:i.kind})}),e.on(S.outcome.submit,async e=>{let n=x[`outcome.submit`].request.parse(e.payload),r=Z(e,n.executionAttemptId),i=await t.authority.getInstruction(r);if(i===null)throw Error(`No instruction belongs to this authenticated Attempt`);if(!Ai(await t.authority.getAttemptControlState(r.executionAttemptId),n)){e.setResult({decision:`fenced`});return}let a={runtimeGeneration:n.runtimeGeneration,operationId:n.operationId??null},o=await t.decodeOutcome({instruction:i,outcome:n.outcome});try{let n=await ki(t,{...r,outcome:o,runtimeFence:a});e.setResult({decision:n})}catch(t){if(!(t instanceof at))throw t;e.setResult({decision:`fenced`})}})];return()=>{for(let e of n)e()}}function Ni(e,t){return e.origin.local?{executionAttemptId:t.executionAttemptId,executionId:t.executionId}:c(e)}var Pi=class{acceptOutcome;constructor(e){this.acceptOutcome=e}converge(e){return this.acceptOutcome(e)}};function Fi(e){return{authority:e.authority,decodeOutcome:et,convergence:new Pi(e.acceptOutcome)}}function Ii(e,t){let n=Fi(t),r=Mi(e,n),i=e.on(bt.control.outcome.submit,async e=>{let r=Ni(e,e.payload);if(r===null)throw Error(`Outcome submission requires an authenticated workflow-execution-attempt peer`);let{result:i}=e.payload;if(!e.origin.local){if(e.payload.executionId!==r.executionId)throw Error(`Outcome payload executionId '${e.payload.executionId}' does not match authenticated peer claim '${r.executionId}'`);if(e.payload.executionAttemptId!==r.executionAttemptId)throw Error(`Outcome payload executionAttemptId '${e.payload.executionAttemptId}' does not match authenticated peer identity '${r.executionAttemptId}'`)}if(i.executionId!==r.executionId)throw Error(`Nested result.executionId '${i.executionId}' does not match trusted identity '${r.executionId}'`);let a=Tt.parse(i),o=await t.authority.getInstruction(r);if(o===null)throw Error(`No instruction belongs to this workflow Attempt`);let s=await n.decodeOutcome({instruction:o,outcome:{kind:`workload-result`,result:a}}),c=await ki(n,{executionId:r.executionId,executionAttemptId:r.executionAttemptId,outcome:s});e.setResult({decision:Li(c)})});return()=>{i(),r()}}function Li(e){return e}function Ri(e,t){return e.on(S.operation.admit,async e=>{let n=c(e);if(n===null)throw Error(`Operation admission requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:r,operationKind:i,admissionKey:a,runtimeGeneration:o}=x[`operation.admit`].request.parse(e.payload);if(r!==n.executionAttemptId)throw Error(`Admission payload executionAttemptId '${r}' does not match authenticated peer identity '${n.executionAttemptId}'`);if(i===`runtime-probe`)throw Error(`Operation admission does not accept 'runtime-probe' (executionAttemptId='${r}'): the bounded probe is admitted only by runtime registration`);let s=await t.authority.admitOperation({executionAttemptId:r,executionId:n.executionId,operationKind:i,admissionKey:a,runtimeGeneration:o});if(s.kind===`admitted`||s.kind===`duplicate`){await t.bus.emit(S.operation.admitted,{executionAttemptId:r,operationId:s.operationId,operationKind:i,runtimeGeneration:s.runtimeGeneration,admittedAt:s.admittedAt}),e.setResult({decision:s.kind,operationId:s.operationId});return}e.setResult({decision:`refused`,refusalReason:s.kind})})}const zi=1e4;function Bi(e,t){let n=t.probeDeliveryTimeoutMs??1e4;return e.on(S.runtime.register,async e=>{let r=c(e);if(r===null)throw Error(`Runtime registration requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:i,runtimeIncarnationId:a}=x[`runtime.register`].request.parse(e.payload);if(i!==r.executionAttemptId)throw Error(`Registration payload executionAttemptId '${i}' does not match authenticated peer identity '${r.executionAttemptId}'`);let o=await t.authority.registerRuntime({executionAttemptId:i,executionId:r.executionId,runtimeIncarnationId:a});if(o.kind===`duplicate`&&o.runtimeReadyAt!==null){await Vi(t,i,o.runtimeGeneration),e.setResult({decision:`duplicate`,runtimeGeneration:o.runtimeGeneration});return}if(o.kind!==`registered`&&o.kind!==`duplicate`){e.setResult(Wi(o.kind));return}let s=o.runtimeGeneration;if(await Hi(t,n,{executionAttemptId:i,executionId:r.executionId,runtimeIncarnationId:a,runtimeGeneration:s})===null){e.setResult(Wi(`probe-failed`));return}await Vi(t,i,s),e.setResult({decision:`ready`,runtimeGeneration:s})})}async function Vi(e,t,n){let r=await e.authority.getAttemptControlState(t);r===null||r.runtimeGeneration!==n||r.runtimeReadyAt===null||await e.bus.emit(S.runtime.ready,{executionAttemptId:t,runtimeGeneration:n,acceptedAt:r.runtimeReadyAt})}async function Hi(e,t,n){let{executionAttemptId:r,executionId:i,runtimeIncarnationId:a,runtimeGeneration:o}=n,s=await e.authority.admitOperation({executionAttemptId:r,executionId:i,operationKind:`runtime-probe`,admissionKey:`probe:${a}`,runtimeGeneration:o});if(s.kind!==`admitted`&&s.kind!==`duplicate`)return null;let c=s.operationId,l=()=>Ui(e,{executionAttemptId:r,operationId:c,runtimeGeneration:o}),u;try{u=(await e.bus.request(S.operation.deliver,{executionAttemptId:r,runtimeIncarnationId:a,operationId:c,operationKind:`runtime-probe`,runtimeGeneration:o},{timeout:t})).receipt}catch{return await l(),null}if(u!==`completed`&&u!==`duplicate`)return await l(),null;let d=await e.authority.completeOperation({executionAttemptId:r,operationId:c,runtimeGeneration:o});if(d.kind!==`completed`&&d.kind!==`duplicate`)return null;let f=await e.authority.markRuntimeReady({executionAttemptId:r,executionId:i,runtimeGeneration:o,readyAt:new Date().toISOString()});return f.kind!==`ready`&&f.kind!==`duplicate`?null:{kind:f.kind,acceptedAt:f.acceptedAt}}async function Ui(e,t){try{await e.authority.completeOperation(t)}catch{}}function Wi(e){return{decision:`refused`,runtimeGeneration:0,refusalReason:e}}function Gi(e,t,n){n(Bi(e,{bus:e,authority:t})),n(Ri(e,{bus:e,authority:t}))}function Ki(e,t){let n=new AbortController,r=e.on(S.bootstrap.awaitStart,async e=>{let r=c(e);if(r===null)throw Error(`Bootstrap start requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:i}=x[`bootstrap.awaitStart`].request.parse(e.payload);if(i!==r.executionAttemptId)throw Error(`Bootstrap start executionAttemptId does not match authenticated peer identity`);let a=e.signal?AbortSignal.any([e.signal,n.signal]):n.signal;e.setResult(await t.awaitBootstrapStart({executionAttemptId:i,executionId:r.executionId},{signal:a,deadline:e.deadline??Date.now()+31e3}))});return()=>{n.signal.aborted||(n.abort(Error(`Bootstrap start handler shut down`)),r())}}function qi(e){return e.on(s.finalizeDelegateResult,async t=>{let n=t.payload;Ji(t,n.executionId);let{execution:r}=await e.request(_.getExecution,{executionId:n.executionId});if(r===null||r.workflowId!==n.workflowId)throw Error(`delegate result finalization execution does not own the requested workflow`);let{runContext:i}=await e.request(_.getRunContext,{executionId:n.executionId});if(i===null||i.executionId!==n.executionId||i.workflowId!==n.workflowId)throw Error(`delegate result finalization run context does not own the requested workflow execution`);if(i.definitionSnapshot===void 0)throw Error(`delegate result finalization requires an Authority-owned definition snapshot`);Yi(i.definitionSnapshot,n.nodeId,n.nodeType,n.finalizerId);let{subjects:a}=Ot(n.finalizerId),o=await e.request(a.finalize,{executionId:n.executionId,workflowId:n.workflowId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,rawResult:n.rawResult,toolObservations:n.toolObservations,...n.economics===void 0?{}:{economics:n.economics}});t.setResult(o)})}function Ji(e,t){if(!g(e,t))throw Error(`delegate result finalization requires its authenticated workflow-execution-attempt peer`)}function Yi(e,t,n,r){let i=!1;if(Nt(e.root,{enter(e){if(!(e.type!==`delegate-agent`&&e.type!==`delegate-role`||e.id!==t||e.type!==n))return e.resultFinalizerId===r&&(i=!0),!1}}),!i)throw Error(`delegate result finalizer is not selected by the requested durable delegate node`)}async function Xi(e,t,n){let[{execution:r},{runContext:i}]=await Promise.all([e.bus.request(_.getExecution,{executionId:t}),e.bus.request(_.getRunContext,{executionId:t})]);if(!r)throw Error(`Authority execution not found: ${t}`);if(i?.executionId!==t||i.workflowId!==r.workflowId)throw Error(`authority technical failure run context identity mismatch`);if(i.terminalAuthority!==`authority`)throw Error(`authority technical failure requires terminalAuthority=authority`);if(r.status===`failed`||r.status===`cancelled`)return{accepted:!0,status:r.status};if(r.status!==`running`)throw Error(`Authority technical failure conflicts with execution status: ${r.status}`);await te(e,r,t,`${n.stage}: ${n.message}`);let a=await e.bus.request(_.getExecution,{executionId:t});if(a.execution?.status!==`failed`&&a.execution?.status!==`cancelled`)throw Error(`Authority technical failure did not settle as failed or cancelled`);return{accepted:!0,status:a.execution.status}}async function Zi(e,t,n){let[{execution:r},{runContext:i}]=await Promise.all([e.bus.request(_.getExecution,{executionId:t}),e.bus.request(_.getRunContext,{executionId:t})]);if(!r)throw Error(`Authority execution not found: ${t}`);if(i?.executionId!==t||i.workflowId!==r.workflowId)throw Error(`authority cancellation run context identity mismatch`);if(i.terminalAuthority!==`authority`)throw Error(`authority cancellation requires terminalAuthority=authority`);if(r.status===`cancelled`)return{accepted:!0,status:`cancelled`};if(r.status!==`running`)throw Error(`Authority cancellation conflicts with execution status: ${r.status}`);if(await m(e,t,n.reason),(await e.bus.request(_.getExecution,{executionId:t})).execution?.status!==`cancelled`)throw Error(`Authority cancellation did not settle as cancelled`);return{accepted:!0,status:`cancelled`}}async function Qi(e,t,n){if(t.status===`finalizing`){if(n.status!==`completed`)throw Error(`authority runner result conflicts with terminal execution`);await u(e);let r=await e.bus.request(_.getExecution,{executionId:t.id});if(!r.execution)throw Error(`Authority runner success finalization execution is missing`);if(!o(r.execution.status,n.status))throw Error(`authority runner result conflicts with terminal execution`);return r.execution.status}if(!(t.status!==`completed`&&t.status!==`failed`&&t.status!==`cancelled`)){if(!o(t.status,n.status))throw Error(`authority runner result conflicts with terminal execution`);return t.status}}async function $i(e,t){return h(e,t.executionId,async()=>{let{execution:n}=await e.bus.request(_.getExecution,{executionId:t.executionId});if(!n)throw Error(`Authority execution not found: ${t.executionId}`);if(!(`kind`in t.outcome)&&(t.outcome.executionId!==n.id||t.outcome.workflowId!==n.workflowId))throw Error(`authority outcome execution or workflow identity mismatch`);return n})}async function ea(e,t){let n=await $i(e.lifecycle,t),r=`kind`in t.outcome?t.outcome.kind===`cancelled`:t.outcome.status===`cancelled`;if(n.status===`cancelled`&&!r)return`recorded-only`;if(!r&&t.controlObservation!==null&&t.controlObservation.controlRevision>0&&(n.status===`running`||n.status===`paused`))throw Error(`Workflow owner cancellation is not durably settled for '${t.executionId}'`);let i=await ta(e,t);if((await $i(e.lifecycle,t)).status===`cancelled`&&!r)return`recorded-only`;if(!i)throw Error(`Workflow outcome did not converge execution '${t.executionId}'`);return`projected`}async function ta(e,t){if(`kind`in t.outcome){let n=t.outcome.kind===`cancelled`?await e.acceptCancellation(t.executionId,t.outcome):await e.acceptTechnicalFailure(t.executionId,t.outcome);return n.accepted&&(t.outcome.kind===`cancelled`?n.status===`cancelled`:n.status===`failed`||n.status===`cancelled`)}if(t.outcome.status===`paused`)return je(e.lifecycle,t.outcome);let n=await e.acceptTerminalResult(t.executionId,t.outcome);return n.accepted&&o(n.status,t.outcome.status)}var na=class extends Pt{workflowRunner;executionAttemptAuthority;static storage={drizzle:ei};config;stopBootstrapWaits;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;workflowAbortControllers=new Map;successFinalizers=new Map;durableLifecycleTransitions=new Map;lifecyclePublications=new Map;publishingLifecycleExecutions=new Set;materializationSpecResolvers=new Set;constructor(e,t,n,r){super(e),this.workflowRunner=n,this.executionAttemptAuthority=r,this.config={...l,...t},this.gateTimeoutScheduler=new vi(e,e=>this.resumePausedExecution(e))}registerWorkflowMaterializationSpecResolver(e){return this.materializationSpecResolvers.add(e),()=>this.materializationSpecResolvers.delete(e)}async registerSuccessFinalizer(e){if(!this.initialized)throw Error(`[WorkflowExecutor] Initialize the executor before registering success finalizers`);if(this.successFinalizers.has(e))throw Error(`[WorkflowExecutor] Success finalizer already registered: ${e}`);let{namespace:t,subjects:n}=kt(e);this.bus.registerNamespace(t);let r={finalizerId:e,finalizeSubject:n.finalize};this.successFinalizers.set(e,r);try{await u(this.buildFinalizerDeps())}catch(t){throw this.successFinalizers.get(e)===r&&this.successFinalizers.delete(e),t}let i=!1;return()=>{i||(i=!0,this.successFinalizers.get(e)===r&&this.successFinalizers.delete(e))}}async acceptAuthorityRunnerResult(e,n){if(n.status===`paused`)throw Error(`authority runner result must be terminal`);if(n.executionId!==e)throw Error(`authority runner result execution identity mismatch`);let{execution:r}=await this.bus.request(_.getExecution,{executionId:e});if(!r)throw Error(`Authority runner execution not found: ${e}`);if(r.workflowId!==n.workflowId)throw Error(`authority runner result workflow identity mismatch`);if(r.status===`cancelled`&&n.status!==`cancelled`)return{accepted:!1,status:r.status};let i;if(r.status===`finalizing`){let{workflow:t}=await this.loadAuthorityRunnerContext(e,n.workflowId);i=await this.registerAuthorityResultFinalizer(t)}let a=await Qi(this.buildFinalizerDeps(),r,n).finally(()=>i?.());if(a!==void 0)return{accepted:!0,status:a};if(r.status!==`running`)throw Error(`Authority runner execution is ${r.status}`);let{runContext:s,workflow:c}=await this.loadAuthorityRunnerContext(e,n.workflowId),l=await this.registerAuthorityResultFinalizer(c),u=this.activeExecutions.get(e),d=!1;if(!u)this.activeExecutions.set(e,{execution:r,workflow:c,runContext:s,runtimeHandlers:new Map,runtimeLoopGates:new Map}),d=!0;else if(u.execution.workflowId!==n.workflowId)throw Error(`authority runner active execution identity mismatch`);try{await t({activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps()},n)}finally{d&&this.activeExecutions.delete(e),l?.()}let f=await this.bus.request(_.getExecution,{executionId:e});if(f.execution?.status===`cancelled`&&n.status!==`cancelled`)return{accepted:!1,status:f.execution.status};if(!f.execution||!o(f.execution.status,n.status))throw Error(`Authority runner result did not settle compatibly with ${n.status}`);return{accepted:!0,status:f.execution.status}}acceptAuthorityTechnicalFailure=(e,t)=>Xi(this.buildFinalizerDeps(),e,t);acceptAuthorityCancellation=(e,t)=>Zi(this.buildFinalizerDeps(),e,t);acceptAuthorityOutcome=e=>ea({lifecycle:this.buildFinalizerDeps(),acceptTerminalResult:(e,t)=>this.acceptAuthorityRunnerResult(e,t),acceptTechnicalFailure:this.acceptAuthorityTechnicalFailure,acceptCancellation:this.acceptAuthorityCancellation},e);async loadAuthorityRunnerContext(e,t){let{runContext:n}=await this.bus.request(_.getRunContext,{executionId:e});if(!n)throw Error(`Authority runner run context not found: ${e}`);if(n.executionId!==e||n.workflowId!==t)throw Error(`authority runner run context identity mismatch`);if(n.terminalAuthority!==`authority`)throw Error(`authority runner result requires terminalAuthority=authority`);let r=n.definitionSnapshot??(await this.bus.request(_.get,{id:n.workflowId})).workflow;if(!r||r.id!==t)throw Error(`authority runner workflow definition is unavailable or mismatched`);return{runContext:n,workflow:r}}registerAuthorityResultFinalizer(e){return!e.successFinalizerId||this.successFinalizers.has(e.successFinalizerId)?Promise.resolve(void 0):this.registerSuccessFinalizer(e.successFinalizerId)}async onInit(){this.registerExecutionHandlers(),this.addCleanup(ze(this.bus,(e,t)=>{let n=this.activeExecutions.get(e);n!==void 0&&(n.workflow=t)})),this.addCleanup(qi(this.bus)),this.executionAttemptAuthority!==void 0&&(this.stopBootstrapWaits=Ki(this.bus,this.executionAttemptAuthority),this.addCleanup(this.stopBootstrapWaits),this.addCleanup(Ii(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority,acceptOutcome:this.acceptAuthorityOutcome})),Gi(this.bus,this.executionAttemptAuthority,e=>this.addCleanup(e))),ai(this.bus).forEach(e=>this.addCleanup(e)),li(this.bus).forEach(e=>this.addCleanup(e)),await this.rehydratePausedGateTimeouts()}async onDestroy(){this.stopBootstrapWaits?.();let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await p(e,t,`Workflow engine shutdown`)&&(this.workflowAbortControllers.get(t)?.abort(),this.workflowAbortControllers.delete(t))}));for(let e of this.workflowAbortControllers.values())e.abort();this.workflowAbortControllers.clear(),await Promise.allSettled(this.executionTasks.values()),await Promise.allSettled(this.durableLifecycleTransitions.values()),await Promise.allSettled(this.lifecyclePublications.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){let e=this.executionAttemptAuthority;return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs,requestAttemptCancellation:e===void 0?void 0:(t,n)=>e.requestCancellation({executionId:t,reason:n}),notifyAttemptCancellation:(e,t)=>this.notifyAttemptCancellation(e,t),successFinalizers:this.successFinalizers,resolveSuccessFinalizerId:e=>this.activeExecutions.get(e)?.workflow.successFinalizerId,durableLifecycleTransitions:this.durableLifecycleTransitions,lifecyclePublications:this.lifecyclePublications,publishingLifecycleExecutions:this.publishingLifecycleExecutions}}async notifyAttemptCancellation(e,t){this.workflowAbortControllers.get(e)?.abort(t??C),await this.bus.emit(Dt(`workflow.${e}.cancel`),{executionId:e,reason:t}).catch(t=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${e}:`,t)})}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(vt.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${e}`);return t.targetWorkingDirectory??this.config.platformDefaults.cwd}resolveEphemeralPlatformFields(){return Ye(this.config.platformDefaults.cwd,this.config.makaioHome)}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Si(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e),executionAttemptAuthority:this.executionAttemptAuthority,materializationSpecResolvers:this.materializationSpecResolvers}}registerExecutionHandlers(){this.registerHandler(s.acceptAuthorityRunnerResult,async e=>{if(!e.origin.local)throw Error(`authority runner result acceptance is local-authority only`);let{executionId:t,result:n}=e.payload;e.setResult(await this.acceptAuthorityRunnerResult(t,n))}),this.registerHandler(s.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s}=e.payload;try{let c=await Ce(this.buildStartDeps(),t,{input:xi(n),config:yi(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,scopeOverride:s});e.setResult({executionId:c})}catch(e){if(e instanceof w)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(s.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,reason:l}=e.payload;try{let u=await fi(this.buildStartDeps(),{executionId:t,mode:n,input:xi(r),config:yi(i),parentSessionId:a,triggerPayload:o,artifactRef:s,scopeOverride:c,reason:l});e.setResult({executionId:u})}catch(e){if(e instanceof w)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(s.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,materializationSpec:n,triggerPayload:r,triggerMode:i,scope:a}=e.payload;try{let o=await Ue(this.buildStartDeps(),t,{...n===void 0?{}:{materializationSpec:n},triggerPayload:r,triggerMode:i,scopeOverride:a});e.setResult({executionId:o})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(s.cancel,async e=>{let{executionId:t,reason:n}=e.payload,r=await p(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:r})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(s.gate.respond,async e=>{let{executionId:t,executionAttemptId:n,gateId:r,frameId:i,action:a,resumeData:o,reason:s}=e.payload,c=await this.respondToPausedGate({executionId:t,executionAttemptId:n,gateId:r,frameId:i,action:a,resumeData:o,reason:s});e.setResult({accepted:c})},{priority:-100}))}registerGateTimeoutHandlers(){this.addCleanup(this.bus.on(s.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(s.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(_.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Di(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let n=new AbortController;this.workflowAbortControllers.set(e,n);try{let r;try{let i=await ye({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new Fe(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,n.signal,void 0,i,{context:this.resolveEphemeralPlatformFields(),env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});Ge(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();r=await ke(t.workflow.root,a,o)}catch(r){if(n.signal.aborted||t.execution.status===`cancelled`){await m(this.buildFinalizerDeps(),e,C);return}let i=r instanceof Error?r.message:String(r);await te(this.buildFinalizerDeps(),t.execution,e,i);return}let i=this.buildFinalizerDeps();r.status===`cancelled`||n.signal.aborted||t.execution.status===`cancelled`?await m(i,e,C):r.status===`failed`?await te(i,t.execution,e,r.error):r.status===`paused`?(t.execution.status=`paused`,await this.bus.request(_.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await ie(i,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,executionAttemptId:n,gateId:r,frameId:i,resumeData:a,reason:o}=e,{execution:s}=await this.bus.request(_.getExecution,{executionId:t});if(!Ci(s))return!1;let c=await Oi(this.bus,{executionId:t,nodeId:r,frameId:i});if(c===null||n!==c.executionAttemptId||!Ve(r,c.schema,a).valid)return!1;let{runContext:l}=await this.bus.request(_.getRunContext,{executionId:t});if(l===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Ei(this.bus,l);let{accepted:u}=await this.bus.request(_.resolveWaitingGateInstance,{gate:{...c,status:e.action===`reject`?`rejected`:`resumed`,resumeData:a,...o===void 0?{}:{reason:o},resolvedAt:Date.now()}});if(!u)return!1;try{await this.resumePausedExecution(s.id)}catch(e){throw await Ti(this.buildFinalizerDeps(),this.activeExecutions,this.executionTasks,this.workflowAbortControllers,s,c,r),e}return this.gateTimeoutScheduler.clear(t,r,c.frameId),!0}async resumePausedExecution(e){let{runContext:t}=await this.bus.request(_.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let n=t.definitionSnapshot??(await this.bus.request(_.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})();await Ei(this.bus,t);let r=Ne(t,n,{resume:!0}),i=me(this.buildStartDeps(),r);await h(this.buildFinalizerDeps(),e,async()=>{let{execution:a}=await this.bus.request(_.getExecution,{executionId:e});if(a===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(a.status!==`paused`)return;await this.bus.request(_.setExecution,{execution:{...a,status:`running`}}),this.activeExecutions.set(e,{execution:{...a,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let o=Te(this.buildStartDeps(),r,i);De(this.executionTasks,e,o)})}};const Q=`[WorkflowTriggerReconciler]`;function ra(e){return e.map(ia)}function ia(e){let t=xt.parse(e);return{binding:t,matches:st(t),subscription:void 0}}function aa(e,t,n){let r=e.triggers??[];try{return n===void 0?ra(r):r.map(e=>n.has(e.kind)?ia(e):void 0)}catch(i){if(t){console.error(`${Q} keeping last-good triggers for workflow "${e.id}": its trigger bindings are invalid`,i);return}return r.map((t,r)=>{if(!(n!==void 0&&!n.has(t.kind)))try{return ia(t)}catch(t){console.error(`${Q} leaving invalid trigger ${r} of workflow "${e.id}" inactive`,t);return}})}}function oa(e,t){return e.scope.type!==`global`||t.kind!==pt}async function sa(e,t,n,r){if(r!==void 0)for(let[i,a]of Array.from(r)){let o=e.triggers?.[i];if(o!==void 0&&n!==void 0&&!n.has(o.kind))continue;let s=t[i];s!==void 0&&oa(e,s.binding)||(r.delete(i),await $(a.subscription))}}async function $(e){if(e!==void 0)try{await e.detach()}catch(t){console.error(`${Q} detach failed for '${e.bindingKey}':`,t)}}var ca=class{bus;resolveRuntime;consumers=new Map;cleanupFns=[];initialized=!1;initialization;lane=new ut;pendingChanges=[];constructor(e,t){this.bus=e,this.resolveRuntime=t}async init(){if(this.initialized)return;if(this.initialization!==void 0)return this.initialization;let e=this.initialize();return this.initialization=e,e.then(()=>this.clearInitialization(e),()=>this.clearInitialization(e)),e}clearInitialization(e){this.initialization===e&&(this.initialization=void 0)}async initialize(){try{let e=({payload:e})=>{this.onSignal(`refresh of workflow "${e.id}"`,()=>this.refreshDefinition(e.id))};this.cleanupFns.push(this.bus.on(T.definition.created,e),this.bus.on(T.definition.updated,e),this.bus.on(T.definition.deleted,e),this.bus.on(ft.changed,e=>{this.scheduleRegistryReconcile(e.payload)})),await this.reconcileStored(`keep-last-good`),this.initialized=!0}catch(e){throw await this.teardown(),e}}async destroy(){await this.teardown(),this.initialized=!1}activeConsumerCount(){let e=0;for(let t of this.consumers.values())e+=t.size;return e}onSignal(e,t){t().catch(t=>{console.error(`${Q} ${e} failed:`,t)})}scheduleRegistryReconcile(e){let t=this.pendingChanges.length>0;this.pendingChanges.push(e),!t&&queueMicrotask(()=>{if(this.pendingChanges.length===0)return;let e=this.pendingChanges.splice(0),t=new Set(e.flatMap(({kinds:e})=>e)),n=e.map(({owner:e,revision:t})=>`${e}@${t}`).join(`, `);this.onSignal(`reconciliation after trigger registry changes (${n})`,()=>this.reconcileStored(`drop-unavailable`,t))})}async reconcileStored(e,t){await this.lane.run(async()=>{let{workflows:n}=await this.bus.request(_.list,{}),r=new Set(n.map(e=>e.id));for(let r of n){let n=r.triggers??[];t!==void 0&&!n.some(e=>t.has(e.kind))||await this.applyDefinitionWithinLane(r,e,t)}for(let e of Array.from(this.consumers.keys()))r.has(e)||await this.forgetWorkflowWithinLane(e)})}async refreshDefinition(e){await this.lane.run(async()=>{let{workflow:t}=await this.bus.request(_.get,{id:e});if(t===null){await this.forgetWorkflowWithinLane(e);return}await this.applyDefinitionWithinLane(t,`keep-last-good`)})}async applyDefinitionWithinLane(e,t,n){let r=aa(e,(this.consumers.get(e.id)?.size??0)>0,n);if(r===void 0)return;let i=this.consumers.get(e.id);if(await sa(e,r,n,i),i?.size===0&&this.consumers.delete(e.id),!r.some(t=>t!==void 0&&oa(e,t.binding)&&(n===void 0||n.has(t.binding.kind))))return;let a=this.resolveRuntime();if(a===void 0){r.length>0&&console.warn(`${Q} no automation trigger binding runtime is available; declarative triggers of workflow "${e.id}" stay inactive`);return}let o=this.consumers.get(e.id);o===void 0&&(o=new Map,this.consumers.set(e.id,o));for(let[i,s]of r.entries())s!==void 0&&oa(e,s.binding)&&(n!==void 0&&!n.has(s.binding.kind)||await this.refreshConsumerWithinLane(a,e.id,i,s,o,t));o.size===0&&this.consumers.delete(e.id)}async refreshConsumerWithinLane(e,t,n,r,i,a){let o=i.get(n),s=this.createListener(t,n,r);try{let t=o?.subscription?.bindingKey,a=e.prepareBinding(r.binding);if(a===void 0)throw Error(`Automation trigger kind '${r.binding.kind}' is not registered`);if(!a.workflowCompatible)throw Error(`Automation trigger kind '${r.binding.kind}' does not emit an object-root payload`);(t===void 0||t!==a.bindingKey)&&i.set(n,r),r.subscription=await a.subscribe(s),i.set(n,r),await $(o?.subscription);return}catch(e){if(o===void 0?i.delete(n):i.set(n,o),a===`keep-last-good`){console.error(`${Q} keeping last-good trigger ${n} of workflow "${t}": binding '${r.binding.kind}' could not be activated`,e);return}console.warn(`${Q} dropping trigger ${n} of workflow "${t}": binding '${r.binding.kind}' is no longer available`,e),i.delete(n),await $(o?.subscription)}}async forgetWorkflowWithinLane(e){let t=this.consumers.get(e);if(t!==void 0){this.consumers.delete(e);for(let e of t.values())await $(e.subscription)}}createListener(e,t,n){let r=`trigger ${t} ('${n.binding.kind}') of workflow "${e}"`;return async i=>{if(this.consumers.get(e)?.get(t)!==n)return;let a;try{a=n.matches(i.payload)}catch(e){console.error(`${Q} filter evaluation failed for ${r}:`,e);return}if(a)try{await this.bus.request(T.start,{workflowId:e,triggerPayload:ot(i.payload)})}catch(t){console.error(`${Q} failed to start workflow "${e}" from ${r}:`,t)}}}async teardown(){this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.pendingChanges.length=0,await this.lane.run(async()=>{for(let e of Array.from(this.consumers.keys()))await this.forgetWorkflowWithinLane(e)})}};const la=1e3;function ua(e){if(e===null)return{status:`refused`,reason:`not-found`};if(e.settled)return{status:`refused`,reason:`resolved`};if(!e.active)return{status:`refused`,reason:`fenced`};if(e.allocationTerminated)return{status:`refused`,reason:`allocation-terminated`};if(e.operationStartGate===`closed`)return{status:`refused`,reason:`gate-closed`};let t=e.bootstrapDeadlineAt===null?NaN:Date.parse(e.bootstrapDeadlineAt);return!Number.isFinite(t)||t<=Date.now()?{status:`refused`,reason:`bootstrap-expired`}:{status:e.allocated?`permitted`:`pending`}}function da(e,t){return new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),t.aborted&&i(),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function fa(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),n()},a=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),r(t.reason)},o=setTimeout(i,e);t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}function pa(e,t){return setTimeout(()=>e.abort(Error(`Bootstrap start observation timed out`)),Math.max(0,t-Date.now()))}async function ma(e,t,n){if(n.signal.throwIfAborted(),!Number.isFinite(n.deadline))throw Error(`Bootstrap start request requires a finite deadline`);let r=Math.min(Date.now()+3e4,n.deadline-la),i=new AbortController,a=AbortSignal.any([n.signal,i.signal]),o=Math.min(n.deadline,r+la),s=pa(i,o);try{for(;;){a.throwIfAborted();let n=await da(e.readBootstrapStartState(t),a);a.throwIfAborted();let c=ua(n);if(c.status!==`pending`)return c;let l=Date.parse(n?.bootstrapDeadlineAt??``);clearTimeout(s),s=pa(i,Math.min(o,l+la));let u=Math.min(r,l)-Date.now();if(u<=0)return c;await fa(Math.min(100,u),a)}}finally{clearTimeout(s)}}var ha=class{repository;bootstrapTimeoutMs;waiters=new Map;constructor(e,t){if(!Number.isSafeInteger(t?.bootstrapTimeoutMs)||t.bootstrapTimeoutMs<=0)throw Error(`ExecutionAttemptAuthority requires an explicit positive safe-integer bootstrapTimeoutMs`);this.repository=e,this.bootstrapTimeoutMs=t.bootstrapTimeoutMs}awaitBootstrapStart(e,t){return ma(this.repository,e,t)}async createAttempt(e,t){let n=crypto.randomUUID(),r=await this.repository.createAttempt({executionAttemptId:n,executionId:e,instruction:t,bootstrapTimeoutMs:this.bootstrapTimeoutMs});return this.installWaiter(n),r}async ensureAttempt(e){let t=lt(e);return this.repository.ensureAttempt({...t,executionAttemptId:crypto.randomUUID(),bootstrapTimeoutMs:this.bootstrapTimeoutMs})}async readAttemptSettlement(e){return this.repository.readAttemptSettlement(ct(e))}async getInstruction(e){return this.repository.getInstruction(e)}async requestAttemptCancellation(e){return this.repository.requestAttemptCancellation(rt(e))}async requestCancellation(e){return this.repository.requestCancellation(it(e))}async readCancellation(e){return this.repository.readCancellation(e)}async reportOperation(e){return this.repository.reportOperation(e)}async beginProvisioning(e){return this.repository.beginProvisioning(e)}async getProviderOperation(e){return this.repository.getProviderOperation(e)}async renewProviderOperationClaim(e){return this.repository.renewProviderOperationClaim(e)}async takeOverProviderOperation(e){return this.repository.takeOverProviderOperation(e)}async handoffProviderOperation(e){return this.repository.handoffProviderOperation(e)}async recordProviderOperationUncertainty(e){return this.repository.recordProviderOperationUncertainty(e)}async completeProviderOperation(e){return this.repository.completeProviderOperation(e)}async recordAllocation(e){return this.repository.recordAllocation(e)}async recordProvisioningAbsent(e){let t=await this.repository.recordProvisioningAbsent(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' provisioning produced no allocation: ${e.evidence.source} reported '${e.evidence.summary}'`)),t}async recordProvisionerIncarnationLost(e){let t=await this.repository.recordProvisionerIncarnationLost(e);if(t.kind===`recorded`){let{evidence:t,provisionerIncarnationId:n}=e.proof;this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' lost the provisioner incarnation '${n}' its allocation was bound to: ${t.source} reported '${t.summary}'`))}return t}async recordAllocationTerminated(e){return this.repository.recordAllocationTerminated(e)}async registerRuntime(e){return this.repository.registerRuntime(e)}async admitOperation(e){return this.repository.admitOperation(e)}async completeOperation(e){return this.repository.completeOperation(e)}async markRuntimeReady(e){return this.repository.markRuntimeReady(e)}async getAttemptControlState(e){return this.repository.getAttemptControlState(e)}async readAttemptCancellationControl(e){return this.repository.readAttemptCancellationControl(e)}async recordAttemptControlReceipt(e){return this.repository.recordAttemptControlReceipt(e)}async reportAttemptControl(e){return this.repository.reportAttemptControl(e)}async getActiveAttempt(e,t){return this.repository.getActiveAttempt(e,t)}canonicalizeOutcome(e){return this.repository.canonicalizeOutcome(e)}decodeOutcome(e){return this.repository.decodeOutcome(e)}async commitOutcome(e,t,n,r){let i=await this.repository.commitOutcome({executionAttemptId:e,executionId:t,result:n,...r===void 0?{}:{runtimeFence:r}});return(i.kind===`conflict`||i.kind===`fenced`)&&this.settleWaiterInternal(e,i),i}waitForOutcome(e){return this.waiters.get(e)?.promise}settleOutcome(e,t){this.settleWaiterInternal(e,t)}discardWaiter(e){this.waiters.delete(e)}rejectAndDiscardWaiter(e,t){this.rejectWaiterWith(e,()=>t)}rejectWaiterWith(e,t){let n=this.waiters.get(e);n!==void 0&&(n.promise.catch(()=>void 0),n.reject(t()),this.waiters.delete(e))}get supportsRecovery(){return this.repository.recovery!==void 0}async getAttemptWithAllocation(e){return this.requireRecovery(`getAttemptWithAllocation`).getAttemptWithAllocation(e)}async recordDiscoveredAllocation(e){return this.requireRecovery(`recordDiscoveredAllocation`).recordDiscoveredAllocation(e)}async evolveAllocationRef(e){let t=this.requireRecovery(`evolveAllocationRef`);if(e.currentRef.providerId!==e.nextRef.providerId)throw Error(`Provider identity mismatch in allocation ref evolution: currentRef.providerId '${e.currentRef.providerId}' !== nextRef.providerId '${e.nextRef.providerId}'. Provider identity must not change during correlation.`);return t.evolveAllocationRef(e)}async getRecoverableAttempts(e){return this.requireRecovery(`getRecoverableAttempts`).getRecoverableAttempts(e)}async listOpenProviderOperations(e){return this.requireRecovery(`listOpenProviderOperations`).listOpenProviderOperations(e)}async recordInfrastructureFailure(e){let t=await this.repository.recordInfrastructureFailure(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' suffered infrastructure failure: the provider allocation terminated without an acknowledged outcome`)),t}async abandonPendingAttempt(e,t){let n=await this.repository.abandonPendingAttempt(e,t);return(n.kind===`abandoned`||n.kind===`already-abandoned`)&&this.waiters.delete(e),n}requireRecovery(e){let{recovery:t}=this.repository;if(t===void 0)throw Error(`Recovery operation '${e}' requires a repository that exposes recovery operations. The injected repository does not support recovery.`);return t}installWaiter(e){this.waiters.set(e,ge())}settleWaiterInternal(e,t){let n=this.waiters.get(e);if(n){switch(t.kind){case`accepted`:case`duplicate`:n.resolve({outcome:t.outcome,controlObservation:t.controlObservation,acceptance:t.acceptance});break;case`conflict`:n.reject(Error(`Outcome conflict for attempt '${e}': a different outcome was already committed`));break;case`fenced`:n.reject(Error(`Attempt '${e}' has been fenced: it is no longer the active attempt for this execution`));break}this.waiters.delete(e)}}},ga=class extends Pt{workflowExecutor;triggerReconcilerInstance;attemptAuthority;workspaceRootResolvers=new Set;constructor(e,t){super(e);let n=t?.executionAttemptAuthority;if(!n&&t?.executionAttemptRepository){let e=t.executionAttemptBootstrapTimeoutMs;if(e===void 0)throw Error(`An ExecutionAttemptRepository requires executionAttemptBootstrapTimeoutMs`);n=new ha(t.executionAttemptRepository,{bootstrapTimeoutMs:e})}this.attemptAuthority=n,this.workflowExecutor=new na(e,t?.executorConfig,t?.workflowRunner,this.attemptAuthority);for(let e of t?.workflowMaterializationSpecResolvers??[])this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e);let r=t?.automationTriggerBindingRuntime;this.triggerReconcilerInstance=new ca(e,()=>r?.())}get executor(){return this.workflowExecutor}get executionAttemptAuthority(){return this.attemptAuthority}registerSuccessFinalizer(e){return this.workflowExecutor.registerSuccessFinalizer(e)}acceptAuthorityRunnerResult(e,t){return this.workflowExecutor.acceptAuthorityRunnerResult(e,t)}get triggerReconciler(){return this.triggerReconcilerInstance}registerWorkflowMaterializationSpecResolver(e){return this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e)}registerWorkspaceRootResolver(e){return this.workspaceRootResolvers.add(e),()=>{this.workspaceRootResolvers.delete(e)}}async resolveWorkspaceRoot(e){for(let t of this.workspaceRootResolvers){let n=await t(e);if(n!==void 0)return n}}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.triggerReconcilerInstance.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.triggerReconcilerInstance.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const _a=jt(`makaio.workflow-engine`);function va(e){return{name:_a.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[At(Gt.name),At(Kt.name,void 0,!0)],critical:!0,namespaces:[Ct,f],storage:{registerHandlers:Lt(ei)},create:t=>new ga(t.bus,{...e,automationTriggerBindingRuntime:()=>t.getService(Kt)})}}const ya=va();export{Fn as _,ha as a,Ki as c,Ri as d,Mi as f,Nn as g,Pn as h,ga as i,zi as l,ei as m,va as n,ca as o,ki as p,ya as r,na as s,_a as t,Bi as u};
|
package/dist/package.json
CHANGED