@makaio/framework 1.0.0-dev-1781260968078 → 1.0.0-dev-1781354548379

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/adapter-UpcpZDOv.mjs +1 -0
  3. package/dist/adapters/config/index.d.mts +1 -1
  4. package/dist/adapters/index.d.mts +11 -3
  5. package/dist/adapters/index.mjs +1 -1
  6. package/dist/bus/index.mjs +1 -1
  7. package/dist/clients/index.d.mts +4 -7
  8. package/dist/clients/index.mjs +1 -1
  9. package/dist/contracts/adapter/index.d.mts +2 -2
  10. package/dist/contracts/adapter/index.mjs +1 -1
  11. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  12. package/dist/contracts/artifact/index.d.mts +1 -1
  13. package/dist/contracts/client/index.d.mts +1 -1
  14. package/dist/contracts/extension/index.d.mts +2 -2
  15. package/dist/contracts/facet/index.d.mts +1 -1
  16. package/dist/contracts/index.d.mts +219 -54
  17. package/dist/contracts/index.mjs +1 -1
  18. package/dist/contracts/materialization/index.d.mts +3 -3
  19. package/dist/contracts/session/index.d.mts +3 -3
  20. package/dist/contracts/session/index.mjs +1 -1
  21. package/dist/{definition-SiimP25_.d.mts → definition-DqJOg6Lv.d.mts} +1 -1
  22. package/dist/drizzle/0015_m_mqbh8q5b.sql +1 -0
  23. package/dist/drizzle/0016_m_mqbmq8h7.sql +1 -0
  24. package/dist/drizzle/0017_m_mqbnf924.sql +1 -0
  25. package/dist/drizzle/meta/0015_snapshot.json +2966 -0
  26. package/dist/drizzle/meta/0016_snapshot.json +2973 -0
  27. package/dist/drizzle/meta/0017_snapshot.json +2980 -0
  28. package/dist/drizzle/meta/_journal.json +21 -0
  29. package/dist/{handler-DSfSAlxx.mjs → handler-DqpiV9eA.mjs} +1 -1
  30. package/dist/handlers-BAB4fQNH.mjs +41 -0
  31. package/dist/{index-B2xbnMZe.d.mts → index-BCKRUuI2.d.mts} +1 -1
  32. package/dist/{index-CARxIllg.d.mts → index-BHAOu6Hs.d.mts} +20 -20
  33. package/dist/{index-Cb64d5c5.d.mts → index-BHzgDuRE.d.mts} +20 -3
  34. package/dist/{index-BtztOqaF.d.mts → index-BheaEhyI.d.mts} +6 -6
  35. package/dist/{index-CZ_TcT6J.d.mts → index-Bibt5jAX.d.mts} +8 -8
  36. package/dist/{index-D5CI1V5d.d.mts → index-C3zfJg6s.d.mts} +16 -16
  37. package/dist/{index-DTdqGAfH2.d.mts → index-CH5U3zSA2.d.mts} +1 -1
  38. package/dist/{index-CgjslA5-.d.mts → index-CTn_Xi-p.d.mts} +4 -4
  39. package/dist/{index-DDQkhhRo.d.mts → index-DPIdX6kb.d.mts} +363 -123
  40. package/dist/{index-BQiHs8EF.d.mts → index-Da4ABgRq.d.mts} +12 -12
  41. package/dist/{index-BvSyOgTY.d.mts → index-DrGLAuZc.d.mts} +98 -29
  42. package/dist/{index-BKKNWqkP2.d.mts → index-zgm2j9V92.d.mts} +44 -2
  43. package/dist/kernel/extension/index.d.mts +1 -1
  44. package/dist/kernel/index.d.mts +2 -2
  45. package/dist/kernel/observability/index.d.mts +1 -1
  46. package/dist/mcp-http-server/index.d.mts +132 -19
  47. package/dist/mcp-http-server/index.mjs +1 -1
  48. package/dist/{namespace-D1Iw_d1P.d.mts → namespace--s0d86h-.d.mts} +144 -0
  49. package/dist/{namespace-7tsuJhQ9.d.mts → namespace-Boe6l5n9.d.mts} +78 -42
  50. package/dist/{namespace-Ba4bxtHQ.d.mts → namespace-BxxBhcV_.d.mts} +9 -9
  51. package/dist/{namespace-DwE2g8Wm.mjs → namespace-Dfq6MDN9.mjs} +1 -1
  52. package/dist/{namespace-DDCjoQUj.d.mts → namespace-aJJfBJU5.d.mts} +170 -0
  53. package/dist/{orchestrator-shared-Dt4WDse7.mjs → orchestrator-shared-BKFXaKPL.mjs} +1 -1
  54. package/dist/{package-BSnp1zOR.d.mts → package--RZnpN2J.d.mts} +2 -3
  55. package/dist/package-BzJvtM5O.mjs +1 -0
  56. package/dist/package-DzN_jdqd.mjs +1 -0
  57. package/dist/package.json +1 -1
  58. package/dist/primitive-runtime-CNC_bSac.mjs +1 -0
  59. package/dist/runtime-node/bus/runtime/namespace.d.mts +8 -8
  60. package/dist/runtime-node/bus/runtime/schemas.d.mts +11 -4
  61. package/dist/runtime-node/bus/runtime/schemas.mjs +1 -1
  62. package/dist/runtime-node/index.d.mts +19 -1
  63. package/dist/runtime-node/index.mjs +1 -1
  64. package/dist/{schema-BerZmr2q.mjs → schema-C3TgjrsV.mjs} +1 -1
  65. package/dist/{schema-BrnYlDwZ.mjs → schema-CzhOc7TV.mjs} +1 -1
  66. package/dist/{schema-BNrM9LWb.d.mts → schema-DGMLvVoQ.d.mts} +23 -3
  67. package/dist/schemas-CuKayWhA.mjs +1 -0
  68. package/dist/{schemas-DAFYpgHk2.d.mts → schemas-kVcJMjjn2.d.mts} +8 -8
  69. package/dist/{schemas-CkOSG2eJ.d.mts → schemas-t1VR6_b_.d.mts} +3 -3
  70. package/dist/services/filesystem/namespace.d.mts +6 -6
  71. package/dist/services/filesystem/schemas.d.mts +3 -3
  72. package/dist/services/git/namespace.d.mts +2 -2
  73. package/dist/services/git/schemas.d.mts +2 -2
  74. package/dist/services/harness/index.d.mts +3 -4
  75. package/dist/services/harness/index.mjs +1 -1
  76. package/dist/services/index.d.mts +112 -15
  77. package/dist/services/index.mjs +1 -1
  78. package/dist/services/log-import/browser.d.mts +2 -2
  79. package/dist/services/log-import/index.d.mts +4 -5
  80. package/dist/services/log-import/index.mjs +1 -1
  81. package/dist/services/log-import/log-import.d.mts +1 -1
  82. package/dist/services/log-import/namespace.d.mts +2 -2
  83. package/dist/services/log-import/schemas.d.mts +1 -1
  84. package/dist/services/provider-context/index.mjs +1 -1
  85. package/dist/services/session/handlers/index.mjs +1 -1
  86. package/dist/services/session/index.d.mts +6 -6
  87. package/dist/services/session/index.mjs +1 -1
  88. package/dist/services/session/messages/namespace.mjs +1 -1
  89. package/dist/services/session/orchestrator-testing/index.mjs +1 -1
  90. package/dist/services/session/session-events/namespace.d.mts +1 -1
  91. package/dist/services/session/session-events/namespace.mjs +1 -1
  92. package/dist/services/session/storage/namespace.d.mts +1 -1
  93. package/dist/services/session/storage/schema.d.mts +1 -1
  94. package/dist/services/session/storage/schema.mjs +1 -1
  95. package/dist/services/session/testing/index.mjs +5 -3
  96. package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
  97. package/dist/services/session/turns/namespace.d.mts +1 -1
  98. package/dist/services/session/turns/namespace.mjs +1 -1
  99. package/dist/services/settings/index.mjs +1 -1
  100. package/dist/services/settings/namespace.d.mts +8 -8
  101. package/dist/services/settings/storage/clients-namespace.mjs +1 -1
  102. package/dist/services/settings/storage/index.mjs +1 -1
  103. package/dist/services/settings/storage/providers-namespace.mjs +1 -1
  104. package/dist/services/subagent/index.d.mts +1 -1
  105. package/dist/services/subagent/index.mjs +1 -1
  106. package/dist/services/subagent-template/index.d.mts +1 -1
  107. package/dist/services/subagent-template/schemas.d.mts +1 -1
  108. package/dist/services/tool-approval/index.mjs +1 -1
  109. package/dist/services/tools/index.mjs +1 -1
  110. package/dist/services/turn/index.d.mts +1 -1
  111. package/dist/services/turn/namespace.d.mts +1 -1
  112. package/dist/services/turn/schemas.d.mts +72 -0
  113. package/dist/services/turn/schemas.mjs +1 -1
  114. package/dist/{session-C1Cami7U.mjs → session-BwX5_k47.mjs} +1 -1
  115. package/dist/session-P4nX60Xx.mjs +39 -0
  116. package/dist/{session-lineage-CXzV_hAP.d.mts → session-lineage-CKg6mErA.d.mts} +1 -1
  117. package/dist/storage/drizzle/index.d.mts +1 -1
  118. package/dist/storage/drizzle/index.mjs +1 -1
  119. package/dist/{tool-approval-service-Cb2F1yT6.mjs → tool-approval-service-DNHV5x0M.mjs} +1 -1
  120. package/dist/{tools-D5DVHC-R.mjs → tools-CQImrHAp.mjs} +1 -1
  121. package/dist/{types-DLVitCZP.d.mts → types-BpuLMR2m.d.mts} +626 -443
  122. package/dist/{types-D5IMwOkJ.d.mts → types-D0fPFh-D.d.mts} +1 -1
  123. package/dist/{types-BMpIa4fx.d.mts → types-D6jnDjP2.d.mts} +18 -5
  124. package/dist/ui-components/index.d.mts +36 -37
  125. package/dist/ui-views/index.d.mts +2 -2
  126. package/dist/workflow-engine/index.d.mts +58 -25
  127. package/dist/workflow-engine/index.mjs +1 -1
  128. package/dist/workflow-engine/package.d.mts +1 -1
  129. package/dist/workflow-engine/package.mjs +1 -1
  130. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  131. package/package.json +10 -1
  132. package/dist/adapter-Dt2FDMs4.mjs +0 -1
  133. package/dist/handlers-C8EtpSqK.mjs +0 -41
  134. package/dist/package-Be2Ez4vv.mjs +0 -1
  135. package/dist/package-OE9dMQsq.mjs +0 -1
  136. package/dist/primitive-runtime-Xrc9xh6p.mjs +0 -1
  137. package/dist/schemas-CSUwpaNm.mjs +0 -1
  138. package/dist/session-KnewDVxt.mjs +0 -39
  139. /package/dist/{provider-context-lfG0BpqX.mjs → provider-context-wp4VSJFI.mjs} +0 -0
  140. /package/dist/{shared-schemas-CKe2uN4-.mjs → shared-schemas-DYL7a-No.mjs} +0 -0
@@ -0,0 +1 @@
1
+ import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S as u,T as d,_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,m as ee,n as te,o as ne,p as w,t as re,u as ie,v as ae,w as oe,x as se,y as ce}from"./primitive-runtime-CNC_bSac.mjs";import{isAbsolute as le,resolve as ue}from"node:path";import{matchesFilter as de,matchesSubscription as fe}from"@makaio/framework/bus";import{ArtifactSubjects as pe,EXECUTION_LIST_DEFAULT_LIMIT as me,EXECUTION_LIST_MAX_LIMIT as T,EXECUTION_LIST_MIN_LIMIT as E,ExecutionHintsSchema as he,JsonValueSchema as ge,SessionSubjects as D,WORKFLOW_CANCELLED_REASON as O,WorkerNodeSubjects as _e,WorkflowNamespace as ve,WorkflowSubjects as k,WorkflowWorkerSourceSchema as ye,createWorkflowCancelSubject as be,dep as xe,extensionToken as Se}from"@makaio/framework/contracts";import{BaseService as Ce}from"@makaio/framework/service-base";import{defineDialectSchema as we,executeTransaction as A,registerDrizzleHandlers as Te,resolveSchema as j}from"@makaio/framework/storage/drizzle";import{and as M,asc as N,count as Ee,desc as P,eq as F,getTableColumns as De,gte as Oe,isNotNull as ke,lt as Ae,lte as je,or as Me,sql as I,sum as L}from"drizzle-orm";import{compile as Ne}from"@makaio/framework/expression";import*as Pe from"node:os";import{SessionToken as Fe}from"@makaio/framework/services";const Ie=y.postgres,Le=se.postgres,Re=f.postgres,ze=t.postgres,Be=n.postgres,Ve=ce.postgres,He=d.postgres,Ue=i.postgres,We=x.postgres,Ge=S.postgres,Ke=s.postgres,R=we({workflowDefinitions:ee,workflowExecutions:m,workflowExecutionFrames:v,workflowGateInstances:u,workflowStepSpans:r,workflowExecutionLinks:ae,workflowRunContexts:oe,worklogSummaries:l,worklogFrameEntries:e,worklogArtifactWrites:c,worklogGateEvents:o},{workflowDefinitions:Ie,workflowExecutions:Le,workflowExecutionFrames:Re,workflowGateInstances:ze,workflowStepSpans:Be,workflowExecutionLinks:Ve,workflowRunContexts:He,worklogSummaries:Ue,worklogFrameEntries:We,worklogArtifactWrites:Ge,worklogGateEvents:Ke});function z(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 qe(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 Je(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=z(t);return[F(e.scopeType,n),F(e.scopeKind,r),F(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,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:qe(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executionHints:e.executionHints??void 0}}function Ye(e,t){let n=z(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,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executionHints:e.executionHints??null,createdAt:t,updatedAt:t,...n}}function Xe(e,t){let{workflowDefinitions:n}=j(t,R),r=De(n),i=e.on(w.get,async e=>{let r=await t.select().from(n).where(F(n.id,e.payload.id)).limit(1);e.setResult({workflow:r[0]?B(r[0]):null})}),o=e.on(w.set,async i=>{let o=i.payload.workflow,s=Date.now(),c=Ye(o,s),l=await t.insert(n).values(c).onConflictDoNothing({target:n.id}).returning();if(l.length>0){await e.emit(a.definition.created,B(l[0])),i.setResult({id:o.id});return}let[u]=await t.update(n).set({name:c.name,root:c.root,updatedAt:s,createdAt:I`COALESCE(${r.createdAt}, ${s})`,description:c.description===null?I`${r.description}`:c.description,inputSchema:c.inputSchema===null?I`${r.inputSchema}`:c.inputSchema,configSchema:c.configSchema===null?I`${r.configSchema}`:c.configSchema,outputSchema:c.outputSchema===null?I`${r.outputSchema}`:c.outputSchema,artifact:c.artifact===null?I`${r.artifact}`:c.artifact,triggers:c.triggers===null?I`${r.triggers}`:c.triggers,canvasLayout:c.canvasLayout===null?I`${r.canvasLayout}`:c.canvasLayout,source:c.source===null?I`${r.source}`:c.source,executionHints:c.executionHints===null?I`${r.executionHints}`:c.executionHints,...z(o.scope)}).where(F(n.id,o.id)).returning();u&&await e.emit(a.definition.updated,B(u)),i.setResult({id:o.id})}),s=e.on(w.delete,async r=>{let i=(await t.delete(n).where(F(n.id,r.payload.id)).returning()).length>0;i&&await e.emit(a.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),c=e.on(w.list,async e=>{let r=e.payload,i=r.scope?Je(n,r.scope):[],a=i.length>0?await t.select().from(n).where(M(...i)):await t.select().from(n);e.setResult({workflows:a.map(B)})});return()=>{i(),o(),s(),c()}}function Ze(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 Qe(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 $e(e,t){let{workflowExecutionFrames:n}=j(t,R),r=e.on(w.setFrame,async e=>{let{executionId:r,frame:i}=e.payload,a=Qe(r,i);await t.insert(n).values(a).onConflictDoUpdate({target:n.frameId,set:a}),e.setResult({frameId:i.frameId})}),i=e.on(w.getFrame,async e=>{let r=await t.select().from(n).where(F(n.frameId,e.payload.frameId)).limit(1);e.setResult({frame:r[0]?Ze(r[0]):null})}),a=e.on(w.listFrames,async e=>{let r=await t.select().from(n).where(F(n.executionId,e.payload.executionId)).orderBy(N(n.startedAt),N(n.frameId));e.setResult({frames:r.map(Ze)})});return()=>{r(),i(),a()}}function et(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:et(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 tt(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??me;if(!Number.isInteger(i)||i<E||i>T)throw Error(`Gate instance list limit must be an integer between ${E} and ${T}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[F(r.executionId,e)],...t===void 0?[]:[F(r.status,t)]]}}function nt(e,t){let{workflowExecutions:n,workflowGateInstances:r}=j(t,R),i=e.on(w.setGateInstance,async e=>{let n=e.payload.gate,i=H(n);await t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),e.setResult({id:i.id})}),a=e.on(w.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,i=H(n),a=await t.update(r).set(i).where(M(F(r.id,i.id),F(r.status,`waiting`))).returning({id:r.id});e.setResult({accepted:a.length===1})}),o=e.on(w.getGateInstance,async e=>{let{executionId:n,nodeId:i,frameId:a}=e.payload,o=[F(r.executionId,n),F(r.nodeId,i)];a!==void 0&&o.push(F(r.frameId,a));let s=await t.select().from(r).where(M(...o)).limit(1);e.setResult({gate:s[0]?V(s[0]):null})}),s=e.on(w.listGateInstances,async e=>{let{executionId:n,status:i,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=tt(n,i,a,r),c=await t.select().from(r).where(M(...s)).orderBy(P(r.createdAt),P(r.id)).limit(o);e.setResult({gates:c.map(V)})}),c=e.on(w.listPausedGateTimeouts,async e=>{let i=await t.select({gate:r}).from(r).innerJoin(n,F(r.executionId,n.id)).where(M(F(r.status,`waiting`),F(n.status,`paused`),ke(r.timeoutMs)));e.setResult({gates:i.map(e=>V(e.gate))})});return()=>{i(),a(),o(),s(),c()}}function rt(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 it(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function at(e,t){let{workflowStepSpans:n,workflowExecutionLinks:r}=j(t,R),i=e.on(w.setSpan,async e=>{let{span:r}=e.payload;await t.insert(n).values(r).onConflictDoUpdate({target:[n.executionId,n.frameId],set:r}),e.setResult({id:`${r.executionId}:${r.frameId}`})}),a=e.on(w.listSpans,async e=>{let r=await t.select().from(n).where(F(n.executionId,e.payload.executionId)).orderBy(N(n.startedAt),N(n.stepId),N(n.frameId));e.setResult({spans:r.map(rt)})}),o=e.on(w.setExecutionLink,async e=>{let{link:n}=e.payload;await t.insert(r).values(n).onConflictDoUpdate({target:[r.sourceExecutionId,r.targetExecutionId],set:n}),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),s=e.on(w.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?[]:[F(r.sourceExecutionId,n)],...i===void 0?[]:[F(r.targetExecutionId,i)]],o=t.select().from(r).where(M(...a));e.setResult({links:(await o).map(it)})});return()=>{i(),a(),o(),s()}}function ot(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 st(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 ct(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:st(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:qe(e),...e.executionHints===null?{}:{executionHints:e.executionHints},...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function lt(e){let t=ot(e.source),n=z(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,artifactRef:e.artifactRef??null,executionHints:e.executionHints??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy}}async function ut(e,t,n){let r=lt(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function dt(e,t){let{workflowRunContexts:n}=j(t,R),r=e.on(w.setRunContext,async e=>{let r=e.payload.runContext;await ut(t,r,n),e.setResult({executionId:r.executionId})}),i=e.on(w.getRunContext,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(F(n.executionId,r)),a=i[0]?ct(i[0]):null;e.setResult({runContext:a})});return()=>{r(),i()}}function ft(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 U(e,t){let{worklogSummaries:n}=j(e,R);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:t})}async function W(e,t){let{worklogSummaries:n}=j(e,R),r=await e.select().from(n).where(F(n.executionId,t)).limit(1);return r[0]?ft(r[0]):null}async function pt(e,t={}){let{worklogSummaries:n}=j(e,R),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[F(n.workflowId,r)],...i===void 0?[]:[F(n.status,i)]],c=s.length>0?M(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(P(n.startedAt)).limit(a).offset(o),e.select({count:Ee()}).from(n).where(c)]);return{items:l.map(ft),total:u[0]?.count??0}}async function mt(e,t){let{worklogFrameEntries:n}=j(e,R);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t})}async function ht(e,t){let{worklogFrameEntries:n}=j(e,R);return(await e.select().from(n).where(F(n.frameId,t)).limit(1))[0]??null}async function gt(e,t){let{worklogArtifactWrites:n}=j(e,R);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function _t(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function vt(e,t){let{worklogGateEvents:n}=j(e,R);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function yt(e,t){let{worklogGateEvents:n}=j(e,R);return(await e.select().from(n).where(F(n.id,t)).limit(1))[0]??null}function bt(e,t,n){return`${e}:${t}:${n}`}async function xt(e,t){let{worklogFrameEntries:n}=j(e,R),[r]=await e.select({totalInputTokens:L(n.inputTokens),totalOutputTokens:L(n.outputTokens),totalEstimatedCost:L(n.estimatedCost)}).from(n).where(F(n.executionId,t));return{totalInputTokens:r?.totalInputTokens===null?0:Number(r?.totalInputTokens),totalOutputTokens:r?.totalOutputTokens===null?0:Number(r?.totalOutputTokens),totalEstimatedCost:r?.totalEstimatedCost===null?0:Number(r?.totalEstimatedCost)}}async function St(e,t={}){let{worklogSummaries:n}=j(e,R),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[F(n.workflowId,r)],...i===void 0?[]:[Oe(n.startedAt,i)],...a===void 0?[]:[je(n.startedAt,a)]],s=o.length>0?M(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:Ee()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:L(n.durationMs),totalInputTokens:L(n.totalInputTokens),totalOutputTokens:L(n.totalOutputTokens),totalEstimatedCost:L(n.totalEstimatedCost)}).from(n).where(s)]),u={pending:0,running:0,paused: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 Ct(e,t,n,r,i){let a=await ht(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(pe.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 G(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function K(e,t){try{await e.emit(a.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}async function wt(e,t,n){await U(t,{executionId:n.executionId,workflowId:n.workflowId,workflowName:null,status:`running`,startedAt:n.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),await K(e,n.executionId)}async function Tt(e,t,n){let r=n.completedAt??Date.now(),i=await W(t,n.executionId);await U(t,{executionId:n.executionId,workflowId:i?.workflowId??n.executionId,workflowName:i?.workflowName??null,status:`completed`,startedAt:i?.startedAt??r-n.totalDuration,completedAt:r,durationMs:n.totalDuration,totalInputTokens:i?.totalInputTokens??null,totalOutputTokens:i?.totalOutputTokens??null,totalEstimatedCost:i?.totalEstimatedCost??null,error:null,failedNodeId:null}),await K(e,n.executionId)}async function Et(e,t,n,r,i,a,o){let s=await W(t,n),c=s?.startedAt??o;await U(t,{executionId:n,workflowId:s?.workflowId??n,workflowName:s?.workflowName??null,status:r,startedAt:c,completedAt:o,durationMs:o-c,totalInputTokens:s?.totalInputTokens??null,totalOutputTokens:s?.totalOutputTokens??null,totalEstimatedCost:s?.totalEstimatedCost??null,error:i,failedNodeId:a}),await K(e,n)}async function Dt(e,t,n){let r=await xt(t,n);if(r.totalInputTokens>0||r.totalOutputTokens>0||r.totalEstimatedCost>0){let e=await W(t,n);e&&await U(t,{executionId:n,workflowId:e.workflowId,workflowName:e.workflowName??null,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??null,durationMs:e.durationMs??null,totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost,error:e.error??null,failedNodeId:e.failedNodeId??null})}}function Ot(e,t){return[e.on(a.execution.started,async n=>{let{executionId:r}=n.payload;await G(`execution.started[${r}]`,()=>wt(e,t,n.payload))}),e.on(a.execution.completed,async n=>{let{executionId:r}=n.payload;await G(`execution.completed[${r}]`,()=>Tt(e,t,n.payload))}),e.on(a.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await G(`execution.failed[${r}]`,()=>Et(e,t,r,`failed`,i,a??null,o))}),e.on(a.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await G(`execution.cancelled[${r}]`,()=>Et(e,t,r,`cancelled`,null,null,i))})]}function kt(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 At(e,t,n,r,i,a,o){let s=o??Date.now();await mt(t,{frameId:r,executionId:n,...kt(await ht(t,r),i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await Dt(e,t,n),await K(e,n)}async function jt(e,t,n,r,i,a,o,s){let c=s??Date.now();await mt(t,{frameId:r,executionId:n,...kt(await ht(t,r),i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await K(e,n)}function Mt(e,t){return[e.on(a.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await G(`frame.started[${i}]`,async()=>{await mt(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 K(e,r)})}),e.on(a.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await G(`frame.completed[${i}]`,()=>At(e,t,r,i,a,o,s))}),e.on(a.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await G(`frame.failed[${i}]`,()=>jt(e,t,r,i,a,o,s,c))})]}const Nt={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function Pt(e,t){return[e.on(a.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await G(`gate.suspended[${i}]`,async()=>{await vt(t,{id:bt(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await K(e,r)})}),e.on(a.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await G(`gate.resumed[${i}]`,async()=>{let n=bt(r,a,i),s=await yt(t,n),c=Date.now();await vt(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await K(e,r)})}),e.on(a.gate.resolved,async n=>Ft(n.payload,e,t)),e.on(a.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await G(`artifact.updated[${r}:${i}]`,async()=>{let n=await Ct(e,t,i,a,o);if(n===null)return;let s=Date.now();await gt(t,{id:_t(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await K(e,r)})})]}async function Ft(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await G(`gate.resolved[${i}]`,async()=>{let s=bt(r,a,i),c=await yt(n,s),l=Date.now();await vt(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Nt[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await K(t,r)})}function It(e,t){let n=[...Ot(e,t),...Mt(e,t),...Pt(e,t),e.on(a.worklog.get,async e=>{let{executionId:n}=e.payload,r=await W(t,n);e.setResult({summary:r})}),e.on(a.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await pt(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(a.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await St(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function Lt(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:qe(e)}}function Rt(e){let t=z(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 zt(e,t,n,r,i,a){let o=[...e?[F(a.workflowId,e)]:[],...n?[F(a.status,n)]:[],...i===void 0?[]:[F(a.artifactKind,i.kind),F(a.artifactId,i.id)]];if(t&&o.push(...Je(a,t)),r){let e=Me(Ae(a.startedAt,r.startedAt),M(F(a.startedAt,r.startedAt),Ae(a.id,r.id)));e&&o.push(e)}return o}async function Bt(e,t,n){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);let{workflowExecutions:r,workflowRunContexts:i}=j(e,R),a=Rt(t);await A(e,async e=>{await e.insert(r).values(a).onConflictDoUpdate({target:r.id,set:a}),await ut(e,n,i)})}async function Vt(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}=j(e,R),a=Rt(t),o=H(n);await A(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 Ht(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=j(e,R);return A(e,async e=>{if((await e.select().from(i).where(F(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(M(F(a.executionId,t),F(a.status,`waiting`)))).map(e=>({...V(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(F(i.id,t));for(let t of o){let n=H(t);await e.update(a).set(n).where(F(a.id,n.id))}return{cancelled:!0,gates:o}})}async function Ut(e,t,n,r,i,a){let{workflowExecutions:o}=j(e,R);return A(e,async e=>{if((await e.select({id:o.id}).from(o).where(F(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(F(o.id,t)),!0})}function Wt(e,t){let{workflowExecutions:n}=j(t,R),r=e.on(w.getExecution,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(F(n.id,r));e.setResult({execution:i[0]?Lt(i[0]):null})}),i=e.on(w.setExecution,async e=>{let r=e.payload.execution,i=Rt(r);await t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:i}),e.setResult({id:r.id})}),a=e.on(w.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await Bt(t,n,r),e.setResult({id:n.id,executionId:n.id})}),o=e.on(w.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await Vt(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),s=e.on(w.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await Ut(t,n,r,i,a,o);e.setResult({success:s})}),c=e.on(w.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await Ht(t,n,r,i))}),l=e.on(w.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=zt(r,i,a,s,c,n),u=o??me;if(!Number.isInteger(u)||u<E||u>T)throw Error(`Execution list limit must be an integer between ${E} and ${T}.`);let d=await t.select().from(n).where(M(...l)).orderBy(P(n.startedAt),P(n.id)).limit(u);e.setResult({executions:d.map(Lt)})});return()=>{r(),i(),a(),o(),s(),c(),l()}}function Gt(e,t){let n=Xe(e,t),r=Wt(e,t),i=$e(e,t),a=nt(e,t),o=at(e,t),s=dt(e,t),c=It(e,t);return()=>{n(),r(),i(),a(),o(),s(),c()}}function Kt(e,t){if(e.origin.local)return!0;let n=e.transport?.peer;return n?.authenticated!==!0||n.id!==t?!1:n.kind===`workflow-execution`?!0:n.kind===`e2e`&&n.encrypted===!0}function qt(e){return[e.on(a.getDefinition,async t=>{let n=await e.request(w.get,{id:t.payload.id});t.setResult(n)}),e.on(a.setDefinition,async t=>{let n=await e.request(w.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(a.deleteDefinition,async t=>{let n=await e.request(w.delete,{id:t.payload.id});t.setResult(n)}),e.on(a.listDefinitions,async t=>{let n=await e.request(w.list,t.payload);t.setResult(n)}),e.on(a.getExecution,async t=>{let n=await e.request(w.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(a.listExecutions,async t=>{let n=await e.request(w.listExecutions,t.payload);t.setResult(n)}),e.on(a.listSpans,async t=>{let n=await e.request(w.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(a.listFrames,async t=>{let n=await e.request(w.listFrames,{executionId:t.payload.executionId});t.setResult(n)}),e.on(a.listGateInstances,async t=>{let n=await e.request(w.listGateInstances,t.payload);t.setResult(n)}),e.on(a.setExecutionLink,async t=>{let n=await e.request(w.setExecutionLink,{link:t.payload.link});t.setResult(n)}),e.on(a.listExecutionLinks,async t=>{let n=await e.request(w.listExecutionLinks,t.payload);t.setResult(n)}),e.on(a.getRunContext,async t=>{let{executionId:n}=t.payload;if(!Kt(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(w.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)})]}function Jt(e,t){return[e.on(a.listTriggerTypes,e=>{let n=t()?.getAll()??[];e.setResult({triggerTypes:n})})]}const Yt=[`darwin`,`linux`,`win32`];function Xt(e){return Yt.find(t=>t===e)??`linux`}function Zt(e,t){return t}function Qt(e,t){return{...t}}function $t(e){return e.reason instanceof Error?e.reason.message:typeof e.reason==`string`&&e.reason.length>0?e.reason:O}async function en(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return;let i=e.buildFinalizerDeps(),{execution:a}=await i.bus.request(w.getExecution,{executionId:t});a?.status===`running`&&(r.execution=a,await h(i,t,$t(n))||console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${t}: execution not active`))}async function tn(e,t){if(t.pausedAtGateId===void 0||t.pausedAtFrameId===void 0)throw Error(`Paused runner result for '${t.executionId}' is missing gate identity`);let{bus:n}=e.buildFinalizerDeps(),{execution:r}=await n.request(w.getExecution,{executionId:t.executionId});if(r?.status!==`running`){let n=e.activeExecutions.get(t.executionId);n!==void 0&&r?.status===`paused`&&(n.execution.status=`paused`,e.activeExecutions.delete(t.executionId));return}let i={...r,status:`paused`};await n.request(w.setExecution,{execution:i});let o=e.activeExecutions.get(t.executionId);o!==void 0&&(o.execution=i),await n.emit(a.execution.paused,{executionId:t.executionId,workflowId:t.workflowId,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}),e.activeExecutions.delete(t.executionId)}async function nn(e,t){let n=e.activeExecutions.get(t.executionId);if(!n||n.execution.status!==`running`)return;let r=e.buildFinalizerDeps(),{execution:i}=await r.bus.request(w.getExecution,{executionId:t.executionId});if(i?.status===`running`){if(n.execution=i,t.status===`completed`){await ie(r,n.execution,t.executionId,n.execution.startedAt);return}if(t.status===`cancelled`){await h(r,t.executionId,t.reason??O);return}if(t.status===`failed`){await C(r,n.execution,t.executionId,t.error);return}}}function rn(e,t){let{executionId:n,workflowId:r,filePath:i,coordinatorSessionId:a,sanitizedTriggerPayload:o,scope:s,workspaceRoot:c}=t,{workflowRunner:l,workflowAbortControllers:u,executionTasks:d,activeExecutions:f,config:p}=e,m=new AbortController;u.set(n,m);let h={source:{kind:`path`,path:i},executionId:n,workflowId:r,triggerPayload:o,inputs:{},config:{},scope:s,busUrl:p.busUrl,busAuth:p.busAuth,context:e.resolveWorkflowContext(c),env:p.platformDefaults.env??{},coordinatorSessionId:a,cancelSubject:`workflow.${n}.cancel`,suspensionStrategy:`wait-in-process`};return Promise.resolve().then(()=>l.run(h,m.signal)).then(async t=>{if(t.status===`paused`){await tn(e,t);return}await nn(e,t)}).catch(async t=>{if(m.signal.aborted){await en(e,n,m.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner cancellation for ${n}:`,e)});return}let r=f.get(n);if(r){let i=t instanceof Error?t.message:String(t);await C(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner boot failure for ${n}:`,e)})}}).finally(()=>{u.delete(n),d.delete(n),f.delete(n)})}function an(e,t){let{config:n}=e;return{source:t.source,...t.source.kind===`definition`?{definition:t.workflow}:{},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},...t.executionHints===void 0?{}:{executionHints:t.executionHints},scope:t.scope,busUrl:n.busUrl,busAuth:n.busAuth,context:e.resolveWorkflowContext(t.workspaceRoot),env:n.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:t.suspensionStrategy??`wait-in-process`}}function on(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=an(e,t),l=t.dispatchMetadata===void 0?void 0:{dispatchMetadata:t.dispatchMetadata};return Promise.resolve().then(()=>r.run(c,s.signal,void 0,l)).then(async t=>{if(t.status===`paused`){await tn(e,t);return}await nn(e,t)}).catch(async t=>{if(s.signal.aborted){await en(e,n,s.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${n}:`,e)});return}let r=o.get(n);if(r){let i=t instanceof Error?t.message:String(t);await C(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner boot failure for ${n}:`,e)})}}).finally(()=>{i.delete(n),a.delete(n),o.delete(n)})}function sn(e,t,n={}){let r=cn(e,n);return{executionId:e.executionId,workflowId:e.workflowId,workflow:t,source:e.source,coordinatorSessionId:e.coordinatorSessionId,sanitizedTriggerPayload:e.triggerPayload,boundInputs:e.inputs,boundConfig:e.config??{},...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},scope:e.scope,workspaceRoot:e.context.repoPath,suspensionStrategy:e.suspensionStrategy,...r===void 0?{}:{dispatchMetadata:r}}}function cn(e,t){return t.resume===!0?{...e.dispatchMetadata,resume:!0}:e.dispatchMetadata}const ln=/(?:^|[_-])(authorization|token|cookie|password|set[_-]?cookie|api[_-]?key|secret|credential|private[_-]?key|api[_-]?secret)(?:$|[_-])/i;function un(e){if(!e)return;let t={remainingBytes:65536},n={},r=Object.entries(e).slice(0,100);for(let[e,i]of r){if(t.remainingBytes<=0)break;let r=dn(e,i,0,t);r!==void 0&&(n[e]=r)}return Object.keys(n).length>0?n:void 0}function dn(e,t,n,r){if(!(r.remainingBytes<=0||n>6)&&(r.remainingBytes-=e.length,!(r.remainingBytes<=0))){if(ln.test(e))return r.remainingBytes-=10,`[REDACTED]`;if(t===null)return r.remainingBytes-=4,null;if(typeof t==`string`){let e=t.slice(0,2e3);return r.remainingBytes-=e.length,e}if(typeof t==`number`||typeof t==`boolean`)return r.remainingBytes-=String(t).length,t;if(Array.isArray(t)){let i=[];for(let a of t.slice(0,100)){if(r.remainingBytes<=0)break;let t=dn(e,a,n+1,r);t!==void 0&&i.push(t)}return i}if(typeof t==`object`){let e={},i=Object.entries(t).slice(0,100);for(let[t,a]of i){if(r.remainingBytes<=0)break;let i=dn(t,a,n+1,r);i!==void 0&&(e[t]=i)}return e}}}function fn(e,t,n){let r=t?.requirements?.capabilities??[];if(r.length!==0)return{run:(t,i)=>e.request(_e.dispatch,{config:t,requirements:{customCapabilities:r},...n===void 0?{}:{metadata:n}},{signal:i})}}function pn(e,t){let n=fn(e.bus,t.executionHints,t.dispatchMetadata);return n===void 0?e.workflowRunner===void 0?e.runExecution(t.executionId).finally(()=>{e.executionTasks.delete(t.executionId)}):on(e.buildRunnerTaskDeps(e.workflowRunner),t):on(e.buildRunnerTaskDeps(n),t)}async function mn(e,t){try{await e.emit(a.execution.started,t)}catch(e){console.error(`[WorkflowExecutor] execution.started listener failed:`,e)}}async function hn(e,t){await e.request(D.close,{sessionId:t}).catch(e=>{console.error(`[WorkflowExecutor] Failed to close coordinator session "${t}" after launch failure:`,e)})}function gn(e,t,n,r,i,a,o,s,c){let l={id:t,workflowId:n.id,coordinatorSessionId:r,status:`running`,inputs:i,config:a,startedAt:Date.now(),triggerPayload:o,...c.artifactRef===void 0?{}:{artifactRef:c.artifactRef},scope:s};return e.set(t,{execution:l,workflow:n,runContext:c,runtimeHandlers:new Map}),l}async function _n(e,t,n){await e.request(w.setExecutionStart,{execution:t,runContext:n})}function vn(e,t){let n=e?.source;if(n===void 0)return;let r=ye.parse(n);return r.kind===`path`&&!le(r.path)?{...r,path:ue(t,r.path)}:r}function yn(e,t,n){return vn(t,n)??{kind:`definition`,workflowId:e}}async function bn(e,t,n,r){return e.set(t,n),await r,t}async function xn(e,t){let{workflow:n}=await e.request(w.get,{id:t});if(!n)throw Error(`Workflow not found: ${t}`);return n}function Sn(e,t){if(e===void 0&&t===void 0)return;let n=[...new Set([...e?.capabilities??[],...t?.capabilities??[]])];return{...e,...t,...n.length>0&&{capabilities:n}}}function Cn(e,t){if(e===void 0&&t===void 0)return;let n=Sn(e?.requirements,t?.requirements),r=e?.providers!==void 0||t?.providers!==void 0?{...e?.providers,...t?.providers}:void 0;return{...e,...t,...n!==void 0&&{requirements:n},...r!==void 0&&{providers:r}}}function wn(e){return{...e,input:e.input===void 0?{}:e.input,config:e.config??{}}}async function Tn(e,t,n,r){let{sessionId:i}=await e.request(D.create,{parentSessionId:t,branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}async function En(e,t,n={}){let{bus:r,activeExecutions:i,executionTasks:a}=e,{input:o,config:s,parentSessionId:c,triggerPayload:l,artifactRef:u,executionHints:d,scopeOverride:f}=wn(n),p=await xn(r,t),m=ne(`wfx`),h=un(l),g=Zt(p,o),_=Qt(p,s),v=f??p.scope,y=Cn(p.executionHints,d),b=await e.resolveExecutionWorkspaceRoot(c),x=yn(t,y,b),S=await Tn(r,c,p.name,b),C=!1;try{let n=e.buildRunContext({executionId:m,workflowId:t,coordinatorSessionId:S,source:x,...x.kind===`definition`?{definitionSnapshot:p}:{},inputs:g,config:_,scope:v,triggerPayload:h??{},...u===void 0?{}:{artifactRef:u},...y===void 0?{}:{executionHints:y},workspaceRoot:b}),o=gn(i,m,p,S,g,_,h,v,n);await _n(r,o,n);let s=o.startedAt,c=mn(r,{executionId:m,workflowId:t,coordinatorSessionId:S,startedAt:s,...u===void 0?{}:{artifactRef:u}}),l=pn(e,{executionId:m,workflowId:t,workflow:p,source:x,coordinatorSessionId:S,sanitizedTriggerPayload:h??{},boundInputs:g,boundConfig:_,scope:v,...u===void 0?{}:{artifactRef:u},...y===void 0?{}:{executionHints:y},workspaceRoot:b,suspensionStrategy:n.suspensionStrategy});return C=!0,bn(a,m,l,c)}catch(e){throw C||(i.delete(m),a.delete(m),await hn(r,S)),e}}function Dn(e,t,n,r,i){e.set(t.id,{execution:t,workflow:{id:t.workflowId,name:n,scope:r,root:{id:`${t.workflowId}-root`,type:`sequence`,nodes:[]}},runContext:i,runtimeHandlers:new Map})}async function On(e,t,n={}){let{bus:r,config:i,activeExecutions:a,executionTasks:o}=e,{triggerPayload:s,scopeOverride:c}=n,l=ne(`wfx`),u=un(s),d=c??{type:`global`},f=i.platformDefaults.cwd,{sessionId:p}=await r.request(D.create,{branchKind:`coordinator`,title:`Workflow: ${t}`,targetWorkingDirectory:f}),m=l,h={id:l,workflowId:m,coordinatorSessionId:p,status:`running`,inputs:{},config:{},startedAt:Date.now(),triggerPayload:u,scope:d},g=!1;try{let{workflowRunner:n}=e;if(n===void 0)throw Error(`[WorkflowExecutor] startFileExecution called without a workflow runner`);let i=e.buildRunContext({executionId:l,workflowId:m,coordinatorSessionId:p,source:{kind:`path`,path:t},inputs:{},config:{},scope:d,triggerPayload:u??{},workspaceRoot:f});await _n(r,h,i),Dn(a,h,t,d,i);let s=mn(r,{executionId:l,workflowId:m,coordinatorSessionId:p,startedAt:h.startedAt}),c=rn(e.buildRunnerTaskDeps(n),{executionId:l,workflowId:m,filePath:t,coordinatorSessionId:p,sanitizedTriggerPayload:u??{},scope:d,workspaceRoot:f});return g=!0,bn(o,l,c,s)}catch(e){throw g||(a.delete(l),o.delete(l),await hn(r,p)),e}}var kn=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(w.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(w.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function An(e){if(e!==void 0)return ge.parse(e)}function jn(e){if(e!==void 0)return he.parse(e)}function Mn(e,t){return{repoPath:t,makaioHome:e.makaioHome??process.env.MAKAIO_HOME??`${Pe.homedir()}/.makaio`,os:Xt(process.platform),arch:process.arch}}function Nn(e,t){return{executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{packages:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,context:Mn(t,e.workspaceRoot),env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Pn(e){return e?.status===`paused`}function Fn(e){return e?.status===`waiting`}async function In(e,t,n,r,i,a,o){t.delete(i.id),n.delete(i.id),r.delete(i.id);try{await e.request(w.restorePausedGateResumeState,{execution:i,gate:a})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${o}' after resume launch failure:`,e)}}async function Ln(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(w.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Rn(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function zn(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(w.getGateInstance,t);return Fn(n)?n:null}let{gates:n}=await e.request(w.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}var Bn=class extends Ce{static storage={drizzle:Gt};config;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;resumeDispatches=new Set;workflowAbortControllers=new Map;workflowRunner;triggerTypeRegistry;constructor(e,t,n){super(e),this.config={...g,...t},this.workflowRunner=n,this.gateTimeoutScheduler=new kn(e,e=>this.resumePausedExecution(e))}setTriggerTypeRegistry(e){this.triggerTypeRegistry=e}getTriggerTypeRegistry(){return this.triggerTypeRegistry}async onInit(){this.registerExecutionHandlers();for(let e of qt(this.bus))this.addCleanup(e);for(let e of Jt(this.bus,()=>this.triggerTypeRegistry))this.addCleanup(e);await this.rehydratePausedGateTimeouts()}async onDestroy(){let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await h(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());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(){return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs}}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveWorkflowContext:e=>Mn(this.config,e),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(D.get,{sessionId:e});return t?.targetWorkingDirectory??this.config.platformDefaults.cwd}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Nn(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e)}}registerExecutionHandlers(){this.registerHandler(a.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s,executionHints:c}=e.payload,l=typeof r==`object`&&r&&!Array.isArray(r)?r:{};try{let r=await En(this.buildStartDeps(),t,{input:An(n),config:l,parentSessionId:i,triggerPayload:a,artifactRef:o,executionHints:jn(c),scopeOverride:s});e.setResult({executionId:r})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(a.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,triggerPayload:n,scope:r}=e.payload;try{let i=await On(this.buildStartDeps(),t,{triggerPayload:n,scopeOverride:r});e.setResult({executionId:i})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(a.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(be(`workflow.${t}.cancel`),{executionId:t,reason:n}).catch(e=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${t}:`,e)});let r=this.workflowAbortControllers.get(t);if(r){r.abort(n??O);let i=await h(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await h(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(a.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(a.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(a.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(w.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Rn(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 b({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new p(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,n.signal,void 0,i,{context:t.runContext.context,env:t.runContext.env}),o=a.buildExpressionContext();r=await re(t.workflow.root,a,o)}catch(r){if(n.signal.aborted||t.execution.status===`cancelled`){await h(this.buildFinalizerDeps(),e,O);return}let i=r instanceof Error?r.message:String(r);await C(this.buildFinalizerDeps(),t.execution,e,i);return}let i=this.buildFinalizerDeps();r.status===`cancelled`||n.signal.aborted||t.execution.status===`cancelled`?await h(i,e,O):r.status===`failed`?await C(i,t.execution,e,r.error):r.status===`paused`?(t.execution.status=`paused`,await this.bus.request(w.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(w.getExecution,{executionId:t});if(!Pn(o))return!1;let s=await zn(this.bus,{executionId:t,nodeId:n,frameId:r});if(s===null||!te(n,s.schema,i).valid)return!1;let{runContext:c}=await this.bus.request(w.getRunContext,{executionId:t});if(c===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Ln(this.bus,c);let{accepted:l}=await this.bus.request(w.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 In(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,o,s,n),e}return this.gateTimeoutScheduler.clear(t,n,s.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(w.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(w.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:r}=await this.bus.request(w.getExecution,{executionId:e});if(r===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(r.status!==`paused`)return!1;await Ln(this.bus,t),await this.bus.request(w.setExecution,{execution:{...r,status:`running`}}),this.activeExecutions.set(e,{execution:{...r,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map});let i=sn(t,n,{resume:!0}),a=pn(this.buildStartDeps(),i).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,a),!0}};function Vn(e,t){try{return Ne(e)}catch(n){console.error(`[BusEventTriggerEvaluator] Invalid trigger.filterExpression for workflow "${t}": "${e}"`,n);return}}function Hn(e){let t=e.indexOf(`.`),n=e.indexOf(`:`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function Un(e){return{subject:`*`,$meta:{namespace:e,isRequest:!1}}}var Wn=class{bus;cleanupFns=[];initialized=!1;triggerIndex=new Map;subscribedNamespaces=new Set;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(k.definition.created,e=>{this.indexWorkflow(e.payload)}),this.bus.on(k.definition.updated,e=>{this.removeWorkflow(e.payload.id),this.indexWorkflow(e.payload)}),this.bus.on(k.definition.deleted,e=>{this.removeWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),!1)}getTestState(){return{initialized:this.initialized,cleanupFns:[...this.cleanupFns],subscribedNamespaces:new Set(this.subscribedNamespaces)}}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(w.list,{});for(let t of e)this.indexWorkflow(t)}indexWorkflow(e){let t=e.triggers??[],n=[];for(let r of t){if(r.type!==`bus-event`)continue;let t=typeof r.filterExpression==`string`?Vn(r.filterExpression,e.id):void 0;typeof r.filterExpression==`string`&&t===void 0||(n.push({workflowId:e.id,subject:r.subject,filter:r.filter,compiledFilterExpr:t}),this.ensureNamespaceSubscribed(Hn(r.subject)))}n.length>0&&this.triggerIndex.set(e.id,n)}removeWorkflow(e){this.triggerIndex.delete(e)}ensureNamespaceSubscribed(e){if(this.subscribedNamespaces.has(e))return;let t=Un(e),n=this.bus.on(t,e=>{if(e.isRequest)return;let t=typeof e.payload==`object`&&e.payload!==null?e.payload:{};this.handleBusEvent(e.subject,t)});this.cleanupFns.push(n),this.subscribedNamespaces.add(e)}handleBusEvent(e,t){for(let n of this.triggerIndex.values())for(let r of n)if(fe(e,r.subject)&&!(r.filter&&!de(t,r.filter))){if(r.compiledFilterExpr){let n;try{n=r.compiledFilterExpr.evalSync({payload:t})}catch(n){console.error(`[BusEventTriggerEvaluator] filterExpression eval failed for workflow "${r.workflowId}" on subject "${e}" payload keys: [${Object.keys(t).join(`, `)}]`,n);continue}if(!n)continue}this.bus.request(k.start,{workflowId:r.workflowId,triggerPayload:t}).catch(t=>{console.error(`[BusEventTriggerEvaluator] Failed to start workflow "${r.workflowId}" triggered by "${e}":`,t)})}}};function q(e,t,n,r,i,a,o,s){return q.fromTZ(q.tp(e,t,n,r,i,a,o),s)}q.fromTZISO=(e,t,n)=>q.fromTZ(Kn(e,t),n),q.fromTZ=function(e,t){let n=new Date(Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)),r=Gn(e.tz,n),i=new Date(n.getTime()-r),a=Gn(e.tz,i);if(a-r===0)return i;{let r=new Date(n.getTime()-a),o=Gn(e.tz,r);if(o-a===0||!t&&o-a>0)return r;if(t)throw Error(`Invalid date passed to fromTZ()`);return i}},q.toTZ=function(e,t){let n=e.toLocaleString(`en-US`,{timeZone:t}).replace(/[\u202f]/,` `),r=new Date(n);return{y:r.getFullYear(),m:r.getMonth()+1,d:r.getDate(),h:r.getHours(),i:r.getMinutes(),s:r.getSeconds(),tz:t}},q.tp=(e,t,n,r,i,a,o)=>({y:e,m:t,d:n,h:r,i,s:a,tz:o});function Gn(e,t=new Date){let n=t.toLocaleString(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).split(` `).slice(-1)[0],r=t.toLocaleString(`en-US`).replace(/[\u202f]/,` `);return Date.parse(`${r} GMT`)-Date.parse(`${r} ${n}`)}function Kn(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`minitz: Invalid ISO8601 passed to parser.`);let r=e.substring(9);return e.includes(`Z`)||r.includes(`-`)||r.includes(`+`)?q.tp(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):q.tp(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}q.minitz=q;var J=32,Y=31|J,qn=[1,2,4,8,16],Jn=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(e,t){this.pattern=e,this.timezone=t,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.replace(/\s+/g,` `).split(` `);if(e.length<5||e.length>6)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five or six space separated parts are required.`);if(e.length===5&&e.unshift(`0`),e[3].indexOf(`L`)>=0&&(e[3]=e[3].replace(`L`,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.replaceAlphaDays(e[5])),e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0){let t=new Z(new Date,this.timezone).getDate(!0);e[0]=e[0].replace(`?`,t.getSeconds().toString()),e[1]=e[1].replace(`?`,t.getMinutes().toString()),e[2]=e[2].replace(`?`,t.getHours().toString()),this.starDOM||(e[3]=e[3].replace(`?`,t.getDate().toString())),e[4]=e[4].replace(`?`,(t.getMonth()+1).toString()),this.starDOW||(e[5]=e[5].replace(`?`,t.getDay().toString()))}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1),this.partToArray(`dayOfWeek`,e[5],0,Y),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth;if(t===``&&!a)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let o=t.split(`,`);if(o.length>1)for(let t=0;t<o.length;t++)this.partToArray(e,o[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=parseInt(i[0],10)+n;if(isNaN(a))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,a,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`&&(t<0||t>=12))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t);this[e][t]=n}handleRangeWithStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);if(isNaN(l))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(u))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(isNaN(d))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(d===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(d>this[t].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[t].length+`)`);if(l>u)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}return[n,r]}handleRange(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;if(isNaN(o))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(o>s)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);a[0]===``&&(a[0]=`*`);let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(s===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(s>this[t].length)throw TypeError(`CronPattern: Syntax error, max steps for part is (`+this[t].length+`)`);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();return t===`@yearly`||t===`@annually`?`0 0 1 1 *`:t===`@monthly`?`0 0 1 * *`:t===`@weekly`?`0 0 * * 0`:t===`@daily`?`0 0 * * *`:t===`@hourly`?`0 * * * *`:e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|J;else if(t===Y)this.dayOfWeek[e]=Y;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|qn[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},Yn=[31,28,31,30,31,30,31,31,30,31,30,31],X=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Z=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date)if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`);else if(t===void 0)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&Y&&qn[a-1]&r)return!0;if(r&J){let r=new Date(Date.UTC(e,t+1,0)).getUTCDate();for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0)if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else{let t=q.toTZ(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.day>Yn[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}else return!1}fromString(e){if(typeof this.tz==`number`){let t=q.fromTZISO(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(q.fromTZISO(e,this.tz))}findNext(e,t,n,r){let i=this[t],a;n.lastDayOfMonth&&(a=this.month===1?new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate():Yn[this.month]);let o=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let s=this[t]+r;s<n[t].length;s++){let c=n[t][s];if(t===`day`&&n.lastDayOfMonth&&s-r==a&&(c=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(o+(s-r-1))%7];if(t&&t&Y)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,s-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);e.legacyMode&&!n.starDOM?c||=t:c&&=t}if(c)return this[t]=s-r,i===this[t]?1:2}return 3}recurse(e,t,n){let r=this.findNext(t,X[n][0],e,X[n][2]);if(r>1){let i=n+1;for(;i<X.length;)this[X[i][0]]=-X[i][2],i++;if(r===3)return this[X[n][1]]++,this[X[n][0]]=-X[n][2],this.apply(),this.recurse(e,t,0);if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=X.length?this:this.year>=3e3?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):q.fromTZ(q.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Xn(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode=e.legacyMode===void 0?!0:e.legacyMode,e.paused=e.paused===void 0?!1:e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch===void 0?!1:e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.unref=e.unref===void 0?!1:e.unref,e.startAt&&=new Z(e.startAt,e.timezone),e.stopAt&&=new Z(e.stopAt,e.timezone),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);return e}function Q(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function Zn(e){return Q(e)}function Qn(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var $n=30*1e3,$=[],er=class{name;options;_states;fn;constructor(e,t,n){let r,i;if(Q(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(Q(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=Xn(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new Jn(`* * * * *`)},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Z(e,this.options.timezone||this.options.utcOffset):this._states.pattern=new Jn(e,this.options.timezone),this.name){if($.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);$.push(this)}return i!==void 0&&Zn(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?t.getDate(!1):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=[],r=t||this._states.currentRun||void 0;for(;e--&&(r=this.nextRun(r));)n.push(r);return n}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Z||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Z(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=$.indexOf(this);e>=0&&$.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>$n&&(t=$n),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&Qn(this._states.currentTimeout),this)}async _trigger(e){if(this._states.blocking=!0,this._states.currentRun=new Z(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){Q(this.options.catch)&&this.options.catch(e,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Z(e,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&Q(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Z(e,this.options.timezone||this.options.utcOffset),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Z(e,this.options.timezone||this.options.utcOffset);return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_calculatePreviousRun(e,t){let n=new Z(void 0,this.options.timezone||this.options.utcOffset),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Z(r,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function tr(e,t){return`${e}:${t}`}function nr(e){return e??`UTC`}var rr=class{bus;cleanupFns=[];initialized=!1;jobs=new Map;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(k.definition.created,e=>{this.scheduleWorkflow(e.payload)}),this.bus.on(k.definition.updated,e=>{this.unscheduleWorkflow(e.payload.id),this.scheduleWorkflow(e.payload)}),this.bus.on(k.definition.deleted,e=>{this.unscheduleWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),!1)}activeJobCount(){return this.jobs.size}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(w.list,{});for(let t of e)this.scheduleWorkflow(t)}scheduleWorkflow(e){if(e.scope.type===`global`)return;let t=e.triggers??[];for(let n=0;n<t.length;n++){let r=t[n];if(r.type!==`cron`)continue;let i=tr(e.id,n);this.stopJob(i);try{let t=nr(r.timezone),a=new er(r.schedule,{timezone:t},()=>{this.fireTrigger(e.id,n)});this.jobs.set(i,{workflowId:e.id,triggerIndex:n,job:a})}catch(t){console.warn(`[CronTriggerEvaluator] Skipping invalid cron trigger key="${i}" workflowId="${e.id}" triggerIndex=${n} schedule="${r.schedule}" timezone="${r.timezone??`UTC`}"`,t)}}}unscheduleWorkflow(e){for(let[t,n]of this.jobs)n.workflowId===e&&(n.job.stop(),this.jobs.delete(t))}stopJob(e){let t=this.jobs.get(e);t&&(t.job.stop(),this.jobs.delete(e))}stopAllJobs(){for(let e of this.jobs.values())e.job.stop();this.jobs.clear()}fireTrigger(e,t){this.bus.request(k.start,{workflowId:e,triggerPayload:{firedAt:Date.now(),triggerIndex:t}}).catch(n=>{console.error(`[CronTriggerEvaluator] Failed to start workflow "${e}" for cron trigger index ${t}:`,n)})}},ir=class extends Ce{workflowExecutor;busEventTriggerEvaluator;cronTriggerEvaluator;constructor(e,t){super(e),this.workflowExecutor=new Bn(e,t?.executorConfig,t?.workflowRunner),this.busEventTriggerEvaluator=new Wn(e),this.cronTriggerEvaluator=new rr(e)}get executor(){return this.workflowExecutor}get cronTriggers(){return this.cronTriggerEvaluator}setTriggerTypeRegistry(e){this.workflowExecutor.setTriggerTypeRegistry(e)}getTriggerTypeRegistry(){return this.workflowExecutor.getTriggerTypeRegistry()}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.busEventTriggerEvaluator.init(),await this.cronTriggerEvaluator.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.cronTriggerEvaluator.destroy(),()=>this.busEventTriggerEvaluator.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 ar=Se(`makaio.workflow-engine`);function or(e){return{name:ar.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[xe(Fe.name)],critical:!0,namespaces:[ve,_],storage:{registerHandlers:Te(Gt)},create:t=>new ir(t.bus,e)}}const sr=or();export{Bn as a,ir as i,or as n,Gt as o,sr as r,ar as t};
package/dist/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@makaio/framework",
3
- "version": "1.0.0-dev-1781260968078",
3
+ "version": "1.0.0-dev-1781354548379",
4
4
  "type": "module"
5
5
  }
@@ -0,0 +1 @@
1
+ import{o as e}from"./chunk-DTipWd-i.mjs";import{t}from"./ajv-BA2z5ztb.mjs";import{z as n}from"zod";import{execFile as r}from"node:child_process";import{isAbsolute as i,relative as a,resolve as o}from"node:path";import{realpathSync as s}from"node:fs";import{localSubject as c}from"@makaio/framework/core";import{NoHandlerError as l}from"@makaio/framework/bus";import{ArtifactSubjects as u,ExecutionLinkListQuerySchema as d,ExecutionLinkSchema as f,ExecutionListQuerySchema as p,ExecutionStatusSchema as m,GateInstanceListQuerySchema as h,SpanRecordSchema as ee,SubagentSubjects as g,WorkflowDefinitionSchema as _,WorkflowExecutionSchema as v,WorkflowFrameStateSchema as y,WorkflowGateInstanceSchema as b,WorkflowListQuerySchema as te,WorkflowRunContextSchema as x,WorkflowSchemas as ne,WorkflowSubjects as re,WorkflowSubjects as S,createStepCancelSubject as ie}from"@makaio/framework/contracts";import{createStorageNamespaceDefinition as ae}from"@makaio/framework/storage";import{index as C,primaryKey as oe,uniqueIndex as se}from"drizzle-orm/sqlite-core";import{index as w,primaryKey as ce,uniqueIndex as le}from"drizzle-orm/pg-core";import{defineDualTable as T}from"@makaio/framework/storage/drizzle";import{sql as ue}from"drizzle-orm";import{evaluateSync as E,resolveTemplate as D}from"@makaio/framework/expression";import*as de from"node:os";function fe(e){return{scopeType:e.textEnum(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().$type(),scopeKind:e.text(`scope_kind`).notNull().default(``),scopeId:e.text(`scope_id`).notNull().default(``)}}const pe=T(`workflow_definitions`,e=>({id:e.text(`id`).primaryKey(),name:e.text(`name`).notNull(),description:e.text(`description`),root:e.jsonCol(`root`).notNull(),inputSchema:e.jsonCol(`input_schema`),configSchema:e.jsonCol(`config_schema`),outputSchema:e.jsonCol(`output_schema`),artifact:e.jsonCol(`artifact`),triggers:e.jsonCol(`triggers`),...fe(e),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull(),canvasLayout:e.jsonCol(`canvas_layout`),source:e.jsonCol(`source`),executionHints:e.jsonCol(`execution_hints`)}),{sqlite:e=>[se(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),C(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)],postgres:e=>[le(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),w(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)]}),me=pe.sqlite,O=T(`workflow_executions`,e=>({id:e.text(`id`).primaryKey(),workflowId:e.text(`workflow_id`).notNull(),coordinatorSessionId:e.text(`coordinator_session_id`),status:e.textEnum(`status`,{enum:[`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]}).notNull(),inputs:e.jsonCol(`inputs`),error:e.text(`error`),reason:e.text(`reason`),startedAt:e.epochMs(`started_at`).notNull(),completedAt:e.epochMs(`completed_at`),triggerPayload:e.jsonCol(`trigger_payload`),artifactKind:e.text(`artifact_kind`),artifactId:e.text(`artifact_id`),...fe(e)}),{sqlite:e=>[C(`idx_workflow_executions_status`).on(e.status),C(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),C(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),C(`idx_workflow_executions_artifact`).on(e.artifactKind,e.artifactId,e.startedAt)],postgres:e=>[w(`idx_workflow_executions_status`).on(e.status),w(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),w(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),w(`idx_workflow_executions_artifact`).on(e.artifactKind,e.artifactId,e.startedAt)]}),he=O.sqlite,ge=T(`workflow_execution_frames`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),nodeType:e.text(`node_type`).notNull().$type(),path:e.jsonCol(`path`).notNull(),parentFrameId:e.text(`parent_frame_id`),status:e.text(`status`).notNull().default(`pending`).$type(),attempt:e.int4(`attempt`).notNull().default(0),iteration:e.int4(`iteration`),branchKey:e.text(`branch_key`),output:e.jsonCol(`output`),outputPresent:e.bool(`output_present`).notNull().default(!1),error:e.text(`error`),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`)}),{sqlite:e=>[C(`idx_workflow_execution_frames_execution`).on(e.executionId),C(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)],postgres:e=>[w(`idx_workflow_execution_frames_execution`).on(e.executionId),w(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)]}),_e=ge.sqlite,ve=T(`workflow_gate_instances`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),frameId:e.text(`frame_id`).notNull(),schema:e.jsonCol(`schema`).notNull(),prompt:e.text(`prompt`),status:e.text(`status`).notNull().default(`waiting`).$type(),autoAction:e.textEnum(`auto_action`,{enum:[`approve`,`reject`]}).notNull().default(`reject`),timeoutMs:e.int4(`timeout_ms`),resumeData:e.jsonCol(`resume_data`),reason:e.text(`reason`),resumeDataPresent:e.bool(`resume_data_present`).notNull().default(!1),createdAt:e.epochMs(`created_at`).notNull(),resolvedAt:e.epochMs(`resolved_at`)}),{sqlite:e=>[C(`idx_workflow_gate_instances_execution`).on(e.executionId),C(`idx_workflow_gate_instances_frame`).on(e.frameId)],postgres:e=>[w(`idx_workflow_gate_instances_execution`).on(e.executionId),w(`idx_workflow_gate_instances_frame`).on(e.frameId)]}),ye=ve.sqlite,be=T(`workflow_step_spans`,e=>({executionId:e.text(`execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),frameId:e.text(`frame_id`).notNull(),stepId:e.text(`step_id`).notNull(),stepType:e.text(`step_type`).notNull(),status:e.text(`status`).$type().notNull(),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),inputTokens:e.int4(`input_tokens`),outputTokens:e.int4(`output_tokens`),estimatedCost:e.float8(`estimated_cost`),toolCallCount:e.int4(`tool_call_count`),input:e.text(`input`),output:e.text(`output`)}),{sqlite:e=>[oe({columns:[e.executionId,e.frameId]}),C(`idx_workflow_step_spans_status`).on(e.status)],postgres:e=>[ce({columns:[e.executionId,e.frameId]}),w(`idx_workflow_step_spans_status`).on(e.status)]}),xe=be.sqlite,k=T(`workflow_execution_links`,e=>({sourceExecutionId:e.text(`source_execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),targetExecutionId:e.text(`target_execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),linkType:e.text(`link_type`).$type().notNull(),metadata:e.jsonCol(`metadata`)}),{sqlite:e=>[oe({columns:[e.sourceExecutionId,e.targetExecutionId]}),C(`idx_workflow_execution_links_target`).on(e.targetExecutionId)],postgres:e=>[ce({columns:[e.sourceExecutionId,e.targetExecutionId]}),w(`idx_workflow_execution_links_target`).on(e.targetExecutionId)]}),A=k.sqlite,j=T(`workflow_run_contexts`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),coordinatorSessionId:e.text(`coordinator_session_id`).notNull(),sourceKind:e.text(`source_kind`).notNull(),sourcePath:e.text(`source_path`),sourceFilename:e.text(`source_filename`),sourceCode:e.text(`source_code`),definitionSnapshot:e.jsonCol(`definition_snapshot`),workerManifest:e.jsonCol(`worker_manifest`).notNull(),inputs:e.jsonCol(`inputs`),config:e.jsonCol(`config`).notNull().default(ue`'{}'`),triggerPayload:e.jsonCol(`trigger_payload`).notNull(),artifactRef:e.jsonCol(`artifact_ref`),executionHints:e.jsonCol(`execution_hints`),dispatchMetadata:e.jsonCol(`dispatch_metadata`),scopeType:e.textEnum(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().default(`global`).$type(),scopeKind:e.text(`scope_kind`).notNull().default(``),scopeId:e.text(`scope_id`).notNull().default(``),cancelSubject:e.text(`cancel_subject`).notNull(),context:e.jsonCol(`context`).notNull(),env:e.jsonCol(`env`).notNull(),createdAt:e.epochMs(`created_at`).notNull(),suspensionStrategy:e.text(`suspension_strategy`).$type()}),{sqlite:e=>[C(`idx_run_contexts_workflow`).on(e.workflowId)],postgres:e=>[w(`idx_run_contexts_workflow`).on(e.workflowId)]}),Se=j.sqlite,M=T(`worklog_summaries`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),workflowName:e.text(`workflow_name`),status:e.textEnum(`status`,{enum:[`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]}).notNull(),startedAt:e.epochMs(`started_at`).notNull(),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),totalInputTokens:e.int4(`total_input_tokens`),totalOutputTokens:e.int4(`total_output_tokens`),totalEstimatedCost:e.float8(`total_estimated_cost`),error:e.text(`error`),failedNodeId:e.text(`failed_node_id`)}),{sqlite:e=>[C(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),C(`idx_worklog_summaries_status`).on(e.status)],postgres:e=>[w(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),w(`idx_worklog_summaries_status`).on(e.status)]}),Ce=M.sqlite,we=T(`worklog_frame_entries`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),nodeType:e.text(`node_type`).notNull().$type(),path:e.jsonCol(`path`).notNull(),status:e.textEnum(`status`,{enum:[`pending`,`running`,`waiting`,`completed`,`failed`,`skipped`,`cancelled`]}).notNull(),attempt:e.int4(`attempt`).notNull().default(0),iteration:e.int4(`iteration`),branchKey:e.text(`branch_key`),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),inputTokens:e.int4(`input_tokens`),outputTokens:e.int4(`output_tokens`),estimatedCost:e.float8(`estimated_cost`),error:e.text(`error`)}),{sqlite:e=>[C(`idx_worklog_frame_entries_execution`).on(e.executionId)],postgres:e=>[w(`idx_worklog_frame_entries_execution`).on(e.executionId)]}),Te=we.sqlite,Ee=T(`worklog_artifact_writes`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),frameId:e.text(`frame_id`).notNull(),nodeId:e.text(`node_id`).notNull(),artifact:e.jsonCol(`artifact`).notNull(),revision:e.text(`revision`),writtenAt:e.epochMs(`written_at`).notNull()}),{sqlite:e=>[C(`idx_worklog_artifact_writes_execution`).on(e.executionId)],postgres:e=>[w(`idx_worklog_artifact_writes_execution`).on(e.executionId)]}),De=Ee.sqlite,Oe=T(`worklog_gate_events`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>O.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),frameId:e.text(`frame_id`).notNull(),status:e.textEnum(`status`,{enum:[`waiting`,`resumed`,`rejected`,`timed-out`,`cancelled`]}).notNull().$type(),prompt:e.text(`prompt`),openedAt:e.epochMs(`opened_at`).notNull(),resolvedAt:e.epochMs(`resolved_at`),resumeData:e.jsonCol(`resume_data`)}),{sqlite:e=>[C(`idx_worklog_gate_events_execution`).on(e.executionId),C(`idx_worklog_gate_events_status`).on(e.status)],postgres:e=>[w(`idx_worklog_gate_events_execution`).on(e.executionId),w(`idx_worklog_gate_events_status`).on(e.status)]}),ke=Oe.sqlite,Ae=n.object({executionId:n.string().min(1),status:m.optional(),error:n.string().nullable().optional(),reason:n.string().nullable().optional(),completedAt:n.number().nullable().optional()}),je=ae(`workflow`,{schemas:{get:{request:n.object({id:n.string()}),response:n.object({workflow:_.nullable()})},set:{request:n.object({workflow:_}),response:n.object({id:n.string()})},delete:{request:n.object({id:n.string()}),response:n.object({deleted:n.boolean()})},list:{request:te,response:n.object({workflows:n.array(_)})},getExecution:{request:n.object({executionId:n.string()}),response:n.object({execution:v.nullable()})},setExecution:{request:n.object({execution:v}),response:n.object({id:n.string()})},setExecutionStart:{request:n.object({execution:v,runContext:x}),response:n.object({id:n.string(),executionId:n.string()})},updateExecution:{request:Ae,response:n.object({success:n.boolean()})},cancelPausedExecution:{request:n.object({executionId:n.string().min(1),completedAt:n.number(),reason:n.string().optional()}),response:n.object({cancelled:n.boolean(),gates:n.array(b.extend({status:n.literal(`cancelled`)}))})},listExecutions:{request:p,response:n.object({executions:n.array(v)})},setFrame:{request:n.object({executionId:n.string().min(1),frame:y}),response:n.object({frameId:n.string()})},getFrame:{request:n.object({frameId:n.string().min(1)}),response:n.object({frame:y.nullable()})},listFrames:{request:n.object({executionId:n.string().min(1)}),response:n.object({frames:n.array(y)})},setGateInstance:{request:n.object({gate:b}),response:n.object({id:n.string()})},resolveWaitingGateInstance:{request:n.object({gate:b.extend({status:n.enum([`resumed`,`rejected`])})}),response:n.object({accepted:n.boolean()})},restorePausedGateResumeState:{request:n.object({execution:v.extend({status:n.literal(`paused`)}),gate:b.extend({status:n.literal(`waiting`)})}),response:n.object({executionId:n.string(),gateId:n.string()})},getGateInstance:{request:n.object({executionId:n.string().min(1),nodeId:n.string().min(1),frameId:n.string().min(1).optional()}),response:n.object({gate:b.nullable()})},listGateInstances:{request:h,response:n.object({gates:n.array(b)})},listPausedGateTimeouts:c({request:n.object({}),response:n.object({gates:n.array(b)})}),setSpan:{request:n.object({span:ee}),response:n.object({id:n.string()})},listSpans:{request:n.object({executionId:n.string()}),response:n.object({spans:n.array(ee)})},setExecutionLink:{request:n.object({link:f}),response:n.object({id:n.string()})},listExecutionLinks:{request:d,response:n.object({links:n.array(f)})},setRunContext:c({request:n.object({runContext:x}),response:n.object({executionId:n.string()})}),getRunContext:c({request:n.object({executionId:n.string().min(1)}),response:n.object({runContext:x.nullable()})})},extensions:{drizzle:{workflowDefinitions:me,workflowExecutions:he,workflowExecutionFrames:_e,workflowGateInstances:ye,workflowStepSpans:xe,workflowExecutionLinks:A,workflowRunContexts:Se,worklogSummaries:Ce,worklogFrameEntries:Te,worklogArtifactWrites:De,worklogGateEvents:ke}}}),N=je.subjects,Me={stepTimeoutMs:300*1e3,stepCooldownMs:500,busAuth:{kind:`none`},platformDefaults:{cwd:process.cwd()},cancelTimeoutMs:1e4};async function P(e,t,n){if(!(await e.request(N.updateExecution,{executionId:t.id,status:n.status,error:n.error,reason:n.reason,completedAt:n.completedAt})).success)throw Error(`Workflow execution not found: ${t.id}`)}async function Ne(e,t,n,r){t.status=`completed`,t.completedAt=Date.now();try{await P(e.bus,t,{status:t.status,completedAt:t.completedAt}),await e.bus.emit(S.execution.completed,{executionId:n,workflowId:t.workflowId,totalDuration:t.completedAt-r,completedAt:t.completedAt})}finally{e.activeExecutions.delete(n)}}async function Pe(e,t,n,r,i){t.status=`failed`,t.error=r,t.completedAt=Date.now();try{await P(e.bus,t,{status:t.status,error:t.error,completedAt:t.completedAt});try{await i?.()}catch(e){console.error(`[WorkflowFinalizer] Failed to run failure pre-emit hook:`,e)}await e.bus.emit(S.execution.failed,{executionId:n,workflowId:t.workflowId,error:r,completedAt:t.completedAt})}finally{e.activeExecutions.delete(n)}}function Fe(e,t,n){let{activeRunnerSteps:r,bus:i}=e,a=`${t}:`;for(let[e,o]of r){if(!e.startsWith(a))continue;let r=e.slice(a.length);o.controller.abort(),i.emit(ie(o.cancelSubject),{executionId:t,stepId:r,reason:n}).catch(t=>{console.error(`[WorkflowFinalizer] Failed to emit cancellation for ${e}:`,t)})}}async function Ie(e,t,n){let r=await e.bus.request(N.getExecution,{executionId:t});if(r.execution==null)return!1;let i=r.execution.workflowId;if(i===void 0)throw Error(`Paused execution ${t} is missing stored workflowId`);let a=Date.now(),{cancelled:o,gates:s}=await e.bus.request(N.cancelPausedExecution,{executionId:t,completedAt:a,reason:n});if(!o)return!1;for(let n of s)await e.bus.emit(S.gate.resolved,{executionId:t,stepId:n.nodeId,stepType:`gate`,frameId:n.frameId,source:`cancelled`}).catch(e=>{console.error(`[WorkflowFinalizer] Failed to emit cancelled gate resolution for ${n.frameId}:`,e)});return await e.bus.emit(S.execution.cancelled,{executionId:t,workflowId:i,reason:n,completedAt:a}),e.activeExecutions.delete(t),!0}async function Le(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return Ie(e,t,n);let{execution:i}=r;i.status=`cancelled`,i.reason=n,i.completedAt=Date.now();try{for(let[n,r]of e.shellAbortControllers)n.startsWith(`${t}:`)&&(r.abort(),e.shellAbortControllers.delete(n));Fe(e,t,n),await P(e.bus,i,{status:i.status,reason:n,completedAt:i.completedAt}),await e.bus.emit(S.execution.cancelled,{executionId:t,workflowId:i.workflowId,reason:n,completedAt:i.completedAt})}finally{e.activeExecutions.delete(t)}return!0}function Re(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ze(e,t,n){let r=e?D(e,n):t,c=o(t),l=o(i(r)?r:o(t,r)),u,d;try{u=s(c),d=s(l)}catch{return null}let f=a(process.platform===`win32`?u.toLowerCase():u,process.platform===`win32`?d.toLowerCase():d);return f===``||!f.startsWith(`..`)&&!i(f)?d:null}function Be(e){return e instanceof Error&&(`code`in e||`killed`in e)}function Ve(e){let t=e[0];return t===void 0||t.trim()===``?null:t}function He(e){let{command:t,cwd:n,env:i,timeoutMs:a,signal:o}=e,s=Ve(t);if(s===null)return Promise.reject(Error(`Shell step command is empty`));let c=t.slice(1);return new Promise((e,t)=>{let l=null,u=!1,d=r(s,c,{cwd:n,env:{...process.env,...i},timeout:0,maxBuffer:10*1024*1024,shell:!1},(n,r,i)=>{n?t(Object.assign(n,{stdout:r,stderr:i,aborted:u})):e({stdout:r,stderr:i})}),f=()=>{d.exitCode===null&&(d.kill(`SIGTERM`),l=setTimeout(()=>{d.exitCode===null&&d.kill(`SIGKILL`)},5e3))},p=setTimeout(()=>{f()},a);if(d.on(`close`,()=>{clearTimeout(p),l!==null&&clearTimeout(l)}),o){let e=()=>{u=!0,f()};o.aborted?e():(o.addEventListener(`abort`,e,{once:!0}),d.on(`close`,()=>o.removeEventListener(`abort`,e)))}})}async function Ue(e){let{step:t,workspaceRoot:n,expressionContext:r,signal:i}=e,a=ze(t.cwd,n,r);if(a===null)return{status:`failed`,error:`Shell step cwd '${t.cwd}' is outside workspace root '${n}'`};let o=t.command.map(e=>D(e,r));if(Ve(o)===null)return{status:`failed`,error:`Shell step command is empty`};let s=Object.fromEntries(Object.entries(t.env??{}).map(([e,t])=>[e,D(t,r)])),c=t.timeoutMs??3e5;try{let{stdout:e}=await He({command:o,cwd:a,env:s,timeoutMs:c,signal:i});return{status:`completed`,stdout:e}}catch(e){if(!Be(e))return{status:`failed`,error:String(e)};let t=e.aborted===!0,n=!t&&(e.killed===!0||e.signal!=null);return{status:`failed`,error:t?`Command cancelled`:n?`Command timed out after ${c}ms`:e.stderr?.trim()||e.stdout?.trim()||e.message}}}function We(e){let t={};for(let[n,r]of Object.entries(e))r.status===`completed`?t[n]={status:`completed`,output:r.output}:r.status===`skipped`&&(t[n]={status:`skipped`});return t}function F(e){let t={...e,input:e.inputs,steps:e.frames};return{...t,ctx:t}}function Ge(){return{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${de.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:{}}}function Ke(e){return{...e,path:[...e.path]}}function qe(e){if(e===`station`||e===`delegate-agent`||e===`delegate-role`||e===`gate`)return e}function Je(e,t){let n=qe(t.nodeType);if(n===void 0||t.status!==`running`&&t.status!==`completed`&&t.status!==`failed`&&t.status!==`skipped`)return;let r=t.startedAt!==void 0&&t.completedAt!==void 0?Math.max(0,t.completedAt-t.startedAt):void 0;return{executionId:e,frameId:t.frameId,stepId:t.nodeId,stepType:n,status:t.status,...t.startedAt===void 0?{}:{startedAt:t.startedAt},...t.completedAt===void 0?{}:{completedAt:t.completedAt},...r===void 0?{}:{durationMs:r},...t.output===void 0?{}:{output:JSON.stringify(t.output)}}}var Ye=class e{executionId;workflowId;definition;execution;runtimeHandlers;bus;signal;frameRegistry;framePersistenceTasks=new Map;artifactBinding;constructor(e,t,n,r,i,a,o,s,c,l=Ge(),u={}){this.executionId=e,this.workflowId=t,this.definition=n,this.execution=r,this.runtimeHandlers=i,this.bus=a,this.signal=o,this.frameRegistry=s??new Map,this.artifactBinding=c,this.platformContext=l.context,this.env=l.env,this.suspensionStrategy=u.suspensionStrategy??`wait-in-process`,this.resumeFrames=u.resumeFrames}platformContext;env;suspensionStrategy;resumeFrames;withSignal(t){return new e(this.executionId,this.workflowId,this.definition,this.execution,this.runtimeHandlers,this.bus,t,this.frameRegistry,this.artifactBinding,{context:this.platformContext,env:this.env},{suspensionStrategy:this.suspensionStrategy,resumeFrames:this.resumeFrames})}buildExpressionContext(){return{inputs:this.execution.inputs,config:this.execution.config??{},trigger:this.execution.triggerPayload??{},frames:{},previousSteps:{}}}createFrame(e){let t=Re(`frm`),n=[...e.path,t],r={frameId:t,nodeId:e.nodeId,nodeType:e.nodeType,path:n,parentFrameId:e.parentFrameId,status:`pending`,attempt:0,iteration:e.iteration,branchKey:e.branchKey};return this.frameRegistry.set(t,r),this.persistFrame(r).catch(()=>void 0),r}async persistFrame(e,t={}){let n=t.requireFrameStorage===!0||this.suspensionStrategy!==`wait-in-process`,r=Ke(e),i=Je(this.executionId,r),a=(this.framePersistenceTasks.get(e.frameId)??Promise.resolve()).catch(()=>void 0).then(async()=>{n?await this.bus.request(N.setFrame,{executionId:this.executionId,frame:r}):await this.bus.requestOptional(N.setFrame,{executionId:this.executionId,frame:r}),i!==void 0&&await this.bus.requestOptional(N.setSpan,{span:i})}).catch(t=>{if(n)throw t;console.warn(`[RuntimeContext] Failed to persist frame ${e.frameId}:`,t)});this.framePersistenceTasks.set(e.frameId,a);try{await a}finally{this.framePersistenceTasks.get(e.frameId)===a&&this.framePersistenceTasks.delete(e.frameId)}}async updateFrame(e,t,n={}){let r=this.frameRegistry.get(e);if(!r)throw Error(`Frame not found: ${e}`);Object.assign(r,t),await this.persistFrame(r,n)}getFrame(e){return this.frameRegistry.get(e)}getFramesByNodeId(e){let t=[];for(let n of this.frameRegistry.values())n.nodeId===e&&t.push(n);return t.sort((e,t)=>(e.startedAt??0)-(t.startedAt??0))}async emitFrameStarted(e){try{await this.bus.emit(S.frame.started,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId,startedAt:e.startedAt})}catch(t){console.error(`[RuntimeContext] frame.started observer failed for ${e.frameId}:`,t)}}async emitFrameCompleted(e,t){try{await this.bus.emit(S.frame.completed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,output:e.output,duration:t,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.completed observer failed for ${e.frameId}:`,t)}}async emitFrameFailed(e,t,n){try{await this.bus.emit(S.frame.failed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,error:t,duration:n,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.failed observer failed for ${e.frameId}:`,t)}}};function Xe(e){return{kind:`workflow-execution`,id:e,displayName:`Workflow Engine`}}function Ze(e,t,n){return{inputs:n.inputs,config:n.config??{},trigger:n.triggerPayload,scope:n.scope,context:n.context,env:n.env,execution:{id:t.id,workflowId:t.workflowId,scope:t.scope},workflow:{id:e.id,name:e.name,scope:e.scope}}}function Qe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $e(e){if(e!=null){if(Qe(e)&&typeof e.kind==`string`&&typeof e.id==`string`)return{kind:e.kind,id:e.id};throw Error(`Artifact resolve expression must return an object with string kind and id fields.`)}}function et(e){if(e!==void 0){if(Qe(e))return e;throw Error(`Artifact create expression must return an object.`)}}async function tt(e){let{bindingOptions:t,binding:n,existingArtifactRef:r,executionId:i,scope:a,initialData:o,bus:s}=e,c=null;if(r!==void 0){let e=await s.request(u.query,{kind:r.kind,ids:[r.id],currentOnly:!0});if(e.artifacts.length>0)c=e.artifacts[0];else return}else c=(await s.request(u.create,{kind:n.kind,schemaVersion:n.schemaVersion,scope:a??n.scope,data:o??{},relations:[],actor:Xe(i)})).artifact;return{current:c,schemaVersion:n.schemaVersion,statusPath:t.statusPath,zodSchema:t.schema}}async function nt(e){let{definition:t,execution:n,runContext:r,zodSchema:i,bus:a}=e,o=t.artifact;if(o===void 0)return;let s=Ze(t,n,r),c=r.artifactRef??(o.resolve===void 0?void 0:$e(E(o.resolve,s))),l=c===void 0&&o.create!==void 0?et(E(o.create,s)):void 0,u=await tt({bindingOptions:{kind:o.kind,schemaVersion:o.schemaVersion,scope:o.scope,...o.resolve===void 0?{}:{resolve:o.resolve},...o.create===void 0?{}:{create:o.create},...o.statusPath===void 0?{}:{statusPath:o.statusPath},...i===void 0?{}:{schema:i}},binding:o,existingArtifactRef:c,executionId:n.id,scope:o.scope,initialData:l,bus:a});if(u===void 0)throw Error(`Workflow artifact binding could not be resolved for the configured artifact reference.`);return u}const rt=new WeakMap;function it(e,t){let n=(rt.get(e)??Promise.resolve()).catch(()=>void 0).then(t);return rt.set(e,n.then(()=>void 0,()=>void 0)),n}function at(e,t){switch(t.operation){case`set`:return t.data;case`merge`:return{...e,...t.data};case`append`:{let n={...e};for(let[r,i]of Object.entries(t.data)){let t=e[r];Array.isArray(t)&&Array.isArray(i)?n[r]=[...t,...i]:n[r]=i}return n}}}function ot(e,t,n){let[r,...i]=t;if(i.length===0)return{...e,[r]:n};let a=e[r]!==null&&typeof e[r]==`object`&&!Array.isArray(e[r])?e[r]:{};return{...e,[r]:ot(a,i,n)}}function st(e,t,n){return ot(e,t.startsWith(`/`)?t.slice(1).split(`/`):t.split(`.`),n)}function ct(e,t,n){if(n===`set`||n===`functional`)return[];let r=[];for(let n of Object.keys(t))e[n]!==t[n]&&r.push(`/${n}`);return r}async function lt(e,t){if(typeof t==`function`)return{nextData:await t(Object.freeze({...e})),operationLabel:`functional`,changedPaths:[]};let n=at(e,t),r=ct(e,n,t.operation);return{nextData:n,operationLabel:t.operation,changedPaths:r}}function ut(e){let{executionId:t,frameId:n,bindingState:r,bus:i}=e,a=Object.freeze({...r.current.data}),o=async e=>it(r,async()=>{let a=r.current,{nextData:o,operationLabel:s,changedPaths:c}=await lt(a.data,e);if(r.zodSchema!==void 0){let e=r.zodSchema.safeParse(o);if(!e.success)throw Error(`Artifact data validation failed: ${e.error.message}`)}let l=await i.request(u.revise,{previous:{refClass:`artifact`,kind:a.kind,id:a.id,revision:a.revision},revision:{kind:a.kind,schemaVersion:r.schemaVersion,scope:a.scope,data:o,relations:a.relations,actor:Xe(t)}});r.current=l.artifact;let d=l.artifact.revision;return i.emit(re.artifact.updated,{executionId:t,frameId:n,artifactRef:{kind:l.artifact.kind,id:l.artifact.id},paths:c,operation:s,revision:d}).catch(e=>{console.error(`[ArtifactContext] Failed to emit artifact.updated event:`,e)}),d});return{data:a,updateArtifact:o,updateStatus:async e=>{if(r.statusPath===void 0)throw Error(`updateStatus() called but no statusPath is configured on the artifact binding. Set statusPath in the .artifact() builder call to use updateStatus().`);let t=r.statusPath;return o(n=>st(n,t,e))}}}async function dt(e,t,n){if(t.signal.aborted)return{status:`cancelled`};let r=await t.bus.requestOptional(S.resolveRole,{roleId:e.roleId});if(!r.handled)return{status:`failed`,error:e.unresolvedRoleError};let i=D(e.prompt,F(n));return ft({...e,task:i,resolvedConfig:r.data},t)}async function ft(e,t){if(t.signal.aborted)return{status:`cancelled`};let n=await t.bus.requestOptional(g.spawn,{parentSessionId:t.execution.coordinatorSessionId??t.executionId,depth:1,config:gt(e.task,e.resolvedConfig,e.outputSchema)});if(!n.handled)return{status:`failed`,error:e.unavailableRuntimeError};let r=await I(e,t,n.data.subagentId,{attempts:5}),i=await _t(e,t,n.data.subagentId);return i===`aborted`?{status:`cancelled`}:(r||await I(e,t,n.data.subagentId,{attempts:1}),i.handled?t.signal.aborted||i.data.status===`cancelled`?{status:`cancelled`}:i.data.status===`completed`?{status:`completed`,output:i.data.result??null}:{status:`failed`,error:`${e.nodeLabel} '${e.nodeId}' subagent ${i.data.status}: ${i.data.error??`no result`}`}:{status:`failed`,error:e.unavailableAwaitError})}async function I(e,t,n,r){if(e.frameId===void 0)return!0;try{let i=await pt(t,n,r.attempts);return i===void 0?!1:(await t.bus.emit(S.frame.sessionLinked,{executionId:t.executionId,frameId:e.frameId,sessionId:i}),!0)}catch(t){return console.warn(`[workflow-engine] Failed to emit frame.sessionLinked for frame '${e.frameId}' and subagent '${n}'`,t),!1}}async function pt(e,t,n){for(let r=0;r<n;r+=1){if(e.signal?.aborted)return;let i=await mt(e,t);if(i===void 0||!i.handled)return;if(i.data.childSessionId!==void 0)return i.data.childSessionId;if(r<n-1&&!await ht(e.signal,20))return}}async function mt(e,t){try{return await e.bus.requestOptional(g.getStatus,{subagentId:t},{timeout:25,signal:e.signal})}catch{return}}function ht(e,t){return e.aborted?Promise.resolve(!1):new Promise(n=>{let r,i=t=>{r!==void 0&&(clearTimeout(r),r=void 0),e.removeEventListener(`abort`,a),n(t)},a=()=>i(!1);r=setTimeout(()=>i(!0),t),e.addEventListener(`abort`,a,{once:!0}),e.aborted&&i(!1)})}function gt(e,t,n){return{task:e,adapterName:t.adapterName,...t.model===void 0?{}:{model:t.model},...t.reasoningEffort===void 0?{}:{reasoningEffort:t.reasoningEffort},...t.harnessId===void 0?{}:{harnessId:t.harnessId},...t.systemPrompt===void 0?{}:{systemPrompt:t.systemPrompt},...t.contextMode===void 0?{}:{contextMode:t.contextMode},...t.providerContext===void 0?{}:{providerContext:t.providerContext},...n===void 0?{}:{responseSchema:n}}}async function _t(e,t,n){if(t.signal.aborted)return await L(e,t,n),`aborted`;let r=t.bus.requestOptional(g.await,{subagentId:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}},{timeout:0});if(t.signal.aborted)return await L(e,t,n),`aborted`;let i,a=new Promise(e=>{i=()=>e(`aborted`),t.signal.addEventListener(`abort`,i,{once:!0})}),o=await Promise.race([r,a]);return i!==void 0&&t.signal.removeEventListener(`abort`,i),o===`aborted`&&await L(e,t,n),o}async function L(e,t,n){try{await t.bus.requestOptional(g.kill,{subagentId:n,reason:`Workflow execution '${t.executionId}' cancelled ${e.cancellationLabel} '${e.nodeId}'`})}catch(t){console.warn(`[workflow-engine] Best-effort subagent kill failed for '${n}' (${e.cancellationLabel} '${e.nodeId}')`,t)}}async function vt(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=We(n.frames),a=t.runtimeHandlers.get(e.id);if(a===void 0)return yt(e,t,n,r);let o=t.artifactBinding!==void 0&&r!==void 0?ut({executionId:t.executionId,frameId:r,bindingState:t.artifactBinding,bus:t.bus}):void 0;async function s(n){if(r===void 0){console.warn(`[station-node] updateProgress called without frameId for node '${e.id}'; skipping emit`);return}let i=ne[`execution.progress`].parse({executionId:t.executionId,workflowId:t.workflowId,frameId:r,nodeId:e.id,progress:n,emittedAt:Date.now()});try{await t.bus.emit(S.execution.progress,i)}catch(t){console.error(`[station-node] execution.progress observer failed for ${e.id}:`,t)}}let c;try{c=await a({...t.platformContext,env:t.env,executionId:t.executionId,workflowId:t.workflowId,inputs:t.execution.inputs,config:t.execution.config??{},trigger:t.execution.triggerPayload??{},previousSteps:i,...n.item!==void 0&&{item:n.item},...n.index!==void 0&&{index:n.index},...n.previous!==void 0&&{previous:n.previous},signal:t.signal,...o!==void 0&&{artifact:o},bus:t.bus,updateProgress:s})}catch(e){return{status:`failed`,error:e instanceof Error?e.message:String(e)}}return{status:`completed`,output:c}}async function yt(e,t,n,r){if(e.role===void 0)return{status:`failed`,error:`No handler registered for station node '${e.id}'`};let i=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return dt({nodeId:e.id,nodeLabel:`Station node`,roleId:e.role,prompt:e.prompt,...i===void 0?{}:{outputSchema:i},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},unresolvedRoleError:`No runtime handler registered for station node '${e.id}', and role '${e.role}' could not be resolved`,unavailableRuntimeError:`Subagent runtime is not available for station node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await station node '${e.id}'`,cancellationLabel:`station`,...r===void 0?{}:{frameId:r}},t,n)}async function bt(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(S.resolveAgent,{agentId:e.agentId});if(!i.handled)return{status:`failed`,error:`Agent '${e.agentId}' could not be resolved for delegate-agent node '${e.id}'`};if(t.signal.aborted)return{status:`cancelled`};let a=St(e,n);if(a.status===`failed`)return a;let o=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return ft({nodeId:e.id,nodeLabel:`Delegate-agent node`,task:a.task,resolvedConfig:i.data,...o===void 0?{}:{outputSchema:o},unavailableRuntimeError:`Subagent runtime is not available for delegate-agent node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-agent node '${e.id}'`,cancellationLabel:`delegate-agent`,...r===void 0?{}:{frameId:r}},t)}async function xt(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return dt({nodeId:e.id,nodeLabel:`Delegate-role node`,roleId:e.role,prompt:e.prompt,...i===void 0?{}:{outputSchema:i},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},unresolvedRoleError:`Role '${e.role}' could not be resolved for delegate-role node '${e.id}'`,unavailableRuntimeError:`Subagent runtime is not available for delegate-role node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-role node '${e.id}'`,cancellationLabel:`delegate-role`,...r===void 0?{}:{frameId:r}},t,n)}function St(e,t){try{let n=F(t);return{status:`completed`,task:Ct(e.inputExpression===void 0?n:E(e.inputExpression,n))}}catch(t){let n=t instanceof Error?t.message:String(t);return{status:`failed`,error:`delegate-agent node '${e.id}': input expression evaluation failed: ${n}`}}}function Ct(e){if(typeof e==`string`)return e;if(e===void 0)return``;try{return JSON.stringify(e,null,2)??``}catch{return String(e)}}function wt(e,t,n,r){try{let i=E(n,F(r));return Array.isArray(i)?i:{status:`failed`,error:`${t} node '${e}': collection expression did not resolve to an array (got ${typeof i})`}}catch(n){return{status:`failed`,error:`${t} node '${e}': collection expression evaluation failed: ${n instanceof Error?n.message:String(n)}`}}}function Tt(e,t,n){for(let r of[...e.nodes].reverse()){let e=n.getFramesByNodeId(r.id);for(let n of e)if(n.parentFrameId===t&&n.status===`completed`)return n.output}}function Et(e,t,n){return Tt(e.body,t,n)}function Dt(e){if(e.length===0)return;let t=new Map,n=new Map;for(let r of e){n.set(r.frameId,r);let e=t.get(r.nodeId)??[];e.push(r),t.set(r.nodeId,e)}return{byNodeId:t,byFrameId:n}}const Ot=new Set([`completed`,`skipped`,`waiting`]);function R(e,t,n){let r=e?.byNodeId.get(t)??[],i=n.statuses??Ot;return r.find(e=>e.parentFrameId===n.parentFrameId&&e.branchKey===n.branchKey&&e.iteration===n.iteration&&i.has(e.status))}function z(e,t,n){let r={...e.frames,[t]:n};return{...e,frames:r,previousSteps:We(r),output:n.status===`completed`?n.output:e.output}}function B(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController,r=()=>n.abort();return e.addEventListener(`abort`,r,{once:!0}),t.addEventListener(`abort`,r,{once:!0}),n.signal}const kt=new Set([`completed`,`running`]);function At(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function jt(e,t,n,r,i,a,o=`all-settled`){if(t.signal.aborted)return{status:`cancelled`};let s=Object.entries(e.branches);if(s.length===0)return{status:`completed`,output:V({},o)};let c=new AbortController,l=new AbortController,u=t.suspensionStrategy!==`wait-in-process`,d=o===`fail-fast`?B(c.signal,l.signal):u?l.signal:void 0,f=d===void 0?t.signal:B(t.signal,d),p=f===t.signal?t:t.withSignal(f),m=s.map(([s,c])=>Mt(s,c,e,p,n,r,i,a,{outerSignal:t.signal,pauseSignal:o===`fail-fast`||u?l.signal:void 0}));if(o===`all-settled`){let e=await Promise.all(u?m.map(e=>e.then(e=>(e.status===`paused`&&l.abort(),e))):m),t=e.find(e=>e.status===`paused`);return t===void 0?{status:`completed`,output:V(Pt(s,e),o)}:t}let h=await Nt(s,m,c,l);return h.type===`cancelled`?{status:`cancelled`}:h.type===`paused`?h.outcome:h.type===`failed`?{status:`failed`,error:h.error}:{status:`completed`,output:V(Pt(s,h.outcomes),o)}}async function Mt(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l=R(r.resumeFrames,n.id,{parentFrameId:o,branchKey:e,statuses:kt});if(l?.status===`completed`)return{status:`completed`,...l.output===void 0?{}:{output:l.output}};let u=l??r.createFrame({nodeId:n.id,nodeType:`parallel`,path:s,parentFrameId:o,branchKey:e});if(r.signal.aborted)return At(u,c)||await $(u,r),{status:`cancelled`};l===void 0&&await Y(u,r);let d;try{d=await a(t,r,i,u.frameId,u.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Z(u,r,t),{status:`failed`,error:t}}switch(d.status){case`completed`:{let e=Tt(t,u.frameId,r);return await X(u,r,e),{status:`completed`,output:e}}case`skipped`:return await X(u,r),{status:`completed`};case`cancelled`:return At(u,c)||await $(u,r),{status:`cancelled`};case`paused`:return d;case`failed`:return await Z(u,r,d.error),{status:`failed`,error:d.error}}}async function Nt(e,t,n,r){let i,a,o=t.map(e=>e.then(e=>(e.status===`failed`&&i===void 0?(i=e.error,n.abort()):e.status===`paused`&&a===void 0&&(a=e,r.abort()),e),e=>{let t=e instanceof Error?e.message:String(e);return i===void 0&&(i=t,n.abort()),{status:`failed`,error:t}})),s=await Promise.all(o);return a===void 0?s.some(e=>e.status===`cancelled`)&&i===void 0?{type:`cancelled`}:i===void 0?{type:`completed`,outcomes:s}:{type:`failed`,error:i}:{type:`paused`,outcome:a}}function V(e,t){return{mode:t,branches:e}}function Pt(e,t){let n={};for(let r=0;r<e.length;r++){let[i]=e[r],a=t[r];n[i]=Ft(a)}return n}function Ft(e){switch(e.status){case`completed`:return{status:`fulfilled`,...e.output===void 0?{}:{value:e.output}};case`skipped`:return{status:`fulfilled`,value:null};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:e.pausedAtGateId,pausedAtFrameId:e.pausedAtFrameId};case`failed`:return{status:`rejected`,reason:e.error}}}const It=new(e(t(),1)).default({allErrors:!0,strict:!1});function H(e,t){if(t===void 0)return{status:`ok`};try{return{status:`ok`,validator:It.compile(t)}}catch(t){return{status:`failed`,error:`Gate '${e}' has an invalid resumeSchema: ${t instanceof Error?t.message:String(t)}`}}}function U(e,t){return e===void 0||e(t)?{valid:!0}:{valid:!1,error:Rt(e.errors??[])}}function Lt(e,t,n){let r=H(e,t);return r.status===`failed`?{valid:!1,error:r.error}:U(r.validator,n)}function Rt(e){return e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`/`} ${e.message??`is invalid`}`).join(`; `)}const W={action:`approve`,source:`timeout`};function G(e){return e===void 0?{}:{reason:e}}async function zt(e,t,n,r){let i=()=>{t.value&&(t.value=!1,e.reject(`cancelled`))};n.addEventListener(`abort`,i,{once:!0}),n.aborted&&i();let a=[e.promise],o;if(r!==null){let e=Ut();o=setTimeout(()=>{t.value&&(t.value=!1,n.removeEventListener(`abort`,i),e.reject(`timed-out`))},r),a.push(e.promise)}try{let e=await Promise.race(a);return n.removeEventListener(`abort`,i),o!==void 0&&clearTimeout(o),{action:e.action,resumeData:e.resumeData,timedOut:!1,wasCancelled:!1,reason:e.reason}}catch(e){return o!==void 0&&clearTimeout(o),n.removeEventListener(`abort`,i),e===`timed-out`?{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1}:{action:`reject`,resumeData:null,timedOut:!1,wasCancelled:!0}}}async function Bt(e,t,n,r,i,a){let o={required:e.suspensionStrategy!==`wait-in-process`};if(a.timedOut){let a=Date.now();if(r.autoAction===`approve`){let s=U(i,W);return s.valid?(await K(e,{...r,status:`resumed`,resumeData:W,resolvedAt:a},o),await q(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:{resumeData:W}}):(await K(e,{...r,status:`timed-out`,resolvedAt:a},o),await q(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' auto-approve timeout resume data does not match resumeSchema: ${s.error}`})}return await K(e,{...r,status:`timed-out`,resolvedAt:a},o),await q(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' timed out after ${String(r.timeoutMs)}ms and auto-rejected`}}if(a.wasCancelled||e.signal.aborted)return await K(e,{...r,status:`cancelled`,resolvedAt:Date.now()},o),await q(e,t.id,n,{source:`cancelled`}),{status:`cancelled`};let s=Date.now();await K(e,{...r,status:a.action===`reject`?`rejected`:`resumed`,resumeData:a.resumeData,...G(a.reason),resolvedAt:s},o);try{await e.bus.emit(S.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:a.resumeData}),await q(e,t.id,n,{action:a.action,source:`user`,...G(a.reason)})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return{status:`completed`,output:{resumeData:a.resumeData}}}async function Vt(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.resumeSchema??{};if(t.suspensionStrategy!==`wait-in-process`){let n=await Kt(t,e,r);if(n!==void 0)return n}let a=H(e.id,e.resumeSchema);return a.status===`failed`?{status:`failed`,error:a.error}:Ht(t,e,n,r,i,a.validator)}async function Ht(e,t,n,r,i,a){let o=D(t.prompt,F(n)),s={executionId:e.executionId,nodeId:t.id,frameId:r,schema:i,prompt:o,status:`waiting`,autoAction:t.autoAction,timeoutMs:t.timeoutMs,createdAt:Date.now()},c=e.suspensionStrategy!==`wait-in-process`;if(await K(e,s,{required:c}),await e.updateFrame(r,{status:`waiting`},{requireFrameStorage:c}),c)return await Wt(e,t,r,i,o,s.createdAt),{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:r};let u={value:!0},d=Ut(),f=e.bus.on(S.gate.respond,async n=>{let{executionId:i,gateId:o,frameId:s,action:c,resumeData:f,reason:p}=n.payload;if(i!==e.executionId||o!==t.id||s!==void 0&&s!==r){try{await n.next()}catch(e){if(e instanceof l)n.setResult({accepted:!1});else throw e}return}if(!u.value){n.setResult({accepted:!1});return}if(!U(a,f).valid){n.setResult({accepted:!1});return}u.value=!1,n.setResult({accepted:!0}),d.resolve({action:c,resumeData:f,reason:p})});await Wt(e,t,r,i,o,s.createdAt);let p=await zt(d,u,e.signal,t.timeoutMs);return f(),Bt(e,t,r,s,a,p)}function Ut(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}async function Wt(e,t,n,r,i,a){try{await e.bus.emit(S.gate.suspended,{executionId:e.executionId,frameId:n,nodeId:t.id,schema:r,prompt:i,...t.title!==void 0&&{title:t.title},autoAction:t.autoAction,timeoutMs:t.timeoutMs,openedAt:a})}catch(e){console.error(`[GateNode] gate.suspended emit failed for '${t.id}':`,e)}}async function Gt(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function Kt(e,t,n){let r=await Gt(e,t.id,n);if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData!==void 0){let i=Lt(t.id,r.schema,r.resumeData);if(!i.valid)return{status:`failed`,error:`Gate '${t.id}' persisted resumeData is invalid: ${i.error}`};try{await e.bus.emit(S.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:r.resumeData})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return await q(e,t.id,n,{action:r.status===`rejected`?`reject`:`approve`,source:`user`,...G(r.reason)}),{status:`completed`,output:{resumeData:r.resumeData}}}if(r?.status===`waiting`){if(r.timeoutMs!==null&&Date.now()>=r.createdAt+r.timeoutMs){let i=H(t.id,r.schema);return i.status===`failed`?{status:`failed`,error:i.error}:Bt(e,t,n,r,i.validator,{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1})}return{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:n}}if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData===void 0)return{status:`failed`,error:`Gate '${t.id}' has status '${r.status}' but resumeData is missing — cannot reconstruct output`};if(r!==null)return{status:`failed`,error:`Gate '${t.id}' cannot resume from status '${r.status}'`}}async function K(e,t,n={}){try{n.required===!0?await e.bus.request(N.setGateInstance,{gate:t}):await e.bus.requestOptional(N.setGateInstance,{gate:t})}catch(e){if(n.required===!0)throw e;console.warn(`[GateNode] Failed to upsert gate instance for '${t.nodeId}':`,e)}}async function q(e,t,n,r){try{await e.bus.emit(S.gate.resolved,{executionId:e.executionId,stepId:t,stepType:`gate`,frameId:n,...r})}catch(e){console.error(`[GateNode] gate.resolved emit failed for '${t}':`,e)}}function J(e){return{status:`fulfilled`,...e===void 0?{}:{value:e}}}const qt=new Set([`completed`,`running`]);function Jt(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function Yt(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=wt(e.id,`iterate`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:$t([])};let c=await Xt(s,e,t,n,r,i,a,e.concurrency!==void 0&&e.concurrency>0?e.concurrency:0);if(t.signal.aborted&&c.every(e=>e.status===`cancelled`))return{status:`cancelled`};let l=c.find(e=>e.status===`paused`);return l===void 0?{status:`completed`,output:$t(c)}:{status:`paused`,pausedAtGateId:l.pausedAtGateId,pausedAtFrameId:l.pausedAtFrameId}}async function Xt(e,t,n,r,i,a,o,s){let c=new AbortController,l=n.suspensionStrategy!==`wait-in-process`,u=l?B(n.signal,c.signal):n.signal,d=u===n.signal?n:n.withSignal(u),f={outerSignal:n.signal,...l?{pauseSignal:c.signal}:{}};if(s===0){let n=e.map((e,n)=>Qt(e,n,t,d,r,i,a,o,f));return Promise.all(l?n.map(e=>Zt(e,c)):n)}let p=Array(e.length);for(let n=0;n<e.length;n+=s){if(d.signal.aborted){for(let t=n;t<e.length;t++)p[t]={status:`cancelled`};break}let u=Math.min(n+s,e.length),m=[];for(let s=n;s<u;s++)m.push(Qt(e[s],s,t,d,r,i,a,o,f));let h=await Promise.all(l?m.map(e=>Zt(e,c)):m);for(let e=0;e<h.length;e++)p[n+e]=h[e];if(h.some(e=>e.status===`paused`)){for(let t=u;t<e.length;t++)p[t]={status:`cancelled`};break}}return p}function Zt(e,t){return e.then(e=>(e.status===`paused`&&t.abort(),e))}async function Qt(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l={...i,item:e,index:t},u=R(r.resumeFrames,n.id,{parentFrameId:o,iteration:t,statuses:qt});if(u?.status===`completed`)return J(u.output);let d=u??r.createFrame({nodeId:n.id,nodeType:`iterate`,path:s,parentFrameId:o,iteration:t});if(r.signal.aborted)return Jt(d,c)||await $(d,r),{status:`cancelled`};u===void 0&&await Y(d,r);let f;try{f=await a(n.body,r,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Z(d,r,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=Et(n,d.frameId,r);return await X(d,r,e),J(e)}case`skipped`:return await X(d,r),J();case`cancelled`:return Jt(d,c)||await $(d,r),{status:`cancelled`};case`paused`:return f;case`failed`:return await Z(d,r,f.error),{status:`rejected`,reason:f.error}}}function $t(e){return{items:e}}const en=new Set([`completed`,`running`]);async function tn(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=wt(e.id,`iterate-chain`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:rn([])};let c=[],l;for(let o=0;o<s.length;o++){if(t.signal.aborted)return{status:`cancelled`};let u=s[o],d=await nn(u,o,l,e,t,n,r,i,a);switch(c.push(d),d.status){case`fulfilled`:l=d.value;break;case`rejected`:return{status:`failed`,error:d.reason};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:d.pausedAtGateId,pausedAtFrameId:d.pausedAtFrameId}}}return{status:`completed`,output:rn(c)}}async function nn(e,t,n,r,i,a,o,s,c){if(i.signal.aborted)return{status:`cancelled`};let l={...a,item:e,index:t,...n!==void 0&&{previous:n}},u=R(i.resumeFrames,r.id,{parentFrameId:s,iteration:t,statuses:en});if(u?.status===`completed`)return J(u.output);let d=u??i.createFrame({nodeId:r.id,nodeType:`iterate-chain`,path:c,parentFrameId:s,iteration:t});if(i.signal.aborted)return await $(d,i),{status:`cancelled`};u===void 0&&await Y(d,i);let f;try{f=await o(r.body,i,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Z(d,i,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=Et(r,d.frameId,i);return await X(d,i,e),J(e)}case`skipped`:return await X(d,i),J();case`cancelled`:return await $(d,i),{status:`cancelled`};case`paused`:return f;case`failed`:return await Z(d,i,f.error),{status:`rejected`,reason:f.error}}}function rn(e){return{items:e}}async function Y(e,t){e.status=`running`,e.startedAt=Date.now(),await t.persistFrame(e),await t.emitFrameStarted(e)}async function X(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`completed`,e.output=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameCompleted(e,i)}async function Z(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`failed`,e.error=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameFailed(e,n,i)}async function Q(e,t){e.status=`skipped`,e.completedAt=Date.now(),await t.persistFrame(e)}async function $(e,t){e.status=`cancelled`,e.completedAt=Date.now(),await t.persistFrame(e)}function an(e,t){return!!E(e,F(t))}async function on(e,t,n,r,i,a=[]){if(t.signal.aborted)return{status:`cancelled`};switch(e.type){case`sequence`:return r(e,t,n,i,a);case`station`:return vt(e,t,n,i);case`delegate-agent`:return bt(e,t,n,i);case`delegate-role`:return xt(e,t,n,i);case`parallel`:return jt(e,t,n,r,i??``,a,e.mode??`all-settled`);case`gate`:return Vt(e,t,n,i??``);case`iterate`:return Yt(e,t,n,r,i??``,a);case`iterate-chain`:return tn(e,t,n,r,i??``,a);default:return{status:`failed`,error:`Unknown node type: ${String(e.type)}`}}}const sn=new Set([`completed`,`skipped`,`waiting`,`running`]);function cn(e){return e.type===`parallel`||e.type===`iterate`||e.type===`iterate-chain`}function ln(e,t,n){return R(e.resumeFrames,t.id,{parentFrameId:n,...cn(t)?{statuses:sn}:{}})}function un(e,t,n){if(n?.status===`completed`)return z(e,t.id,{status:`completed`,...n.output===void 0?{}:{output:n.output}});if(n?.status===`skipped`)return z(e,t.id,{status:`skipped`})}async function dn(e,t,n,r,i,a,o){try{return{result:an(e,i)}}catch(e){let i=e instanceof Error?e.message:String(e);return await Z(r.createFrame({nodeId:n.id,nodeType:n.type,path:a,parentFrameId:o}),r,`'${t}' condition evaluation failed: ${i}`),{status:`failed`,error:`'${t}' condition evaluation failed for '${n.id}': ${i}`}}}async function fn(e,t,n,r,i,a){let o=a??t.createFrame({nodeId:e.id,nodeType:e.type,path:r,parentFrameId:i});if(t.signal.aborted)return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};a===void 0&&await Y(o,t);let s;try{s=await on(e,t,n,pn,o.frameId,o.path)}catch(e){let r=e instanceof Error?e.message:String(e);return await Z(o,t,r),{updatedCtx:n,outcome:{status:`failed`,error:r}}}switch(s.status){case`completed`:return await X(o,t,s.output),{updatedCtx:z(n,e.id,{status:`completed`,output:s.output})};case`skipped`:return await Q(o,t),{updatedCtx:z(n,e.id,{status:`skipped`})};case`cancelled`:return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};case`paused`:return{updatedCtx:n,outcome:s};case`failed`:return await Z(o,t,s.error),{updatedCtx:n,outcome:{status:`failed`,error:s.error}}}}async function pn(e,t,n,r,i=[]){let a=n;for(let n of e.nodes){if(t.signal.aborted)return{status:`cancelled`};let e=ln(t,n,r),o=un(a,n,e);if(o!==void 0){a=o;continue}if(n.when!==void 0){let e=await dn(n.when,`when`,n,t,a,i,r);if(`status`in e)return e;if(!e.result){await Q(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=z(a,n.id,{status:`skipped`});continue}}if(n.skip!==void 0){let e=await dn(n.skip,`skip`,n,t,a,i,r);if(`status`in e)return e;if(e.result){await Q(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=z(a,n.id,{status:`skipped`});continue}}let s=e?.status===`waiting`&&n.type===`gate`||e?.status===`running`&&cn(n)?e:void 0,{updatedCtx:c,outcome:l}=await fn(n,t,a,i,r,s);if(a=c,l!==void 0)return l}return{status:`completed`}}export{Te as A,ve as C,be as D,xe as E,M as F,S as I,ke as M,Oe as N,De as O,Ce as P,ye as S,j as T,ge as _,Ye as a,he as b,Le as c,Me as d,je as f,_e as g,pe as h,nt as i,we as j,Ee as k,Pe as l,me as m,Lt as n,Re as o,N as p,Dt as r,Ue as s,pn as t,Ne as u,A as v,Se as w,O as x,k as y};
@@ -10,18 +10,18 @@ import * as _$zod_v4_core0 from "zod/v4/core";
10
10
  * Registered globally so lifecycle files can import subjects.
11
11
  */
12
12
  declare const RuntimeNamespace: _$_makaio_core0.BusNamespaceDefinition<"runtime", {
13
- database: {
13
+ database: _$_makaio_core0.LocalSubjectSchema<{
14
14
  request: _$zod.ZodObject<{}, _$zod_v4_core0.$strip>;
15
15
  response: _$zod.ZodObject<{
16
16
  db: _$zod.ZodUnknown;
17
17
  }, _$zod_v4_core0.$strip>;
18
- };
19
- machineIdentity: {
18
+ }>;
19
+ machineIdentity: _$_makaio_core0.LocalSubjectSchema<{
20
20
  request: _$zod.ZodObject<{}, _$zod_v4_core0.$strip>;
21
21
  response: _$zod.ZodObject<{
22
22
  identity: _$zod.ZodUnknown;
23
23
  }, _$zod_v4_core0.$strip>;
24
- };
24
+ }>;
25
25
  busPort: {
26
26
  request: _$zod.ZodObject<{}, _$zod_v4_core0.$strip>;
27
27
  response: _$zod.ZodObject<{
@@ -38,18 +38,18 @@ declare const RuntimeNamespace: _$_makaio_core0.BusNamespaceDefinition<"runtime"
38
38
  * - busPort: Query for the bus server WebSocket port
39
39
  */
40
40
  declare const RuntimeSubjects: _$_makaio_core0.BusSubjects<_$_makaio_core0.FlatSubjectDefinitions<"runtime", {
41
- database: {
41
+ database: _$_makaio_core0.LocalSubjectSchema<{
42
42
  request: _$zod.ZodObject<{}, _$zod_v4_core0.$strip>;
43
43
  response: _$zod.ZodObject<{
44
44
  db: _$zod.ZodUnknown;
45
45
  }, _$zod_v4_core0.$strip>;
46
- };
47
- machineIdentity: {
46
+ }>;
47
+ machineIdentity: _$_makaio_core0.LocalSubjectSchema<{
48
48
  request: _$zod.ZodObject<{}, _$zod_v4_core0.$strip>;
49
49
  response: _$zod.ZodObject<{
50
50
  identity: _$zod.ZodUnknown;
51
51
  }, _$zod_v4_core0.$strip>;
52
- };
52
+ }>;
53
53
  busPort: {
54
54
  request: _$zod.ZodObject<{}, _$zod_v4_core0.$strip>;
55
55
  response: _$zod.ZodObject<{
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import * as _$_makaio_core0 from "@makaio/framework/core";
2
3
 
3
4
  //#region runtimes/node/src/bus/runtime/schemas.d.ts
4
5
  /**
@@ -13,28 +14,34 @@ declare const RuntimeSchemas: {
13
14
  * Query for database handle.
14
15
  * Registered by NodeRuntime. Absent in memory-only runtimes.
15
16
  *
17
+ * Local-only: the response carries a live database handle that cannot be
18
+ * serialized across a transport. Use `getRuntimeDatabase` for typed access.
19
+ *
16
20
  * Subject: `runtime.database`
17
21
  * Type: Request (RPC)
18
22
  */
19
- database: {
23
+ database: _$_makaio_core0.LocalSubjectSchema<{
20
24
  request: z.ZodObject<{}, z.core.$strip>;
21
25
  response: z.ZodObject<{
22
26
  db: z.ZodUnknown;
23
27
  }, z.core.$strip>;
24
- };
28
+ }>;
25
29
  /**
26
30
  * Query for machine identity (E2E encryption keys).
27
31
  * Registered by NodeRuntime. Absent in memory-only runtimes.
28
32
  *
33
+ * Local-only: the response carries private key material that must never
34
+ * cross a transport.
35
+ *
29
36
  * Subject: `runtime.machineIdentity`
30
37
  * Type: Request (RPC)
31
38
  */
32
- machineIdentity: {
39
+ machineIdentity: _$_makaio_core0.LocalSubjectSchema<{
33
40
  request: z.ZodObject<{}, z.core.$strip>;
34
41
  response: z.ZodObject<{
35
42
  identity: z.ZodUnknown;
36
43
  }, z.core.$strip>;
37
- };
44
+ }>;
38
45
  /**
39
46
  * Query for the bus server WebSocket port.
40
47
  * Registered at the app entry point (Electron main, CLI) where the bus
@@ -1 +1 @@
1
- import{z as e}from"zod";const t={database:{request:e.object({}),response:e.object({db:e.unknown()})},machineIdentity:{request:e.object({}),response:e.object({identity:e.unknown()})},busPort:{request:e.object({}),response:e.object({port:e.number()})}};export{t as RuntimeSchemas};
1
+ import{z as e}from"zod";import{localSubject as t}from"@makaio/framework/core";const n={database:t({request:e.object({}),response:e.object({db:e.unknown()})}),machineIdentity:t({request:e.object({}),response:e.object({identity:e.unknown()})}),busPort:{request:e.object({}),response:e.object({port:e.number()})}};export{n as RuntimeSchemas};
@@ -682,6 +682,24 @@ declare class FileRegistryCache implements IModelRegistryCache {
682
682
  set(registry: ModelRegistry): Promise<void>;
683
683
  }
684
684
  //#endregion
685
+ //#region runtimes/node/src/bus/runtime/get-runtime-database.d.ts
686
+ /**
687
+ * Resolve the runtime database handle with `db` narrowed to
688
+ * {@link MakaioDatabase}.
689
+ *
690
+ * Wraps the `runtime.database` request so the single cast from the opaque
691
+ * wire shape lives here — at the runtime boundary — instead of being repeated
692
+ * at every consumer. For storage handler registration prefer
693
+ * `registerDrizzleHandlers` from `@makaio/storage-drizzle`, which receives the
694
+ * handle through the extension storage lifecycle; this helper covers typed
695
+ * ad-hoc access outside that seam.
696
+ * @typeParam TSchema - Drizzle table schema record. Defaults to an empty schema.
697
+ * @param bus - Connected bus instance.
698
+ * @returns The runtime's Drizzle database handle.
699
+ * @throws When no runtime registered a database provider (memory-only runtimes).
700
+ */
701
+ declare function getRuntimeDatabase<TSchema extends Record<string, unknown> = Record<string, never>>(bus: IMakaioBus): Promise<MakaioDatabase<TSchema>>;
702
+ //#endregion
685
703
  //#region runtimes/node/src/extension-browser-entry-paths.d.ts
686
704
  /**
687
705
  * Build the Rollup input name for a descriptor browser entry.
@@ -763,4 +781,4 @@ declare function findWorkspaceRoot(startDir: string): string;
763
781
  */
764
782
  declare function findWorkspaceRootInfo(startDir: string): WorkspaceRootInfo;
765
783
  //#endregion
766
- export { type ActivateAdapterRuntimeIdentityInput, type ActivatedAdapterRuntimeIdentity, type AttachedUpstreamTelemetry, type BootCoordinatorSetupContext, type BootMakaioRuntimeOptions, type BridgeBrowserOptions, type BundledMigrationsProbes, type BusServerTransportOptions, BusServerTransportProvider, type ConfiguredRuntimeOptions, type CoreBootOptions, type CredentialProvider, type DatabaseBootOptions, type DescriptorSourcePackageGroup, type DiscoveredExtension, ExplicitDescriptorDiscovery, type ExtensionDiscovery, FileConfigStorage, FileRegistryCache, FilesystemDescriptorDiscovery, type FilesystemDescriptorDiscoveryOptions, type FrameworkModuleResolver, type HonoRouteGraph, type HonoRouteGraphOptions, type HttpContributionPhase, type HttpRouteContribution, type HttpRouteGraphBuilder, type IWorkflowRunner, InProcessWorkflowRunner, type InProcessWorkflowRunnerOptions, type InitializeNodeDatabaseOptions, type InitializeNodeDatabaseResult, type LoadExtensionsOptions, type LoadMakaioConfigOptions, type LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MAKAIO_UPSTREAM_SECRET_ENV, MAKAIO_UPSTREAM_URL_ENV, type MachineKeyStatus, type MachineKeyValidation, type MakaioConfig, type MakaioRuntime, NodeCredentialProvider, NodeFrameworkModuleResolver, type NodeRuntimeOptions, NoopFrameworkModuleResolver, type ParseMakaioConfigOptions, type ParsedMakaioConfig, type PersistedMachineIdentity, type PrepareAdapterRuntimeInput, type PreparedAdapterRuntime, type ResolveUpstreamTelemetryBootOptionsFromEnvOptions, RuntimeSubjects, type ServerTransportProvider, StoredCredentialProvider, ThinWorkflowPiscinaRunner, type ThinWorkflowPiscinaRunnerOptions, type TransportReadyInfo, type UpstreamTelemetryBootOptions, type UpstreamTelemetryEnv, type UpstreamTelemetryTransportConfig, type WorkflowRunResult, type WorkflowRunnerBootOptions, type WorkflowRunnerConfig, type WorkflowWorkerEntryMode, type WorkflowWorkerEntryResolverOptions, type WorkspaceRootInfo, WorkspaceRootNotFoundError, activateAdapterRuntimeIdentity, attachUpstreamTelemetry, bootMakaioRuntime, bootMakaioRuntimeCore, bridgeExtensionBrowserEntries, buildConfiguredRuntimeOptions, buildExtensionBrowserRollupInputName, buildExtensionBrowserRuntimeEntrypoint, buildNodeRuntimeOptions, createHonoRouteGraph, createHttpRouteGraphBuilder, createMakaioConfigDiscovery, createUpstreamTelemetryTransport, defineMakaioConfig, entrypointStem, findWorkspaceRoot, findWorkspaceRootInfo, initializeNodeDatabase, isCliContributionLike, isMakaioExtensionLike, isMissingOptionalRuntimePackage, isWithinDirectory, loadExtensions, loadMakaioConfig, loadOrCreateMachineIdentity, machineKeysExist, normalizeNodeHostCapabilities, parseMakaioConfig, prepareAdapterRuntime, readFrameworkVersion, registerAdapterNameResolver, resolveBundledMigrationsDir, resolveConventionEntrypoint, resolveFrameworkSpecifier, resolveListeningPort, resolveMakaioConfigPath, resolveMakaioHome, resolveStaticModelRegistryPath, resolveUpstreamTelemetryBootOptionsFromEnv, resolveWorkflowWorkerEntry, runMigrations, selectFrameworkCorePackages, shouldIncludeExtension, tryImport, validateMachineKeys, waitForServerListening };
784
+ export { type ActivateAdapterRuntimeIdentityInput, type ActivatedAdapterRuntimeIdentity, type AttachedUpstreamTelemetry, type BootCoordinatorSetupContext, type BootMakaioRuntimeOptions, type BridgeBrowserOptions, type BundledMigrationsProbes, type BusServerTransportOptions, BusServerTransportProvider, type ConfiguredRuntimeOptions, type CoreBootOptions, type CredentialProvider, type DatabaseBootOptions, type DescriptorSourcePackageGroup, type DiscoveredExtension, ExplicitDescriptorDiscovery, type ExtensionDiscovery, FileConfigStorage, FileRegistryCache, FilesystemDescriptorDiscovery, type FilesystemDescriptorDiscoveryOptions, type FrameworkModuleResolver, type HonoRouteGraph, type HonoRouteGraphOptions, type HttpContributionPhase, type HttpRouteContribution, type HttpRouteGraphBuilder, type IWorkflowRunner, InProcessWorkflowRunner, type InProcessWorkflowRunnerOptions, type InitializeNodeDatabaseOptions, type InitializeNodeDatabaseResult, type LoadExtensionsOptions, type LoadMakaioConfigOptions, type LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MAKAIO_UPSTREAM_SECRET_ENV, MAKAIO_UPSTREAM_URL_ENV, type MachineKeyStatus, type MachineKeyValidation, type MakaioConfig, type MakaioRuntime, NodeCredentialProvider, NodeFrameworkModuleResolver, type NodeRuntimeOptions, NoopFrameworkModuleResolver, type ParseMakaioConfigOptions, type ParsedMakaioConfig, type PersistedMachineIdentity, type PrepareAdapterRuntimeInput, type PreparedAdapterRuntime, type ResolveUpstreamTelemetryBootOptionsFromEnvOptions, RuntimeSubjects, type ServerTransportProvider, StoredCredentialProvider, ThinWorkflowPiscinaRunner, type ThinWorkflowPiscinaRunnerOptions, type TransportReadyInfo, type UpstreamTelemetryBootOptions, type UpstreamTelemetryEnv, type UpstreamTelemetryTransportConfig, type WorkflowRunResult, type WorkflowRunnerBootOptions, type WorkflowRunnerConfig, type WorkflowWorkerEntryMode, type WorkflowWorkerEntryResolverOptions, type WorkspaceRootInfo, WorkspaceRootNotFoundError, activateAdapterRuntimeIdentity, attachUpstreamTelemetry, bootMakaioRuntime, bootMakaioRuntimeCore, bridgeExtensionBrowserEntries, buildConfiguredRuntimeOptions, buildExtensionBrowserRollupInputName, buildExtensionBrowserRuntimeEntrypoint, buildNodeRuntimeOptions, createHonoRouteGraph, createHttpRouteGraphBuilder, createMakaioConfigDiscovery, createUpstreamTelemetryTransport, defineMakaioConfig, entrypointStem, findWorkspaceRoot, findWorkspaceRootInfo, getRuntimeDatabase, initializeNodeDatabase, isCliContributionLike, isMakaioExtensionLike, isMissingOptionalRuntimePackage, isWithinDirectory, loadExtensions, loadMakaioConfig, loadOrCreateMachineIdentity, machineKeysExist, normalizeNodeHostCapabilities, parseMakaioConfig, prepareAdapterRuntime, readFrameworkVersion, registerAdapterNameResolver, resolveBundledMigrationsDir, resolveConventionEntrypoint, resolveFrameworkSpecifier, resolveListeningPort, resolveMakaioConfigPath, resolveMakaioHome, resolveStaticModelRegistryPath, resolveUpstreamTelemetryBootOptionsFromEnv, resolveWorkflowWorkerEntry, runMigrations, selectFrameworkCorePackages, shouldIncludeExtension, tryImport, validateMachineKeys, waitForServerListening };